@phantomclient/plugin 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/lib/chunks/api-DhaU9Jsd.js +1667 -0
- package/dist/lib/chunks/sdk-permissions-CyDMa4we.js +429 -0
- package/dist/lib/chunks/{state-kAlKf5xt.js → state-BGYMFLti.js} +9 -8
- package/dist/lib/guest.js +2174 -3171
- package/dist/lib/index.js +44 -37
- package/dist/lib/styles.css +1 -1
- package/dist/lib/vue.js +281 -121
- package/dist/runtime/chunks/api-DCkkcNDr.js +1 -0
- package/dist/runtime/chunks/{runtime-dom.esm-bundler-BbCcCl6A.js → runtime-dom.esm-bundler-Dcouf4CU.js} +1 -1
- package/dist/runtime/chunks/sdk-permissions-AYsXGgro.js +1 -0
- package/dist/runtime/chunks/{state-CFbUQLzX.js → state-CyERnsrb.js} +1 -1
- package/dist/runtime/frame.html +4 -4
- package/dist/runtime/runtime.css +1 -1
- package/dist/runtime/runtime.js +4 -1
- package/dist/runtime/sdk-vue.js +1 -1
- package/dist/runtime/sdk.js +1 -1
- package/dist/runtime/vue.js +1 -1
- package/dist/types/index.d.ts +4528 -425
- package/dist/types/vue.d.ts +3954 -424
- package/package.json +5 -2
- package/dist/lib/chunks/api-B2tHXZiJ.js +0 -9
- package/dist/lib/chunks/sdk-permissions-BnKU1K9D.js +0 -43
- package/dist/runtime/chunks/api-Bj1J6wAH.js +0 -1
- package/dist/runtime/chunks/sdk-permissions-D_NYB67a.js +0 -1
package/dist/runtime/runtime.js
CHANGED
|
@@ -1 +1,4 @@
|
|
|
1
|
-
import{S as Rn,i as $n,P as F,a as Fn}from"./chunks/sdk-permissions-D_NYB67a.js";import{P as E}from"./chunks/api-Bj1J6wAH.js";import{i as Un,t as Bn,d as _n,o as we,c as ve,a as ne,b as $e,e as vt,f as zn,g as bt,h as It}from"./chunks/runtime-dom.esm-bundler-BbCcCl6A.js";import{f as T,b as Hn,r as Vn,s as Tt,P as Wn}from"./chunks/state-CFbUQLzX.js";function xe(e){return e instanceof E?{code:e.code,message:e.message,...e.stack?{stack:e.stack}:{}}:e instanceof Error?{code:"FAILED",message:e.message||e.name,...e.stack?{stack:e.stack}:{}}:{code:"FAILED",message:L(e)}}function Gn(e){const t=e&&typeof e.code=="string"&&e.code?e.code:"FAILED";return new E(t,(e==null?void 0:e.message)||"Phantom could not do this")}function Ne(e){return Y(e,new WeakMap)}function Y(e,t){if(Un(e))return Y(e.value,t);if(typeof e=="function"||typeof e=="symbol")return;if(typeof e!="object"||e===null)return e;const n=Bn(e);if(t.has(n))return t.get(n);if(n instanceof Date||n instanceof RegExp||n instanceof ArrayBuffer||ArrayBuffer.isView(n))return n;if(Array.isArray(n)){const i=[];t.set(n,i);for(const a of n)i.push(Y(a,t));return i}if(n instanceof Map){const i=new Map;t.set(n,i);for(const[a,s]of n)i.set(Y(a,t),Y(s,t));return i}if(n instanceof Set){const i=new Set;t.set(n,i);for(const a of n)i.add(Y(a,t));return i}if(n instanceof Error)return xe(n);const r={};t.set(n,r);for(const[i,a]of Object.entries(n)){const s=Y(a,t);s!==void 0&&(r[i]=s)}return r}function L(e){if(typeof e=="string")return e;if(e instanceof Error)return e.stack||`${e.name}: ${e.message}`;if(e===void 0)return"undefined";if(typeof e=="function")return`[Function ${e.name||"anonymous"}]`;if(typeof e=="symbol"||typeof e=="bigint")return e.toString();try{const t=new WeakSet,n=JSON.stringify(Ne(e),(r,i)=>{if(typeof i=="object"&&i!==null){if(t.has(i))return"[Circular]";t.add(i)}return typeof i=="bigint"?`${i}n`:i});return xt(n??String(e))}catch{return xt(String(e))}}const Fe=1e4;function xt(e){return e.length>Fe?`${e.slice(0,Fe)}… (${e.length-Fe} more)`:e}const Kn=["log","info","warn","error"];function Xn(e,t){const n=new Map;let r=!1;for(const i of Kn){const a=e[i].bind(e);n.set(i,a),e[i]=(...s)=>{if(a(...s),!r){r=!0;try{t(i,s.map(L))}finally{r=!1}}}}return()=>{for(const[i,a]of n)e[i]=a}}class D extends Error{constructor(t,n,r=null){super(Yn(n,r,t)),this.code=t,this.flash=r,this.name="BridgeError"}code;flash}function Yn(e,t,n){if(typeof e=="string"&&e.trim()!=="")return Qn(e,t);const r=Zn(e);if(r)return r;const i=typeof(t==null?void 0:t.name)=="string"?t.name.trim():"";return i||`The game answered with no reason (${n})`}const Jn={1006:"that member is not a method",1009:"something the call reached was null",1010:"that member is not there",1034:"a value was not of the type the member takes",1056:"that object has nowhere to put the value",1063:"the call was given the wrong number of arguments",1069:"the object has no member of that name",1502:"a script in the game ran for longer than the player allows",2007:"a value the call needs was null"};function Qn(e,t){const n=typeof(t==null?void 0:t.errorId)=="number"?t.errorId:0,r=Jn[n];return!r||!/^\s*Error #\d+\s*$/.test(e)?e:`${e.trim()}: ${r}`}function Zn(e){if(e==null)return"";if(typeof e=="string")return e.trim();if(typeof e!="object")return String(e);const t=e;if(typeof t.message=="string"&&t.message.trim()!=="")return t.message;try{const n=JSON.stringify(e);return n&&n!=="{}"?n:""}catch{return""}}const kt=2;function ie(e){return encodeURIComponent(JSON.stringify(e))}function sn(e){return JSON.parse(decodeURIComponent(e))}function er(e){return typeof e=="object"&&e!==null&&"$handle"in e}function tr(e){switch(e.kind){case"result":return e.id;case"event":return e.listener;case"callback":return e.callback;case"hook":case"override":case"hook-dropped":case"hook-failed":return e.registration;case"watch":return e.watch;case"tick":return e.tick;case"overlay":return e.node;case"key":return e.key;case"drive-failed":return e.drive;case"track":return e.track;default:return null}}class ct{constructor(t,n=[]){this.className=t,this.args=n}className;args}class R{constructor(t,n,r){this.bridge=t,this.handle=n,this.className=r}bridge;handle;className;at(...t){return new Q(this.bridge,{kind:"handle",handle:this.handle},t)}release(){return this.bridge.release([this])}}class Q{constructor(t,n,r=[]){this.bridge=t,this.target=n,this.path=r}bridge;target;path;at(...t){return new Q(this.bridge,this.target,[...this.path,...t])}get(){return this.bridge.request({op:"get",target:this.target,path:[...this.path]})}set(t){return this.bridge.request({op:"set",target:this.target,path:[...this.path],value:this.bridge.encode(t)}).then(()=>{})}call(...t){return this.bridge.request({op:"call",target:this.target,path:[...this.path],args:t.map(n=>this.bridge.encode(n))})}describe(){return this.bridge.request({op:"describe",target:this.target,path:[...this.path]})}listen(t,n){return this.bridge.listen(this,t,n)}get entry(){return{target:this.target,path:[...this.path]}}}const nr=new Set(["drive-failed","track","hook","override","hook-dropped","hook-failed","watch","tick","overlay","key"]);class rr{constructor(t,n={}){this.transport=t,this.timeoutMs=n.timeoutMs??5e3,this.firstId=n.firstId??1,this.nextId=this.firstId,this.batchOption=n.batch,this.stopReceiving=t.onMessage(r=>this.receive(r))}transport;stateValue="waiting";nextId;pending=new Map;listeners=new Map;callbacks=new Map;readyWaiters=[];clientListeners=new Set;uncaughtListeners=new Set;timeoutMs;stopReceiving;clientVersion=null;featureList=[];firstId;batchOption;queue=[];batches=new Map;subscriptions=new Map;ticks=new Map;get state(){return this.stateValue}get client(){return this.clientVersion}get features(){return this.featureList}allocate(){return this.nextId++}whenReady(){return this.stateValue==="ready"?Promise.resolve():this.stateValue==="closed"?Promise.reject(new D("CLOSED","The game is closed")):new Promise((t,n)=>this.readyWaiters.push({resolve:t,reject:n}))}definition(t){return new Q(this,{kind:"definition",name:t})}gameClient(){return new Q(this,{kind:"client"})}stage(){return new Q(this,{kind:"stage"})}construct(t,...n){return this.request({op:"construct",className:t,args:n.map(r=>this.encode(r))})}onClient(t){return this.clientListeners.add(t),()=>this.clientListeners.delete(t)}onUncaught(t){return this.uncaughtListeners.add(t),()=>this.uncaughtListeners.delete(t)}async listen(t,n,r){const i=this.nextId++;this.listeners.set(i,r);try{await this.request({op:"listen",target:t.target,path:[...t.path],event:n,listener:i})}catch(a){throw this.listeners.delete(i),a}return async()=>{!this.listeners.delete(i)||this.stateValue==="closed"||await this.request({op:"unlisten",listener:i})}}async subscribe(t,n,r){const i=this.nextId++;this.subscriptions.set(i,r);try{await this.request(t(i))}catch(a){throw this.subscriptions.delete(i),a}return async()=>{!this.subscriptions.delete(i)||this.stateValue==="closed"||await this.request(n(i))}}onSubscription(t,n){return this.subscriptions.set(t,n),()=>{this.subscriptions.get(t)===n&&this.subscriptions.delete(t)}}async hookTable(t){return await this.request(t===void 0?{op:"hookTable"}:{op:"hookTable",url:t})}async hook(t,n,r){let i=0;const a=await this.subscribe(s=>(i=s,{op:"hook",registration:s,hook:t,rules:n}),s=>({op:"unhook",registration:s}),r);return{registration:i,stop:a}}watch(t,n,r){return this.subscribe(i=>({op:"watch",watch:i,entries:t.map(a=>({target:a.target,path:[...a.path]})),everyFrames:Math.max(1,Math.floor(n.everyFrames??1)),handles:n.handles??!1}),i=>({op:"unwatch",watch:i}),i=>{i.kind==="watch"&&r(i.values.map(a=>this.decode(a)),i.errors??null)})}async tick(t,n){const r=Math.max(1,Math.floor(t));let i=this.ticks.get(r);if(!i){const o=new Set,l=this.subscribe(c=>({op:"tick",tick:c,everyFrames:r}),c=>({op:"untick",tick:c}),c=>{if(c.kind==="tick")for(const d of[...o])d(c.frame,c.time)});i={listeners:o,started:l},this.ticks.set(r,i),l.catch(()=>{this.ticks.get(r)===i&&this.ticks.delete(r)})}const a=i;a.listeners.add(n);try{await a.started}catch(o){throw a.listeners.delete(n),o}let s=!1;return async()=>{s||(s=!0,a.listeners.delete(n),!(a.listeners.size>0||this.ticks.get(r)!==a)&&(this.ticks.delete(r),await(await a.started)()))}}highlight(t,n){return this.subscribe(r=>({op:"highlight",highlight:r,target:t.target,path:[...t.path],effect:n}),r=>({op:"unhighlight",highlight:r}),()=>{})}style(t,n){return this.subscribe(r=>({op:"style",style:r,target:t.target,path:[...t.path],format:n}),r=>({op:"unstyle",style:r}),()=>{})}invokeOriginal(t,n,r){return this.request({op:"invokeOriginal",registration:t,token:n,arguments:r===null?null:r.map(i=>this.encode(i))})}async overrideDone(t,n){this.stateValue!=="closed"&&await this.request({op:"overrideDone",registration:t,token:n})}onKey(t,n){return this.subscribe(r=>({op:"key",key:r,spec:t}),r=>({op:"unkey",key:r}),r=>{r.kind==="key"&&n(r)})}async draw(t,n){await this.request({op:"draw",node:t,spec:n})}async erase(t){if(!(t.length===0||this.stateValue==="closed")){for(const n of t)this.subscriptions.delete(n);await this.request({op:"erase",nodes:[...t]})}}drive(t,n){return this.subscribe(r=>({op:"drive",drive:r,spec:t}),r=>({op:"undrive",drive:r}),r=>{r.kind==="drive-failed"&&(n==null||n(r.error))})}async collect(t,n){const i=await this.request({op:"collect",target:t.target,path:[...t.path],spec:n});return{items:Array.isArray(i==null?void 0:i.items)?i.items:[],total:typeof(i==null?void 0:i.total)=="number"?i.total:0}}track(t,n,{mode:r="displayList",everyFrames:i=15}={},a){return this.subscribe(s=>({op:"track",track:s,target:t.target,path:[...t.path],className:n,mode:r,everyFrames:i}),s=>({op:"untrack",track:s}),s=>{s.kind==="track"&&a({added:s.added.map(o=>this.decode(o)),removed:s.removed.map(o=>this.decode(o))})})}async snapshot(t,{scale:n=1,background:r=null,maxSize:i=0}={}){const a=await this.request({op:"snapshot",target:t.target,path:[...t.path],scale:n,background:r,maxSize:i});if(typeof a!="string")throw new D("FLASH","The picture came back empty");return a}note(t,n,r,i){if(n==="keys"||n==="clear")return this.request({op:"note",table:t,verb:n});if(!r)throw new TypeError(`A note to ${n} is kept beside an object; name the place`);const a={target:r.target,path:[...r.path]};return n==="write"?this.request({op:"note",table:t,verb:n,...a,value:this.encode(i)}):this.request({op:"note",table:t,verb:n,...a})}async find(t,n){const r=await this.request({op:"find",target:t.target,path:[...t.path],spec:n});return(Array.isArray(r)?r:[]).filter(i=>i instanceof R)}async answer(t,n){this.stateValue!=="closed"&&await this.request({op:"answer",callback:t,...n===void 0?{}:{value:this.encode(n)}})}async release(t){t.length===0||this.stateValue==="closed"||await this.request({op:"release",handles:t.map(n=>n.handle)})}close(){if(this.stateValue==="closed")return;if(this.stateValue==="ready"&&this.featureList.includes("dispose")){const n=this.nextId++;try{this.transport.send(ie({id:n,op:"dispose",from:this.firstId,to:this.nextId}))}catch{}}this.stateValue="closed",this.stopReceiving();const t=new D("CLOSED","The game was closed");for(const n of this.pending.values())clearTimeout(n.timer),n.reject(t);this.pending.clear();for(const n of this.batches.values())clearTimeout(n.timer);this.batches.clear(),this.queue=[],this.listeners.clear(),this.callbacks.clear(),this.subscriptions.clear(),this.ticks.clear(),this.readyWaiters.splice(0).forEach(n=>n.reject(t))}readyWithin(t){return new Promise((n,r)=>{const i=setTimeout(()=>r(new D("NOT_READY","The game has not started yet")),t);this.whenReady().then(()=>{clearTimeout(i),n()},a=>{clearTimeout(i),r(a)})})}encodeRequest(t){return ie({...t,id:this.nextId++})}request(t){if(this.stateValue==="closed")return Promise.reject(new D("CLOSED","The game is closed"));if(this.stateValue!=="ready")return this.readyWithin(this.timeoutMs).then(()=>this.request(t));const n=this.nextId++;return new Promise((r,i)=>{const a=setTimeout(()=>{this.pending.delete(n),i(new D("TIMEOUT",`The game did not answer "${t.op}" in ${this.timeoutMs}ms`))},this.timeoutMs);this.pending.set(n,{resolve:r,reject:i,timer:a});const s={...t,id:n};if(!this.batching||s.op==="hookTable"||s.op==="batch"){this.transport.send(ie(s));return}this.queue.push(s),this.queue.length===1&&queueMicrotask(()=>this.flush())})}get batching(){return this.batchOption??this.featureList.includes("batch")}flush(){const t=this.queue;if(this.queue=[],t.length===0||this.stateValue!=="ready")return;if(t.length===1){this.transport.send(ie(t[0]));return}const n=this.nextId++,r=t.map(a=>a.id),i=setTimeout(()=>this.batches.delete(n),this.timeoutMs+1e3);this.batches.set(n,{ids:r,timer:i}),this.transport.send(ie({id:n,op:"batch",requests:t}))}settle(t,n){const r=this.pending.get(t);r&&(this.pending.delete(t),clearTimeout(r.timer),n.ok?r.resolve(this.decode(n.value)):r.reject(new D("FLASH",n.error.message,n.error)))}encode(t){if(t===void 0)return{$undefined:!0};if(t===null||typeof t!="object"){if(typeof t=="function"){const n=this.nextId++;return this.callbacks.set(n,t),{$callback:n}}return t}return t instanceof R?{$handle:t.handle}:t instanceof ct?{$new:t.className,args:t.args.map(n=>this.encode(n))}:Array.isArray(t)?t.map(n=>this.encode(n)):Object.fromEntries(Object.entries(t).map(([n,r])=>[n,this.encode(r)]))}decode(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>this.decode(n));if(er(t))return new R(this,t.$handle,t.className);if(!("$undefined"in t))return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,this.decode(r)]))}receive(t){var n,r,i;if(this.stateValue==="closed")return;let a;try{a=sn(t)}catch{return}switch(a.kind){case"ready":if(a.version!==kt){const s=new D("VERSION",`The loader speaks bridge ${a.version}; this Phantom speaks ${kt}`);this.readyWaiters.splice(0).forEach(o=>o.reject(s)),this.close();return}this.stateValue="ready",this.clientVersion=a.client,this.featureList=Array.isArray(a.features)?[...a.features]:[],this.readyWaiters.splice(0).forEach(s=>s.resolve());return;case"client-loaded":this.clientListeners.forEach(s=>s(!0,null));return;case"client-failed":this.clientListeners.forEach(s=>s(!1,a.message));return;case"result":{const s=this.batches.get(a.id);if(s){this.batches.delete(a.id),clearTimeout(s.timer);const o=a.ok&&Array.isArray(a.value)?a.value:null;s.ids.forEach((l,c)=>{a.ok?o&&c<o.length&&this.settle(l,o[c]):this.settle(l,a)});return}this.settle(a.id,a.ok?{ok:!0,value:a.value}:a);return}case"event":(n=this.listeners.get(a.listener))==null||n(this.decode(a.event));return;case"callback":(r=this.callbacks.get(a.callback))==null||r(...a.args.map(s=>this.decode(s)));return;case"uncaught":{const s=new D("FLASH",a.error.message,a.error);this.uncaughtListeners.forEach(o=>o(s));return}default:if(nr.has(a.kind)){const s=tr(a);s!==null&&((i=this.subscriptions.get(s))==null||i(a))}}}}const ir=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],on={r:.3086,g:.6094,b:.082};function be(e,t){const n=new Array(20).fill(0);for(let r=0;r<4;r++)for(let i=0;i<5;i++){let a=i===4?t[r*5+4]:0;for(let s=0;s<4;s++)a+=t[r*5+s]*e[s*5+i];n[r*5+i]=a}return n}function cn(e){const t=e,{r:n,g:r,b:i}=on;return[n*(1-t)+t,r*(1-t),i*(1-t),0,0,n*(1-t),r*(1-t)+t,i*(1-t),0,0,n*(1-t),r*(1-t),i*(1-t)+t,0,0,0,0,0,1,0]}function ar(e){const t=e*255;return[1,0,0,0,t,0,1,0,0,t,0,0,1,0,t,0,0,0,1,0]}function sr(e){const t=e+1,n=128*(1-t);return[t,0,0,0,n,0,t,0,0,n,0,0,t,0,n,0,0,0,1,0]}function or(e){const t=e*Math.PI/180,n=Math.cos(t),r=Math.sin(t),{r:i,g:a,b:s}=on;return[i+n*(1-i)+r*-i,a+n*-a+r*-a,s+n*-s+r*(1-s),0,0,i+n*-i+r*.143,a+n*(1-a)+r*.14,s+n*-s+r*-.283,0,0,i+n*-i+r*-.6914,a+n*-a+r*a,s+n*(1-s)+r*s,0,0,0,0,0,1,0]}const cr={grayscale:cn(0),sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],invert:[-1,0,0,0,255,0,-1,0,0,255,0,0,-1,0,255,0,0,0,1,0],night:[.45,0,0,0,0,0,.5,0,0,0,0,0,.8,0,20,0,0,0,1,0]};function ln(e){if(typeof e=="string"){const n=cr[e];if(!n)throw new TypeError(`Unknown colour look "${String(e)}"`);return{matrix:[...n],colorTransform:null}}if("matrix"in e){if(e.matrix.length!==20)throw new TypeError("A colour matrix has twenty numbers");return{matrix:[...e.matrix],colorTransform:null}}if("tint"in e){const n=Math.max(0,Math.min(1,e.amount??.5)),r=i=>(e.tint>>i&255)*n;return{matrix:null,colorTransform:At({redMultiplier:1-n,greenMultiplier:1-n,blueMultiplier:1-n,redOffset:r(16),greenOffset:r(8),blueOffset:r(0)})}}if("transform"in e)return{matrix:null,colorTransform:At(e.transform)};let t=[...ir];return e.saturation!==void 0&&(t=be(t,cn(e.saturation))),e.hue!==void 0&&(t=be(t,or(e.hue))),e.contrast!==void 0&&(t=be(t,sr(e.contrast))),e.brightness!==void 0&&(t=be(t,ar(e.brightness))),{matrix:t,colorTransform:null}}function At(e){return{redMultiplier:e.redMultiplier??1,greenMultiplier:e.greenMultiplier??1,blueMultiplier:e.blueMultiplier??1,alphaMultiplier:e.alphaMultiplier??1,redOffset:e.redOffset??0,greenOffset:e.greenOffset??0,blueOffset:e.blueOffset??0,alphaOffset:e.alphaOffset??0}}function de(e={}){const t=e.recolor?ln(e.recolor):{matrix:null,colorTransform:null},r=e.glow??!(e.recolor||e.hide)?{color:e.color??9133302,alpha:e.alpha??1,blur:e.blur??8,strength:e.strength??2,inner:e.inner??!1,knockout:e.knockout??!1}:null;if(r&&t.matrix)throw new TypeError("A highlight is a glow or a colour matrix, not both: use two highlights");const i=e.pulse===void 0||e.pulse===!1?null:e.pulse===!0?{frames:60,from:.6,to:1}:{frames:e.pulse.frames??60,from:e.pulse.from??.6,to:e.pulse.to??1};return{glow:r,matrix:t.matrix,colorTransform:t.colorTransform,hide:e.hide??!1,pulse:i}}const Ee=Symbol.for("phantom.typedFlash");function un(e){return typeof e=="function"&&e[Ee]!==void 0}function M(e,t,n={}){const r={reference:t,handle:n.handle??null,className:n.className??null},i=o=>N(e,o),a={$get:()=>t.get().then(i),$set:async o=>t.set((await Z(e,[o]))[0]),$listen:(o,l)=>t.listen(o,c=>l(i(c))),$describe:()=>t.describe(),$at:(...o)=>M(e,t.at(...o)),$as:()=>M(e,t,{...r.handle?{handle:r.handle}:{}}),$release:()=>r.handle?r.handle.release():Promise.resolve(),$reference:t,$new:async(...o)=>{if(!r.className)throw new TypeError("Only a class can make objects with $new");return i(await e.construct(r.className,...await Z(e,o)))},toJSON:()=>`[Flash ${lr(r)}]`},s=(()=>{});return new Proxy(s,{get:(o,l)=>{if(l===Ee)return r;if(typeof l!="symbol"&&l!=="then")return Object.prototype.hasOwnProperty.call(a,l)?a[l]:M(e,t.at(l))},apply:async(o,l,c)=>i(await t.call(...await Z(e,c)))})}function he(e){return un(e)?e[Ee].reference:e instanceof R?e.at():e&&typeof e=="object"&&"target"in e&&"path"in e&&typeof e.at=="function"?e:null}function N(e,t){if(t instanceof R)return M(e,t.at(),{handle:t});if(Array.isArray(t))return t.map(n=>N(e,n));if(t&&typeof t=="object"){const n={};for(const[r,i]of Object.entries(t))n[r]=N(e,i);return n}return t}async function Z(e,t){return Promise.all(t.map(n=>Qe(e,n)))}async function Qe(e,t){if(un(t)){const n=t[Ee];return n.handle&&n.reference.path.length===0?n.handle:n.reference.get()}if(typeof t=="function"){const n=t;return(...r)=>n(...r.map(i=>N(e,i)))}if(Array.isArray(t))return Promise.all(t.map(n=>Qe(e,n)));if(t&&typeof t=="object"&&Object.getPrototypeOf(t)===Object.prototype){const n={};for(const[r,i]of Object.entries(t))n[r]=await Qe(e,i);return n}return t}function lr({reference:e,className:t}){const n=e.target,r=n.kind==="definition"?n.name:n.kind==="handle"?`object ${n.handle}`:n.kind,i=e.path.join(".");return t??(i?`${r}.${i}`:r)}class ur{constructor(t,n,r){this.bridge=t;const i=t.encode(n);this.callback=i.$callback,r!==void 0&&this.answers(r)}bridge;callback;stopped=!1;get argument(){return{$callback:this.callback}}async answers(t){if(this.stopped)return;await this.ready();const[n]=await Z(this.bridge,[t]);await this.bridge.answer(this.callback,n)}async answersNothing(){this.stopped||(await this.ready(),await this.bridge.answer(this.callback))}async stop(){this.stopped||(this.stopped=!0,await this.bridge.answer(this.callback))}async ready(){if(await this.bridge.whenReady(),!this.bridge.features.includes("answer"))throw new Error("This game is running a loader from before answers; a function of yours gives the game nothing back")}}function S(e){const t=he(e);if(!t)throw new TypeError("Expected a place in Flash: a typed place, an object read from Flash, or a reference");return{target:t.target,path:[...t.path]}}async function dr(e,t,n,r){if(await e.whenReady(),!e.features.includes("collect"))throw new Error("This game is running a loader from before collects; read the items one by one");const i={fields:hr(n)};r.skip!==void 0&&(i.skip=Math.max(0,Math.trunc(r.skip))),r.limit!==void 0&&(i.limit=Math.max(1,Math.trunc(r.limit))),r.handles!==void 0&&(i.handles=r.handles);const a=await e.collect(S(t),i);return{rows:a.items.map(s=>N(e,s)),total:a.total}}function hr(e){const t=Array.isArray(e)?e.map(n=>[n,n]):Object.entries(e);if(t.length===0)throw new TypeError("A collect needs the members to read");return t.map(([n,r])=>({name:n,path:(Array.isArray(r)?r:String(r).split(".")).filter(i=>i.length>0)}))}function pe(e){const t=`${e.className}.${e.member}`;return e.kind==="getter"?`${t}@get`:e.kind==="setter"?`${t}@set`:t}const Me=Symbol.for("phantom.hookRead"),ee=Symbol.for("phantom.hookTest");class mr{constructor(t){this.table=t;for(const n of t.hooks){this.byId.set(n.id,n);const r=pe(n);this.byKey.has(r)||this.byKey.set(r,n)}}table;byKey=new Map;byId=new Map;get size(){return this.byId.size}names(){return[...this.byKey.keys()]}find(t){return t.startsWith("#")?this.byId.get(Number(t.slice(1)))??null:this.byKey.get(t)??this.byKey.get(`${t}@get`)??this.byKey.get(`${t}@set`)??null}}function J(e){return e.flatMap(t=>Array.isArray(t)?t:t.includes("::")?[t]:t.split(".").filter(Boolean))}function X(e){return Object.freeze({[Me]:e})}function $(e,t,n){return Object.freeze({[ee]:n===void 0&&e==="exists"?{test:e,left:t}:{test:e,left:t,right:n}})}const gr={self:(...e)=>X({from:"self",path:J(e)}),arg:(e,...t)=>X({from:"arg",arg:e,path:J(t)}),returned:(...e)=>X({from:"return",path:J(e)}),fromClass:(e,...t)=>X({from:"class",name:e,path:J(t)}),place:(e,...t)=>X({from:"place",place:e,path:J(t)}),calls:()=>X({from:"calls"}),constant:e=>X({from:"constant",value:e}),equals:(e,t)=>$("equals",e,t),notEquals:(e,t)=>$("notEquals",e,t),less:(e,t)=>$("less",e,t),lessOrEqual:(e,t)=>$("lessOrEqual",e,t),greater:(e,t)=>$("greater",e,t),greaterOrEqual:(e,t)=>$("greaterOrEqual",e,t),contains:(e,t)=>$("contains",e,t),startsWith:(e,t)=>$("startsWith",e,t),endsWith:(e,t)=>$("endsWith",e,t),oneOf:(e,t)=>$("in",e,t),exists:e=>$("exists",e),all:(...e)=>Object.freeze({[ee]:{all:e}}),any:(...e)=>Object.freeze({[ee]:{any:e}}),not:e=>Object.freeze({[ee]:{not:e}})};function dn(e){return typeof e=="object"&&e!==null&&Me in e}function hn(e){return typeof e=="object"&&e!==null&&ee in e}function Ze(e,t,n,r){const i=h=>{if(typeof h=="number")return St(t,h);const m=t.parameters.findIndex(f=>f.name===h);if(m>=0)return m;if(/^\d+$/.test(h))return St(t,Number(h));const p=t.parameters.map(f=>f.name).join(", ")||"none";throw new TypeError(`${pe(t)} has no argument "${h}" (its arguments: ${p})`)},a=h=>{if(!dn(h))return Ce(h)??{from:"constant",value:se(e,h)};const m=h[Me];switch(m.from){case"constant":return{from:"constant",value:se(e,m.value)};case"arg":return{from:"arg",index:i(m.arg),path:m.path};case"self":return{from:"self",path:m.path};case"return":return{from:"return",path:m.path};case"class":return{from:"class",name:m.name,path:m.path};case"calls":return{from:"calls"};case"place":{const p=Ce(m.place,m.path);if(!p)throw new TypeError("rules.place takes a place in the game");return p}}},s=h=>{if(!hn(h)){const p=Object.entries(h).map(([f,g])=>({test:"equals",left:{from:"arg",index:i(f),path:[]},right:a(g)}));if(p.length===0)throw new TypeError("A hook condition names nothing to compare");return p.length===1?p[0]:{all:p}}const m=h[ee];return"all"in m?{all:m.all.map(s)}:"any"in m?{any:m.any.map(s)}:"not"in m?{not:s(m.not)}:m.test==="exists"?{test:m.test,left:a(m.left)}:{test:m.test,left:a(m.left),right:a(m.right)}},o=n.phase??(r?"enter":"none"),l=n.capture??{},c=t.parameters.map((h,m)=>m),d=l.args===!0||l.args===void 0&&r?c:(l.args??[]).map(i);return{observe:o==="both"?["enter","exit"]:o==="none"?[]:[o],capture:{args:d,self:et(l.self).map(([,h])=>h),value:l.value??!1,handles:l.handles??!1},when:n.when===void 0?null:s(n.when),first:n.first??null,every:n.every??null,skip:n.skip===void 0||n.skip===!1?null:n.skip===!0?{from:"constant",value:{$undefined:!0}}:a(n.skip.returns),replaceArgs:Object.entries(n.replaceArgs??{}).map(([h,m])=>({index:i(h),value:a(m)})),replaceReturn:"replaceReturn"in n?a(n.replaceReturn):null,perFrame:n.perFrame??20}}function St(e,t){if(!Number.isInteger(t)||t<0||e.parameters.length>0&&t>=e.parameters.length)throw new RangeError(`${pe(e)} has no argument ${t}`);return t}function et(e){return e?Array.isArray(e)?e.map(t=>[t,J([t])]):Object.entries(e).map(([t,n])=>[t,J([n])]):[]}function mn(e,t){const n=r=>{if(!hn(r))throw new TypeError("A condition between calls has no call to read: compare with rules.equals and its like");const i=r[ee];return"all"in i?{all:i.all.map(n)}:"any"in i?{any:i.any.map(n)}:"not"in i?{not:n(i.not)}:i.test==="exists"?{test:i.test,left:le(e,i.left)}:{test:i.test,left:le(e,i.left),right:le(e,i.right)}};return n(t)}function Ce(e,t=[]){const n=he(e);return n?{from:"place",target:n.target,path:[...n.path,...t]}:null}function le(e,t){if(!dn(t))return Ce(t)??{from:"constant",value:se(e,t)};const n=t[Me];switch(n.from){case"constant":return{from:"constant",value:se(e,n.value)};case"class":return{from:"class",name:n.name,path:n.path};case"place":{const r=Ce(n.place,n.path);if(!r)throw new TypeError("rules.place takes a place in the game");return r}default:throw new TypeError(`rules.${n.from} reads the call it is in; a value held between calls is a constant, rules.fromClass or a place`)}}function se(e,t){if(t===void 0)return{$undefined:!0};if(t instanceof R||t instanceof ct)return e.encode(t);const n=he(t);if(n){if(n.target.kind==="handle"&&n.path.length===0)return{$handle:n.target.handle};throw new TypeError("A place inside a list or object in a rule cannot be read there: pass the place on its own, or read it first")}if(typeof t=="function")throw new TypeError("A hook rule cannot call a function");return Array.isArray(t)?t.map(r=>se(e,r)):t!==null&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([r,i])=>[r,se(e,i)])):t}async function pr(e,t,n,r,i){var a;const s=t.find(n);if(!s)throw new TypeError(`There is no hook "${n}" in the hook table`);let o=r,l=et((a=r.capture)==null?void 0:a.self).map(([p])=>p),c=Ze(e,s,r,i!==void 0);const{registration:d,stop:h}=await e.hook(s.id,c,p=>{var f;switch(p.kind){case"hook":{if(!i)return;const g=(p.args??[]).map(I=>N(e,e.decode(I))),y={};c.capture.args.forEach((I,k)=>{var q;y[((q=s.parameters[I])==null?void 0:q.name)??String(I)]=g[k]});const v={};(p.self??[]).forEach((I,k)=>{v[l[k]??String(k)]=N(e,e.decode(I))}),i({phase:p.phase,call:p.call,args:y,argList:g,self:v,..."value"in p?{value:N(e,e.decode(p.value))}:{},skipped:p.skipped===!0,hook:s});return}case"hook-dropped":(f=o.onDropped)==null||f.call(o,p.dropped);return;case"hook-failed":{const g=new D("FLASH",`The hook on ${pe(s)} failed and is off: ${p.error.message}`,p.error);o.onError?o.onError(g):console.error(g.message);return}}});return Object.assign(()=>h(),{registration:d,hook:s,update:async(p,f={})=>{var g;const y=Ze(e,s,p,i!==void 0);await e.request({op:"rehook",registration:d,rules:y,resetCounts:f.resetCounts??!1}),o=p,c=y,l=et((g=p.capture)==null?void 0:g.self).map(([v])=>v)},stats:async()=>(await e.request({op:"hookStats"})).find(f=>f.registration===d)??null})}async function fr(e,t,n){if(await e.whenReady(),!e.features.includes("drive"))throw new Error("This game is running a loader from before repeated calls; call it yourself each frame");const r=S(t);if(r.path.length===0)throw new TypeError("A repeat calls a method, so name one: `place.method`, not the object");const i=n.while?mn(e,n.while):null;return e.drive({writes:[],calls:[{target:r.target,path:r.path,args:(n.args??[]).map(a=>le(e,a)),times:Math.max(1,Math.trunc(n.times??1))}],everyFrames:Math.max(1,Math.trunc(n.everyFrames??1)),while:i,restore:!1,once:n.once===!0},n.onFailed)}async function Nt(e,t,n){if(await e.whenReady(),!e.features.includes("drive"))throw new Error("This game is running a loader from before held values; write it yourself each frame");if(t.length===0)throw new TypeError("A hold needs a value to keep");const r=t.map(({place:a,value:s})=>{const o=S(a);if(o.path.length===0)throw new TypeError("A hold writes to a member, so name one: `place.member`, not the object");return{target:o.target,path:o.path,value:le(e,s)}}),i=n.while?mn(e,n.while):null;return e.drive({writes:r,everyFrames:Math.max(1,Math.trunc(n.everyFrames??1)),while:i,restore:n.restore!==!1,once:n.once===!0},n.onFailed)}class Ue{constructor(t,n,r,i,a,s,o){this.host=t,this.kind=n,this.id=r,this.name=i,this.tagY=s,this.handle=o,this.place=a}host;kind;id;name;tagY;handle;place;highlight(t={}){return this.host.bridge.highlight(this.entry(),de(t))}tag(t,n={}){const{anchorX:r,anchorY:i,...a}=n;return this.host.overlay.text(t,{centered:!0,font:{size:12,bold:!0,color:16777215},outline:0,...a,anchor:{place:this.place,x:r??0,y:i??this.tagY}})}onClick(t){const n=this.host.bridge;return this.kind!=="object"?this.place.$listen("mouseDown",()=>t(this)):n.stage().listen("mouseDown",r=>{const{stageX:i,stageY:a}=r??{};typeof i!="number"||typeof a!="number"||this.place.$reference.at("hitTestPoint").call(i,a,!0).then(s=>{s===!0&&t(this)}).catch(()=>{})})}async release(){this.handle&&await this.handle.release()}entry(){const t=this.place.$reference;return{target:t.target,path:[...t.path]}}}class yr{constructor(t){this.host=t}host;async players(){const t=this.host.bridge,n=t.definition("avatar.AvatarManager").at("avatarViewList"),r=await n.get(),i=r&&typeof r=="object"&&!(r instanceof R)?Object.keys(r):[],a=i.map(s=>r[s]).filter(s=>s instanceof R);try{const s=await Promise.all(i.map(o=>V(n.at(o,"userName").get())));return i.map((o,l)=>new Ue(this.host,"player",o,typeof s[l]=="string"?s[l]:null,M(t,n.at(o)),-80,null))}finally{await t.release(a)}}async npcs(){const t=this.host.bridge,n=t.definition("quest.QuestManager").at("_questActors"),r=await V(n.at("length").get());if(typeof r!="number"||r<=0)return[];const i=Array.from({length:Math.min(r,500)},(c,d)=>String(d)),[a,s,o]=await Promise.all([Promise.all(i.map(c=>V(n.at(c).get()))),Promise.all(i.map(c=>V(n.at(c,"_actorId").get()))),Promise.all(i.map(c=>V(n.at(c,"currAvatar","avName").get())))]),l=[];return i.forEach((c,d)=>{const h=a[d];if(!(h instanceof R))return;const m=o[d];l.push(new Ue(this.host,"npc",typeof s[d]=="string"?s[d]:c,typeof m=="string"&&m?m:null,M(t,h.at(),{handle:h}),-90,h))}),l}async objects(){const t=this.host.bridge,n=t.definition("room.RoomManagerWorld").at("instance","volumeManager","_volumeActors");let r;try{r=await n.at("length").get()}catch(d){throw d instanceof D&&d.code==="FLASH"?new D("FLASH",`The room's objects are private to the client, and this client does not reach them: ${d.message}`,d.flash):d}if(typeof r!="number"||r<=0)return[];const i=Array.from({length:Math.min(r,500)},(d,h)=>String(h)),[a,s]=await Promise.all([Promise.all(i.map(d=>V(n.at(d,"name").get()))),Promise.all(i.map(d=>V(n.at(d,"interactiveObjs","length").get())))]),o=[];i.forEach((d,h)=>{const m=s[h],p=a[h];for(let f=0;typeof m=="number"&&f<Math.min(m,50);f++)o.push([d,String(f),typeof p=="string"?p:null])});const l=await Promise.all(o.map(([d,h])=>V(n.at(d,"interactiveObjs",h,"mc").get()))),c=[];return o.forEach(([d,h,m],p)=>{const f=l[p];f instanceof R&&c.push(new Ue(this.host,"object",`${m??d}#${h}`,m,M(t,f.at(),{handle:f}),0,f))}),c}}function V(e){return e.catch(()=>null)}async function wr(e,t,n){if(await e.whenReady(),!e.features.includes("find"))throw new Error("This game is running a loader from before searches; only a path reaches an object");const r=t===void 0?{target:{kind:"stage"},path:[]}:S(t);return(await e.find(r,vr(n))).map(a=>M(e,a.at(),{handle:a}))}function vr(e){const t={};return e.ofClass!==void 0&&(t.ofClass=e.ofClass),e.named!==void 0&&(t.named=e.named),e.containing!==void 0&&(t.containing=e.containing),e.visibleOnly!==void 0&&(t.visibleOnly=e.visibleOnly),e.through!==void 0&&(t.through=e.through),e.depth!==void 0&&(t.depth=e.depth),e.limit!==void 0&&(t.limit=e.limit),t}const Ct={backspace:8,tab:9,enter:13,return:13,shift:16,control:17,ctrl:17,alt:18,pause:19,capslock:20,escape:27,esc:27,space:32,pageup:33,pagedown:34,end:35,home:36,left:37,arrowleft:37,up:38,arrowup:38,right:39,arrowright:39,down:40,arrowdown:40,insert:45,delete:46,";":186,"=":187,",":188,"-":189,".":190,"/":191,"`":192,"[":219,"\\":220,"]":221,"'":222};function br(e,t={}){const n={phase:t.phase??"down",consume:t.consume??!1,whileTyping:t.whileTyping??!1,repeat:t.repeat??!1};if(typeof e=="number")return{code:e,ctrl:null,shift:null,alt:null,...n};const r=e==="+"||e.endsWith("++"),i=(r?e.slice(0,-1):e).split("+").map(o=>o.trim()).filter(Boolean);r&&i.push("+");const a={ctrl:!1,shift:!1,alt:!1};let s=null;for(const o of i){const l=o.toLowerCase();l==="ctrl"||l==="control"||l==="cmd"||l==="meta"?a.ctrl=!0:l==="shift"?a.shift=!0:l==="alt"||l==="option"?a.alt=!0:l==="any"?s=null:s=Ir(o)}if(s===null&&!i.some(o=>o.toLowerCase()==="any"))throw new TypeError(`"${e}" names no key`);return{code:s,...a,...n}}function Ir(e){const t=e.toLowerCase();if(t in Ct)return Ct[t];if(/^[a-z0-9]$/i.test(e))return e.toUpperCase().charCodeAt(0);const n=/^f([1-9]|1[0-5])$/i.exec(e);if(n)return 111+Number(n[1]);const r=/^num(?:pad)?([0-9])$/i.exec(e);if(r)return 96+Number(r[1]);if(e==="+")return 187;throw new TypeError(`Unknown key "${e}"`)}class Tr{constructor(t){this.bridge=t}bridge;table=null;async set(t,n){const[r]=await Z(this.bridge,[n]);await this.bridge.note(await this.number(),"write",S(t),r)}async get(t){const n=await this.bridge.note(await this.number(),"read",S(t));return n==null?void 0:N(this.bridge,n)}async has(t){return await this.bridge.note(await this.number(),"has",S(t))===!0}async forget(t){return await this.bridge.note(await this.number(),"forget",S(t))===!0}async objects(){const t=await this.bridge.note(await this.number(),"keys");return Array.isArray(t)?t.filter(n=>n instanceof R).map(n=>M(this.bridge,n.at(),{handle:n})):[]}async clear(){this.table!==null&&await this.bridge.note(this.table,"clear")}async number(){if(await this.bridge.whenReady(),!this.bridge.features.includes("notes"))throw new Error("This game is running a loader from before notes; nothing can be kept beside its objects");return this.table??=this.bridge.allocate(),this.table}}const xr=127;function gn(e){const t=[],n=[];let r="",i=0;const a=()=>{const o={};for(const l of n)Object.assign(o,l.look);return o},s=()=>{if(r==="")return;const o={text:r,...a()},l=t[t.length-1];l&&Er(l,o)?l.text+=r:t.push(o),r=""};for(;i<e.length;){const o=e[i];if(o!=="["){r+=o,i++;continue}if(e[i+1]==="["){r+="[",i+=2;continue}const l=e.indexOf("]",i+1),c=l<0?null:kr(e.slice(i+1,l));if(c===null){r+=o,i++;continue}if(c.closing){const d=Cr(n,c.name);d<0?r+=e.slice(i,l+1):(s(),n.splice(d))}else s(),n.push({tag:c.name,look:c.look});i=l+1}return s(),t}function kr(e){if(e.startsWith("/")){const i=e.slice(1);return Ar.has(i)?{name:i,closing:!0}:null}const t=e.indexOf("="),n=t<0?e:e.slice(0,t),r=t<0?null:e.slice(t+1);switch(n){case"b":return r===null?{name:n,closing:!1,look:{bold:!0}}:null;case"i":return r===null?{name:n,closing:!1,look:{italic:!0}}:null;case"u":return r===null?{name:n,closing:!1,look:{underline:!0}}:null;case"color":{const i=r===null?null:Nr(r);return i===null?null:{name:n,closing:!1,look:{color:i}}}case"size":{const i=r===null?NaN:Number(r);return Number.isInteger(i)&&i>=1&&i<=xr?{name:n,closing:!1,look:{size:i}}:null}case"link":return r===null||r===""?null:{name:n,closing:!1,look:{link:r}};default:return null}}const Ar=new Set(["b","i","u","color","size","link"]),Sr="0123456789abcdef";function Nr(e){const t=e.toLowerCase(),n=t.startsWith("#")?t.slice(1):t.startsWith("0x")?t.slice(2):null;if(n===null||n.length!==6)return null;let r=0;for(const i of n){const a=Sr.indexOf(i);if(a<0)return null;r=r*16+a}return r}function Cr(e,t){for(let n=e.length-1;n>=0;n--)if(e[n].tag===t)return n;return-1}function Er(e,t){return["color","bold","italic","underline","size","font","link"].every(r=>e[r]===t[r])}const Be={className:"avatar.AvatarManager",path:["playerAvatarWorldView","parent"]},Et=new Set(["click","down","up","over","out"]);class Mr{constructor(t){this.bridge=t}bridge;nodes=new Map;async draw(t,n={}){const{handle:r}=await this.make(t,n);return r}world(t={x:0,y:0},n={}){return{place:this.bridge.definition(Be.className).at(Be.path[0],Be.path[1]),x:t.x,y:t.y,...n}}marker(t,n={}){const{kind:r="circle",...i}=n;return this.draw(r,{radius:8,...i,anchor:this.world(t)})}group(t={}){return this.draw("group",t)}text(t,n={}){return this.draw("text",{...n,text:t})}rich(t,n={}){return this.draw("text",{...n,rich:t})}rect(t){return this.draw("rect",t)}circle(t){return this.draw("circle",t)}line(t){return this.draw("line",t)}image(t,n={}){return this.draw("image",{...n,url:t})}async input(t={}){const{handle:n,state:r}=await this.make("input",{width:200,height:24,fill:16777215,stroke:10265519,padding:4,...t,font:{color:1120295,...t.font}});return r.value=t.value??"",Object.assign(n,{value:()=>r.value,setValue:async a=>{r.value=a,r.removed||await this.bridge.draw(n.node,{value:a})},focus:async()=>{r.removed||await this.bridge.draw(n.node,{focus:!0})}})}async button(t,n={}){const{handle:r,state:i}=await this.make("button",{width:72,height:24,fill:8141549,hoverFill:9133302,pressedFill:7153881,cornerRadius:4,...n,font:{color:16777215,bold:!0,...n.font},label:t});return Object.assign(r,{setLabel:a=>i.removed?Promise.resolve():this.bridge.draw(r.node,{label:a}),setDisabled:a=>i.removed?Promise.resolve():this.bridge.draw(r.node,{disabled:a})})}async panel(t={}){const{onMove:n,onResize:r,...i}=t,{handle:a}=await this.make("panel",{width:260,height:200,fill:{color:1120295,alpha:.92},stroke:3621201,titleFill:2042167,titleHeight:22,cornerRadius:6,...i,titleFont:{color:16777215,bold:!0,...i.titleFont}}),s=a;return n&&s.on("move",n),r&&s.on("resize",r),s}async list(t={}){const{handle:n,state:r}=await this.make("list",{width:240,height:160,fill:{color:0,alpha:.55},padding:4,...t,font:{color:16777215,...t.font}});return Object.assign(n,{append:(...i)=>r.removed||i.length===0?Promise.resolve():this.bridge.draw(n.node,{append:i.map(_e)}),setRows:i=>r.removed?Promise.resolve():this.bridge.draw(n.node,{rows:i.map(_e)})})}async replace(t,n){return await n.update({parent:null,host:null,replaces:t}),()=>n.remove()}async attach(t,n){return await n.update({parent:null,replaces:null,host:t}),()=>n.remove()}async focusGame(){await this.bridge.stage().at("focus").set(null)}async clear(){const t=[...this.nodes.entries()].filter(([,n])=>n.parent===null||!this.nodes.has(n.parent)).map(([n])=>n);await this.remove(t)}async make(t,n){var r;const i=this.bridge.allocate(),a={type:t,...this.specOf(n)},s={parent:n.parent?n.parent.node:null,children:new Set,listeners:new Map,failed:new Set,stopHearing:()=>{},removed:!1,value:""};s.stopHearing=this.bridge.onSubscription(i,o=>{var l;if(o.kind==="overlay"){if(o.event==="failed"){s.failed.forEach(c=>c(o.message??"The image did not load"));return}(o.event==="change"||o.event==="submit")&&o.value!==void 0&&(s.value=o.value),(l=s.listeners.get(o.event))==null||l.forEach(c=>c(o))}}),this.nodes.set(i,s);try{await this.bridge.draw(i,a)}catch(o){throw s.stopHearing(),this.nodes.delete(i),o}return s.parent!==null&&((r=this.nodes.get(s.parent))==null||r.children.add(i)),{handle:this.handle(i,t,s),state:s}}handle(t,n,r){const i=()=>this.remove([t]);return Object.assign(i,{node:t,type:n,update:async s=>{var o,l;if(r.removed)return;const c=this.specOf(s);"parent"in s&&(r.parent!==null&&((o=this.nodes.get(r.parent))==null||o.children.delete(t)),r.parent=s.parent?s.parent.node:null,r.parent!==null&&((l=this.nodes.get(r.parent))==null||l.children.add(t))),await this.bridge.draw(t,c)},show:()=>r.removed?Promise.resolve():this.bridge.draw(t,{visible:!0}),hide:()=>r.removed?Promise.resolve():this.bridge.draw(t,{visible:!1}),remove:i,on:(s,o)=>{const l=o,c=f=>{switch(f.event){case"change":case"submit":case"link":l(f.value??"");return;case"focus":case"blur":l(void 0);return;case"row":l(f.index??-1);return;case"move":l({x:f.x,y:f.y});return;case"resize":l({width:f.width??0,height:f.height??0});return;default:l({x:f.x,y:f.y})}};let d=r.listeners.get(s);const h=!d||d.size===0;d||(d=new Set,r.listeners.set(s,d)),d.add(c);const m=Et.has(s);h&&m&&this.sendMouse(t,r);let p=!1;return async()=>{p||(p=!0,d.delete(c),m&&d.size===0&&!r.removed&&await this.sendMouse(t,r))}},onFailed:s=>(r.failed.add(s),()=>{r.failed.delete(s)})})}async sendMouse(t,n){const r=[...n.listeners.entries()].filter(([i,a])=>Et.has(i)&&a.size>0).map(([i])=>i);await this.bridge.draw(t,{mouse:r})}async remove(t){const n=[],r=a=>{var s;const o=this.nodes.get(a);!o||o.removed||(o.removed=!0,o.stopHearing(),this.nodes.delete(a),n.push(a),o.children.forEach(r),o.parent!==null&&((s=this.nodes.get(o.parent))==null||s.children.delete(a)))};t.forEach(r);const i=t.filter(a=>n.includes(a));await this.bridge.erase(i)}specOf(t){const n={};for(const[r,i]of Object.entries(t))if(i!==void 0)switch(r){case"parent":n.parent=i===null?null:i.node;break;case"anchor":n.anchor=i===null?null:Or(i);break;case"host":case"replaces":n[r]=i===null?null:Dr(i);break;case"fill":case"background":case"hoverFill":case"pressedFill":case"titleFill":n[r]=i===null?null:Pr(i);break;case"stroke":n.stroke=i===null?null:Lr(i);break;case"font":case"titleFont":n[r]=qr(i);break;case"rich":n.spans=i===null?null:typeof i=="string"?gn(i):i;break;case"rows":case"append":n[r]=i.map(_e);break;default:n[r]=i}return n}}function qr(e){return{family:"_sans",size:12,color:16777215,bold:!1,italic:!1,...e}}function _e(e){if(typeof e=="string")return e||" ";const t=(Array.isArray(e)?e:gn(e.markup)).filter(n=>n.text.length>0);return t.length?t:" "}function Or(e){const t=typeof e=="object"&&e!==null&&"place"in e?e:{place:e},n=S(t.place);return{target:n.target,path:n.path,x:t.x??0,y:t.y??0,refreshFrames:t.refreshFrames??12,hideWhenGone:t.hideWhenGone??!0}}function Dr(e){const t=typeof e=="object"&&e!==null&&"place"in e?e:{place:e},n=S(t.place);return{target:n.target,path:n.path,refreshFrames:t.refreshFrames??12}}function Pr(e){return typeof e=="number"?{color:e,alpha:1}:{color:e.color,alpha:e.alpha??1}}function Lr(e){return typeof e=="number"?{color:e,alpha:1,width:1}:{color:e.color,alpha:e.alpha??1,width:e.width??1}}async function jr(e,t,n,r,i={}){const a=t.find(n);if(!a)throw new TypeError(`There is no hook "${n}" in the hook table`);const s={perFrame:i.perFrame??50};i.when!==void 0&&(s.when=i.when),i.first!==void 0&&(s.first=i.first),i.every!==void 0&&(s.every=i.every),i.replaceArgs!==void 0&&(s.replaceArgs=i.replaceArgs),"returns"in i&&(s.skip={returns:i.returns});const o={...Ze(e,a,s,!1),override:!0};let l=0,c=Promise.resolve();const d=pe(a),h=async g=>{l++;let y=!1,v=!1;const I=g.args.map(C=>N(e,e.decode(C))),k={};I.forEach((C,B)=>{var w;k[((w=a.parameters[B])==null?void 0:w.name)??String(B)]=C});const q=a.isStatic?M(e,e.definition(a.className),{className:a.className}):N(e,e.decode(g.self)),U={hook:a,call:g.call,self:q,args:k,argList:I,original:async(...C)=>{if(v)throw new D("FLASH",`The call of ${d} has ended: its handler finished`);y=!0;const B=await e.invokeOriginal(m,g.token,C.length===0?null:await Z(e,C));return N(e,B)}};try{await r(U)}catch(C){if(console.error(`The override of ${d} failed: ${C instanceof Error?C.message:String(C)}`),!y&&(i.onError??"original")==="original")try{await e.invokeOriginal(m,g.token,null)}catch(B){console.error(`The original ${d} failed after its override did: ${B instanceof Error?B.message:String(B)}`)}}finally{v=!0,l--;try{await e.overrideDone(m,g.token)}catch{}}},{registration:m,stop:p}=await e.hook(a.id,o,g=>{var y;switch(g.kind){case"override":i.sequential?c=c.then(()=>h(g)):h(g);return;case"hook-dropped":(y=i.onDropped)==null||y.call(i,g.dropped);return;case"hook-failed":console.error(`The override of ${d} failed and is off: ${g.error.message}`);return}}),f=Object.assign(()=>p(),{registration:m,hook:a,stats:async()=>(await e.request({op:"hookStats"})).find(y=>y.registration===m)??null});return Object.defineProperty(f,"running",{get:()=>l,enumerable:!0}),f}const Rr={fit:"showAll",stretch:"exactFit",fill:"noBorder",none:"noScale"};class $r{constructor(t){this.bridge=t}bridge;async zoom(t){await this.bridge.definition("room.RoomManagerWorld").at("instance","updateRoomZoom").call(Math.round(t))}async zoomLevel(){return await this.bridge.definition("gMainFrame").at("layerManager","bkg","scaleX").get()*100}async stretch(t){await this.bridge.stage().at("scaleMode").set(Rr[t])}hideHud(t){return this.bridge.highlight({target:{kind:"definition",name:"gui.GuiManager"},path:t?["mainHud",t]:["mainHud"]},de({hide:!0}))}hideLayer(t){return this.bridge.highlight({target:{kind:"definition",name:"gMainFrame"},path:["layerManager",t]},de({hide:!0}))}async setQuality(t){await this.bridge.stage().at("quality").set(t)}async setFrameRate(t){const n=this.bridge.stage().at("frameRate"),r=await n.get();return await n.set(Math.max(1,Math.min(120,t))),r}}class x extends Error{constructor(t,n,r){super(r===void 0?t:`${t} (at ${r})`),this.code=n,this.offset=r,this.name="ProtocolError"}code;offset}new TextEncoder;const Fr={lt:"<",gt:">",amp:"&",apos:"'",quot:'"'};function lt(e){if(!e.includes("&"))return e;let t="",n=0;for(;n<e.length;){const r=e.indexOf("&",n);if(r===-1)break;const i=e.indexOf(";",r+1);t+=e.slice(n,r);const a=i===-1?null:Ur(e.slice(r+1,i));a===null?(t+="&",n=r+1):(t+=a,n=i+1)}return t+e.slice(n)}function Ur(e){if(e.startsWith("#")){const t=e[1]==="x"||e[1]==="X",n=e.slice(t?2:1);if(n.length===0||!(t?_r(n):Br(n)))return null;const r=Number.parseInt(n,t?16:10);return r<=1114111?String.fromCodePoint(r):null}return Fr[e]??null}function Br(e){for(const t of e)if(t<"0"||t>"9")return!1;return!0}function _r(e){for(const t of e.toLowerCase())if(!(t>="0"&&t<="9"||t>="a"&&t<="f"))return!1;return!0}function tt(e){let t="";for(const n of e)n==="&"?t+="&":n==="<"?t+="<":n===">"?t+=">":t+=n;return t}function Mt(e,t){let n="";for(const r of e)r==="&"?n+="&":r==="<"?n+="<":r===t?n+=t==='"'?""":"'":n+=r;return n}class z{constructor(t,n,r="'",i=" ",a=["",""]){this.name=t,this.quote=r,this.leading=i,this.around=a,this.written=n,this.decoded=lt(n)}name;quote;leading;around;written;decoded;static create(t,n,r="'"){return new z(t,Mt(n,r),r)}get value(){return this.decoded}set value(t){this.decoded=t,this.written=Mt(t,this.quote)}get raw(){return this.written}}class qe{type="text";written;decoded;constructor(t){this.written=t,this.decoded=lt(t)}static create(t){return new qe(tt(t))}get value(){return this.decoded}set value(t){this.decoded=t,this.written=tt(t)}get raw(){return this.written}}class te{constructor(t){this.value=t}value;type="cdata"}class zr{constructor(t){this.value=t}value;type="comment"}class Hr{constructor(t,n){this.target=t,this.content=n}target;content;type="instruction"}class _{constructor(t,n={}){this.name=t,this.attributes=n.attributes??[],this.children=n.children??[],this.selfClosing=n.selfClosing??!1,this.trailing=n.trailing??"",this.closingTrailing=n.closingTrailing??""}name;type="element";attributes;children;selfClosing;trailing;closingTrailing;attribute(t){var n;return((n=this.attributes.find(r=>r.name===t))==null?void 0:n.value)??null}setAttribute(t,n){const r=this.attributes.find(i=>i.name===t);r?r.value=n:this.attributes.push(z.create(t,n))}removeAttribute(t){const n=this.attributes.findIndex(r=>r.name===t);return n===-1?!1:(this.attributes.splice(n,1),!0)}get elements(){return this.children.filter(t=>t.type==="element")}child(t){return this.elements.find(n=>n.name===t)??null}childrenNamed(t){return this.elements.filter(n=>n.name===t)}get textContent(){return this.children.map(t=>{switch(t.type){case"element":return t.textContent;case"text":case"cdata":return t.value;default:return""}}).join("")}set textContent(t){const n=this.children.some(r=>r.type==="cdata");this.children=[n?new te(t):qe.create(t)],this.selfClosing=!1}append(...t){this.children.push(...t),t.length>0&&(this.selfClosing=!1)}}class pn{constructor(t){this.children=t}children;get root(){return this.children.find(t=>t.type==="element")??null}}class Vr{constructor(t){this.input=t}input;index=0;get offset(){return this.index}get done(){return this.index>=this.input.length}peek(t=0){return this.input.charAt(this.index+t)}startsWith(t){return this.input.startsWith(t,this.index)}advance(t=1){this.index=Math.min(this.index+t,this.input.length)}expect(t){this.startsWith(t)||this.fail(`Expected "${t}"`),this.index+=t.length}whitespace(){const t=this.index;for(;!this.done&&Yr(this.input.charCodeAt(this.index));)this.index++;return this.input.slice(t,this.index)}until(t,n){const r=this.input.indexOf(t,this.index);r===-1&&this.fail(`Unterminated ${n}`);const i=this.input.slice(this.index,r);return this.index=r,i}name(){const t=this.index;for((this.done||!fn(this.input.charCodeAt(this.index)))&&this.fail("Expected a name"),this.index++;!this.done&&Jr(this.input.charCodeAt(this.index));)this.index++;return this.input.slice(t,this.index)}fail(t){throw new x(t,"XML_SYNTAX",this.index)}}const Wr=32,Gr=9,Kr=10,Xr=13;function Yr(e){return e===Wr||e===Gr||e===Kr||e===Xr}function fn(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===58||e>127}function Jr(e){return fn(e)||e>=48&&e<=57||e===45||e===46}const qt=64;function yn(e){const t=new Vr(e),n=wn(t,null,0);return n.some(r=>r.type==="element")||t.fail("Expected an element"),new pn(n)}function wn(e,t,n){const r=[];for(;!e.done;){if(e.startsWith("</"))return t===null&&e.fail("Closing tag with nothing open"),r;e.startsWith("<![CDATA[")?(e.advance(9),r.push(new te(e.until("]]>","CDATA section"))),e.advance(3)):e.startsWith("<!--")?(e.advance(4),r.push(new zr(e.until("-->","comment"))),e.advance(3)):e.startsWith("<?")?r.push(Zr(e)):e.startsWith("<!")?e.fail("Document type declarations are not supported"):e.peek()==="<"?r.push(ei(e,n)):r.push(Qr(e))}return t!==null&&e.fail(`Unclosed element <${t}>`),r}function Qr(e){const t=e.offset;for(;!e.done&&e.peek()!=="<";)e.advance();return new qe(e.input.slice(t,e.offset))}function Zr(e){e.expect("<?");const t=e.name(),n=e.until("?>","processing instruction");return e.advance(2),new Hr(t,n)}function ei(e,t){t>=qt&&e.fail(`Elements nested deeper than ${qt}`),e.expect("<");const n=e.name(),r=[];for(;;){const i=e.whitespace();if(e.startsWith("/>"))return e.advance(2),new _(n,{attributes:r,selfClosing:!0,trailing:i});if(e.peek()===">"){e.advance();const a=wn(e,n,t+1);e.expect("</");const s=e.name();s!==n&&e.fail(`Expected </${n}> but found </${s}>`);const o=e.whitespace();return e.expect(">"),new _(n,{attributes:r,children:a,trailing:i,closingTrailing:o})}e.done&&e.fail(`Unterminated tag <${n}>`),i.length===0&&e.fail("Expected whitespace before an attribute"),r.push(ti(e,i,r))}}function ti(e,t,n){const r=e.name();n.some(l=>l.name===r)&&e.fail(`Attribute "${r}" given twice`);const i=e.whitespace();e.expect("=");const a=e.whitespace(),s=e.peek();s!=='"'&&s!=="'"&&e.fail("Expected a quoted attribute value"),e.advance();const o=e.until(s,"attribute value");return o.includes("<")&&e.fail('"<" is not allowed in an attribute value'),e.advance(),new z(r,o,s,t,[i,a])}function Ot(e){return e instanceof pn?e.children.map(nt).join(""):nt(e)}function nt(e){switch(e.type){case"element":return ni(e);case"text":return e.raw;case"cdata":return`<![CDATA[${e.value.split("]]>").join("]]]]><![CDATA[>")}]]>`;case"comment":return`<!--${e.value}-->`;case"instruction":return`<?${e.target}${e.content}?>`}}function ni(e){const t=e.attributes.map(ri).join(""),n=`<${e.name}${t}${e.trailing}`;if(e.selfClosing&&e.children.length===0)return`${n}/>`;const r=e.children.map(nt).join("");return`${n}>${r}</${e.name}${e.closingTrailing}>`}function ri(e){const[t,n]=e.around,{leading:r,name:i,quote:a,raw:s}=e;return`${r}${i}${t}=${n}${a}${s}${a}`}function ii(e){const t=yn(e).root;if(!t||t.name!=="dataObj")throw new x("Expected a <dataObj> element","DATA_OBJECT");return vn(t,{})}function vn(e,t){const n=t;for(const r of e.elements)if(r.name==="var")n[ke(r,"n")]=ai(r);else if(r.name==="obj"){const i=ke(r,"t");if(i!=="a"&&i!=="o")throw new x(`Unknown object kind "${i}"`,"DATA_OBJECT");n[ke(r,"o")]=vn(r,i==="a"?[]:{})}return t}function ai(e){const t=e.textContent;switch(ke(e,"t")){case"s":return t;case"n":return Number(t);case"b":return t!=="0";case"x":return null;default:throw new x(`Unknown variable type "${e.attribute("t")}"`,"DATA_OBJECT")}}function ke(e,t){const n=e.attribute(t);if(n===null)throw new x(`<${e.name}> is missing its "${t}" attribute`,"DATA_OBJECT");return n}function si(e){return`<dataObj>${bn(e)}</dataObj>`}function bn(e){return Object.entries(e).map(([t,n])=>n===null?`<var n='${t}' t='x'></var>`:typeof n=="object"?`<obj t='${Array.isArray(n)?"a":"o"}' o='${t}'>${bn(n)}</obj>`:typeof n=="boolean"?`<var n='${t}' t='b'>${n?1:0}</var>`:typeof n=="number"?`<var n='${t}' t='n'>${n}</var>`:`<var n='${t}' t='s'>${tt(n)}</var>`).join("")}class Oe{constructor(t,n){this.raw=t,this.direction=n}raw;direction;wasModified=!1;wasDropped=!1;get modified(){return this.wasModified}get dropped(){return this.wasDropped}drop(){this.wasDropped=!0}encode(){return this.wasModified?this.serialize():this.raw}toString(){return this.encode()}markModified(){this.wasModified=!0}}class ut extends Oe{format="json";envelope;constructor(t,n){super(t,n),this.envelope=oi(t)}static create(t,n,r,i=-1,a="o"){const s=t==="toServer"?{t:"xt",b:{x:a,c:n,r:i,p:r}}:{t:"xt",b:{r:i,o:{_cmd:n,...r}}};return new ut(JSON.stringify(s),t)}get type(){return this.envelope.t}get command(){var t;const n=this.direction==="toServer"?this.envelope.b.c:(t=this.envelope.b.o)==null?void 0:t._cmd;return typeof n=="string"?n:null}get room(){const t=this.envelope.b.r;return typeof t=="number"&&Number.isInteger(t)?t:null}get params(){if(this.direction==="toServer")return this.envelope.b.p??{};const{_cmd:t,...n}=this.envelope.b.o??{};return n}get value(){return this.envelope}edit(t){t(this.envelope),this.markModified()}serialize(){return JSON.stringify(this.envelope)}}function oi(e){let t;try{t=JSON.parse(e)}catch(n){throw new x(`Not JSON: ${n.message}`,"JSON_SYNTAX")}if(!Dt(t)||typeof t.t!="string"||!Dt(t.b))throw new x('A JSON message is an object with "t" and "b"',"JSON_SYNTAX");return t}function Dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}class Pt extends Oe{constructor(t,n,r=null){super(t,n),this.problem=r}problem;format="raw";get command(){return null}get room(){return null}serialize(){return this.raw}}const Lt="xt";class me extends Oe{format="xml";document;constructor(t,n){super(t,n),this.document=yn(t)}static create(t,n,r,i,a=[]){const s=new _("msg",{attributes:[z.create("t",n)],children:[new _("body",{attributes:[z.create("action",r),z.create("r",String(i))],children:[...a]})]});return new me(Ot(s),t)}get element(){return this.document.root.name}get type(){var t;return((t=this.envelope)==null?void 0:t.attribute("t"))??null}get command(){var t;return((t=this.body)==null?void 0:t.attribute("action"))??null}get room(){const t=this.body,n=Number((t==null?void 0:t.attribute("r"))??(t==null?void 0:t.attribute("id"))??Number.NaN);return Number.isInteger(n)?n:null}get signed(){var t;return(((t=this.envelope)==null?void 0:t.attribute("h"))??null)!==null}get body(){var t;return((t=this.envelope)==null?void 0:t.child("body"))??null}get data(){return this.type!==Lt||!this.body?null:ii(this.body.textContent)}set data(t){if(this.type!==Lt||!this.body)throw new x("Only an extension message carries an object","PACKET_FORMAT");this.edit(n=>{const r=n.root.child("body");r.children=[new te(si(t))]})}edit(t){if(this.signed)throw new x("This message is signed by the client; changing it would fail the server’s check","PACKET_FORMAT");t(this.document),this.markModified()}serialize(){return Ot(this.document)}get envelope(){const t=this.document.root;return(t==null?void 0:t.name)==="msg"?t:null}}const G="%",rt="xt";class ge extends Oe{format="xt";fields;constructor(t,n){super(t,n),this.fields=ci(t,n)}static create(t,n,r,i=[],a="o"){return new ge(jt(t,{extension:a,command:n,room:String(r),args:i.map(String)}),t)}get command(){return this.fields.command}set command(t){Ae(t),this.fields.command=t,this.markModified()}get extension(){return this.fields.extension}get room(){const t=Number(this.fields.room);return Number.isInteger(t)?t:null}set room(t){this.fields.room=String(t),this.markModified()}get args(){return[...this.fields.args]}get length(){return this.fields.args.length}arg(t){return this.fields.args[t]}setArg(t,n){if(!Number.isInteger(t)||t<0||t>this.fields.args.length)throw new RangeError(`Argument ${t} is outside a message of ${this.length} arguments`);const r=String(n);Ae(r),this.fields.args[t]=r,this.markModified()}setArgs(t){const n=t.map(String);n.forEach(Ae),this.fields.args=n,this.markModified()}serialize(){return jt(this.direction,this.fields)}}function ci(e,t){if(e.length<2||!e.startsWith(G)||!e.endsWith(G))throw new x('An extension message starts and ends with "%"',"XT_SYNTAX");const n=e.slice(1,-1).split(G);if(n[0]!==rt)throw new x(`Expected the "xt" handler, found "${n[0]}"`,"XT_SYNTAX",1);const r=t==="toServer"?4:3;if(n.length<r)throw new x(`A message to the ${t==="toServer"?"server":"client"} has at least ${r} fields`,"XT_SYNTAX");return t==="toServer"?{extension:n[1],command:n[2],room:n[3],args:n.slice(4)}:{extension:null,command:n[1],room:n[2],args:n.slice(3)}}function jt(e,t){const r=[...e==="toServer"?[rt,t.extension??"o",t.command,t.room]:[rt,t.command,t.room],...t.args];return r.forEach(Ae),G+r.map(i=>i+G).join("")}function Ae(e){if(e.includes(G))throw new x(`An extension message value cannot contain "${G}": ${e}`,"XT_VALUE")}function In(e,t){try{switch(e.charAt(0)){case"<":return new me(e,t);case G:return new ge(e,t);case"{":return new ut(e,t);default:return new Pt(e,t)}}catch(n){return new Pt(e,t,n)}}class fe{constructor(t,n){this.values=t,this.packet=n}values;packet;index=0;get position(){return this.index}get remaining(){return this.values.length-this.index}string(t){return this.next(t)}int(t){const n=this.next(t),r=Number(n);return(n.trim()===""||!Number.isInteger(r))&&this.fail(t,this.index-1,"is not an integer",n),r}number(t){const n=this.next(t),r=Number(n);return(n.trim()===""||!Number.isFinite(r))&&this.fail(t,this.index-1,"is not a number",n),r}flag(t){return this.next(t)!=="0"}repeat(t,n){return Array.from({length:t},(r,i)=>n(i))}rest(){const t=this.values.slice(this.index);return this.index=this.values.length,t}next(t){return this.index>=this.values.length&&this.fail(t,this.index,`is missing: the message has ${this.values.length} arguments`),this.values[this.index++]}fail(t,n,r,i){const a=i===void 0?"":` ("${i}")`;throw new x(`${this.packet}: field "${t}" (${n}) ${r}${a}`,"PACKET_FIELD")}}class li{written=[];string(t){return this.written.push(t),this}int(t){if(!Number.isInteger(t))throw new RangeError(`${t} is not an integer`);return this.written.push(t),this}number(t){if(!Number.isFinite(t))throw new RangeError(`${t} is not a finite number`);return this.written.push(t),this}flag(t){return this.written.push(t?"1":"0"),this}each(t,n){return t.forEach(n),this}raw(t){return this.written.push(...t),this}get values(){return this.written}}function u(e){const{name:t,description:n,direction:r,command:i,extension:a="o",read:s,write:o}=e,l=c=>c instanceof ge&&c.direction===r&&c.command===i&&(r==="toClient"||c.extension===a);return{name:t,description:n,format:"xt",direction:r,command:i,matches:l,decode(c){return Tn(l(c),t,c),{...s(new fe(c.args,t)),room:c.room??-1}},encode(c){const d=new li;return o(d,c),ge.create(r,i,c.room,d.values,a)}}}function ye(e){const{name:t,description:n,direction:r,command:i,type:a,read:s,write:o}=e,l=c=>c instanceof me&&c.direction===r&&c.type===a&&c.command===i;return{name:t,description:n,format:"xml",direction:r,command:i,matches:l,decode(c){return Tn(l(c),t,c),{...s(c),room:c.room??-1}},encode(c){return me.create(r,a,i,c.room,o(c))}}}function Tn(e,t,n){if(!e)throw new TypeError(`A ${n.format} "${n.command}" message ${n.direction} is not ${t}`)}function xn(e){return{invId:e.int("invId"),defId:e.int("defId")}}function kn(e,t){e.int(t.length).each(t,({invId:n,defId:r})=>e.int(n).int(r))}u({name:"achievement.list-request",description:"The client asks for a player’s achievements.",direction:"toServer",command:"za",read:e=>({userName:e.string("userName"),secondsSinceLastAsked:e.int("secondsSinceLastAsked")}),write:(e,{userName:t,secondsSinceLastAsked:n})=>e.string(t).int(n)});u({name:"achievement.set-user-var",description:"The client sets one of the player’s user variables.",direction:"toServer",command:"zs",read:e=>({userVarId:e.int("userVarId"),value:e.int("value"),notify:e.flag("notify")}),write:(e,{userVarId:t,value:n,notify:r})=>e.int(t).int(n).int(r?1:0)});u({name:"achievement.user-vars-request",description:"The client asks for all of the player’s user variables.",direction:"toServer",command:"zg",read:()=>({}),write:()=>{}});u({name:"achievement.list",description:"The server gives a player’s achievements.",direction:"toClient",command:"za",read:e=>{const t=e.string("userName"),n=e.int("count");return{userName:t,archived:n===-1,achievements:e.repeat(Math.max(n,0),()=>xn(e))}},write:(e,{userName:t,archived:n,achievements:r})=>{e.string(t),n?e.int(-1):kn(e,r)}});u({name:"achievement.user-var-changed",description:"One of the player’s user variables changed, and any achievements it earned.",direction:"toClient",command:"zs",read:e=>({userVarId:e.int("userVarId"),value:e.number("value"),achievements:e.repeat(e.int("count"),()=>xn(e))}),write:(e,{userVarId:t,value:n,achievements:r})=>{e.int(t).number(n),kn(e,r)}});u({name:"achievement.user-vars",description:"The server gives all of the player’s user variables.",direction:"toClient",command:"zg",read:e=>({userVars:e.repeat(e.int("count"),()=>({userVarId:e.int("userVarId"),type:e.int("type"),value:e.number("value")}))}),write:(e,{userVars:t})=>e.int(t.length).each(t,({userVarId:n,type:r,value:i})=>e.int(n).int(r).number(i))});function An(e){return{lBits:e.int("lBits"),uBits:e.int("uBits"),eBits:e.int("eBits"),name:e.string("petName"),createdTs:e.number("createdTs"),personalityDefId:e.int("personalityDefId"),favoriteFoodDefId:e.int("favoriteFoodDefId"),favoriteToyDefId:e.int("favoriteToyDefId")}}function Sn(e,t){e.int(t.lBits).int(t.uBits).int(t.eBits).string(t.name).number(t.createdTs).int(t.personalityDefId).int(t.favoriteFoodDefId).int(t.favoriteToyDefId)}u({name:"pet.list-request",description:"The client asks for a player’s pets.",direction:"toServer",command:"pl",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"pet.list",description:"The server lists a player’s pets.",direction:"toClient",command:"pl",read:e=>{const t=e.string("found")==="1";if(!t)return{found:t,userName:"",pets:[]};const n=e.string("userName"),r=e.repeat(e.int("count"),()=>({invId:e.int("invId"),createdTs:e.number("createdTs"),name:e.string("name"),lBits:e.int("lBits"),uBits:e.int("uBits"),eBits:e.int("eBits"),masteryCounter:e.int("masteryCounter"),personalityDefId:e.int("personalityDefId"),favoriteToyDefId:e.int("favoriteToyDefId"),favoriteFoodDefId:e.int("favoriteFoodDefId"),denStoreInvId:e.int("denStoreInvId")}));return{found:t,userName:n,pets:r}},write:(e,{found:t,userName:n,pets:r})=>{e.string(t?"1":"0"),t&&e.string(n).int(r.length).each(r,i=>e.int(i.invId).number(i.createdTs).string(i.name).int(i.lBits).int(i.uBits).int(i.eBits).int(i.masteryCounter).int(i.personalityDefId).int(i.favoriteToyDefId).int(i.favoriteFoodDefId).int(i.denStoreInvId))}});u({name:"pet.switch-request",description:"The player brings out a pet, or puts theirs away.",direction:"toServer",command:"ps",read:e=>({invId:e.int("invId")}),write:(e,{invId:t})=>e.int(t)});u({name:"pet.switched",description:"Someone brought out a pet or put theirs away.",direction:"toClient",command:"ps",read:e=>{const t=e.string("success")==="1";if(!t)return{success:t,userId:-1,activePetInvId:null,pet:null};const n=e.int("userId");return e.remaining===1?{success:t,userId:n,activePetInvId:e.int("activePetInvId"),pet:null}:{success:t,userId:n,activePetInvId:null,pet:An(e)}},write:(e,{success:t,userId:n,activePetInvId:r,pet:i})=>{if(e.string(t?"1":"0"),!!t)if(e.int(n),i)Sn(e,i);else if(r!==null)e.int(r);else throw new x("pet.switched: a success names a pet or an inventory id","PACKET_FIELD")}});u({name:"pet.mastery-display-request",description:"The player shows or hides a pet’s mastery badge.",direction:"toServer",command:"pm",read:e=>({show:e.flag("show"),invId:e.int("invId")}),write:(e,{show:t,invId:n})=>e.flag(t).int(n)});u({name:"pet.mastery-displayed",description:"The server says whether a pet’s mastery badge changed.",direction:"toClient",command:"pm",read:e=>{const t=e.flag("success");return t?{success:t,invId:e.int("invId"),lBits:e.int("lBits"),uBits:e.int("uBits"),eBits:e.int("eBits")}:{success:t,invId:-1,lBits:0,uBits:0,eBits:0}},write:(e,{success:t,invId:n,lBits:r,uBits:i,eBits:a})=>{e.flag(t),t&&e.int(n).int(r).int(i).int(a)}});u({name:"pet.egg-name-request",description:"The player names a newly hatched egg pet from two lists of predefined name parts.",direction:"toServer",command:"pn",read:e=>({invId:e.int("invId"),firstNameLocId:e.int("firstNameLocId"),secondNameLocId:e.int("secondNameLocId")}),write:(e,{invId:t,firstNameLocId:n,secondNameLocId:r})=>e.int(t).int(n).int(r)});u({name:"pet.egg-named",description:"The server says whether an egg pet was named.",direction:"toClient",command:"pn",read:e=>({success:e.flag("success"),invId:e.int("invId"),name:e.string("name")}),write:(e,{success:t,invId:n,name:r})=>e.flag(t).int(n).string(r)});u({name:"pet.create-request",description:"The player adopts a new pet.",direction:"toServer",command:"pc",read:e=>({shopId:e.int("shopId"),lBits:e.int("lBits"),uBits:e.int("uBits"),eBits:e.int("eBits"),firstNameLocId:e.int("firstNameLocId"),secondNameLocId:e.int("secondNameLocId"),fromRedemption:e.flag("fromRedemption")}),write:(e,t)=>e.int(t.shopId).int(t.lBits).int(t.uBits).int(t.eBits).int(t.firstNameLocId).int(t.secondNameLocId).flag(t.fromRedemption)});u({name:"pet.created",description:"The server says whether a new pet was adopted.",direction:"toClient",command:"pc",read:e=>{const t=e.flag("success");if(!t)return{success:t,balance:0,currencyType:0,pet:null};const n=e.int("balance"),r=e.int("currencyType"),i=e.int("invId"),a=e.int("lBits"),s=e.int("uBits"),o=e.int("eBits"),l=e.string("name"),c=e.number("createdTs"),d=e.int("personalityDefId"),h=e.int("favoriteToyDefId"),m=e.int("favoriteFoodDefId"),p=e.flag("broughtOut");return{success:t,balance:n,currencyType:r,pet:{invId:i,lBits:a,uBits:s,eBits:o,name:l,createdTs:c,personalityDefId:d,favoriteToyDefId:h,favoriteFoodDefId:m,broughtOut:p}}},write:(e,t)=>{e.flag(t.success),!(!t.success||!t.pet)&&e.int(t.balance).int(t.currencyType).int(t.pet.invId).int(t.pet.lBits).int(t.pet.uBits).int(t.pet.eBits).string(t.pet.name).number(t.pet.createdTs).int(t.pet.personalityDefId).int(t.pet.favoriteToyDefId).int(t.pet.favoriteFoodDefId).flag(t.pet.broughtOut)}});u({name:"pet.dismiss-request",description:"The player frees one of their pets.",direction:"toServer",command:"pd",read:e=>({invId:e.int("invId")}),write:(e,{invId:t})=>e.int(t)});u({name:"pet.dismissed",description:"The server says whether a pet was freed.",direction:"toClient",command:"pd",read:e=>({success:e.string("success")==="1",invId:e.int("invId")}),write:(e,{success:t,invId:n})=>e.string(t?"1":"0").int(n)});u({name:"avatar.move",description:"The player walks or is placed somewhere in the room.",direction:"toServer",command:"au",read:e=>{const t=e.int("count"),n=e.repeat(t,()=>({x:e.int("x"),y:e.int("y")})),r=e.int("animation")>>>0;return{points:n,animation:r,immediate:e.flag("immediate")}},write:(e,{points:t,animation:n,immediate:r})=>e.int(t.length).each(t,({x:i,y:a})=>e.int(i).int(a)).int(n>>>0).flag(r)});u({name:"avatar.moved",description:"Avatars in the room walked or were placed.",direction:"toClient",command:"au",read:e=>({avatars:e.repeat(e.int("users"),()=>{const t=e.int("userId"),n=e.int("count"),r=e.repeat(n,()=>({x:e.int("x"),y:e.int("y")}));return{userId:t,path:r,teleport:e.flag("teleport")}})}),write:(e,{avatars:t})=>e.int(t.length).each(t,({userId:n,path:r,teleport:i})=>e.int(n).int(r.length).each(r,({x:a,y:s})=>e.int(a).int(s)).flag(i))});u({name:"avatar.paint",description:"The player changes their avatar’s colours.",direction:"toServer",command:"ap",read:e=>({colors:[e.int("color1"),e.int("color2"),e.int("color3")],avatarId:e.int("avatarId")}),write:(e,{colors:t,avatarId:n})=>e.int(t[0]).int(t[1]).int(t[2]).int(n)});function De(e){return[e.int("color1"),e.int("color2"),e.int("color3")]}function Pe(e,t){e.int(t[0]).int(t[1]).int(t[2])}function Rt(e){return e!==void 0&&e.trim()!==""&&Number.isInteger(Number(e))}u({name:"avatar.paint-result",description:"The server says whether the player’s colours changed.",direction:"toClient",command:"ap",read:e=>({success:e.string("success")==="1",extra:e.rest()}),write:(e,{success:t,extra:n})=>e.string(t?"1":"0").raw(n)});u({name:"avatar.switch-request",description:"The player switches to another of their avatars.",direction:"toServer",command:"as",read:e=>({perUserAvId:e.int("perUserAvId")}),write:(e,{perUserAvId:t})=>e.int(t)});u({name:"avatar.switched",description:"Someone in the room switched avatars.",direction:"toClient",command:"as",read:e=>{if(!e.flag("success"))return{success:!1,extra:e.rest()};const t=e.int("userId"),n={perUserAvId:e.int("perUserAvId"),avInvId:e.int("avInvId"),customAvId:e.int("customAvId"),avTypeId:e.int("avTypeId"),colors:De(e),avName:e.string("avName")};if(e.remaining===2){const i={activePetInvId:e.int("activePetInvId"),questLevel:e.int("questLevel")};return{success:!0,userId:t,avatar:n,player:i,other:null}}const r={pet:An(e),questLevel:e.int("questLevel")};return{success:!0,userId:t,avatar:n,player:null,other:r}},write:(e,t)=>{if(!t.success){e.flag(!1).raw(t.extra);return}const{userId:n,avatar:r,player:i,other:a}=t;if(e.flag(!0).int(n).int(r.perUserAvId).int(r.avInvId).int(r.customAvId).int(r.avTypeId),Pe(e,r.colors),e.string(r.avName),i)e.int(i.activePetInvId).int(i.questLevel);else if(a)Sn(e,a.pet),e.int(a.questLevel);else throw new x("avatar.switched: a success has a player or an other part","PACKET_FIELD")}});u({name:"avatar.list-request",description:"The client asks for a player’s avatars.",direction:"toServer",command:"al",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"avatar.list",description:"The server lists a player’s avatars.",direction:"toClient",command:"al",read:e=>{const t=e.rest(),n=new fe(t,"avatar.list"),r=n.string("userName"),i=Number(t[1]);if(Rt(t[1])&&t.length===2+i&&t.slice(2).every(c=>Rt(c))){const c=n.int("count");return{own:!1,userName:r,perUserAvIds:n.repeat(c,()=>n.int("perUserAvId"))}}const s=n.int("slotFlags")>>>0,o=n.string("uuid"),l=n.repeat(n.int("count"),()=>({perUserAvId:n.int("perUserAvId"),avInvId:n.int("avInvId"),avName:n.string("avName"),avTypeId:n.int("avTypeId"),customAvId:n.int("customAvId")}));return{own:!0,userName:r,slotFlags:s,uuid:o,avatars:l}},write:(e,t)=>{if(e.string(t.userName),!t.own){e.int(t.perUserAvIds.length).each(t.perUserAvIds,n=>e.int(n));return}e.int(t.slotFlags>>>0).string(t.uuid).int(t.avatars.length).each(t.avatars,n=>e.int(n.perUserAvId).int(n.avInvId).string(n.avName).int(n.avTypeId).int(n.customAvId))}});u({name:"avatar.data-request",description:"The client asks for one of a player’s avatars.",direction:"toServer",command:"ad",read:e=>({userName:e.string("userName"),perUserAvId:e.int("perUserAvId"),items:e.int("items")}),write:(e,{userName:t,perUserAvId:n,items:r})=>e.string(t).int(n).int(r)});u({name:"avatar.data",description:"The server describes one of a player’s avatars.",direction:"toClient",command:"ad",read:e=>{const t={userName:e.string("userName"),uuid:e.string("uuid"),nameBarData:e.int("nameBarData"),enviroType:e.int("enviroType"),userNameModeratedFlag:e.int("userNameModeratedFlag"),timeLeftHostingCustomParty:e.int("timeLeftHostingCustomParty"),daysSinceLastLogin:e.int("daysSinceLastLogin"),perUserAvId:e.int("perUserAvId"),avTypeId:e.int("avTypeId"),customAvId:e.int("customAvId"),colors:De(e),avName:e.string("avName"),questLevel:e.int("questLevel")};if(e.remaining===8){const r={avInvId:e.int("avInvId"),landPetInvId:e.int("landPetInvId"),oceanPetInvId:e.int("oceanPetInvId"),attackBase:e.int("attackBase"),attackMax:e.int("attackMax"),defenseBase:e.int("defenseBase"),defenseMax:e.int("defenseMax"),healthBase:e.int("healthBase")};return{...t,player:r,other:null}}const n={lBits:e.int("lBits"),uBits:e.int("uBits"),eBits:e.int("eBits"),petName:e.string("petName")};return{...t,player:null,other:n}},write:(e,t)=>{e.string(t.userName).string(t.uuid).int(t.nameBarData).int(t.enviroType).int(t.userNameModeratedFlag).int(t.timeLeftHostingCustomParty).int(t.daysSinceLastLogin).int(t.perUserAvId).int(t.avTypeId).int(t.customAvId),Pe(e,t.colors),e.string(t.avName).int(t.questLevel);const{player:n,other:r}=t;if(n)e.int(n.avInvId).int(n.landPetInvId).int(n.oceanPetInvId).int(n.attackBase).int(n.attackMax).int(n.defenseBase).int(n.defenseMax).int(n.healthBase);else if(r)e.int(r.lBits).int(r.uBits).int(r.eBits).string(r.petName);else throw new x("avatar.data: an avatar has a player or an other part","PACKET_FIELD")}});u({name:"avatar.lookup-request",description:"The client looks a player up by name.",direction:"toServer",command:"ag",read:e=>({userName:e.string("userName"),userLookup:e.flag("userLookup")}),write:(e,{userName:t,userLookup:n})=>e.string(t).flag(n)});u({name:"avatar.lookup",description:"The server describes a player looked up by name.",direction:"toClient",command:"ag",read:e=>{const t=e.string("userName"),n=e.string("uuid"),r=e.int("status");if(r!==0&&r!==1)return{userName:t,uuid:n,status:r,avatar:null};const i={accountType:e.int("accountType"),isGuide:e.string("isGuide")==="1",daysSinceLastLogin:e.int("daysSinceLastLogin"),perUserAvId:e.int("perUserAvId"),avInvId:e.int("avInvId"),nameBarData:e.int("nameBarData"),avTypeId:e.int("avTypeId"),customAvId:e.int("customAvId"),colors:De(e),avName:e.string("avName"),eyesDefId:e.int("eyesDefId"),patternDefId:e.int("patternDefId"),questLevel:e.int("questLevel")},a=e.int("count"),s={userId:e.int("userId"),userNameModeratedFlag:e.int("userNameModeratedFlag"),pet:{lBits:e.int("lBits"),uBits:e.int("uBits"),eBits:e.int("eBits"),name:e.string("petName")},items:e.repeat(a,()=>({defId:e.int("defId"),color:e.int("color")}))};return{userName:t,uuid:n,status:r,avatar:{...i,...s}}},write:(e,{userName:t,uuid:n,status:r,avatar:i})=>{e.string(t).string(n).int(r),i&&(e.int(i.accountType).string(i.isGuide?"1":"0").int(i.daysSinceLastLogin).int(i.perUserAvId).int(i.avInvId).int(i.nameBarData).int(i.avTypeId).int(i.customAvId),Pe(e,i.colors),e.string(i.avName).int(i.eyesDefId).int(i.patternDefId).int(i.questLevel).int(i.items.length).int(i.userId).int(i.userNameModeratedFlag).int(i.pet.lBits).int(i.pet.uBits).int(i.pet.eBits).string(i.pet.name).each(i.items,({defId:a,color:s})=>e.int(a).int(s)))}});u({name:"avatar.joined",description:"An avatar appears in the room.",direction:"toClient",command:"ac",read:e=>({userId:e.int("userId"),x:e.int("x"),y:e.int("y"),animation:e.int("animation")>>>0,userName:e.string("userName"),uuid:e.string("uuid"),perUserAvId:e.int("perUserAvId"),avName:e.string("avName"),avTypeId:e.int("avTypeId"),customAvId:e.int("customAvId"),colors:De(e),questLevel:e.int("questLevel"),details:e.rest()}),write:(e,t)=>{e.int(t.userId).int(t.x).int(t.y).int(t.animation>>>0).string(t.userName).string(t.uuid).int(t.perUserAvId).string(t.avName).int(t.avTypeId).int(t.customAvId),Pe(e,t.colors),e.int(t.questLevel).raw(t.details)}});u({name:"avatar.kill-request",description:"The player deletes one of their avatars for good.",direction:"toServer",command:"ak",read:e=>({perUserAvId:e.int("perUserAvId")}),write:(e,{perUserAvId:t})=>e.int(t)});u({name:"avatar.killed",description:"The server says whether an avatar was deleted for good.",direction:"toClient",command:"ak",read:e=>({success:e.flag("success"),extra:e.int("extra")}),write:(e,{success:t,extra:n})=>e.flag(t).int(n)});u({name:"avatar.left",description:"An avatar leaves the room.",direction:"toClient",command:"ar",read:e=>{const t=e.int("userId");if(e.remaining===0)return{userId:t,walkOut:0,walkTo:null,extra:[]};const n=e.int("walkOut"),r=n>0?{x:e.int("x"),y:e.int("y")}:null;return{userId:t,walkOut:n,walkTo:r,extra:e.rest()}},write:(e,{userId:t,walkOut:n,walkTo:r,extra:i})=>{e.int(t),!(n===0&&!r&&i.length===0)&&(e.int(n),n>0&&r&&e.int(r.x).int(r.y),e.raw(i))}});u({name:"buddy.list-request",description:"The player asks for their buddy and blocked lists.",direction:"toServer",command:"bl",read:()=>({}),write:()=>{}});u({name:"buddy.list",description:"The server sends the buddy list or the blocked list.",direction:"toClient",command:"bl",read:e=>{if(e.string("list")!=="0"){const r=e.int("blocked");return{blocked:!0,buddies:[],blockedUserNames:e.repeat(r,()=>e.string("userName"))}}const t=e.repeat(e.int("online"),()=>$t(e,!0)),n=e.repeat(e.int("offline"),()=>$t(e,!1));return{blocked:!1,buddies:[...t,...n],blockedUserNames:[]}},write:(e,{blocked:t,buddies:n,blockedUserNames:r})=>{if(t){e.string("1").int(r.length),r.forEach(s=>e.string(s));return}const i=n.filter(s=>s.online),a=n.filter(s=>!s.online);e.string("0").int(i.length),i.forEach(s=>Ft(e,s,!0)),e.int(a.length),a.forEach(s=>Ft(e,s,!1))}});u({name:"buddy.add-request",description:"The player asks someone to be their buddy.",direction:"toServer",command:"ba",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"buddy.add-result",description:"Someone asks to be a buddy, or the server answers the player’s request.",direction:"toClient",command:"ba",read:e=>({status:e.int("status"),userName:e.string("userName"),userNameModerationFlag:e.int("userNameModerationFlag")}),write:(e,{status:t,userName:n,userNameModerationFlag:r})=>e.int(t).string(n).int(r)});u({name:"buddy.confirm",description:"The player accepts or declines a buddy request.",direction:"toServer",command:"bc",read:e=>({userName:e.string("userName"),accept:e.flag("accept")}),write:(e,{userName:t,accept:n})=>e.string(t).flag(n)});u({name:"buddy.status",description:"A buddy comes online or goes offline, is added, or is renamed.",direction:"toClient",command:"bs",read:e=>{const t=e.string("withAvatar")==="1",n={userName:e.string("userName"),uuid:e.string("uuid"),userNameModerationFlag:e.int("userNameModerationFlag"),online:e.string("online")==="1",accountType:e.int("accountType"),change:e.int("change")};return t?{withAvatar:t,...n,newUserName:null,avatarName:e.string("avatarName"),perUserAvatarId:e.int("perUserAvatarId"),partyTimeLeft:e.int("partyTimeLeft")}:{withAvatar:t,...n,newUserName:e.string("newUserName"),avatarName:null,perUserAvatarId:null,partyTimeLeft:null}},write:(e,t)=>{e.flag(t.withAvatar).string(t.userName).string(t.uuid).int(t.userNameModerationFlag).flag(t.online).int(t.accountType).int(t.change),t.withAvatar?e.string(t.avatarName??"").int(t.perUserAvatarId??-1).int(t.partyTimeLeft??-1):e.string(t.newUserName??"")}});u({name:"buddy.remove-request",description:"The player removes a buddy.",direction:"toServer",command:"bd",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"buddy.removed",description:"A buddy is no longer a buddy.",direction:"toClient",command:"bd",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"buddy.location-request",description:"The player asks where a buddy is.",direction:"toServer",command:"br",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"buddy.location",description:"The server says where a buddy is.",direction:"toClient",command:"br",read:e=>({roomName:e.string("roomName"),displayName:e.string("displayName"),displayNameId:e.int("displayNameId"),locked:e.string("locked")==="1"}),write:(e,{roomName:t,displayName:n,displayNameId:r,locked:i})=>e.string(t).string(n).int(r).flag(i)});u({name:"buddy.block-request",description:"The player blocks someone.",direction:"toServer",command:"bb",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"buddy.block-result",description:"The server says whether someone was blocked.",direction:"toClient",command:"bb",read:e=>({userName:e.string("userName"),success:e.string("success")==="1"}),write:(e,{userName:t,success:n})=>e.string(t).flag(n)});u({name:"buddy.unblock-request",description:"The player unblocks someone.",direction:"toServer",command:"bu",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"buddy.unblock-result",description:"The server says whether someone was unblocked.",direction:"toClient",command:"bu",read:e=>({userName:e.string("userName"),success:e.string("success")==="1"}),write:(e,{userName:t,success:n})=>e.string(t).flag(n)});u({name:"buddy.block-info-request",description:"The player asks whether someone is blocking them.",direction:"toServer",command:"bi",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"buddy.block-info",description:"The server says whether someone is blocking the player.",direction:"toClient",command:"bi",read:e=>({userName:e.string("userName"),blockingPlayer:e.string("blockingPlayer")==="1"}),write:(e,{userName:t,blockingPlayer:n})=>e.string(t).flag(n)});function $t(e,t){return{userName:e.string("userName"),uuid:e.string("uuid"),userNameModerationFlag:e.int("userNameModerationFlag"),online:t,accountType:e.int("accountType"),partyTimeLeft:t?e.int("partyTimeLeft"):null}}function Ft(e,t,n){e.string(t.userName).string(t.uuid).int(t.userNameModerationFlag).int(t.accountType),n&&e.int(t.partyTimeLeft??-1)}const ze={free:0,safeChat:1,emote:2,action:3,attachmentEmote:4,permanentEmote:5,slide:6,petAction:7,blendColor:8,freeSafeChat:9,alpha:10,customAdventure:11,customPvp:12};ye({name:"chat.public",description:"The player says something in the room.",direction:"toServer",type:"sys",command:"pubMsg",read:e=>{var t,n;const r=lt(((n=(t=e.body)==null?void 0:t.child("txt"))==null?void 0:n.textContent)??""),i=r.lastIndexOf("%");if(i===-1)throw new x("chat.public: the text has no kind after it","PACKET_FIELD");const a=Number(r.slice(i+1));if(!Number.isInteger(a))throw new x("chat.public: the kind is not an integer","PACKET_FIELD");return{text:r.slice(0,i),kind:a}},write:({text:e,kind:t})=>[new _("txt",{children:[new te(ui(`${e}%${t}`))]})]});u({name:"chat.room",description:"Someone in the room said something.",direction:"toClient",command:"uc",read:e=>({userId:e.int("userId"),text:e.string("text"),kind:e.int("kind"),level:e.remaining>0?e.int("level"):null,extra:e.rest()}),write:(e,{userId:t,text:n,kind:r,level:i,extra:a})=>{e.int(t).string(n).int(r),i!==null&&e.int(i),e.raw(a)}});u({name:"chat.moderation",description:"A moderator bans, silences, kicks, warns or messages the player.",direction:"toClient",command:"fd",read:e=>({action:e.string("action"),extra:e.rest()}),write:(e,{action:t,extra:n})=>e.string(t).raw(n)});u({name:"facilitator.invis-mode",description:"The server confirms the player's ghost mode.",direction:"toClient",command:"fi",read:e=>({invisible:e.flag("invisible")}),write:(e,{invisible:t})=>e.flag(t)});u({name:"facilitator.report-request",description:"The player reports someone.",direction:"toServer",command:"fr",read:e=>({userName:e.string("userName"),reasonId:e.int("reasonId")}),write:(e,{userName:t,reasonId:n})=>e.string(t).int(n)});u({name:"facilitator.report-result",description:"The server confirms a report.",direction:"toClient",command:"fr",read:e=>({success:e.flag("success")}),write:(e,{success:t})=>e.flag(t)});u({name:"facilitator.report-with-data-request",description:"The player reports someone over something specific they sent.",direction:"toServer",command:"fra",read:e=>({userName:e.string("userName"),reasonId:e.int("reasonId"),dataType:e.int("dataType"),data:e.string("data")}),write:(e,{userName:t,reasonId:n,dataType:r,data:i})=>e.string(t).int(n).int(r).string(i)});u({name:"facilitator.report-with-data-result",description:"The server confirms a report with content attached.",direction:"toClient",command:"fra",read:e=>({success:e.flag("success")}),write:(e,{success:t})=>e.flag(t)});function ui(e){let t="";for(const n of e)t+=di[n]??n;return t}const di={"&":"&","<":"<",">":">","'":"'",'"':"""},Ut=100;u({name:"currency.update",description:"One or more of the player’s balances changed.",direction:"toClient",command:"cu",read:e=>{const t=e.int("currency"),n=t===Ut?hi(e.string("balances")):[{currency:t,amount:e.int("amount")}],r=e.remaining>0?e.int("reason"):null;return{currency:t,balances:n,reason:r,extra:e.rest()}},write:(e,{currency:t,balances:n,reason:r,extra:i})=>{var a;e.int(t),t===Ut?e.string(n.map(({currency:s,amount:o})=>`${s}x${o}`).join(",")):e.int(((a=n[0])==null?void 0:a.amount)??0),r!==null&&e.int(r),e.raw(i)}});function hi(e){return e===""?[]:e.split(",").map(t=>{const n=t.split("x"),[r="",i=""]=n,a=Number(r),s=Number(i),o=r.trim()===""||i.trim()==="";if(n.length!==2||o||!Number.isInteger(a)||!Number.isInteger(s))throw new x(`currency.update: field "balances" has "${t}", not <currency>x<amount>`,"PACKET_FIELD");return{currency:a,amount:s}})}u({name:"currency.donate",description:"The player donates gems.",direction:"toServer",command:"cd",read:e=>({amount:e.int("amount")}),write:(e,{amount:t})=>e.int(t)});u({name:"currency.donate-result",description:"The server says whether the donation went through.",direction:"toClient",command:"cd",read:e=>({success:e.string("result")==="1",extra:e.rest()}),write:(e,{success:t,extra:n})=>e.string(t?"1":"0").raw(n)});u({name:"currency.exchange",description:"The player exchanges one currency for another at a shop.",direction:"toServer",command:"ce",read:e=>({shopId:e.int("shopId"),exchangeDefId:e.int("exchangeDefId")}),write:(e,{shopId:t,exchangeDefId:n})=>e.int(t).int(n)});u({name:"currency.exchange-result",description:"The server says whether the exchange went through.",direction:"toClient",command:"ce",read:e=>({success:e.string("result")==="1",balance:e.remaining>0?e.string("balance"):"",extra:e.rest()}),write:(e,{success:t,balance:n,extra:r})=>e.string(t?"1":"0").string(n).raw(r)});u({name:"currency.redeem-code",description:"The player redeems a code.",direction:"toServer",command:"grc",read:e=>({code:e.string("code"),captchaQuestion:e.string("captchaQuestion"),captchaAnswer:e.string("captchaAnswer")}),write:(e,{code:t,captchaQuestion:n,captchaAnswer:r})=>e.string(t).string(n).string(r)});u({name:"currency.redeem-code-result",description:"The server says what a redeemed code came to.",direction:"toClient",command:"grc",read:e=>{const t=e.string("result"),n=e.remaining>0?e.string("details"):"",r=e.remaining>0?e.string("hasGiftsElsewhere")==="1":!1;return{result:t,details:mi(n),hasGiftsElsewhere:r,extra:e.rest()}},write:(e,{result:t,details:n,hasGiftsElsewhere:r,extra:i})=>e.string(t).string(n===null?"":JSON.stringify(n)).string(r?"1":"0").raw(i)});function mi(e){if(e==="")return null;try{return JSON.parse(e)}catch{throw new x(`currency.redeem-code-result: field "details" is not JSON ("${e}")`,"PACKET_FIELD")}}u({name:"currency.membership-redeemed",description:"A membership was redeemed on the account.",direction:"toClient",command:"grm",read:e=>{const t=e.int("result");return t!==1?{result:t,accountType:null,daysLeft:null,sourceType:null,extra:e.rest()}:{result:t,accountType:e.int("accountType"),daysLeft:e.int("daysLeft"),sourceType:e.string("sourceType"),extra:e.rest()}},write:(e,{result:t,accountType:n,daysLeft:r,sourceType:i,extra:a})=>{e.int(t),t===1&&e.int(n??0).int(r??0).string(i??""),e.raw(a)}});u({name:"den.join-request",description:"The player asks to join a den.",direction:"toServer",command:"dj",read:e=>({denName:e.string("denName"),confirmLanguageChange:e.flag("confirmLanguageChange"),doorItem:e.int("doorItem")}),write:(e,{denName:t,confirmLanguageChange:n,doorItem:r})=>e.string(t).flag(n).int(r)});u({name:"den.privacy-request",description:"The player sets their den’s privacy, or asks for someone else’s.",direction:"toServer",command:"dp",read:e=>({query:e.flag("lookup")?{request:"lookup",userName:e.string("userName")}:{request:"set",privacy:e.int("privacy")}}),write:(e,{query:t})=>{t.request==="lookup"?e.flag(!0).string(t.userName):e.flag(!1).int(t.privacy)}});u({name:"den.privacy-result",description:"The server says who may come into someone’s den.",direction:"toClient",command:"dp",read:e=>({userName:e.string("userName"),privacy:e.int("privacy")}),write:(e,{userName:t,privacy:n})=>e.string(t).int(n)});u({name:"den.kicked",description:"The player was sent out of a den its owner locked.",direction:"toClient",command:"dpk",read:()=>({}),write:()=>{}});u({name:"den.visitor-count",description:"The server says how many are in a den.",direction:"toClient",command:"drc",read:e=>({count:e.int("count"),countsOwner:e.flag("countsOwner"),ownerName:e.string("ownerName")}),write:(e,{count:t,countsOwner:n,ownerName:r})=>e.int(t).flag(n).string(r)});u({name:"den.room-list-request",description:"The player asks for their den rooms.",direction:"toServer",command:"dl",read:()=>({}),write:()=>{}});u({name:"den.room-list",description:"The server lists the player’s den rooms.",direction:"toClient",command:"dl",read:e=>({rooms:e.repeat(e.int("count"),()=>({invIdx:e.int("invIdx"),defId:e.int("defId")}))}),write:(e,{rooms:t})=>e.int(t.length).each(t,({invIdx:n,defId:r})=>e.int(n).int(r))});u({name:"den.change-request",description:"The player switches to another of their den rooms.",direction:"toServer",command:"dc",read:e=>({invIdx:e.int("invIdx")}),write:(e,{invIdx:t})=>e.int(t)});u({name:"den.change-result",description:"The server says which den room the player switched to.",direction:"toClient",command:"dc",read:e=>{const t=e.int("denRoomDefId"),n=e.remaining>=2;return{denRoomDefId:t,perUserAvId:n?e.int("perUserAvId"):null,activePetInvId:n?e.int("activePetInvId"):null,extra:e.rest()}},write:(e,{denRoomDefId:t,perUserAvId:n,activePetInvId:r,extra:i})=>{e.int(t),n!==null&&r!==null&&e.int(n).int(r),e.raw(i)}});u({name:"den.masterpiece-items-request",description:"The player asks for every masterpiece placed in someone’s den.",direction:"toServer",command:"dmi",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"den.masterpiece-items",description:"The server lists every masterpiece placed in a den.",direction:"toClient",command:"dmi",read:e=>({items:e.repeat(e.int("count"),()=>({defId:e.int("defId"),invIdx:e.int("invIdx"),version:e.int("version"),approved:e.string("approved")!=="",uniqueImageId:e.string("uniqueImageId"),uniqueImageCreatorDbId:e.int("uniqueImageCreatorDbId"),uniqueImageCreatorUUID:e.string("uniqueImageCreatorUUID")}))}),write:(e,{items:t})=>e.int(t.length).each(t,n=>e.int(n.defId).int(n.invIdx).int(n.version).string(n.approved?"1":"").string(n.uniqueImageId).int(n.uniqueImageCreatorDbId).string(n.uniqueImageCreatorUUID))});u({name:"den.masterpiece-creator-request",description:"The player asks who drew a masterpiece.",direction:"toServer",command:"dmc",read:e=>({denUserName:e.string("denUserName"),uniqueImageId:e.string("uniqueImageId")}),write:(e,{denUserName:t,uniqueImageId:n})=>e.string(t).string(n)});u({name:"den.masterpiece-creator",description:"The server names who drew a masterpiece.",direction:"toClient",command:"dmc",read:e=>({creatorName:e.string("creatorName")}),write:(e,{creatorName:t})=>e.string(t)});u({name:"ecard.list-request",description:"The player asks for their jam-a-grams.",direction:"toServer",command:"el",read:e=>({interactive:e.flag("interactive")}),write:(e,{interactive:t})=>e.flag(t)});u({name:"ecard.list",description:"The server sends the player’s jam-a-grams.",direction:"toClient",command:"el",read:e=>{const t=e.int("count");return{cards:e.repeat(Math.max(t,0),()=>Nn(e))}},write:(e,{cards:t})=>{e.int(t.length),t.forEach(n=>Cn(e,n))}});u({name:"ecard.received",description:"The player receives a jam-a-gram.",direction:"toClient",command:"ep",read:e=>({card:Nn(e)}),write:(e,{card:t})=>Cn(e,t)});u({name:"ecard.send",description:"The player sends a jam-a-gram.",direction:"toServer",command:"es",read:e=>({userName:e.string("userName"),cardMediaId:e.int("cardMediaId"),stampMediaId:e.int("stampMediaId"),messageType:e.int("messageType"),message:e.string("message"),type:e.int("type"),giftInvIdx:e.int("giftInvIdx"),specialType:e.int("specialType")}),write:(e,t)=>e.string(t.userName).int(t.cardMediaId).int(t.stampMediaId).int(t.messageType).string(t.message).int(t.type).int(t.giftInvIdx).int(t.specialType)});u({name:"ecard.send-result",description:"The server says whether a jam-a-gram was sent.",direction:"toClient",command:"es",read:e=>({result:e.int("result")}),write:(e,{result:t})=>e.int(t)});u({name:"ecard.read",description:"The player opens a jam-a-gram.",direction:"toServer",command:"er",read:e=>({messageId:e.int("messageId")}),write:(e,{messageId:t})=>e.int(t)});u({name:"ecard.read-result",description:"The server says whether a jam-a-gram was marked read.",direction:"toClient",command:"er",read:e=>({messageId:e.int("messageId"),success:e.string("success")==="1"}),write:(e,{messageId:t,success:n})=>e.int(t).flag(n)});u({name:"ecard.delete",description:"The player deletes a jam-a-gram.",direction:"toServer",command:"ed",read:e=>({messageId:e.int("messageId")}),write:(e,{messageId:t})=>e.int(t)});u({name:"ecard.delete-result",description:"The server says which jam-a-grams were deleted.",direction:"toClient",command:"ed",read:e=>({success:e.string("success")==="1",messageIds:e.repeat(e.int("count"),()=>e.int("messageId"))}),write:(e,{success:t,messageIds:n})=>{e.flag(t).int(n.length),n.forEach(r=>e.int(r))}});u({name:"ecard.gift",description:"The player accepts or discards a jam-a-gram’s gift.",direction:"toServer",command:"eg",read:e=>({messageId:e.int("messageId"),accept:e.flag("accept"),option:e.remaining>0?e.int("option"):null}),write:(e,{messageId:t,accept:n,option:r})=>{e.int(t).flag(n),r!==null&&e.int(r)}});u({name:"ecard.gift-result",description:"The server says whether a jam-a-gram’s gift was accepted or discarded.",direction:"toClient",command:"eg",read:e=>({messageId:e.int("messageId"),success:e.string("success")==="1"}),write:(e,{messageId:t,success:n})=>e.int(t).flag(n)});u({name:"ecard.update",description:"The server changes a jam-a-gram’s message.",direction:"toClient",command:"eu",read:e=>({messageId:e.int("messageId"),message:e.string("message")}),write:(e,{messageId:t,message:n})=>e.int(t).string(n)});u({name:"ecard.privacy",description:"The player changes who may send them jam-a-grams.",direction:"toServer",command:"ei",read:e=>({setting:e.int("setting")}),write:(e,{setting:t})=>e.int(t)});u({name:"ecard.privacy-result",description:"The server says whether the jam-a-gram privacy setting changed.",direction:"toClient",command:"ei",read:e=>({success:e.string("success")==="1"}),write:(e,{success:t})=>e.flag(t)});function Nn(e){return{messageId:e.int("messageId"),senderUserName:e.string("senderUserName"),cardMediaId:e.int("cardMediaId"),stampMediaId:e.int("stampMediaId"),read:e.string("read")==="1",message:e.string("message"),type:e.int("type"),giftId:e.int("giftId"),giftColor:e.int("giftColor"),giftName:e.string("giftName"),senderAccountType:e.int("senderAccountType"),senderNameBarData:e.int("senderNameBarData"),secondaryType:e.int("secondaryType"),senderType:e.int("senderType"),userNameModerationFlag:e.int("userNameModerationFlag"),additionalGiftData:e.string("additionalGiftData"),specialType:e.int("specialType")}}function Cn(e,t){e.int(t.messageId).string(t.senderUserName).int(t.cardMediaId).int(t.stampMediaId).flag(t.read).string(t.message).int(t.type).int(t.giftId).int(t.giftColor).string(t.giftName).int(t.senderAccountType).int(t.senderNameBarData).int(t.secondaryType).int(t.senderType).int(t.userNameModerationFlag).string(t.additionalGiftData).int(t.specialType)}u({name:"item.list-request",description:"The client asks for an avatar’s items.",direction:"toServer",command:"il",read:e=>({userName:e.string("userName"),perUserAvId:e.int("perUserAvId"),full:e.flag("full")}),write:(e,{userName:t,perUserAvId:n,full:r})=>e.string(t).int(n).flag(r)});u({name:"item.list",description:"The server lists or changes an avatar’s items.",direction:"toClient",command:"il",read:e=>{const t=e.string("type");if(t==="-1")return{kind:"failed",extra:e.rest()};if(t==="0"||t==="1"){const h={unused:e.string("unused"),perUserAvId:e.int("perUserAvId"),userName:e.string("userName"),eyesDefId:e.int("eyesDefId"),patternDefId:e.int("patternDefId")},m=e.int("count"),p=m>0&&e.remaining===m*5,f=e.repeat(m,()=>gi(e,p));return{kind:t==="0"?"inventory":"worn",...h,items:f}}const n=t==="3",r=e.string("wear")==="1",i=e.int("perUserAvId"),a=e.string("userName"),s=e.int("color")>>>0,o=e.int("added"),l=e.int("removed"),c=e.repeat(o,()=>({invId:e.int("invId"),defId:e.int("defId")})),d=e.repeat(l,()=>e.int("invId"));return{kind:"changed",wornOnly:n,wear:r,perUserAvId:i,userName:a,color:s,added:c,removed:d}},write:(e,t)=>{if(t.kind==="failed"){e.string("-1").raw(t.extra);return}if(t.kind==="changed"){e.string(t.wornOnly?"3":"2").string(t.wear?"1":"0").int(t.perUserAvId).string(t.userName).int(t.color>>>0).int(t.added.length).int(t.removed.length).each(t.added,({invId:n,defId:r})=>e.int(n).int(r)).each(t.removed,n=>e.int(n));return}e.string(t.kind==="inventory"?"0":"1").string(t.unused).int(t.perUserAvId).string(t.userName).int(t.eyesDefId).int(t.patternDefId).int(t.items.length).each(t.items,n=>{e.int(n.defId).int(n.invId).int(n.color>>>0),n.equippedAvatars!==null&&e.string(n.equippedAvatars).int(n.denStoreInvId??0)})}});function gi(e,t){const n=e.int("defId"),r=e.int("invId"),i=e.int("color")>>>0;return t?{defId:n,invId:r,color:i,equippedAvatars:e.string("equippedAvatars"),denStoreInvId:e.int("denStoreInvId")}:{defId:n,invId:r,color:i,equippedAvatars:null,denStoreInvId:null}}u({name:"item.use",description:"The player puts items on and takes items off.",direction:"toServer",command:"iu",read:e=>{const t=e.int("wearCount"),n=e.int("removeCount");return{wear:e.repeat(t,()=>e.int("invId")),remove:e.repeat(n,()=>e.int("invId"))}},write:(e,{wear:t,remove:n})=>e.int(t.length).int(n.length).each(t,r=>e.int(r)).each(n,r=>e.int(r))});u({name:"item.use-result",description:"The server says whether the player’s items changed.",direction:"toClient",command:"iu",read:e=>({success:e.string("success")==="1",extra:e.rest()}),write:(e,{success:t,extra:n})=>e.string(t?"1":"0").raw(n)});u({name:"item.buy",description:"The player buys an item.",direction:"toServer",command:"ib",read:e=>({shopId:e.int("shopId"),quantity:e.int("quantity"),defId:e.int("defId"),colorIndex:e.int("colorIndex"),diamond:e.flag("diamond"),targetInvId:e.int("targetInvId"),targetUserName:e.string("targetUserName")}),write:(e,t)=>e.int(t.shopId).int(t.quantity).int(t.defId).int(t.colorIndex).flag(t.diamond).int(t.targetInvId).string(t.targetUserName)});u({name:"item.buy-result",description:"The server says whether an item was bought.",direction:"toClient",command:"ib",read:e=>{const t=e.int("status"),n=e.int("shopId"),r=e.string("balance"),i=r===""?null:Number(r);return{status:t,shopId:n,balance:i,currencyType:e.int("currencyType"),extra:e.rest()}},write:(e,{status:t,shopId:n,balance:r,currencyType:i,extra:a})=>e.int(t).int(n).string(r===null?"":String(r)).int(i).raw(a)});u({name:"item.recycle",description:"The player recycles items.",direction:"toServer",command:"ir",read:e=>({invIds:e.repeat(e.remaining,()=>e.int("invId"))}),write:(e,{invIds:t})=>e.each(t,n=>e.int(n))});u({name:"item.recycle-result",description:"The server says which items were recycled.",direction:"toClient",command:"ir",read:e=>{const t=e.int("count");return{gems:e.int("gems"),invIds:e.repeat(t,()=>e.int("invId"))}},write:(e,{gems:t,invIds:n})=>e.int(n.length).int(t).each(n,r=>e.int(r))});u({name:"item.diamond-bundle-buy",description:"The player buys the bundle shop’s whole bundle for diamonds.",direction:"toServer",command:"id",read:e=>({shopId:e.int("shopId")}),write:(e,{shopId:t})=>e.int(t)});u({name:"item.diamond-bundle-buy-result",description:"The server says whether the bundle shop’s whole bundle was bought.",direction:"toClient",command:"id",read:e=>({bought:e.string("bought")==="true",balance:e.remaining>0?e.int("balance"):null,extra:e.rest()}),write:(e,{bought:t,balance:n,extra:r})=>{e.string(t?"true":"false"),n!==null&&e.int(n),e.raw(r)}});const pi=["hc","pf","mo","as","ul"];u({name:"minigame.info-request",description:"The client asks the server to describe minigames.",direction:"toServer",command:"mi",read:e=>({gameDefIds:e.repeat(e.remaining,()=>e.int("gameDefId"))}),write:(e,{gameDefIds:t})=>e.each(t,n=>e.int(n))});u({name:"minigame.join",description:"The player asks to play a minigame.",direction:"toServer",command:"mj",read:e=>({gameDefId:e.int("gameDefId"),multiplayer:e.flag("multiplayer"),proModeId:e.int("proModeId"),hostUserId:e.int("hostUserId")}),write:(e,{gameDefId:t,multiplayer:n,proModeId:r,hostUserId:i})=>e.int(t).flag(n).int(r).int(i)});u({name:"minigame.start-request",description:"The player starts a waiting minigame now.",direction:"toServer",command:"ms",read:e=>({gameDefId:e.int("gameDefId")}),write:(e,{gameDefId:t})=>e.int(t)});u({name:"minigame.leave",description:"The player leaves an in-room minigame.",direction:"toServer",command:"ml",read:()=>({}),write:()=>{}});u({name:"minigame.send",description:"A minigame sends its own message to the server.",direction:"toServer",command:"mm",read:e=>({gameDefId:e.int("gameDefId"),data:e.rest()}),write:(e,{gameDefId:t,data:n})=>e.int(t).raw(n)});u({name:"minigame.pvp",description:"The player challenges, accepts, or turns down a two player game.",direction:"toServer",command:"mp",read:e=>({gameDefId:e.int("gameDefId"),action:e.int("action"),userName:e.remaining>0?e.string("userName"):""}),write:(e,{gameDefId:t,action:n,userName:r})=>{e.int(t).int(n),r!==""&&e.string(r)}});u({name:"minigame.custom-pvp-join",description:"The player joins a two player game another player set up.",direction:"toServer",command:"mcp",read:e=>({gameDefId:e.int("gameDefId"),action:e.int("action"),userName:e.string("userName")}),write:(e,{gameDefId:t,action:n,userName:r})=>e.int(t).int(n).string(r)});u({name:"minigame.leaderboard-request",description:"The client asks for a minigame’s leaderboard.",direction:"toServer",command:"mlb",read:e=>({gameDefId:e.int("gameDefId")}),write:(e,{gameDefId:t})=>e.int(t)});u({name:"minigame.info",description:"The server describes minigames.",direction:"toClient",command:"mi",read:e=>({games:e.repeat(e.int("count"),()=>({gameDefId:e.int("gameDefId"),titleStrId:e.int("titleStrId"),extName:e.string("extName"),swfName:e.string("swfName"),minPlayers:e.int("minPlayers"),maxPlayers:e.int("maxPlayers"),maxSpectators:e.int("maxSpectators"),type:e.int("type"),gameCardMediaId:e.int("gameCardMediaId"),gameCountUserVarRef:e.int("gameCountUserVarRef"),custom1UserVarRef:e.int("custom1UserVarRef"),custom2UserVarRef:e.int("custom2UserVarRef"),readyForPvp:e.flag("readyForPvp"),gemMultiplier:e.number("gemMultiplier"),petDefId:e.int("petDefId"),proModeUserVarRefId:e.int("proModeUserVarRefId"),leaderboardUserVarRef:e.int("leaderboardUserVarRef"),gameLibraryIconMediaId:e.int("gameLibraryIconMediaId"),requiredAvatarType:e.int("requiredAvatarType")}))}),write:(e,{games:t})=>e.int(t.length).each(t,n=>e.int(n.gameDefId).int(n.titleStrId).string(n.extName).string(n.swfName).int(n.minPlayers).int(n.maxPlayers).int(n.maxSpectators).int(n.type).int(n.gameCardMediaId).int(n.gameCountUserVarRef).int(n.custom1UserVarRef).int(n.custom2UserVarRef).flag(n.readyForPvp).number(n.gemMultiplier).int(n.petDefId).int(n.proModeUserVarRefId).int(n.leaderboardUserVarRef).int(n.gameLibraryIconMediaId).int(n.requiredAvatarType))});u({name:"minigame.join-result",description:"The server seats the player in a minigame, or says why not.",direction:"toClient",command:"mj",read:e=>{if(e.remaining===0)return{joined:!0,refusal:null,waitingUserIds:[],detail:[]};const t=e.string("result"),n=pi.find(a=>a===t);if(n)return{joined:!1,refusal:n,waitingUserIds:[],detail:e.rest()};const r=new fe([t],"minigame.join-result").int("userId"),i=e.repeat(e.remaining,()=>e.int("userId"));return{joined:!0,refusal:null,waitingUserIds:[r,...i],detail:[]}},write:(e,t)=>{t.joined?e.each(t.waitingUserIds,n=>e.int(n)):e.string(t.refusal).raw(t.detail)}});u({name:"minigame.started",description:"The minigame starts, with its players.",direction:"toClient",command:"ms",read:e=>({playerIds:e.repeat(e.int("playerCount"),()=>e.int("userId")),data:e.rest()}),write:(e,{playerIds:t,data:n})=>e.int(t.length).each(t,r=>e.int(r)).raw(n)});function Le(e,t,n){return u({name:e,description:n,direction:"toClient",command:t,read:r=>({data:r.rest()}),write:(r,{data:i})=>r.raw(i)})}Le("minigame.message","mm","A minigame’s own message from the server.");Le("minigame.left","ml","A player left the minigame.");Le("minigame.ended","me","The minigame ended.");Le("minigame.room-removed","mr","The minigame’s room was removed.");u({name:"minigame.pvp-invite",description:"A player challenges the player to a two player game, or turns them down.",direction:"toClient",command:"mp",read:e=>{const t=e.int("gameDefId"),n=e.int("action");return n!==0?{gameDefId:t,action:n,userName:"",nameVisible:!1,extra:e.rest()}:{gameDefId:t,action:n,userName:e.string("userName"),nameVisible:e.int("nameVisible")>0,extra:e.rest()}},write:(e,{gameDefId:t,action:n,userName:r,nameVisible:i,extra:a})=>{e.int(t).int(n),n===0&&e.string(r).int(i?1:0),e.raw(a)}});u({name:"minigame.leaderboard",description:"The server gives a minigame’s leaderboard.",direction:"toClient",command:"mlb",read:e=>{const t=e.int("gameDefId");if(t===-1)return{gameDefId:t,allTime:[],thisWeek:[],buddies:[]};const n=()=>e.repeat(e.int("count"),()=>({name:e.string("name"),score:e.number("score")})),r=n(),i=n(),a=n();return{gameDefId:t,allTime:r,thisWeek:i,buddies:a}},write:(e,{gameDefId:t,allTime:n,thisWeek:r,buddies:i})=>{if(e.int(t),t!==-1)for(const a of[n,r,i])e.int(a.length).each(a,({name:s,score:o})=>e.string(s).number(o))}});u({name:"party.list-request",description:"The player asks which parties are on.",direction:"toServer",command:"sl",read:()=>({}),write:()=>{}});u({name:"party.list",description:"The server lists Animal Jam’s parties.",direction:"toClient",command:"sl",read:e=>({unread:e.string("unread"),parties:e.repeat(e.int("count"),()=>({defId:e.int("defId"),secondsToStart:e.number("secondsToStart"),secondsToEnd:e.number("secondsToEnd")}))}),write:(e,{unread:t,parties:n})=>e.string(t).int(n.length).each(n,r=>e.int(r.defId).number(r.secondsToStart).number(r.secondsToEnd))});u({name:"party.join-request",description:"The player asks to join a party.",direction:"toServer",command:"sj",read:e=>({defId:e.int("defId")}),write:(e,{defId:t})=>e.int(t)});u({name:"party.join-result",description:"The server says a party could not be joined.",direction:"toClient",command:"sj",read:e=>{const t=e.flag("joined"),n=!t&&e.remaining>0?e.string("reason"):null;return{joined:t,reason:n,extra:e.rest()}},write:(e,{joined:t,reason:n,extra:r})=>{e.flag(t),n!==null&&e.string(n),e.raw(r)}});u({name:"party.custom-list-request",description:"The player asks which parties players are hosting.",direction:"toServer",command:"slp",read:e=>({start:e.int("start"),limit:e.int("limit")}),write:(e,{start:t,limit:n})=>e.int(t).int(n)});u({name:"party.custom-list",description:"The server lists the parties players are hosting.",direction:"toClient",command:"slp",read:e=>{const t=e.flag("unread"),n=e.int("total");if(n<=0)return{unread:t,total:n,skipped:null,parties:[]};const r=[e.int("skipped1"),e.int("skipped2")],i=e.repeat(e.int("count"),()=>({creatorUuid:e.string("creatorUuid"),name:e.string("name"),node:e.string("node"),defId:e.int("defId"),timeLeft:e.number("timeLeft")}));return{unread:t,total:n,skipped:r,parties:i}},write:(e,{unread:t,total:n,skipped:r,parties:i})=>{e.flag(t).int(n),!(n<=0)&&e.int((r==null?void 0:r[0])??0).int((r==null?void 0:r[1])??0).int(i.length).each(i,a=>e.string(a.creatorUuid).string(a.name).string(a.node).int(a.defId).number(a.timeLeft))}});u({name:"party.custom-join-request",description:"The player asks to join a party a player hosts.",direction:"toServer",command:"sjp",read:e=>({creatorUuid:e.string("creatorUuid")}),write:(e,{creatorUuid:t})=>e.string(t)});u({name:"party.custom-join-result",description:"The server says whether a hosted party could be joined.",direction:"toClient",command:"sjp",read:e=>{const t=e.string("joined")==="1",n=!t&&e.remaining>0?e.string("reason"):null;return{joined:t,reason:n,extra:e.rest()}},write:(e,{joined:t,reason:n,extra:r})=>{e.string(t?"1":"0"),n!==null&&e.string(n),e.raw(r)}});u({name:"party.custom-node-request",description:"The player asks which server a hosted party is on.",direction:"toServer",command:"spn",read:e=>({creatorUuid:e.string("creatorUuid")}),write:(e,{creatorUuid:t})=>e.string(t)});u({name:"party.custom-host-result",description:"The server says whether the player may host a party.",direction:"toClient",command:"scp",read:e=>{const t=e.flag("hosting"),n={hosting:t,secondsLeft:null,reason:null};if(!t)return{...n,reason:e.string("reason")};const r=e.flag("stillHosting");return{...n,secondsLeft:r?e.int("secondsLeft"):null}},write:(e,{hosting:t,secondsLeft:n,reason:r})=>{if(e.flag(t),!t){e.string(r??"");return}e.flag(n!==null),n!==null&&e.int(n)}});u({name:"party.custom-killed",description:"The server ends the player’s hosted party from outside the client.",direction:"toClient",command:"spk",read:e=>({diamondsRefunded:e.int("diamondsRefunded")}),write:(e,{diamondsRefunded:t})=>e.int(t)});u({name:"party.custom-node",description:"The server says which server a hosted party is on.",direction:"toClient",command:"spn",read:e=>{const t=e.string("found")==="1",n=t?{creatorUuid:e.string("creatorUuid"),node:e.string("node")}:null;return{found:t,party:n,extra:e.rest()}},write:(e,{found:t,party:n,extra:r})=>{e.string(t?"1":"0"),t&&n&&e.string(n.creatorUuid).string(n.node),e.raw(r)}});u({name:"newspaper.page-seen-request",description:"The player marks a newspaper page seen.",direction:"toServer",command:"nps",read:e=>({defId:e.int("defId")}),write:(e,{defId:t})=>e.int(t)});u({name:"newspaper.page-seen",description:"The server confirms a newspaper page was marked seen.",direction:"toClient",command:"nps",read:e=>({defId:e.int("defId"),timeSeen:e.int("timeSeen")}),write:(e,{defId:t,timeSeen:n})=>e.int(t).int(n)});const ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function fi(e){const t=e.replace(/[\s=]/g,""),n=new Uint8Array(Math.floor(t.length*3/4));let r=0,i=0,a=0;for(const s of t){const o=ce.indexOf(s);if(o===-1)throw new x(`"${s}" is not a Base64 character`,"PACKET_FIELD");r=r<<6|o,i+=6,i>=8&&(i-=8,n[a++]=r>>i&255)}return n.subarray(0,a)}function yi(e){let t="";for(let n=0;n<e.length;n+=3){const r=e[n],i=e[n+1],a=e[n+2],s=r<<16|(i??0)<<8|(a??0);t+=ce[s>>18&63]+ce[s>>12&63],t+=i===void 0?"=":ce[s>>6&63],t+=a===void 0?"=":ce[s&63]}return t}class wi{constructor(t){this.bytes=t}bytes;position=0;readShort(){const n=this.byte()<<8|this.byte();return n>=32768?n-65536:n}readUTF(){const t=this.byte()<<8|this.byte(),n=this.position+t;n>this.bytes.length&&this.fail("A string runs past the end of the bytes");let r="";for(;this.position<n;){const i=this.byte();if(i<128)r+=String.fromCharCode(i);else if((i&224)===192)r+=String.fromCharCode((i&31)<<6|this.byte()&63);else if((i&240)===224){const a=this.byte();r+=String.fromCharCode((i&15)<<12|(a&63)<<6|this.byte()&63)}else this.fail("A string holds a byte modified UTF-8 never starts a character with")}return r}byte(){return this.position>=this.bytes.length&&this.fail("The bytes end early"),this.bytes[this.position++]}fail(t){throw new x(t,"PACKET_FIELD",this.position)}}class vi{bytes=[];writeShort(t){return this.bytes.push(t>>8&255,t&255),this}writeUTF(t){const n=[];for(let r=0;r<t.length;r++){const i=t.charCodeAt(r);i>=1&&i<128?n.push(i):i<2048?n.push(192|i>>6,128|i&63):n.push(224|i>>12,128|i>>6&63,128|i&63)}if(n.length>65535)throw new x("A string is longer than writeUTF can write","PACKET_FIELD");return this.writeShort(n.length),this.bytes.push(...n),this}toBytes(){return Uint8Array.from(this.bytes)}}function bi(e){const t=Math.max(1,Math.ceil(e.length/65535)),n=new Uint8Array(2+t*5+e.length+4);n[0]=120,n[1]=1;let r=2;for(let o=0;o<t;o++){const l=o*65535,c=Math.min(65535,e.length-l);n[r++]=o===t-1?1:0,n[r++]=c&255,n[r++]=c>>8,n[r++]=~c&255,n[r++]=~c>>8&255,n.set(e.subarray(l,l+c),r),r+=c}let i=1,a=0;for(const o of e)i=(i+o)%65521,a=(a+i)%65521;const s=(a<<16|i)>>>0;return n[r++]=s>>>24,n[r++]=s>>>16&255,n[r++]=s>>>8&255,n[r]=s&255,n}function Ii(e){return e.length<2&&j("A zlib stream has a two byte header"),((e[0]&15)!==8||(e[0]<<8|e[1])%31!==0)&&j("Not a zlib stream of deflate data"),e[1]&32&&j("A zlib stream with a preset dictionary cannot be read"),Ci(e.subarray(2))}const Ti=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],Bt=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],xi=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],_t=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ki=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function ue(e){const t=new Uint16Array(16);for(let i=0;i<e.length;i++)t[e[i]]++;t[0]=0;const n=new Uint16Array(16);for(let i=1;i<16;i++)n[i]=n[i-1]+t[i-1];const r=new Uint16Array(e.length);for(let i=0;i<e.length;i++){const a=e[i];a!==0&&(r[n[a]++]=i)}return{counts:t,symbols:r}}let He=null;function Ai(){if(!He){const e=new Uint8Array(288);e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),He={literals:ue(e),distances:ue(new Uint8Array(30).fill(5))}}return He}class Si{constructor(t){this.bytes=t}bytes;position=0;bitBuffer=0;bitCount=0;bits(t){for(;this.bitCount<t;)this.position>=this.bytes.length&&j("The deflate data ends early"),this.bitBuffer|=this.bytes[this.position++]<<this.bitCount,this.bitCount+=8;const n=this.bitBuffer&(1<<t)-1;return this.bitBuffer>>>=t,this.bitCount-=t,n}align(){this.bitBuffer=0,this.bitCount=0}byte(){return this.position>=this.bytes.length&&j("The deflate data ends early"),this.bytes[this.position++]}decode(t){let n=0,r=0,i=0;for(let a=1;a<16;a++){i|=this.bits(1);const s=t.counts[a];if(i-n<s)return t.symbols[r+i-n];r+=s,n=n+s<<1,i<<=1}return j("The deflate data holds a code that is not in its table")}}class Ni{bytes=new Uint8Array(1024);length=0;push(t){if(this.length===this.bytes.length){const n=new Uint8Array(this.bytes.length*2);n.set(this.bytes),this.bytes=n}this.bytes[this.length++]=t}}function Ci(e){const t=new Si(e),n=new Ni;let r=!1;for(;!r;){r=t.bits(1)===1;const i=t.bits(2);if(i===0){t.align();const a=t.byte()|t.byte()<<8,s=t.byte()|t.byte()<<8;(a^65535)!==s&&j("A stored deflate block has a bad length");for(let o=0;o<a;o++)n.push(t.byte())}else if(i===1){const{literals:a,distances:s}=Ai();zt(t,n,a,s)}else if(i===2){const{literals:a,distances:s}=Ei(t);zt(t,n,a,s)}else j("A deflate block has the reserved type 3")}return n.bytes.slice(0,n.length)}function Ei(e){const t=e.bits(5)+257,n=e.bits(5)+1,r=e.bits(4)+4,i=new Uint8Array(19);for(let l=0;l<r;l++)i[Ti[l]]=e.bits(3);const a=ue(i),s=new Uint8Array(t+n);let o=0;for(;o<s.length;){const l=e.decode(a);if(l<16){s[o++]=l;continue}let c,d=0;l===16?(o===0&&j("A deflate block repeats a code length before giving one"),d=s[o-1],c=3+e.bits(2)):l===17?c=3+e.bits(3):c=11+e.bits(7),o+c>s.length&&j("A deflate block has too many code lengths"),s.fill(d,o,o+c),o+=c}return{literals:ue(s.subarray(0,t)),distances:ue(s.subarray(t))}}function zt(e,t,n,r){for(;;){const i=e.decode(n);if(i<256)t.push(i);else{if(i===256)return;{const a=i-257;a>=Bt.length&&j("A deflate block has a bad length code");const s=Bt[a]+e.bits(xi[a]),o=e.decode(r);o>=_t.length&&j("A deflate block has a bad distance code");const l=_t[o]+e.bits(ki[o]);l>t.length&&j("A deflate block points before its start");for(let c=0;c<s;c++)t.push(t.bytes[t.length-l])}}}}function j(e){throw new x(e,"PACKET_FIELD")}const Mi=200,En=16,qi=[11,23],Oi={setState:1},W={denItem:1,clothing:2,gems:3,crystals:4};u({name:"quest.join",description:"The player joins or creates a public adventure.",direction:"toServer",command:"qj",read:e=>({roomName:e.string("roomName"),scriptDefId:e.int("scriptDefId"),difficulty:e.int("difficulty"),reserved:e.int("reserved")}),write:(e,{roomName:t,scriptDefId:n,difficulty:r,reserved:i})=>e.string(t).int(n).int(r).int(i)});u({name:"quest.create-private",description:"The player creates a private adventure to host.",direction:"toServer",command:"qjc",read:e=>({roomName:e.string("roomName"),scriptDefId:e.int("scriptDefId"),difficulty:e.int("difficulty")}),write:(e,{roomName:t,scriptDefId:n,difficulty:r})=>e.string(t).int(n).int(r)});u({name:"quest.join-private",description:"The player joins a private adventure another player hosts.",direction:"toServer",command:"qjp",read:e=>({roomName:e.string("roomName"),hostUserName:e.string("hostUserName")}),write:(e,{roomName:t,hostUserName:n})=>e.string(t).string(n)});u({name:"quest.join-buddy",description:"The player joins the adventure a buddy is in.",direction:"toServer",command:"qjf",read:e=>({roomName:e.string("roomName"),buddyUserName:e.string("buddyUserName")}),write:(e,{roomName:t,buddyUserName:n})=>e.string(t).string(n)});u({name:"quest.join-cancel",description:"The player leaves an adventure lobby before it starts.",direction:"toServer",command:"qjx",read:()=>({}),write:()=>{}});u({name:"quest.kick",description:"The host removes a player from a private adventure lobby.",direction:"toServer",command:"qjk",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"quest.start",description:"The player starts the adventure they are waiting in.",direction:"toServer",command:"qs",read:e=>({roomName:e.string("roomName")}),write:(e,{roomName:t})=>e.string(t)});u({name:"quest.exit",description:"The player leaves the adventure.",direction:"toServer",command:"qx",read:e=>({exitType:e.string("exitType")}),write:(e,{exitType:t})=>e.string(t)});u({name:"quest.actor-trigger",description:"The player sets off an adventure actor, such as a treasure chest.",direction:"toServer",command:"qat",read:e=>({actorId:e.string("actorId"),value:e.int("value")}),write:(e,{actorId:t,value:n})=>e.string(t).int(n)});u({name:"quest.treasure-choice",description:"The player keeps or turns down a treasure chest’s prize.",direction:"toServer",command:"qatt",read:e=>({actorId:e.string("actorId"),keep:e.flag("keep")}),write:(e,{actorId:t,keep:n})=>e.string(t).flag(n)});u({name:"quest.pick-up",description:"The player picks up an item in an adventure.",direction:"toServer",command:"qpup",read:e=>({actorId:e.string("actorId"),userId:e.int("userId")}),write:(e,{actorId:t,userId:n})=>e.string(t).int(n)});function Mn(e,t,n){return u({name:e,description:n,direction:"toServer",command:t,read:r=>({index:r.int("index"),belowGoal:r.flag("belowGoal"),discarded:r.flag("discarded")}),write:(r,{index:i,belowGoal:a,discarded:s})=>r.int(i).flag(a).flag(s)})}Mn("quest.gift-choice","qpgift","The player picks a gift on an adventure’s reward screen.");Mn("quest.player-gift-choice","qpgiftplr","The player picks a gift on their own reward screen.");u({name:"quest.gifts-done",description:"The player finished picking an adventure’s gifts.",direction:"toServer",command:"qpgiftdone",read:e=>({done:e.flag("done")}),write:(e,{done:t})=>e.flag(t)});function dt(e,t,n,r){return u({name:e,description:n,direction:"toClient",command:t,read:i=>{const a=i.flag("joined");return a?{joined:a,status:i.string("status"),scriptDefId:i.int("scriptDefId"),difficulty:r&&i.remaining>0?i.int("difficulty"):null,extra:i.rest(),refusal:null}:{joined:a,refusal:i.string("refusal"),extra:i.rest()}},write:(i,a)=>{i.flag(a.joined),a.joined?(i.string(a.status).int(a.scriptDefId),a.difficulty!==null&&i.int(a.difficulty)):i.string(a.refusal),i.raw(a.extra)}})}dt("quest.join-result","qj","The server says whether the player joined a public adventure.",!0);dt("quest.create-private-result","qjc","The server says whether the player’s private adventure was created.",!1);dt("quest.join-private-result","qjp","The server says whether the player joined a private adventure.",!0);u({name:"quest.waiting",description:"The players waiting in the adventure lobby changed.",direction:"toClient",command:"qw",read:e=>({userIds:e.repeat(e.remaining,()=>e.int("userId"))}),write:(e,{userIds:t})=>e.each(t,n=>e.int(n))});u({name:"quest.join-cancelled",description:"The server confirms the player left the adventure lobby.",direction:"toClient",command:"qjx",read:e=>({extra:e.rest()}),write:(e,{extra:t})=>e.raw(t)});u({name:"quest.started",description:"The adventure starts, with every actor in it.",direction:"toClient",command:"qs",read:e=>{const t=e.int("scriptDefId"),n=e.int("playerCount"),r=e.int("actorCount");if(r<0)return{scriptDefId:t,playerCount:n,started:!1,timestamp:"",actors:[],extra:e.rest()};const i=e.string("timestamp"),a=e.repeat(r,()=>Di(e));return{scriptDefId:t,playerCount:n,started:!0,timestamp:i,actors:a,extra:e.rest()}},write:(e,{scriptDefId:t,playerCount:n,started:r,timestamp:i,actors:a,extra:s})=>{e.int(t).int(n),r?e.int(a.length).string(i).each(a,o=>Pi(e,o)):e.int(-1),e.raw(s)}});function Di(e){const t=e.string("actorId"),n=e.int("type"),r=n===En,i=r?e.string("defName"):null,a=r?null:e.int("defId");return{actorId:t,type:n,defId:a,defName:i,state:e.int("state"),visible:e.int("visible")===1,requireClick:e.int("requireClick")===1,pathName:e.string("pathName"),swfState:e.string("swfState")}}function Pi(e,t){e.string(t.actorId).int(t.type),t.type===En?e.string(t.defName??""):e.int(t.defId??0),e.int(t.state).int(t.visible?1:0).int(t.requireClick?1:0).string(t.pathName).string(t.swfState)}u({name:"quest.treasure",description:"A treasure chest offers the player its prize.",direction:"toClient",command:"qatt",read:e=>({actorId:e.string("actorId"),prize:e.int("prize"),value:e.int("value"),color:e.int("color"),popup:e.int("popup")}),write:(e,{actorId:t,prize:n,value:r,color:i,popup:a})=>e.string(t).int(n).int(r).int(i).int(a)});u({name:"quest.xp",description:"The player earned adventure experience.",direction:"toClient",command:"quxp",read:e=>({earned:e.int("earned"),totalXp:e.int("totalXp"),previousLevel:e.int("previousLevel"),level:e.int("level"),levelProgress:e.number("levelProgress"),actorId:e.string("actorId")}),write:(e,{earned:t,totalXp:n,previousLevel:r,level:i,levelProgress:a,actorId:s})=>e.int(t).int(n).int(r).int(i).number(a).string(s)});u({name:"quest.level-up",description:"A player in the adventure levelled up.",direction:"toClient",command:"qulu",read:e=>({userId:e.int("userId"),level:e.int("level")}),write:(e,{userId:t,level:n})=>e.int(t).int(n)});u({name:"quest.player-left",description:"A player left the adventure.",direction:"toClient",command:"qplq",read:e=>({userId:e.int("userId"),avatarName:e.string("avatarName")}),write:(e,{userId:t,avatarName:n})=>e.int(t).string(n)});function qn(e,t,n){return u({name:e,description:n,direction:"toClient",command:t,read:r=>{const i=r.int("count"),a=r.int("popupType"),s=r.repeat(i,()=>({prize:r.int("prize"),value:r.int("value"),color:r.int("color")}));return{popupType:a,gifts:s}},write:(r,{popupType:i,gifts:a})=>r.int(a.length).int(i).each(a,({prize:s,value:o,color:l})=>r.int(s).int(o).int(l))})}qn("quest.rewards","qpgift","The adventure’s reward screen opens with its gifts.");qn("quest.player-rewards","qpgiftplr","The player’s own reward screen opens with its gifts.");u({name:"quest.award",description:"The adventure awards a stat or achievement.",direction:"toClient",command:"qaward",read:e=>({userVarId:e.int("userVarId"),value:e.int("value")}),write:(e,{userVarId:t,value:n})=>e.int(t).int(n)});u({name:"quest.exit-by-type",description:"The server sends the player out of the adventure.",direction:"toClient",command:"qxt",read:e=>({exitType:e.string("exitType")}),write:(e,{exitType:t})=>e.string(t)});u({name:"quest.bundle",description:"Several adventure messages packed into one.",direction:"toClient",command:"qqm",read:e=>{const t=e.string("payload"),n=new wi(Ii(fi(t))),r=n.readShort();return{messages:Array.from({length:Math.max(0,r)},()=>{const a=n.readShort(),s=n.readUTF(),o=Array.from({length:Math.max(0,a-1)},()=>n.readUTF());return{command:s,args:o}}),extra:e.rest()}},write:(e,{messages:t,extra:n})=>{const r=new vi().writeShort(t.length);for(const{command:i,args:a}of t)r.writeShort(a.length+1).writeUTF(i),a.forEach(s=>r.writeUTF(s));e.string(yi(bi(r.toBytes()))).raw(n)}});u({name:"quest.actor-spawned",description:"An actor appears in the adventure, such as dropped treasure.",direction:"toClient",command:"qspn",read:e=>{const t=e.string("spawnedFrom"),n=e.string("actorId"),r=e.int("type"),i=e.int("defId");let a=null,s=null;if(r===Mi){const o=e.int("subType");a={subType:o,denDefId:null,itemDefId:null,color:null,amount:null},o===W.denItem?a.denDefId=e.int("denDefId"):o===W.clothing?(a.itemDefId=e.int("itemDefId"),a.color=e.int("color")):(o===W.gems||o===W.crystals)&&(a.amount=e.int("amount"))}else qi.includes(r)&&(s={x:e.number("spawnOffsetX"),y:e.number("spawnOffsetY")});return{spawnedFrom:t,actorId:n,type:r,defId:i,dropped:a,spawnOffset:s,extra:e.rest()}},write:(e,{spawnedFrom:t,actorId:n,type:r,defId:i,dropped:a,spawnOffset:s,extra:o})=>{e.string(t).string(n).int(r).int(i),a?(e.int(a.subType),a.subType===W.denItem?e.int(a.denDefId??0):a.subType===W.clothing?e.int(a.itemDefId??0).int(a.color??0):(a.subType===W.gems||a.subType===W.crystals)&&e.int(a.amount??0)):s&&e.number(s.x).number(s.y),e.raw(o)}});u({name:"quest.actor-moved",description:"An adventure actor moved.",direction:"toClient",command:"qau",read:e=>({actorId:e.string("actorId"),x:e.int("x"),y:e.int("y"),velocity:e.int("velocity"),seekType:e.int("seekType"),nearestX:e.int("nearestX"),nearestY:e.int("nearestY")}),write:(e,{actorId:t,x:n,y:r,velocity:i,seekType:a,nearestX:s,nearestY:o})=>e.string(t).int(n).int(r).int(i).int(a).int(s).int(o)});u({name:"quest.actor-position-report",description:"The client reports where an adventure actor it moves is.",direction:"toServer",command:"qau",read:e=>({actorId:e.string("actorId"),x:e.int("x"),y:e.int("y"),velocity:e.int("velocity"),seekType:e.int("seekType"),nearestX:e.int("nearestX"),nearestY:e.int("nearestY")}),write:(e,{actorId:t,x:n,y:r,velocity:i,seekType:a,nearestX:s,nearestY:o})=>e.string(t).int(n).int(r).int(i).int(a).int(s).int(o)});u({name:"quest.actor-seek",description:"An adventure actor starts seeking a player, path or plant.",direction:"toClient",command:"qas",read:e=>({actorId:e.string("actorId"),seekType:e.int("seekType"),userId:e.int("userId")}),write:(e,{actorId:t,seekType:n,userId:r})=>e.string(t).int(n).int(r)});u({name:"quest.actor-seek-request",description:"The client asks for an adventure actor to seek.",direction:"toServer",command:"qas",read:e=>({actorId:e.string("actorId"),seekType:e.int("seekType")}),write:(e,{actorId:t,seekType:n})=>e.string(t).int(n)});u({name:"quest.actor-untrigger",description:"The player left an adventure actor’s area.",direction:"toServer",command:"qaut",read:e=>({actorId:e.string("actorId")}),write:(e,{actorId:t})=>e.string(t)});u({name:"quest.actor-health",description:"An adventure actor was hit, or missed.",direction:"toClient",command:"qahs",read:e=>{const t=e.string("actorId"),n=e.int("healthPercent"),r=n===-1,i=!r&&e.remaining>0?e.int("damage"):null,a=i!==null&&e.remaining>0?e.int("fierce")===1:null;return{actorId:t,healthPercent:n,missed:r,damage:i,fierce:a,extra:e.rest()}},write:(e,{actorId:t,healthPercent:n,damage:r,fierce:i,extra:a})=>{e.string(t).int(n),r!==null&&(e.int(r),i!==null&&e.int(i?1:0)),e.raw(a)}});u({name:"quest.actor-died",description:"An adventure actor was defeated or used up.",direction:"toClient",command:"qad",read:e=>({actorId:e.string("actorId"),damage:e.int("damage"),moved:e.string("moved")==="1",x:e.int("x"),y:e.int("y"),otherActorId:e.string("otherActorId")}),write:(e,{actorId:t,damage:n,moved:r,x:i,y:a,otherActorId:s})=>e.string(t).int(n).flag(r).int(i).int(a).string(s)});u({name:"quest.actor-restored",description:"An adventure actor came back.",direction:"toClient",command:"qrestore",read:e=>({actorId:e.string("actorId"),healthPercent:e.int("healthPercent")}),write:(e,{actorId:t,healthPercent:n})=>e.string(t).int(n)});function On(e,t,n,r){return u({name:e,description:n,direction:"toClient",command:t,read:i=>{const a=i.int("command");if(a!==Oi.setState||i.remaining<2)return{command:a,actorId:null,state:null,visible:null,requireClick:null,args:i.rest()};const s=i.string("actorId"),o=i.int("state"),l=!r&&i.remaining>=2,c=l?i.string("visible")==="1":null,d=l?i.string("requireClick")==="1":null;return{command:a,actorId:s,state:o,visible:c,requireClick:d,args:i.rest()}},write:(i,a)=>{i.int(a.command),a.actorId!==null&&a.state!==null&&(i.string(a.actorId).int(a.state),a.visible!==null&&a.requireClick!==null&&i.flag(a.visible).flag(a.requireClick)),i.raw(a.args)}})}On("quest.command","qcmd","The adventure’s script tells the client to do something, such as change an actor.",!1);On("quest.variable","qcmdVT","The adventure’s script sets one of its variables.",!0);u({name:"quest.actor-swf-state",description:"An adventure actor’s animation changes state.",direction:"toClient",command:"qswfs",read:e=>({actorId:e.string("actorId"),swfState:e.string("swfState")}),write:(e,{actorId:t,swfState:n})=>e.string(t).string(n)});u({name:"quest.actor-path",description:"An adventure actor walks another path.",direction:"toClient",command:"qsp",read:e=>({actorId:e.string("actorId"),pathName:e.string("pathName")}),write:(e,{actorId:t,pathName:n})=>e.string(t).string(n)});u({name:"quest.actor-icon",description:"An adventure actor’s icon shows or hides.",direction:"toClient",command:"qicon",read:e=>({actorId:e.string("actorId"),showing:e.string("showing")==="1"}),write:(e,{actorId:t,showing:n})=>e.string(t).flag(n)});u({name:"quest.moved-items",description:"Where players moved the adventure’s items.",direction:"toClient",command:"qmi",read:e=>({items:e.repeat(Math.floor(e.remaining/5),()=>({actorId:e.string("actorId"),innerRadius:e.int("innerRadius"),outerRadius:e.int("outerRadius"),x:e.number("x"),y:e.number("y")})),extra:e.rest()}),write:(e,{items:t,extra:n})=>e.each(t,r=>e.string(r.actorId).int(r.innerRadius).int(r.outerRadius).number(r.x).number(r.y)).raw(n)});const re={askToDrop:0,pickedUp:1,droppedAt:3,placedAt:4};u({name:"quest.pick-up-result",description:"The server says what came of picking up an adventure item.",direction:"toClient",command:"qpup",read:e=>{const t=e.int("result"),n={result:t,heldItem:null,actorId:null,userId:null,x:null,y:null,innerRadius:null,outerRadius:null,dropperUserId:null};if(t===re.askToDrop)return{...n,heldItem:e.string("heldItem"),extra:e.rest()};if(t!==re.pickedUp&&t!==re.droppedAt&&t!==re.placedAt)return{...n,extra:e.rest()};const r={...n,actorId:e.string("actorId"),userId:e.int("userId")};return t!==re.pickedUp&&(r.x=e.number("x"),r.y=e.number("y")),t===re.placedAt&&(r.innerRadius=e.int("innerRadius"),r.outerRadius=e.int("outerRadius"),r.dropperUserId=e.int("dropperUserId")),{...r,extra:e.rest()}},write:(e,t)=>{e.int(t.result),t.heldItem!==null&&e.string(t.heldItem),t.actorId!==null&&e.string(t.actorId).int(t.userId??0),t.x!==null&&t.y!==null&&e.number(t.x).number(t.y),t.innerRadius!==null&&e.int(t.innerRadius).int(t.outerRadius??0).int(t.dropperUserId??0),e.raw(t.extra)}});u({name:"quest.give-item",description:"The server hands the player an adventure item to pick up.",direction:"toClient",command:"qgi",read:e=>({actorId:e.string("actorId")}),write:(e,{actorId:t})=>e.string(t)});function Dn(e,t,n,r){return u({name:e,description:n,direction:"toClient",command:t,read:i=>{const a=i.int("userId"),s=i.int("healthPercent"),o=i.int("change"),l=i.int("health"),c=i.int("maxHealth"),d=r&&i.remaining>=2,h=d?i.int("x"):null,m=d?i.int("y"):null;return{userId:a,healthPercent:s,change:o,health:l,maxHealth:c,x:h,y:m,extra:i.rest()}},write:(i,{userId:a,healthPercent:s,change:o,health:l,maxHealth:c,x:d,y:h,extra:m})=>{i.int(a).int(s).int(o).int(l).int(c),d!==null&&h!==null&&i.int(d).int(h),i.raw(m)}})}Dn("quest.health","quhp","A player’s health in the adventure changed.",!1);Dn("quest.respawned","qrspn","A player came back to life in the adventure.",!0);u({name:"quest.player-dead",description:"A player in the adventure was defeated.",direction:"toClient",command:"qpd",read:e=>({userId:e.int("userId")}),write:(e,{userId:t})=>e.int(t)});u({name:"quest.crystals",description:"The crystals the player gathered in the adventure changed.",direction:"toClient",command:"qporbs",read:e=>({crystals:e.int("crystals")}),write:(e,{crystals:t})=>e.int(t)});u({name:"quest.exited",description:"The server answers the player leaving the adventure.",direction:"toClient",command:"qx",read:e=>({extra:e.rest()}),write:(e,{extra:t})=>e.raw(t)});u({name:"quest.seed-given",description:"The player’s seed count changed.",direction:"toClient",command:"qseed",read:e=>({defId:e.int("defId"),count:e.int("count"),max:e.int("max")}),write:(e,{defId:t,count:n,max:r})=>e.int(t).int(n).int(r)});u({name:"quest.seed-planted",description:"A seed was planted in the adventure, or refused.",direction:"toClient",command:"qps",read:e=>{const t={planted:e.flag("planted"),userName:e.string("userName"),plant:null};return t.planted?{...t,plant:{actorName:e.string("actorName"),defId:e.int("defId"),x:e.int("x"),y:e.int("y"),launcherUserId:e.int("launcherUserId")}}:t},write:(e,{planted:t,userName:n,plant:r})=>{e.flag(t).string(n),t&&r&&e.string(r.actorName).int(r.defId).int(r.x).int(r.y).int(r.launcherUserId)}});u({name:"quest.plant-ate",description:"A planted seed’s plant ate a phantom.",direction:"toClient",command:"qpa",read:e=>({plantActorId:e.string("plantActorId"),phantomActorId:e.string("phantomActorId")}),write:(e,{plantActorId:t,phantomActorId:n})=>e.string(t).string(n)});u({name:"quest.plant-eat-recoil",description:"A planted seed’s plant recoils after eating.",direction:"toClient",command:"qepr",read:e=>({actorId:e.string("actorId")}),write:(e,{actorId:t})=>e.string(t)});u({name:"quest.volume-progress",description:"An interactive volume’s progress changed.",direction:"toClient",command:"qviu",read:e=>({actorId:e.string("actorId"),progress:e.int("progress")}),write:(e,{actorId:t,progress:n})=>e.string(t).int(n)});u({name:"quest.stats-update",description:"The player’s own attack and defence range in the adventure changed.",direction:"toClient",command:"qusu",read:e=>({attackBase:e.int("attackBase"),attackMax:e.int("attackMax"),defenseBase:e.int("defenseBase"),defenseMax:e.int("defenseMax")}),write:(e,{attackBase:t,attackMax:n,defenseBase:r,defenseMax:i})=>e.int(t).int(n).int(r).int(i)});u({name:"quest.avatar-switch",description:"A player is drawn disguised as a phantom or NPC, or their disguise is taken off.",direction:"toClient",command:"qavsw",read:e=>{const t=e.int("avatarRefId");return{avatarRefId:t===-1?null:t,userId:e.int("userId")}},write:(e,{avatarRefId:t,userId:n})=>e.int(t??-1).int(n)});u({name:"room.join-request",description:"The player asks to join a room.",direction:"toServer",command:"rj",read:e=>({target:e.string("target"),confirmLanguageChange:e.flag("confirmLanguageChange"),invisible:e.flag("invisible"),joinType:e.string("joinType")}),write:(e,{target:t,confirmLanguageChange:n,invisible:r,joinType:i})=>e.string(t).flag(n).flag(r).string(i)});const Li=8;u({name:"room.join-result",description:"The server says whether the player joined, and describes the room.",direction:"toClient",command:"rj",read:e=>{const t=e.flag("joined");if(!t){const i=e.remaining>0?e.string("error"):null;return{joined:t,joinedRoom:null,details:null,error:i,extra:e.rest()}}const n={name:e.string("name"),id:e.int("id"),users:e.int("users"),maxUsers:e.int("maxUsers"),spectators:e.int("spectators"),maxSpectators:e.int("maxSpectators"),isPrivate:e.flag("isPrivate"),isGame:e.flag("isGame"),isLimbo:e.flag("isLimbo")},r=e.remaining>=Li?ji(e):null;return{joined:t,joinedRoom:n,details:r,error:null,extra:e.rest()}},write:(e,{joined:t,joinedRoom:n,details:r,error:i,extra:a})=>{e.flag(t),t&&n?(e.string(n.name).int(n.id).int(n.users).int(n.maxUsers).int(n.spectators).int(n.maxSpectators).flag(n.isPrivate).flag(n.isGame).flag(n.isLimbo),r&&(e.flag(r.isTemp).flag(r.isSubRoom).string(r.displayName).int(r.displayNameId).int(r.perUserAvId).int(r.activePetInvId).int(r.language).int(r.customMusicDef),r.shardId!==null&&e.int(r.shardId))):!t&&i!==null&&e.string(i),e.raw(a)}});function ji(e){return{isTemp:e.flag("isTemp"),isSubRoom:e.flag("isSubRoom"),displayName:e.string("displayName"),displayNameId:e.int("displayNameId"),perUserAvId:e.int("perUserAvId"),activePetInvId:e.int("activePetInvId"),language:e.int("language"),customMusicDef:e.int("customMusicDef"),shardId:e.remaining>0?e.int("shardId"):null}}u({name:"room.properties",description:"The server says which room to load, and how.",direction:"toClient",command:"rp",read:e=>({pathName:e.string("pathName"),environmentType:e.int("environmentType"),roomType:e.int("roomType"),secondaryDefId:e.int("secondaryDefId"),zoom:e.int("zoom"),roomDefId:e.int("roomDefId"),customData:e.remaining>0?e.string("customData"):null}),write:(e,t)=>{e.string(t.pathName).int(t.environmentType).int(t.roomType).int(t.secondaryDefId).int(t.zoom).int(t.roomDefId),t.customData!==null&&e.string(t.customData)}});u({name:"room.leave-request",description:"The player leaves an in room game’s room.",direction:"toServer",command:"rl",read:e=>({roomId:e.int("roomId")}),write:(e,{roomId:t})=>e.int(t)});u({name:"room.list",description:"The server lists the rooms the client knows.",direction:"toClient",command:"rl",read:e=>({rooms:e.repeat(e.int("count"),()=>({id:e.int("id"),name:e.string("name"),maxUsers:e.int("maxUsers"),isTemp:e.flag("isTemp"),isGame:e.flag("isGame"),users:e.int("users")}))}),write:(e,{rooms:t})=>e.int(t.length).each(t,n=>e.int(n.id).string(n.name).int(n.maxUsers).flag(n.isTemp).flag(n.isGame).int(n.users))});ye({name:"session.version-check",description:"The client says which SmartFox version it speaks.",direction:"toServer",type:"sys",command:"verChk",read:e=>{var t,n;return{version:((n=(t=e.body)==null?void 0:t.child("ver"))==null?void 0:n.attribute("v"))??""}},write:({version:e})=>[new _("ver",{attributes:[z.create("v",e)],selfClosing:!0,trailing:" "})]});ye({name:"session.random-key-request",description:"The client asks for the key it signs its login with.",direction:"toServer",type:"sys",command:"rndK",read:()=>({}),write:()=>[]});ye({name:"session.random-key",description:"The server gives the key the login is signed with.",direction:"toClient",type:"sys",command:"rndK",read:e=>{var t,n;return{key:((n=(t=e.body)==null?void 0:t.child("k"))==null?void 0:n.textContent)??""}},write:({key:e})=>[new _("k",{children:[new te(e)]})]});ye({name:"session.login",description:"The client signs in to a zone with its auth token.",direction:"toServer",type:"sys",command:"login",read:e=>{var t,n,r;const i=(t=e.body)==null?void 0:t.child("login");return{zone:(i==null?void 0:i.attribute("z"))??"",nick:((n=i==null?void 0:i.child("nick"))==null?void 0:n.textContent)??"",password:((r=i==null?void 0:i.child("pword"))==null?void 0:r.textContent)??""}},write:({zone:e,nick:t,password:n})=>[new _("login",{attributes:[z.create("z",e)],children:[new _("nick",{children:[new te(t)]}),new _("pword",{children:[new te(n)]})]})]});const ae={clothing:1e3,denItems:1030,denRooms:1040,currencyExchange:1051,diamondShop:1054,combined:1060},Ri=[ae.clothing,ae.denItems,ae.denRooms,ae.currencyExchange,ae.diamondShop];u({name:"shop.list-request",description:"The player asks for a shop’s contents.",direction:"toServer",command:"gl",read:e=>({listId:e.int("listId")}),write:(e,{listId:t})=>e.int(t)});u({name:"shop.list",description:"The server sends a shop’s contents.",direction:"toClient",command:"gl",read:e=>{const t=e.int("listId"),n=e.int("listType"),r=Ri.indexOf(n)!==-1;if(!r&&n!==ae.combined)return{kind:"other",listId:t,listType:n,body:e.rest()};const i={listId:t,listType:n,titleStrId:e.string("titleStrId"),unused:e.string("unused"),diamondBundle:e.string("diamondBundle")!=="",diamondCost:it(e.string("diamondCost"))},a=e.int("count");return r?{...i,kind:"items",defIds:e.repeat(a,()=>e.int("defId"))}:{...i,kind:"combined",groups:$i(e,a)}},write:(e,t)=>{if(e.int(t.listId).int(t.listType),t.kind==="other"){e.raw(t.body);return}if(e.string(t.titleStrId).string(t.unused).string(t.diamondBundle?"1":"").int(t.diamondCost),t.kind==="items"){e.int(t.defIds.length).each(t.defIds,n=>e.int(n));return}e.int(t.groups.length),t.groups.length!==0&&(e.string(t.groups.map(n=>n.listType).join(",")).string(t.groups.map(n=>n.defIds.length).join(",")),t.groups.forEach(n=>n.defIds.forEach(r=>e.int(r))))}});function $i(e,t){if(t===0)return[];const n=e.string("groupTypes").split(","),r=e.string("groupCounts").split(",");return n.map((i,a)=>({listType:it(i),defIds:e.repeat(it(r[a]??""),()=>e.int("defId"))}))}function it(e){const t=Number(e);return Number.isInteger(t)?t:0}u({name:"shop.den-shop-update-request",description:"The player adds, reprices or removes items in their own den shop.",direction:"toServer",command:"dsu",read:e=>({storeInvId:e.int("storeInvId"),state:e.string("state"),upserts:e.repeat(e.int("upsertCount"),()=>({itemKind:e.int("itemKind"),invIdx:e.int("invIdx"),currencyType:e.int("currencyType"),cost:e.int("cost")})),removals:e.repeat(e.int("removeCount"),()=>({itemKind:e.int("itemKind"),invIdx:e.int("invIdx")}))}),write:(e,{storeInvId:t,state:n,upserts:r,removals:i})=>{e.int(t).string(n),e.int(r.length).each(r,a=>e.int(a.itemKind).int(a.invIdx).int(a.currencyType).int(a.cost)),e.int(i.length).each(i,a=>e.int(a.itemKind).int(a.invIdx))}});u({name:"shop.den-shop-update-result",description:"The server answers a change to the player’s own den shop.",direction:"toClient",command:"dsu",read:e=>{const t=e.string("ok")==="1";return{ok:t,state:t?e.string("state"):""}},write:(e,{ok:t,state:n})=>{e.string(t?"1":"0"),t&&e.string(n)}});u({name:"shop.den-shop-info-request",description:"The player asks to see a den shop’s listings.",direction:"toServer",command:"dsi",read:e=>({userName:e.string("userName"),storeInvId:e.int("storeInvId")}),write:(e,{userName:t,storeInvId:n})=>e.string(t).int(n)});u({name:"shop.den-shop-info",description:"The server sends a den shop’s listings.",direction:"toClient",command:"dsi",read:e=>{const t=e.string("ok")==="1",n=e.int("itemCount");if(!t||n<0)return{ok:t,itemCount:-1,state:"",items:[]};const r=e.string("state");return{ok:t,itemCount:n,state:r,items:e.rest()}},write:(e,t)=>{e.string(t.ok?"1":"0").int(t.itemCount),t.ok&&t.itemCount>=0&&e.string(t.state).raw(t.items)}});u({name:"shop.den-shop-buy-request",description:"The player buys an item from a den shop.",direction:"toServer",command:"dsb",read:e=>({userName:e.string("userName"),shopInvIdx:e.int("shopInvIdx"),state:e.string("state"),itemKind:e.int("itemKind"),invIdx:e.int("invIdx"),currencyType:e.int("currencyType"),cost:e.int("cost")}),write:(e,{userName:t,shopInvIdx:n,state:r,itemKind:i,invIdx:a,currencyType:s,cost:o})=>e.string(t).int(n).string(r).int(i).int(a).int(s).int(o)});u({name:"shop.den-shop-buy-result",description:"The server answers a den shop purchase.",direction:"toClient",command:"dsb",read:e=>{const t=e.int("status");if(t!==1)return{status:t,ownerUserName:"",storeInvId:-1,rest:[]};const n=e.string("ownerUserName"),r=e.int("storeInvId");return{status:t,ownerUserName:n,storeInvId:r,rest:e.rest()}},write:(e,t)=>{e.int(t.status),t.status===1&&e.string(t.ownerUserName).int(t.storeInvId).raw(t.rest)}});u({name:"trade.list-request",description:"The player asks for someone’s trade list.",direction:"toServer",command:"tl",read:e=>({userName:e.string("userName")}),write:(e,{userName:t})=>e.string(t)});u({name:"trade.list",description:"The server sends someone’s trade list.",direction:"toClient",command:"tl",read:e=>({userName:e.string("userName"),clothing:e.repeat(e.int("clothing"),()=>({defId:e.int("defId"),invIdx:e.int("invIdx"),color:e.int("color")})),den:e.repeat(e.int("den"),()=>{const t=e.int("defId"),n=e.int("invIdx");return{defId:t,invIdx:n,...ht(e)}}),pets:e.repeat(e.int("pets"),()=>{const t=e.int("defId"),n=e.int("invIdx"),r=e.number("createdAt"),i=gt(e),a=e.string("name");return{defId:t,invIdx:n,createdAt:r,bits:i,name:a,...ft(e)}})}),write:(e,{userName:t,clothing:n,den:r,pets:i})=>{e.string(t).int(n.length),n.forEach(a=>e.int(a.defId).int(a.invIdx??-1).int(a.color)),e.int(r.length),r.forEach(a=>{e.int(a.defId).int(a.invIdx??-1),mt(e,a)}),e.int(i.length),i.forEach(a=>{e.int(a.defId).int(a.invIdx).number(a.createdAt),pt(e,a),e.string(a.name),yt(e,a)})}});u({name:"trade.list-change",description:"The player changes their trade list.",direction:"toServer",command:"ts",read:e=>({removed:e.repeat(e.int("removed"),()=>at(e)),added:e.repeat(e.int("added"),()=>at(e))}),write:(e,{removed:t,added:n})=>{e.int(t.length),t.forEach(r=>e.int(r.itemType).int(r.invIdx)),e.int(n.length),n.forEach(r=>e.int(r.itemType).int(r.invIdx))}});u({name:"trade.busy",description:"The player starts or stops being busy with a trade.",direction:"toServer",command:"tb",read:e=>({busy:e.flag("busy")}),write:(e,{busy:t})=>e.flag(t)});u({name:"trade.action",description:"The player asks for a trade, answers one, withdraws or confirms.",direction:"toServer",command:"ti",read:e=>{const t=e.int("action");switch(t){case 0:{const n=e.string("userName"),r=e.int("itemType"),i=e.int("invIdx"),a=e.int("clothing"),s=e.int("den"),o=e.int("audio"),l=e.int("pets");return{action:"request",userName:n,itemType:r,invIdx:i,clothing:e.repeat(a,()=>e.int("invIdx")),den:e.repeat(s+o,()=>e.int("invIdx")),audio:o,pets:e.repeat(l,()=>e.int("invIdx"))}}case 1:return{action:"respond",response:e.int("response")};case 2:return{action:"cancel"};case 3:return{action:"confirm",confirm:e.flag("confirm")};default:throw new x(`trade.action: unknown action ${t}`,"PACKET_FIELD")}},write:(e,t)=>{switch(t.action){case"request":e.int(0).string(t.userName).int(t.itemType).int(t.invIdx).int(t.clothing.length).int(t.den.length-t.audio).int(t.audio).int(t.pets.length),[...t.clothing,...t.den,...t.pets].forEach(n=>e.int(n));return;case"respond":e.int(1).int(t.response);return;case"cancel":e.int(2);return;case"confirm":e.int(3).int(t.confirm?1:0);return}}});u({name:"trade.result",description:"Someone offers a trade, or a trade is accepted, done or ends.",direction:"toClient",command:"ti",read:e=>{const t=e.int("status");switch(t){case 0:return{kind:"offer",status:0,offer:Fi(e)};case 1:{if(e.int("stage")===0)return{kind:"confirm",status:1};const n=e.repeat(e.int("received"),()=>Bi(e)),r=e.repeat(e.int("removed"),()=>at(e));return{kind:"completed",status:1,received:n,removed:r,extra:e.rest()}}case 6:return{kind:"closed",status:6,extra:e.rest()};case 7:return{kind:"different-server",status:7,roomName:e.string("roomName"),extra:e.rest()};default:return{kind:"failed",status:t,userName:e.string("userName"),userNameModerationFlag:e.int("userNameModerationFlag"),extra:e.rest()}}},write:(e,t)=>{switch(e.int(t.status),t.kind){case"offer":Ui(e,t.offer);return;case"confirm":e.int(0);return;case"completed":e.int(1).int(t.received.length),t.received.forEach(n=>_i(e,n)),e.int(t.removed.length),t.removed.forEach(n=>e.int(n.itemType).int(n.invIdx)),e.raw(t.extra);return;case"closed":e.raw(t.extra);return;case"different-server":e.string(t.roomName).raw(t.extra);return;case"failed":e.string(t.userName).int(t.userNameModerationFlag).raw(t.extra);return}}});function Fi(e){const t=e.string("userName"),n=e.int("userNameModerationFlag"),r=e.int("wantedKind"),i=e.int("wantedInvIdx"),a=e.int("clothing"),s=e.int("den"),o=e.int("pets");return{userName:t,userNameModerationFlag:n,wantedKind:r,wantedInvIdx:i,offered:{clothing:e.repeat(a,()=>({defId:e.int("defId"),color:e.int("color"),invIdx:null})),den:e.repeat(s,()=>({defId:e.int("defId"),invIdx:null,...ht(e)})),pets:e.repeat(o,()=>{const l=e.number("createdAt"),c=e.int("defId"),d=e.int("invIdx"),h=gt(e),m=ft(e);return{defId:c,invIdx:d,createdAt:l,bits:h,name:e.string("name"),...m}})}}}function Ui(e,t){const{clothing:n,den:r,pets:i}=t.offered;e.string(t.userName).int(t.userNameModerationFlag).int(t.wantedKind).int(t.wantedInvIdx).int(n.length).int(r.length).int(i.length),n.forEach(a=>e.int(a.defId).int(a.color)),r.forEach(a=>{e.int(a.defId),mt(e,a)}),i.forEach(a=>{e.number(a.createdAt).int(a.defId).int(a.invIdx),pt(e,a),yt(e,a),e.string(a.name)})}function Bi(e){const t=e.int("type");switch(t){case 0:return{type:"clothing",defId:e.int("defId"),invIdx:e.int("invIdx"),color:e.int("color")};case 1:{const n=e.int("invIdx");return{type:"den",defId:e.int("defId"),invIdx:n,...ht(e)}}case 2:{const n=e.number("createdAt"),r=e.int("invIdx"),i=e.int("defId"),a=gt(e),s=ft(e);return{type:"pet",defId:i,invIdx:r,createdAt:n,bits:a,name:e.string("name"),...s}}default:throw new x(`trade.result: unknown received item type ${t}`,"PACKET_FIELD")}}function _i(e,t){switch(t.type){case"clothing":e.int(0).int(t.defId).int(t.invIdx??-1).int(t.color);return;case"den":e.int(1).int(t.invIdx??-1).int(t.defId),mt(e,t);return;case"pet":e.int(2).number(t.createdAt).int(t.invIdx).int(t.defId),pt(e,t),yt(e,t),e.string(t.name);return}}function at(e){return{itemType:e.int("itemType"),invIdx:e.int("invIdx")}}function ht(e){return{version:e.int("version"),approved:e.string("approved")==="true",uniqueImageId:e.string("uniqueImageId"),creatorDbId:e.int("creatorDbId"),creatorUuid:e.string("creatorUuid")}}function mt(e,t){e.int(t.version).string(t.approved?"true":"false").string(t.uniqueImageId).int(t.creatorDbId).string(t.creatorUuid)}function gt(e){return[e.int("bits1"),e.int("bits2"),e.int("bits3")]}function pt(e,t){e.int(t.bits[0]).int(t.bits[1]).int(t.bits[2])}function ft(e){return{traitDefId:e.int("traitDefId"),toyDefId:e.int("toyDefId"),foodDefId:e.int("foodDefId")}}function yt(e,t){e.int(t.traitDefId).int(t.toyDefId).int(t.foodDefId)}u({name:"world.room-count-request",description:"The player asks how many are in each room.",direction:"toServer",command:"rc",read:()=>({}),write:()=>{}});u({name:"world.room-counts",description:"The server says how many are in each room.",direction:"toClient",command:"rc",read:e=>({rooms:e.repeat(e.int("count"),()=>({name:e.string("name"),users:e.int("users")}))}),write:(e,{rooms:t})=>e.int(t.length).each(t,({name:n,users:r})=>e.string(n).int(r))});u({name:"world.shard-list-request",description:"The player asks for the list of shards.",direction:"toServer",command:"rm",read:()=>({}),write:()=>{}});const Ve=4;u({name:"world.shard-list",description:"The server lists the shards on each server node.",direction:"toClient",command:"rm",read:e=>{const t=e.rest(),n=t[0];return n!==void 0&&Pn(n)?{status:new fe(t,"world.shard-list").int("status"),nodes:[]}:{status:null,nodes:zi(t)}},write:(e,{status:t,nodes:n})=>{if(t!==null){e.int(t);return}e.each(n,({host:r,shards:i})=>e.string(r).each(i,a=>e.int(a.id).int(a.language).int(a.population).int(a.buddies)))}});function zi(e){const t=[];let n=0;for(;n<e.length;){const r=e[n++];let i=n;for(;i<e.length&&Pn(e[i]);)i++;const a=i-n;if(a%Ve!==0)throw new x(`world.shard-list: node "${r}" has ${a} numbers, not shards of ${Ve}`,"PACKET_FIELD");const s=new fe(e.slice(n,i),"world.shard-list"),o=s.repeat(a/Ve,()=>({id:s.int("id"),language:s.int("language"),population:s.int("population"),buddies:s.int("buddies")}));t.push({host:r,shards:o}),n=i}return t}function Pn(e){return e.trim()!==""&&Number.isFinite(Number(e))}u({name:"world.node-hop-request",description:"The player asks to move off a server that is shutting down.",direction:"toServer",command:"nd",read:()=>({}),write:()=>{}});u({name:"world.node-hop",description:"The server names the server to move to.",direction:"toClient",command:"nd",read:e=>({host:e.string("host")}),write:(e,{host:t})=>e.string(t)});const st={send:"avatar.UserCommXtCommManager.onSendMessage",focusChat:"gui.ChatHistory.setFocusOnMsgText"};function Hi(e,t){const n=new Map;for(const[s,o]of Object.entries(t))n.set(s.toLowerCase(),o);if(n.size===0)return e;let r="",i="";const a=()=>{r+=n.get(i.toLowerCase())??i,i=""};for(const s of e)s===" "||s===" "?(a(),r+=s):i+=s;return a(),r}function Vi(e,t){const n=e.toLowerCase();return t.some(r=>typeof r=="string"?r!==""&&n.includes(r.toLowerCase()):(r.lastIndex=0,r.test(e)))}async function Wi(e,t={}){const{arg:n,fromClass:r,equals:i,exists:a,all:s}=e.flash.rules,o=t.shortcuts??{},l=t.blocked??[],c=r("avatar.UserCommXtCommManager","_mainHud","chatBar","text01_chat","text"),d=[],h=wt(async()=>{for(const m of d.splice(0).reverse())await m().catch(()=>{})});try{d.push(await e.flash.hook(st.send,{when:s(i(n("myMsg"),""),a(c)),replaceArgs:{myMsg:c}})),d.push(await e.flash.override(st.send,async m=>{var p;const[f,g]=m.argList,y=typeof g=="string"?g:"";if(y.trim()!==""&&Vi(y,l)){(p=t.onBlocked)==null||p.call(t,y);return}const v=Hi(y,o);v===y?await m.original():await m.original(f,v)},{sequential:!0}))}catch(m){throw await h(),m}return h}async function Gi(e,t={}){const n=t.style??{},r=e.flash.overlay,i=e.flash.use("gui.GuiManager").$at("mainHud"),a=t.maxLength??await e.flash.use("gui.GuiManager").$at("chatHist","chatMsgText","maxChars").$get().then(c=>typeof c=="number"&&c>0?c:70).catch(()=>70),s={family:n.font??"_sans",size:n.size??13},o=[],l=wt(async()=>{for(const c of o.splice(0).reverse())await c().catch(()=>{})});try{o.push(async()=>{await e.flash.use("gui.GuiManager").setFocusToChatText()});const c=await r.input({replaces:i.$at("chatBar"),placeholder:n.placeholderText??"Say something",maxLength:a,fill:n.background??16777215,stroke:n.border??8141549,cornerRadius:n.cornerRadius??6,padding:6,font:{...s,color:n.text??1120295}});o.push(()=>c.remove());const d=await r.button(n.buttonLabel??"Send",{replaces:i.$at("sendChatBtn"),fill:n.button??8141549,hoverFill:n.buttonHover??9133302,cornerRadius:n.cornerRadius??6,font:{...s,color:n.buttonText??16777215,bold:!0}});o.push(()=>d.remove());let h=!1;const m=async()=>{const p=c.value();if(!(h||p.trim()==="")){h=!0;try{await e.chat.say(p),await c.setValue(""),await c.focus()}finally{h=!1}}};return o.push(c.on("submit",()=>{m()})),o.push(d.on("click",()=>{m()})),o.push(await e.flash.hook(st.focusChat,{skip:!0,phase:"enter",capture:{args:[]}},()=>{c.focus()})),(t.focus??!0)&&await c.focus(),Object.assign(l,{input:c,send:m})}catch(c){throw await l(),c}}const Ki=[16096779,1096065,3900150,15485081,9133302,15680580,1357990,15381256],We=22;async function Xi(e,t={}){const n=t.style??{},r=e.flash.overlay,i=n.nameColors&&n.nameColors.length>0?n.nameColors:Ki,a=t.width??280,s=t.height??200,o={family:n.font??"_sans",size:n.size??12},l=new Map,c=[],d=wt(async()=>{for(const h of c.splice(0).reverse())await Promise.resolve(h()).catch(()=>{})});try{const h=await r.panel({title:t.title??"Chat",x:t.x??12,y:t.y??60,width:a,height:s,resizable:!0,fill:{color:n.background??1120295,alpha:n.backgroundAlpha??.9},stroke:n.border??3621201,titleFill:n.titleBar??2042167,titleHeight:We,titleFont:{...o,color:n.titleText??16777215,bold:!0},...t.onMove?{onMove:t.onMove}:{}});c.push(()=>h.remove());const m=await r.list({parent:h,width:a,height:s-We,fill:null,maxRows:t.maxRows??200,font:{...o,color:n.text??15987958}});c.push(h.on("resize",v=>{var I;(I=t.onResize)==null||I.call(t,v),m.update({width:v.width,height:v.height-We})})),c.push(m.on("link",v=>{const I=l.get(v);if(I){if(t.onNameClick){t.onNameClick(I);return}Yi(e,I.userId)}}));const p=async v=>{let I=null;if(v.kind===ze.free||v.kind===ze.freeSafeChat?I=v.text:v.kind===ze.safeChat&&(I=await e.chat.phrase(v.text).catch(()=>null)??null),I===null)return null;const k=e.room.players.get(v.userId),q=(k==null?void 0:k.avatarName)||(k==null?void 0:k.userName)||`#${v.userId}`,U=String(v.userId);return l.set(U,{userId:v.userId,name:q}),[{text:q,bold:!0,color:i[Math.abs(v.userId)%i.length],link:U},{text:`: ${I}`}]},g=(await Promise.all(e.chat.recent.map(p))).filter(v=>v!==null);g.length>0&&await m.append(...g);let y=Promise.resolve();return c.push(e.chat.onMessage(v=>{y=y.then(async()=>{const I=await p(v);I&&await m.append(I)}).catch(()=>{})})),Object.assign(d,{panel:h,note:v=>m.append({markup:v})})}catch(h){throw await d(),h}}async function Yi(e,t){const n=e.flash.use("avatar.AvatarManager").avatarViewList.$at(String(t)),r=await e.flash.highlight(n,{color:16436245,strength:3});setTimeout(()=>{r()},2e3)}function wt(e){let t=null;return()=>t??=e()}class Ji{constructor(t){this.bridge=t,this.overlay=new Mr(t),this.entities=new yr(this),this.view=new $r(t)}bridge;overlay;entities;view;rules=gr;hookIndex=null;use(t){return M(this.bridge,this.bridge.definition(t),{className:t})}global(t){return M(this.bridge,this.bridge.definition(t))}stage(){return M(this.bridge,this.bridge.stage())}client(){return M(this.bridge,this.bridge.gameClient())}whenReady(){return this.bridge.whenReady()}hooks(t){if(t!==void 0||!this.hookIndex){const n=this.bridge.hookTable(t).then(r=>new mr(r));n.catch(()=>{this.hookIndex===n&&(this.hookIndex=null)}),this.hookIndex=n}return this.hookIndex}async hook(t,n={},r){return pr(this.bridge,await this.hooks(),t,n,r)}async override(t,n,...[r]){return jr(this.bridge,await this.hooks(),t,n,r??{})}style(t,n){return this.bridge.style(S(t),n)}hold(t,n,r={}){return Nt(this.bridge,[{place:t,value:n}],r)}holdAll(t,n={}){return Nt(this.bridge,t,n)}repeat(t,n={}){return fr(this.bridge,t,n)}collect(t,n,r={}){return dr(this.bridge,t,n,r)}async track(t,n,r={}){if(await this.bridge.whenReady(),!this.bridge.features.includes("track"))throw new Error("This game is running a loader from before lists; look for them yourself");const i=r.where===void 0?{target:{kind:"stage"},path:[]}:S(r.where),a=s=>s.filter(o=>o instanceof R).map(o=>M(this.bridge,o.at(),{handle:o}));return this.bridge.track(i,t,{...r.mode!==void 0?{mode:r.mode}:{},...r.everyFrames!==void 0?{everyFrames:r.everyFrames}:{}},({added:s,removed:o})=>n({added:a(s),removed:a(o)}))}async snapshot(t,n={}){if(await this.bridge.whenReady(),!this.bridge.features.includes("snapshot"))throw new Error("This game is running a loader from before pictures; nothing can be drawn");return this.bridge.snapshot(S(t),n)}notes(){return new Tr(this.bridge)}async find(t,n){return await wr(this.bridge,n,t??{})}answering(t,n){return new ur(this.bridge,t,n)}watch(t,n,r){const i=r;let a,s=[],o;if(Array.isArray(t))a="list",o=[...t];else if(Zi(t))a="one",o=[t];else{a="record";const h=t;s=Object.keys(h),o=s.map(m=>h[m])}const l=o.map(S),c=h=>a==="one"?h[0]:a==="list"?h:Object.fromEntries(s.map((m,p)=>[m,h[p]]));let d=null;return this.bridge.watch(l,n,(h,m)=>{const p=h.map(y=>N(this.bridge,y)),f=c(p),g=l.map((y,v)=>(m==null?void 0:m[v])??null);i(f,d,a==="one"?g[0]:c(g)),d=f})}onTick(t,n={}){return this.bridge.tick(n.everyFrames??1,t)}highlight(t,n={}){return this.bridge.highlight(S(t),de(n))}hide(t){return this.bridge.highlight(S(t),de({hide:!0}))}recolor(t,n){const r=n?S(n):{target:{kind:"loader"},path:[]};return this.bridge.highlight(r,{glow:null,...ln(t),hide:!1,pulse:null})}onKey(t,n,r={}){return this.bridge.onKey(br(t,r),i=>Qi(n)({code:i.code,char:i.char,ctrl:i.ctrl,shift:i.shift,alt:i.alt,phase:i.phase}))}}function Qi(e){return t=>{try{const n=e(t);n instanceof Promise&&n.catch(r=>Ht(r))}catch(n){Ht(n)}}}function Ht(e){console.error("phantom.flash.onKey: a listener failed",e)}function Zi(e){try{return S(e),!0}catch{return!1}}const ea={avatarManager:"avatar.AvatarManager"},ta={none:0,game:1,denVolume:2,splash:3,storePet:4,socialGroup:5,socialEmoticon:6,guiAction:7,recycleAccessory:8,recycleDenItem:9,triggerWalkIn:11,genericList:12,clickEmoticon:13,air:14,dynamicCollision:15,dynamicAir:16,dynamicPhantomAir:17,plant:18,stealth:19,adventureInteract:20,darkSoft:21,darkHard:22,fallingPhantom:23};Object.fromEntries(Object.entries(ta).map(([e,t])=>[t,e]));const na="com.sbi.loader.LoaderCache.fetchCDNURL",ra=2e4;class ia{channel;flash;hooks=new Map;constructor(t,n){this.channel=t.content??null,this.flash=n}get available(){return this.channel!==null}async replace(t,n){const r=this.reach(),i=Vt(t);await this.unhook(Ge(i));const a=await r.replace(i,Ke(n)),s=[],o=await this.pointClientAt(i,a.url);return o&&(this.hooks.set(Ge(i),o),s.push("client")),s.push("proxy"),{...a,how:s,stop:()=>this.restore(i).then(()=>{})}}async restore(t){const n=this.reach(),r=Vt(t);return await this.unhook(Ge(r)),n.restore(r)}replacements(){return this.reach().list()}onRequest(t){return this.reach().observe(t)}async replaceOnScreen(t,n,r={}){const{url:i,id:a}=await this.addressOf(n),{refreshFrames:s,...o}=r,l=await this.flash.overlay.image(i,{...o,replaces:s===void 0?t:{place:t,refreshFrames:s}});return{url:i,stop:async()=>{await l.remove(),a&&await this.reach().release(a)}}}async load(t,n={}){const r=this.flash.bridge,i=Ke(t),a=await r.construct("flash.display.Loader"),s=[];try{const o=await r.definition("flash.system.ApplicationDomain").at("currentDomain").get();s.push(()=>o.release());const l=await r.construct("flash.system.LoaderContext",!1,o);s.push(()=>l.release()),await l.at("allowCodeImport").set(n.allowCode===!0).catch(()=>{});const c=this.whenLoaded(a,n.timeoutMs??ra);if(i.kind==="data-url"){const h=await this.decodeInFlash(i.url);s.push(()=>h.release()),await a.at("loadBytes").call(h,l)}else{const h=await this.reach().hold(i);s.push(()=>this.reach().release(h.id)),await a.at("load").call(new ct("flash.net.URLRequest",[h.url]),l)}await c;const d=await a.at("content").get();if(!d)throw new Error("Nothing was loaded");return{content:d,loader:a,unload:async()=>{await a.at("unloadAndStop").call().catch(()=>{}),await d.release().catch(()=>{}),await a.release().catch(()=>{})}}}catch(o){throw await a.release().catch(()=>{}),o}finally{for(const o of s)await o().catch(()=>{})}}async pointClientAt(t,n){if(t.kind==="pattern")return null;const r=aa(t.value);if(!r)return null;const{arg:i,equals:a,startsWith:s,any:o}=this.flash.rules,l=t.kind==="prefix"?s:a;try{return await this.flash.hook(na,{when:o(l(i("assetPath"),r),l(i("assetPath"),`/${r}`)),replaceReturn:n})}catch{return null}}async unhook(t){const n=this.hooks.get(t);n&&(this.hooks.delete(t),await n().catch(()=>{}))}async addressOf(t){const n=Ke(t);if(n.kind==="data-url")return{url:n.url,id:null};const r=await this.reach().hold(n);return{url:r.url,id:r.id}}async decodeInFlash(t){const n=t.indexOf(",");if(n===-1||t.slice(0,n).indexOf(";base64")===-1)throw new Error("Only base64 data: URLs can be loaded into the client");const r=await this.flash.bridge.definition("phantom.overlay.Base64").at("decode").call(t.slice(n+1));if(!r)throw new Error("The loader could not decode those bytes");return r}whenLoaded(t,n){const r=t.at("contentLoaderInfo");return new Promise((i,a)=>{const s=[],o=d=>{clearTimeout(l);for(const h of s.splice(0))h().catch(()=>{});d?a(d):i()},l=setTimeout(()=>o(new Error(`Flash did not load those bytes within ${n}ms`)),n),c=(d,h)=>r.listen(d,()=>o(h===null?null:new Error(h))).then(m=>s.push(m),m=>o(m));c("complete",null),c("ioError","Flash could not read those bytes"),c("securityError","Flash refused those bytes")})}reach(){if(!this.channel)throw new Error("This game cannot replace content: it was made without a content origin");return this.channel}}function Ge(e){return`${e.kind}:${e.value}`}function aa(e){let t=e.charAt(0)==="/"?e.slice(1):e;const n=t.indexOf("?");n!==-1&&(t=t.slice(0,n)),t.slice(0,8)==="content/"&&(t=t.slice(8));const r=t.indexOf("/"),i=r===-1?t:t.slice(0,r);return r!==-1&&i.length>0&&sa(i)&&(t=t.slice(r+1)),t}function sa(e){for(const t of e)if(t<"0"||t>"9")return!1;return e.length>0}function Vt(e){const t=typeof e=="string"?{kind:"path",value:e}:e;if(!t||typeof t.value!="string"||!t.value)throw new TypeError("A replacement matches a path, a prefix or a pattern");const n=t.kind;if(n!=="path"&&n!=="prefix"&&n!=="pattern")throw new TypeError(`${n} is not path, prefix or pattern`);const r=t.value.charAt(0)==="/"?t.value:`/${t.value}`;return{kind:n,value:r}}function Ke(e){if(typeof e=="string")return e.slice(0,5).toLowerCase()==="data:"?{kind:"data-url",url:e}:{kind:"file",path:e};if(e instanceof ArrayBuffer)return{kind:"bytes",bytes:new Uint8Array(e)};if(ArrayBuffer.isView(e)){const t=e;return{kind:"bytes",bytes:new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}}if(e&&typeof e=="object"){const t="contentType"in e&&e.contentType?e.contentType:null,n=t?{contentType:t}:{};if("bytes"in e){const r=e.bytes,i=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!(i instanceof Uint8Array))throw new TypeError("bytes are a Uint8Array");return{kind:"bytes",bytes:i,...n}}if("dataUrl"in e&&typeof e.dataUrl=="string")return{kind:"data-url",url:e.dataUrl,...n};if("file"in e&&typeof e.file=="string")return{kind:"file",path:e.file,...n}}throw new TypeError("A source is bytes, a data: URL, or the path of a file on this computer")}const P={definitionByName:"GETDEFINITIONBYNAME",resourceStack:"com.sbi.loader.ResourceStack",guiManager:"gui.GuiManager",loadProgress:"loadProgress.LoadProgress",denEditor:"gui.DenEditor",fonts:"gui.Fonts",palette:"com.sbi.graphics.PaletteHelper",colorTable:"gui.ColorTable",avatarManager:"avatar.AvatarManager"},oa={message:"com.sbi.popup.SBMessage",ok:"com.sbi.popup.SBOkPopup",okCancel:"com.sbi.popup.SBOkCancelPopup",yesNo:"com.sbi.popup.SBYesNoPopup",titled:"com.sbi.popup.SBStandardTitlePopup",parchment:"com.sbi.popup.SBParchmentPopup"},Ln={ink:1118483,line:3816e3,light:15790322,muted:10000543,accent:8141549,danger:15680580,size:12,cornerRadius:4},Se={ink:4403228,line:9071167,light:16643032,muted:9402972,accent:3123423,danger:13369344,size:11,cornerRadius:8},Xe={game:28,phantom:24},ca=18;function Ie(e){return(...t)=>{try{const n=e(...t);n instanceof Promise&&n.catch(Wt)}catch(n){Wt(n)}}}function Wt(e){console.error("phantom.ui: a listener failed",e)}const la={game:110,phantom:96},ot="_sans";function ua(e,t=ot){return{skin:e,font:t,...e==="game"?Se:Ln}}const da={PopupSkin:"The plain popup frame: `ba` (its `t`, `m` and `b` slices) and `c`, its content box.",PopupContent:"What a plain popup shows: a `text` field the popup sizes itself around.",OkPopupSkin:"The frame of a popup with one button.",OkPopupContent:"An OK button (`okBtn`) and the `text` above it.",YesNoPopupSkin:"The frame of a popup with two buttons.",YesNoPopupContent:"Yes (`yesBtn`) and No (`noBtn`), and the `text` above them.",okCancelPopupContent:"OK (`okCancelBtn`) and Cancel (`cancelBtn`).",ConfirmSkin:"The frame the client asks you to confirm something in.",Tooltip:"The client's own tooltip (`gui.ToolTipPopup`): `txt`, and `l`, `m` and `r`.",HelpTxtBubble:"The bubble the client points at something it is explaining.",closeBtn:"The round close button in the corner of the client windows.",scrollbar2:"A scrollbar: `track`, `handle`, `topBtn` and `botBtn`.",BuddyListPopup:"The buddy list window's frame.",BuddyListContent:"What the buddy list shows inside that frame.",BD_AvatarEditorSkin:"The frame of the avatar editor's own dialog.",BD_AvatarEditorContent:"What that dialog shows.",DenEditorAsset:"The whole den editor, as the client builds it.",MySettings:"The settings window.",MainHud:"The whole HUD.",FreeNameBar:"The name bar above a player who is not a member.",memberNameBar:"The name bar above a member.",AnimsTitleBanner:"The banner the client puts a title in.",ChatBalloonAsset:"A chat balloon.",Cursor:"The client's own mouse cursor.",QuestPickupIcon:"The icon an adventure shows over something to pick up.",MinigameLobbySkin:"A minigame lobby's frame.",MinigameLobbyContent:"What a minigame lobby shows.",BroadcastPopupSkin:"The frame an announcement is shown in.",BroadcastPopupContent:"What an announcement shows.",DenLockPopupSkin:"The frame of the den's lock settings.",DenLockPopupContent:"What the den lock settings show.",ReportRulesPopupSkin:"The frame of the report window's rules.",ReportRulesPopupContent:"What the report rules show."},ha=/^[A-Za-z_][A-Za-z0-9_]*$/;function Gt(e){if(!ha.test(e))throw new TypeError(`"${e}" is not a symbol name: a symbol is named in letters, digits and underscores`);return e}const Kt={gui:{className:P.guiManager,path:["guiLayer"]},hud:{className:P.guiManager,path:["mainHud"]},room:{className:P.avatarManager,path:["playerAvatarWorldView","parent"]},avatarEditor:{className:P.guiManager,path:["avatarEditor","avEditor"]},denEditor:{className:P.denEditor,path:["staticEditor"]}},Xt="stage",Yt={avatarEditor:{open:"gui.AvatarEditor.init",close:"gui.AvatarEditor.destroy",spot:"avatarEditor"},denEditor:{open:"gui.DenEditor.init",close:"gui.DenEditor.destroy",spot:"denEditor"},settings:{open:"gui.MySettings.init",close:"gui.MySettings.destroy",spot:null},buddyList:{open:"buddy.BuddyList.init",close:"buddy.BuddyList.destroy",spot:null},petCreator:{open:"gui.PetCreator.init",close:"gui.PetCreator.destroy",spot:null},achievements:{open:"gui.AchievementViewer.init",close:"gui.AchievementViewer.destroy",spot:null},bulletinBoard:{open:"gui.BulletinBoard.init",close:"gui.BulletinBoard.destroy",spot:null},playerSearch:{open:"gui.PlayerSearch.init",close:"gui.PlayerSearch.destroy",spot:null},recycle:{open:"gui.RecycleItems.init",close:"gui.RecycleItems.destroy",spot:null},trade:{open:"gui.TradeManager.init",close:"gui.TradeManager.destroy",spot:null},petInventory:{open:"gui.PetInventory.init",close:"gui.PetInventory.destroy",spot:null},reportPlayer:{open:"gui.ReportAPlayer.init",close:"gui.ReportAPlayer.destroy",spot:null},serverSelector:{open:"gui.ServerSelector.init",close:"gui.ServerSelector.destroy",spot:null}},ma={ok:0,yesNo:1,continueExit:2,continue:3};function ga(e,t,n={}){const r={slot:"layer"},i={slot:"callback"},a=n.name??null,s=oa[e];switch(e){case"message":return{className:s,args:[r,{slot:"skin"},t,!0,!0,n.modal??!1,n.draggable??!0,n.darken??!1,a]};case"ok":return{className:s,args:[r,t,n.darken??!0,null,!0,!0,n.modal??!0,n.draggable??!1,a]};case"yesNo":return{className:s,args:[r,t,n.darken??!0,i,null,!0,!0,n.modal??!0,n.draggable??!1,a]};case"okCancel":return{className:s,args:[r,t,n.darken??!0,i,null]};case"titled":return{className:s,args:[r,t,n.title??null,n.mediaId??370,i,!0,n.darken??!0]};case"parchment":return{className:s,args:[r,ma[n.buttons??"ok"],t,n.darken??!0,i,null]}}}function Jt(e){const t=Math.max(1,Math.floor(e.columns)),n=[];for(let r=0;r<Math.max(0,Math.floor(e.count));r++){const i=Math.floor(r/t),a=r%t;n.push({index:r,row:i,column:a,x:a*(e.tileWidth+e.gap),y:i*(e.tileHeight+e.gap),width:e.tileWidth,height:e.tileHeight})}return n}function pa(e,t){const n=t.gap,r=e.length;if(r===0)return[];const i=(t.width+n)/r;return e.map((a,s)=>{const o=Math.round(s*i),l=s===r-1?t.width+n:Math.round((s+1)*i);return{index:s,value:a,x:o,width:Math.max(0,l-o-n)}})}function fa(e){const t=Math.max(0,e.contentHeight-e.viewHeight),n=Math.min(t,Math.max(0,e.offset)),r=e.minThumb??16,i=e.contentHeight>0?e.viewHeight/e.contentHeight:1,a=Math.max(Math.min(e.trackHeight,r),Math.min(e.trackHeight,Math.round(e.trackHeight*i))),s=e.trackHeight-a;return{offset:n,max:t,thumbY:t>0?Math.round(n/t*s):0,thumbHeight:a}}class ya{bridge;flash;drawn=new Set;popups=new Set;symbolMaker=null;gameFont=null;defaultSkin="phantom";popup;constructor(t,n){this.bridge=t.flash,this.flash=n,this.popup=new wa((r,i,a,s,o)=>this.openPopup(r,i,a,s,o),()=>this.clear())}get skin(){return this.defaultSkin}set skin(t){this.defaultSkin=t}async theme(t){const n=t??this.defaultSkin;return ua(n,n==="game"?await this.clientFont():ot)}symbols(){return Object.entries(da)}async hasSymbol(t){const n=Gt(t);try{return await this.bridge.definition(P.resourceStack).at("hudAssetsLoaderInfo","applicationDomain","hasDefinition").call(n)===!0}catch{return!1}}async symbol(t,n={}){const r=Gt(t),i=await this.flash.overlay.group({x:n.x??0,y:n.y??0,...n.scale===void 0?{}:{scale:n.scale},...n.visible===void 0?{}:{visible:n.visible}});let a;try{a=await(await this.maker()).at("apply").call(null,[r,n.localize===!0]),await(await this.nodeObject(i)).at("addChild").call(a)}catch(l){throw await i.remove(),l}await i.update({...n.parent===void 0?{}:{parent:O(n.parent)},...n.host===void 0?{}:{host:n.host===null?null:this.placeOf(n.host)},...n.replaces===void 0?{}:{replaces:n.replaces===null?null:this.placeOf(n.replaces)}});const s=a.at();return this.widget(i,n.skin??this.defaultSkin,{name:r,object:a,on:async(l,c)=>{const d=await s.listen(ba[l],()=>c());return async()=>{await d()}},size:async()=>({width:await a.at("width").get()??0,height:await a.at("height").get()??0})})}async window(t={}){const n=t.skin??this.defaultSkin,r=await this.theme(n),i={width:t.width??280,height:t.height??200},a=n==="game",s=await this.flash.overlay.panel({x:t.x??40,y:t.y??40,width:i.width,height:i.height,title:t.title??"",titleHeight:a?30:24,draggable:t.draggable!==!1,resizable:t.resizable===!0&&!a,cornerRadius:r.cornerRadius,fill:a?{color:r.light,alpha:0}:{color:r.ink,alpha:.94},stroke:a?null:r.line,titleFill:a?{color:r.line,alpha:.004}:r.line,titleFont:{family:r.font,size:r.size+1,bold:!0,color:a?r.ink:r.light},...t.parent?{parent:O(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}}),o=a?await this.dressWindow(s,i):{...i,top:0};a&&await s.update({width:o.width,height:o.height,titleHeight:Math.round(o.top)+ca});const l=new Set,c=this.widget(s,n,{body:s,width:o.width,height:o.height,setTitle:d=>s.update({title:d}),onClose:d=>(l.add(d),async()=>{l.delete(d)}),onMove:d=>{const h=s.on("move",d);return async()=>{await h()}}});return t.closable!==!1&&(await this.flash.overlay.button("x",{parent:s,x:o.width-(a?26:24),y:2,width:18,height:16,cornerRadius:r.cornerRadius,fill:a?{color:r.line,alpha:.2}:r.line,hoverFill:{color:r.danger,alpha:.8},font:{family:r.font,size:r.size,bold:!0,color:a?r.ink:r.light}})).on("click",()=>{c().then(()=>l.forEach(h=>h()))}),c}async button(t,n={}){const r=n.skin??this.defaultSkin,i=await this.theme(r),a=await this.flash.overlay.button(t,{...this.box(n,{width:la[r],height:Xe[r]}),...oe(i,n.primary===!0),cornerRadius:i.cornerRadius,...n.disabled===void 0?{}:{disabled:n.disabled},font:{family:i.font,size:i.size,bold:!0,color:n.primary===!0||r==="phantom"?i.light:i.ink}});return this.widget(a,r,{setLabel:s=>a.setLabel(s),setDisabled:s=>a.setDisabled(s),onClick:s=>{const o=a.on("click",Ie(s));return async()=>{await o()}}})}async label(t,n={}){const r=n.skin??this.defaultSkin,i=await this.theme(r),a=await this.flash.overlay.text(t,{x:n.x??0,y:n.y??0,...n.parent?{parent:O(n.parent)}:{},...n.visible===void 0?{}:{visible:n.visible},centered:n.centered===!0,font:{family:i.font,size:n.heading===!0?i.size+3:i.size,bold:n.heading===!0,color:n.muted===!0?i.muted:r==="game"?i.ink:i.light},...n.background===!0?{background:r==="game"?{color:i.light,alpha:.9}:{color:i.ink,alpha:.7},padding:4}:{}});return this.widget(a,r,{setText:s=>a.update({text:s})})}async input(t={}){const n=t.skin??this.defaultSkin,r=await this.theme(n),i=await this.flash.overlay.input({...this.box(t,{width:200,height:Xe[n]}),...t.value===void 0?{}:{value:t.value},...t.placeholder===void 0?{}:{placeholder:t.placeholder},...t.maxLength===void 0?{}:{maxLength:t.maxLength},...t.multiline===void 0?{}:{multiline:t.multiline},...t.disabled===void 0?{}:{disabled:t.disabled},fill:n==="game"?r.light:16777215,stroke:r.line,cornerRadius:r.cornerRadius,font:{family:r.font,size:r.size,color:n==="game"?r.ink:1120295}});return this.widget(i,n,{value:()=>i.value(),setValue:a=>i.setValue(a),focus:()=>i.focus(),onChange:a=>{const s=i.on("change",Ie(a));return async()=>{await s()}},onSubmit:a=>{const s=i.on("submit",Ie(a));return async()=>{await s()}}})}async checkbox(t,n={}){const r=n.skin??this.defaultSkin,i=await this.theme(r),a=await this.flash.overlay.group({x:n.x??0,y:n.y??0,...n.parent?{parent:O(n.parent)}:{},...n.visible===void 0?{}:{visible:n.visible}});let s=n.checked===!0;const o=await this.flash.overlay.button(s?"x":"",{parent:a,width:14,height:14,cornerRadius:Math.min(3,i.cornerRadius),fill:r==="game"?i.light:{color:i.ink,alpha:.9},hoverFill:r==="game"?16777215:{color:i.line,alpha:.9},stroke:i.line,font:{family:i.font,size:i.size,bold:!0,color:i.accent}});await this.flash.overlay.text(t,{parent:a,x:20,y:0,font:{family:i.font,size:i.size,color:r==="game"?i.ink:i.light}});const l=new Set,c=async d=>{s=d,await o.setLabel(d?"x":"")};return o.on("click",()=>{c(!s).then(()=>l.forEach(d=>d(s)))}),this.widget(a,r,{checked:()=>s,setChecked:c,onChange:d=>(l.add(d),async()=>{l.delete(d)})})}async dropdown(t){var n;const r=t.skin??this.defaultSkin,i=await this.theme(r),a=t.width??140,s=t.height??Xe[r],o=await this.flash.overlay.group({x:t.x??0,y:t.y??0,...t.parent?{parent:O(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}});let l=[...t.choices],c=t.value??((n=l[0])==null?void 0:n.value)??null;const d=g=>{var y;return((y=l.find(v=>v.value===g))==null?void 0:y.label)??t.placeholder??"Choose..."},h=await this.flash.overlay.button(d(c),{parent:o,width:a,height:s,cornerRadius:i.cornerRadius,...oe(i,!1),font:{family:i.font,size:i.size,color:r==="game"?i.ink:i.light}}),m=await this.flash.overlay.list({parent:o,y:s+2,width:a,height:Math.min(140,Math.max(20,l.length*16+8)),visible:!1,fill:r==="game"?i.light:{color:i.ink,alpha:.96},stroke:i.line,cornerRadius:i.cornerRadius,rows:l.map(g=>g.label),font:{family:i.font,size:i.size,color:r==="game"?i.ink:i.light}});let p=!1;const f=new Set;return h.on("click",()=>{p=!p,p?m.show():m.hide()}),m.on("row",g=>{const y=l[g];p=!1,m.hide(),y&&(c=y.value,h.setLabel(y.label).then(()=>f.forEach(v=>v(y.value))))}),this.widget(o,r,{value:()=>c,setValue:async g=>{c=g,await h.setLabel(d(g))},setChoices:async g=>{l=[...g],await m.setRows(l.map(y=>y.label)),await h.setLabel(d(c))},onChange:g=>(f.add(g),async()=>{f.delete(g)})})}async tabs(t){var n;const r=t.skin??this.defaultSkin,i=await this.theme(r),a=t.width??260,s=t.tabHeight??22,o=await this.flash.overlay.group({x:t.x??0,y:t.y??0,...t.parent?{parent:O(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}}),l=pa(t.tabs.map(f=>f.value),{width:a,gap:2});let c=t.value??((n=t.tabs[0])==null?void 0:n.value)??"";const d=new Map,h=new Map,m=new Set;for(const f of l){const g=t.tabs[f.index];h.set(g.value,await this.flash.overlay.button(g.label,{parent:o,x:f.x,width:f.width,height:s,cornerRadius:i.cornerRadius,...oe(i,g.value===c),font:{family:i.font,size:i.size,bold:g.value===c,color:g.value===c||r==="phantom"?i.light:i.ink}})),d.set(g.value,await this.flash.overlay.group({parent:o,y:s+4,visible:g.value===c}))}const p=async f=>{if(d.has(f)){c=f;for(const[g,y]of d)await(g===f?y.show():y.hide());for(const[g,y]of h)await y.update({...oe(i,g===f),font:{family:i.font,size:i.size,bold:g===f,color:g===f||r==="phantom"?i.light:i.ink}})}};for(const[f,g]of h)g.on("click",()=>{p(f).then(()=>m.forEach(y=>y(f)))});return this.widget(o,r,{current:()=>c,select:p,body:f=>{const g=d.get(f);if(!g)throw new TypeError(`There is no tab called "${f}"`);return g},onSelect:f=>(m.add(f),async()=>{m.delete(f)})})}async list(t={}){const n=t.skin??this.defaultSkin,r=await this.theme(n),i=await this.flash.overlay.list({...this.box(t,{width:240,height:160}),...t.rows===void 0?{}:{rows:[...t.rows]},...t.maxRows===void 0?{}:{maxRows:t.maxRows},fill:n==="game"?r.light:{color:r.ink,alpha:.85},stroke:r.line,cornerRadius:r.cornerRadius,font:{family:r.font,size:r.size,color:n==="game"?r.ink:r.light}});return this.widget(i,n,{setRows:a=>i.setRows([...a]),append:(...a)=>i.append(...a),onRow:a=>{const s=i.on("row",Ie(a));return async()=>{await s()}}})}async grid(t){const n=t.skin??this.defaultSkin,r=await this.theme(n),i={columns:t.columns??4,tileWidth:t.tileWidth??48,tileHeight:t.tileHeight??48,gap:t.gap??4},a=await this.flash.overlay.group({x:t.x??0,y:t.y??0,...t.parent?{parent:O(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}}),s=new Set,o=[],l=async c=>{for(const h of o.splice(0))await h.remove();const d=Jt({count:c.length,...i});for(const h of d){const m=c[h.index],p=await this.flash.overlay.button(m.label??"",{parent:a,x:h.x,y:h.y,width:h.width,height:h.height,cornerRadius:r.cornerRadius,fill:m.color??(n==="game"?r.light:{color:r.ink,alpha:.9}),hoverFill:m.color??(n==="game"?16777215:r.line),pressedFill:m.color??r.accent,stroke:r.line,...m.disabled===void 0?{}:{disabled:m.disabled},font:{family:r.font,size:r.size-2,color:n==="game"?r.ink:r.light}});p.on("click",()=>s.forEach(f=>f(m.value,h.index))),o.push(p),m.image!==void 0&&o.push(await this.flash.overlay.image(m.image,{parent:a,x:h.x+2,y:h.y+2,width:h.width-4,height:h.height-4}))}};return await l(t.items),this.widget(a,n,{setItems:l,onSelect:c=>(s.add(c),async()=>{s.delete(c)})})}async scroll(t={}){const n=t.skin??this.defaultSkin,r=await this.theme(n),i=t.width??220,a=t.height??120,s=t.step??32,o=await this.flash.overlay.panel({x:t.x??0,y:t.y??0,width:i,height:a,titleHeight:0,draggable:!1,cornerRadius:r.cornerRadius,fill:n==="game"?{color:r.light,alpha:.9}:{color:r.ink,alpha:.85},stroke:r.line,...t.parent?{parent:O(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}}),l=await this.flash.overlay.group({parent:o,x:0,y:0});let c=t.contentHeight??a,d=0;const h=async m=>{d=fa({contentHeight:c,viewHeight:a,offset:m,trackHeight:a}).offset,await l.update({y:-d})};for(const[m,p,f]of[["^",-s,0],["v",s,a-16]])(await this.flash.overlay.button(m,{parent:o,x:i-16,y:f,width:14,height:14,cornerRadius:Math.min(3,r.cornerRadius),...oe(r,!1),font:{family:r.font,size:r.size-2,bold:!0,color:n==="game"?r.ink:r.light}})).on("click",()=>{h(d+p)});return this.widget(o,n,{body:l,offset:()=>d,scrollTo:h,setContentHeight:async m=>{c=m,await h(d)}})}async tooltip(t={}){const n=t.skin??this.defaultSkin,r=t.text??"";if(n==="game"){const s=await this.clientTooltip(r,t);if(s)return s}const i=await this.theme(n),a=await this.flash.overlay.text(r,{x:t.x??0,y:t.y??0,visible:t.visible===!0,...t.parent?{parent:O(t.parent)}:{},background:n==="game"?{color:i.light,alpha:.95}:{color:i.ink,alpha:.92},padding:4,font:{family:i.font,size:i.size,color:n==="game"?i.ink:i.light}});return this.widget(a,n,{setText:s=>a.update({text:s}),showAt:async(s,o)=>{await a.update({x:s,y:o,visible:!0})}})}async progress(t={}){const n=t.skin??this.defaultSkin,r=await this.theme(n),i=t.width??200,a=t.height??16,s=await this.flash.overlay.group({x:t.x??0,y:t.y??0,...t.parent?{parent:O(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}});await this.flash.overlay.rect({parent:s,width:i,height:a,cornerRadius:r.cornerRadius,fill:n==="game"?r.light:{color:r.ink,alpha:.9},stroke:r.line});let o=Qt(t.value??0);const l=await this.flash.overlay.rect({parent:s,width:Math.round(i*o),height:a,cornerRadius:r.cornerRadius,fill:r.accent}),c=await this.flash.overlay.text(t.label??"",{parent:s,x:Math.round(i/2),y:Math.round(a/2),centered:!0,font:{family:r.font,size:r.size-1,bold:!0,color:n==="game"?r.ink:r.light}});return this.widget(s,n,{value:()=>o,setValue:async d=>{o=Qt(d),await l.update({width:Math.round(i*o)})},setLabel:d=>c.update({text:d})})}async colors(t={}){const n=t.skin??this.defaultSkin,r=t.columns??10,i=t.swatchWidth??24,a=t.swatchHeight??30,{values:s,indexes:o}=await this.palette(t.palette??1),l=new Set;let c=t.value??o[0]??0;const d=p=>{c=p,l.forEach(f=>f(p,s[p]??0))},h=Math.max(1,Math.ceil(o.length/r)),m=n==="game"?await this.clientColorTable({columns:r,rows:h,width:r*i,height:h*a,values:s,indexes:o,current:c,options:t,tell:d}):await this.swatchGrid({columns:r,swatchWidth:i,swatchHeight:a,values:s,indexes:o,options:t,tell:d});return this.widget(m,n,{value:()=>c,onPick:p=>(l.add(p),async()=>{l.delete(p)})})}async paletteValues(t="game"){const{values:n,indexes:r}=await this.palette(t);return r.map(i=>n[i]??0)}places(){const t=Object.keys(Kt);return[Xt,...t,...Ia]}place(t){if(t===Xt)return this.bridge.stage();const n=Kt[t];return n?this.bridge.definition(n.className).at(...n.path):this.bridge.definition(P.guiManager).at("mainHud",t)}async attach(t,n){const r=O(n);return await this.flash.overlay.attach(this.placeOf(t),r),()=>r.remove()}async replace(t,n){const r=O(n);return await this.flash.overlay.replace(this.placeOf(t),r),()=>r.remove()}async hide(t){const n=await this.flash.hide(this.placeOf(t)),r=async()=>{this.drawn.delete(r),await n()};return this.drawn.add(r),r}piece(t,...n){return this.pieceOf(this.placeOf(t),n)}async feed(t,n,r={}){return typeof n=="function"?this.deferredFeed(t,n,r):this.insideFeed(t,n,r)}async insideFeed(t,n,r){if(!Object.keys(n).length)throw new TypeError(`A feed of ${t} names no argument to change`);let i=null,a=0;const s=await this.flash.hook(t,{phase:"enter",capture:{args:!0},replaceArgs:n,...r.when===void 0?{}:{when:r.when},...r.first===void 0?{}:{first:r.first},...r.every===void 0?{}:{every:r.every},...r.perFrame===void 0?{}:{perFrame:r.perFrame}},o=>{a+=1,i={method:t,call:o.call,args:[...o.argList],named:{...o.args},on:this.pieceOf(this.bridge.stage(),[])}});return this.feedOf(t,!0,s,()=>a,()=>i)}async deferredFeed(t,n,r){if(r.deferred!==!0)throw new TypeError(`A feed of ${t} was given a function, which cannot run inside the call: the client's method is skipped and run again once the function answers. A builder whose result the client uses in the same breath comes up empty that way. Give the arguments themselves to change them inside the call, or set "deferred" to say the waiting is understood.`);let i=null,a=0;const s=async c=>{a+=1;const d={method:t,call:c.call,args:[...c.argList],named:{...c.args},on:this.pieceOf(he(c.self)??this.bridge.stage(),[])};i=d;const h=await n(d);if(!h){await c.original();return}const m=[...d.args];for(const[p,f]of Object.entries(h)){const g=/^\d+$/.test(p)?Number(p):c.hook.parameters.findIndex(y=>y.name===p);if(g<0||g>=m.length){const y=c.hook.parameters.map(v=>v.name).join(", ");throw new TypeError(`${t} has no argument "${p}" (its arguments: ${y})`)}m[g]=f}await c.original(...m)},o={};r.when!==void 0&&(o.when=r.when),r.first!==void 0&&(o.first=r.first),r.every!==void 0&&(o.every=r.every),r.sequential!==void 0&&(o.sequential=r.sequential),r.perFrame!==void 0&&(o.perFrame=r.perFrame),r.returns!==void 0&&(o.returns=r.returns);const l=await this.flash.override(t,s,o);return this.feedOf(t,!1,l,()=>a,()=>i)}feedOf(t,n,r,i,a){const s=async()=>{this.drawn.delete(s),await r()};this.drawn.add(s);const o=s;return Object.defineProperty(o,"method",{value:t,enumerable:!0}),Object.defineProperty(o,"inside",{value:n,enumerable:!0}),Object.defineProperty(o,"calls",{get:i,enumerable:!0}),Object.defineProperty(o,"last",{value:a,enumerable:!0}),o}screens(){return Object.keys(Yt)}onScreen(t,n){const r=Yt[t];let i=!0;const a=[];return(async()=>{for(const[o,l]of[[r.open,!0],[r.close,!1]]){const c=await this.flash.hook(o,{phase:l?"exit":"enter",capture:{args:[]}},()=>n({name:t,open:l,spot:r.spot}));if(!i){await c();return}a.push(c)}})().catch(o=>{console.error(`phantom.ui.onScreen could not hook ${t}: ${Zt(o)}`)}),()=>{i=!1;for(const o of a.splice(0))o().catch(()=>{})}}async clear(){for(const t of[...this.popups])await t().catch(()=>{});for(const t of[...this.drawn])await t().catch(()=>{})}pieceOf(t,n){const r=he(t);if(!r)throw new TypeError("Expected a place in the client, or one of Phantom's spots");const i=r.at(...n);return{place:i,at:(...s)=>this.pieceOf(i,s),exists:async()=>{try{const s=await i.get();return s!=null}catch{return!1}},get:async(...s)=>{try{const o=await i.at(...s).get();return N(this.bridge,o)??null}catch{return null}},set:(s,o)=>i.at(...typeof s=="string"?[s]:s).set(o),read:async(...s)=>{const o=await Promise.all(s.map(c=>i.at(c).get().catch(()=>null))),l={};return s.forEach((c,d)=>{l[c]=N(this.bridge,o[d]??null)}),l},call:async(s,...o)=>{const l=await Z(this.bridge,o);return N(this.bridge,await i.at(s).call(...l))},on:async(s,o)=>{const l=await i.listen(s,d=>o(N(this.bridge,d))),c=async()=>{this.drawn.delete(c),await l()};return this.drawn.add(c),c},attach:s=>this.attach(i,s),replace:s=>this.replace(i,s),hide:()=>this.hide(i),use:()=>M(this.bridge,i)}}widget(t,n,r){const i=async()=>{this.drawn.delete(i),await t.remove()};this.drawn.add(i);const a={skin:n,node:t,move:(s,o)=>t.update({x:s,y:o}),show:()=>t.show(),hide:()=>t.hide(),remove:i,...r};for(const[s,o]of Object.entries(a))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0});return i}box(t,n){return{x:t.x??0,y:t.y??0,width:t.width??n.width,height:t.height??n.height,...t.parent?{parent:O(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}}}placeOf(t){return typeof t=="string"?this.place(t):t}maker(){if(!this.symbolMaker){const t=this.bridge.definition(P.definitionByName).get().then(n=>{if(!n)throw new TypeError("This client has no GETDEFINITIONBYNAME");return n});t.catch(()=>{this.symbolMaker===t&&(this.symbolMaker=null)}),this.symbolMaker=t}return this.symbolMaker}nodeObject(t){return new Q(this.bridge,{kind:"overlay"},[]).at("getChildByName").call(`phantomNode${t.node}`)}clientFont(){if(!this.gameFont){const t=this.bridge.definition(P.fonts),n=(async()=>{for(const r of[["defaultFontFormat","font"],["defaultFont","fontName"]])try{const i=await t.at(...r).get();if(typeof i=="string"&&i.length>0)return i}catch{}return ot})();n.catch(()=>{this.gameFont===n&&(this.gameFont=null)}),this.gameFont=n}return this.gameFont}async frameOnly(t){const n=await t.at("numChildren").get()??0;for(let r=0;r<Math.min(n,32);r+=1){const i=await t.at("getChildAt").call(r);try{await i.at("name").get()!=="ba"&&await i.at("visible").set(!1)}finally{await this.bridge.release([i]).catch(()=>{})}}}async dressWindow(t,n){try{const i=await(await this.maker()).at("apply").call(null,["PopupSkin",!1]),a=i.at("ba"),s=await a.at("t","height").get()??0,o=await a.at("b","height").get()??0,l=Math.max(0,n.height-s-o);await a.at("m","height").set(l),await a.at("m","y").set(-(l/2)),await a.at("t","y").set(-(l/2)-s),await a.at("b","y").set(l/2);const c=await i.at("width").get()??n.width,d=await i.at("height").get()??n.height;return await i.at("x").set(c/2),await i.at("y").set(d/2),await this.frameOnly(i),await(await this.nodeObject(t)).at("addChildAt").call(i,0),{width:c,height:d,top:s}}catch{return await t.update({fill:{color:Se.light,alpha:.96},stroke:{color:Se.line,width:2},titleFill:Se.line}),{...n,top:0}}}async clientTooltip(t,n){let r;try{r=await this.symbol("Tooltip",{skin:"game",x:n.x??0,y:n.y??0,visible:n.visible===!0,...n.parent?{parent:n.parent}:{}})}catch{return null}const i=async a=>{await r.object.at("setToolTipText").call(a)};try{t&&await i(t)}catch{return await r.remove(),null}return Object.assign(r,{setText:i,showAt:async(a,s)=>{await r.node.update({x:a,y:s,visible:!0})}})}async palette(t){const n=this.bridge.definition(P.palette),r=await n.at("gamePalette").get()??[];if(!r.length)throw new TypeError("The client has no palette yet: it is set as the game loads");if(t==="game")return{values:r,indexes:r.map((a,s)=>s)};const i=await n.at(t===1?"avatarPalette1":"avatarPalette2").get()??[];return{values:r,indexes:i.length?i:r.map((a,s)=>s)}}async clientColorTable(t){const n=await this.flash.overlay.group({x:t.options.x??0,y:t.options.y??0,...t.options.parent?{parent:O(t.options.parent)}:{},...t.options.visible===void 0?{}:{visible:t.options.visible}}),r=await this.bridge.construct(P.colorTable);return await r.at("init").call(0,t.width,t.height,t.columns,t.rows,t.values,t.indexes,t.current,(a,s)=>t.tell(Number(s)),-1),await(await this.nodeObject(n)).at("addChild").call(r),n}async swatchGrid(t){const n=await this.flash.overlay.group({x:t.options.x??0,y:t.options.y??0,...t.options.parent?{parent:O(t.options.parent)}:{},...t.options.visible===void 0?{}:{visible:t.options.visible}}),r=Jt({count:t.indexes.length,columns:t.columns,tileWidth:t.swatchWidth,tileHeight:t.swatchHeight,gap:1});for(const i of r){const a=t.indexes[i.index];(await this.flash.overlay.button("",{parent:n,x:i.x,y:i.y,width:i.width,height:i.height,cornerRadius:2,fill:t.values[a]??0,hoverFill:t.values[a]??0,stroke:{color:Ln.line,alpha:.6}})).on("click",()=>t.tell(a))}return n}openPopup(t,n,r,i,a){let s=()=>{};const o=new Promise(g=>{s=g});let l=null,c=!1,d=null;const h=g=>{c||(c=!0,d&&clearTimeout(d),d=null,this.popups.delete(p),s(g))},m=()=>{c||d||(d=setTimeout(()=>h(a),va))},p=async()=>{const g=l;l=null,h(a),g&&await g.at("destroy").call().catch(()=>{})};this.popups.add(p);const f=ga(t,n,r);return(async()=>{const g=this.bridge.definition(r.layer==="load"?P.loadProgress:P.guiManager).at(r.layer==="load"?"loadLayer":"guiLayer"),y=[];for(const I of f.args){if(I!==null&&typeof I=="object"){if(I.slot==="layer")y.push(await g.get());else if(I.slot==="callback")y.push((...k)=>h(i(k[0]??null)));else{const k=await this.maker();y.push(await k.at("apply").call(null,["PopupSkin",!1]))}continue}y.push(I)}const v=await this.bridge.construct(f.className,...y);l=v,await v.at("closeCallback").set(()=>m()).catch(()=>{})})().catch(g=>{this.popups.delete(p),c||(c=!0,s(a)),console.error(`phantom.ui.popup.${t} could not open: ${Zt(g)}`)}),Object.assign(o,{close:p})}}class wa{constructor(t,n){this.open=t,this.closeEverything=n}open;closeEverything;message(t,n={}){return this.open("message",t,n,()=>{},void 0)}ok(t,n={}){return this.open("ok",t,n,()=>{},void 0)}okCancel(t,n={}){return this.open("okCancel",t,n,Ye,null)}yesNo(t,n={}){return this.open("yesNo",t,n,Ye,null)}titled(t,n={}){return this.open("titled",t,n,()=>{},void 0)}parchment(t,n={}){return this.open("parchment",t,n,Ye,null)}async closeAll(){await this.closeEverything()}}const va=50,ba={click:"click",down:"mouseDown",up:"mouseUp",over:"rollOver",out:"rollOut"},Ia=["chatBar","chatHist","chatTxt","sendChatBtn","safeChatBtn","actionsBtn","emotesBtn","denBtn","worldMapBtn","buddyListBtn","newsBtn","partyBtn","mySettingsBtn","money","zoneName"];function O(e){if(!e)throw new TypeError("Expected a widget or an overlay node");return typeof e.node=="number"?e:e.node}function oe(e,t){return t?{fill:e.accent,hoverFill:{color:e.accent,alpha:.85},pressedFill:{color:e.accent,alpha:.7},stroke:e.line}:e.skin==="game"?{fill:e.light,hoverFill:16777215,pressedFill:e.line,stroke:e.line}:{fill:{color:e.ink,alpha:.92},hoverFill:e.line,pressedFill:{color:e.line,alpha:.7},stroke:e.line}}function Ye(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const t=e.status;if(typeof t=="boolean")return t}return null}function Qt(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Zt(e){return e instanceof Error?e.message:String(e)}function Ta(e,t,n){return new Ji(new rr(xa(e,t),{firstId:n}))}function xa(e,t){const n=new Set;let r=null;const i=a=>{for(const s of n)s(a)};return{send(a){e.call("flash.request",t,[a]).catch(s=>{const o=ka(a,s);o?i(o):e.log("warn",[`A Flash request was refused: ${L(s)}`])})},onMessage(a){return n.add(a),r??=e.subscribe("flash.messages",t,{event(s){const[o]=s;typeof o=="string"&&i(o)},ended(s){r=null,s&&e.log("warn",[`Flash stopped answering: ${s.message}`])}}),()=>{n.delete(a),!n.size&&r&&(r(),r=null)}}}}function ka(e,t){let n;try{n=sn(e)}catch{return null}if(typeof(n==null?void 0:n.id)!="number")return null;const r=t instanceof E?t.code:"FAILED",i=t instanceof Error?t.message:L(t);return ie({kind:"result",id:n.id,ok:!1,error:{name:r,message:i,errorId:0}})}function Aa(e){let t=null,n=null;const r=()=>{const i=e.flash();return t??=new ia({flash:i.bridge,content:Sa(e.port,e.game)},i),t};return{avatar:{view:()=>e.flash().bridge.definition(ea.avatarManager).at("playerAvatarWorldView").get()},adventures:{record:()=>Na(e.remote)},content:{load:(i,a)=>r().load(i,a),replaceOnScreen:(i,a,s)=>r().replaceOnScreen(i,a,s)},ui:()=>{const i=e.flash();return n??=new ya({flash:i.bridge},i),n},recipes:{chatShortcuts:async i=>Wi(await Je(e),i),customChatBox:async i=>Gi(await Je(e),i),chatHistoryPanel:async i=>Xi(await Je(e),i)}}}function Sa(e,t){const n=()=>{throw new E("NOT_SUPPORTED","Only holding and releasing content happen in a frame")};return{hold:r=>e.call("content.hold",t,[r]),release:r=>e.call("content.release",t,[r]),replace:n,restore:n,list:n,observe:n}}function Na(e){const t=Date.now(),n=[];let r=null,i=null;const a=()=>{r===null&&e.adventures.current().then(o=>r??=(o==null?void 0:o.scriptDefId)??null).catch(()=>{}),i===null&&e.adventures.actor("diff_level").then(o=>i??=(o==null?void 0:o.state)??null).catch(()=>{})};a();const s=e.adventures.onStep(({time:o,...l})=>{a(),n.push({...l,at:o-t})});return{stop:()=>(s(),{version:1,scriptDefId:r,difficulty:i,steps:[...n]})}}async function Je(e){const t=e.flash(),{remote:n}=e,r=[...await n.chat.recent()],i=new Map;for(const a of await n.room.players.list())i.set(a.userId,a);return n.room.players.onEnter(a=>i.set(a.userId,a)),n.room.players.onLeave(a=>i.delete(a.userId)),n.chat.onMessage(a=>r.push(a)),{flash:t,chat:{say:n.chat.say,phrase:n.chat.phrase,onMessage:n.chat.onMessage,recent:r},room:{players:{get:a=>i.get(a)??null}}}}function Ca(e,t){const n={};for(const r of Object.keys(Rn)){const i=r.split(".");let a=n;for(const o of i.slice(0,-1))a=a[o]??={};const s=i[i.length-1];a[s]=$n(r)?Ma(e,t,r):Ea(e,t,r)}return jn(n)}function Ea(e,t,n){return(...r)=>e.call(`sdk:${n}`,t,r)}function Ma(e,t,n){return r=>{if(typeof r!="function")throw new TypeError(`${n} takes a listener function`);return e.subscribe(`sdk:${n}`,t,{event:i=>r(...i),ended(i){i&&e.log("warn",[`${n} stopped: ${i.code}: ${L(i.message)}`])}})}}function jn(e){for(const t of Object.values(e))typeof t=="object"&&t!==null&&jn(t);return Object.freeze(e)}function en(e,t,n,r){const i=a=>({direction:r,...a==="*"?{}:{commands:[...a]}});return{send(a){return e.call("packets.send",t,[n,String(a)])},watch(a,s){return e.subscribe("packets.watch",t,{event(o){const l=Oa(o,r);l&&s(In(l.text,l.direction))},ended:o=>{o&&e.log("warn",[`Watching the traffic stopped: ${o.message}`])}},i(a))},on(a,s){return e.subscribe("packets.intercept",t,{event:()=>{},intercepted:o=>{qa(e,o,s)},ended:o=>{o&&e.log("warn",[`Hooking the traffic stopped: ${o.message}`])}},i(a))}}}async function qa(e,t,n){let r;try{r=In(t.text,t.direction),await n(r)}catch(i){e.log("error",[`A traffic hook failed: ${L(i)}`]),e.verdict(t.requestId,!1,null);return}e.verdict(t.requestId,r.dropped,r.modified?r.encode():null)}function Oa(e,t){const[n,r]=e;if(typeof n=="string")return{text:n,direction:tn(r)?r:t};if(typeof n=="object"&&n!==null){const{text:i,direction:a}=n;if(typeof i=="string")return{text:i,direction:tn(a)?a:t}}return null}function tn(e){return e==="toServer"||e==="toClient"}function Da(e){const t=new Map,n=new Set;function r(a){var s,o;const l=a??Hn(T.role);if(!l)throw new E("NO_GAME",((s=T.role)==null?void 0:s.kind)==="page"||((o=T.role)==null?void 0:o.kind)==="logic"?"This frame works with several games: name one, as ctx.phantom(id), from ctx.games()":"This frame is not bound to a game yet");let c=t.get(l);return c||(c=Pa(e,l),t.set(l,c)),c}return{ctx:{get plugin(){return T.plugin},get granted(){return T.granted},get preferences(){return T.preferences},can:a=>La(T.granted.scopes,a),games:()=>[...T.games],onGames(a){return n.add(a),()=>n.delete(a)},phantom:r,storage:{get:a=>e.call("storage.get",null,[String(a)]),set:(a,s)=>e.call("storage.set",null,[String(a),s]),remove:a=>e.call("storage.remove",null,[String(a)]),keys:()=>e.call("storage.keys",null,[])},async fetch(a,s){const o=await e.call("fetch",null,[String(a),s??{}]);return ja(o)},copy:a=>e.call("copy",null,[String(a)]),notify:(a,s)=>e.call("notify",null,s===void 0?[String(a)]:[String(a),String(s)]),toast:(a,s)=>e.call("toast",null,[String(a),s??{}]),confirm:(a,s)=>e.call("confirm",null,[String(a),s??{}]),openUrl:a=>e.call("openUrl",null,[String(a)]),log:(...a)=>e.log("log",a.map(L))},notifyGames(a){for(const s of[...n])try{s([...a])}catch(o){e.log("error",[`An onGames listener failed: ${L(o)}`])}},dispose(){n.clear(),t.clear()}}}function Pa(e,t){let n=null;const r=()=>{if(n)return n;if(T.flashIds===null)throw new E("PERMISSION_DENIED","game.flash needs the flash scope, which this plugin was not granted");return n=Ta(e,t,T.flashIds),n},i=Ca(e,t),a=Aa({port:e,game:t,remote:i,flash:r}),s={...i,avatar:Object.freeze({...i.avatar,...a.avatar}),adventures:Object.freeze({...i.adventures,...a.adventures}),content:Object.freeze({...i.content,...a.content}),recipes:Object.freeze(a.recipes),id:t,server:en(e,t,"toServer","toClient"),client:en(e,t,"toClient","toServer")};return Object.defineProperties(s,{flash:{enumerable:!0,get:r},ui:{enumerable:!0,get:a.ui}}),s}function La(e,t){if(e.includes(t))return!0;if(!t.startsWith("network:"))return!1;const n=t.slice(8);return e.some(r=>{if(!r.startsWith("network:*."))return!1;const i=r.slice(9);return n.endsWith(i)&&n.length>i.length})}function ja(e){const t=e.body??"";return{status:e.status,ok:e.status>=200&&e.status<300,headers:e.headers??{},text:async()=>t,json:async()=>JSON.parse(t)}}const Ra=6e4;function $a(e,t={}){const n=t.prefix??`f${Math.random().toString(36).slice(2,10)}-`,r=t.timeoutMs??Ra;let i=0,a=!1;const s=new Map,o=new Map,l=()=>`${n}${i+=1}`;function c(g,y){if(!a)try{e({phantom:F,type:"log",level:g,values:y})}catch{}}function d(g,y,v){if(a)return Promise.reject(new E("FAILED","The frame was closed"));const I=l();return new Promise((k,q)=>{const U=setTimeout(()=>{s.delete(I),q(new E("TIMEOUT",`Phantom did not answer ${g} in ${r/1e3}s`))},r);s.set(I,{resolve:k,reject:q,timer:U});try{e({phantom:F,type:"call",id:I,method:g,game:y,args:Ne(v)})}catch(C){clearTimeout(U),s.delete(I),q(new E("FAILED",`${g} could not be sent: ${L(C)}`))}})}function h(g,y,v,I){if(a)return()=>{};const k=l();o.set(k,v);try{e({phantom:F,type:"subscribe",id:k,topic:g,game:y,...I?{filter:Ne(I)}:{}})}catch(q){throw o.delete(k),new E("FAILED",`${g} could not be heard: ${L(q)}`)}return()=>{!o.delete(k)||a||e({phantom:F,type:"unsubscribe",id:k})}}function m(g,y,v){a||e({phantom:F,type:"verdict",requestId:g,drop:y,text:v})}function p(g){switch(g.type){case"call-result":{const y=s.get(g.id);return y?(s.delete(g.id),clearTimeout(y.timer),g.ok?y.resolve(g.value):y.reject(Gn(g.error)),!0):!1}case"event":{const y=o.get(g.subscription);return y?(f(()=>y.event(Array.isArray(g.args)?g.args:[])),!0):!1}case"intercepted":{const y=o.get(g.subscription);return y!=null&&y.intercepted?(y.intercepted(g),!0):(m(g.requestId,!1,null),!!y)}case"subscription-ended":{const y=o.get(g.subscription);return y?(o.delete(g.subscription),f(()=>{var v;return(v=y.ended)==null?void 0:v.call(y,g.error)}),!0):!1}}}function f(g){try{g()}catch(y){c("error",[`A listener failed: ${L(y)}`])}}return{call:d,subscribe:h,verdict:m,log:c,receive:p,close(g){if(!a){a=!0;for(const y of s.values())clearTimeout(y.timer),y.reject(new E("FAILED",g));s.clear(),o.clear()}}}}function Fa(e,t,n=new Set){const r=new Set;for(const[a,s]of Object.entries((t==null?void 0:t.variables)??{}))!a.startsWith("--phantom-")||typeof s!="string"||(e.style.setProperty(a,s),r.add(a));for(const a of n)r.has(a)||e.style.removeProperty(a);const i=(t==null?void 0:t.mode)==="light"?"light":"dark";return e.dataset.theme=i,e.style.setProperty("color-scheme",i),r}const Ua=2e3;function Ba(e,t){Vn(t.development??!1);let n=!1,r=new Set,i=null,a=null;function s(w){var b;n||(e.post(w),(b=t.tap)==null||b.call(t,w))}const o=$a(s),l=Da(o),c=l.ctx;Tt(c);function d(w){var b;const A=xe(w);try{s({phantom:F,type:"crash",error:A})}catch{}(b=e.view)==null||b.showError(A,T.development)}let h;const p=new Promise(w=>h=w).then(async()=>{try{const w=t.definition,b=await(typeof w=="function"?w():w);return i=_a(b),!0}catch(w){return d(w),!1}}),f=p.then(async w=>{var b;if(!w||((b=T.role)==null?void 0:b.kind)!=="logic")return w;if(s({phantom:F,type:"ready",implements:{pages:Te(i==null?void 0:i.pages),panels:Te(i==null?void 0:i.panels),commands:Te(i==null?void 0:i.commands),commandViews:Te(i==null?void 0:i.commandViews)}}),!(i!=null&&i.setup))return!0;try{const A=await i.setup(c);typeof A=="function"&&(n?U(A):a=A)}catch(A){d(A)}return!0});function g(w){if(n||!Fn(w))return;const b=w;switch(b.type){case"init":y(b);return;case"games":T.games=Array.isArray(b.games)?b.games:[],l.notifyGames(T.games);return;case"stop":B();return;case"mount":I(b);return;case"invoke":q(b);return;case"call-result":case"event":case"subscription-ended":case"intercepted":o.receive(b);return}}function y(w){var b;e.root&&w.theme&&(r=Fa(e.root,w.theme,r)),Object.assign(T,{role:T.role??w.role??null,plugin:w.plugin??T.plugin,mode:((b=w.theme)==null?void 0:b.mode)==="light"?"light":"dark",granted:w.granted??{scopes:[]},preferences:w.preferences??{},games:Array.isArray(w.games)?w.games:[],flashIds:typeof w.flashIds=="number"?w.flashIds:null,development:T.development||!!w.development,initialized:!0}),l.notifyGames(T.games),h()}const v=e.listen(g);async function I(w){var b,A;const[K]=await Promise.all([p,((b=e.loadStyles)==null?void 0:b.call(e))??Promise.resolve()]);n||((A=T.role)==null?void 0:A.kind)==="logic"||(Object.assign(T,{kind:w.kind,contribution:w.contribution,props:w.props??{}}),K&&k())}function k(){var w;if(!T.kind||!T.contribution)return;const[b,A]=T.kind==="page"?[i==null?void 0:i.pages,"pages"]:T.kind==="panel"?[i==null?void 0:i.panels,"panels"]:[i==null?void 0:i.commandViews,"commandViews"],K=b==null?void 0:b[T.contribution];if(!K){d(new E("NOT_SUPPORTED",`definePlugin has no ${A}["${T.contribution}"], so there is nothing to show here`));return}try{(w=e.view)==null||w.mount(K,c)}catch(H){d(H)}}async function q(w){var b,A;const K=(H,je)=>{try{s({phantom:F,type:"result",id:w.id,ok:H,...je})}catch(Re){s({phantom:F,type:"result",id:w.id,ok:!1,error:xe(new E("FAILED",`The answer could not be sent to Phantom: ${L(Re)}`))})}};try{if(!await f||!i)throw new E("FAILED","The plugin did not load");if(w.kind!=="commands")throw new E("NOT_SUPPORTED",`Phantom asked for an unknown kind, "${w.kind}"`);const H=(b=i.commands)==null?void 0:b[w.contribution];if(typeof H!="function")throw new E("NOT_SUPPORTED",`definePlugin has no commands["${w.contribution}"] function`);const je={arguments:((A=w.input)==null?void 0:A.arguments)??{}},Re=await H(je,c.phantom(w.game),c);K(!0,{value:Ne(Re??null)})}catch(H){K(!1,{error:xe(H)})}}function U(w){try{const b=w();b instanceof Promise&&b.catch(A=>C(A))}catch(b){C(b)}}function C(w){o.log("error",[`setup's cleanup failed: ${L(w)}`])}async function B(){const w=a;if(a=null,w)try{await Promise.race([Promise.resolve(w()),new Promise(b=>setTimeout(b,Ua))])}catch(b){C(b)}s({phantom:F,type:"stopped"})}return{ctx:c,crash:d,log:(w,b)=>o.log(w,b),replaceDefinition(w){var b;i=w,((b=T.role)==null?void 0:b.kind)!=="logic"&&k()},stop(){n||(a&&(U(a),a=null),n=!0,v(),o.close("The frame was closed"),l.dispose(),Tt(null))}}}function Te(e){return Object.keys(e??{})}function _a(e){return!e||typeof e!="object"?{}:"default"in e&&e.default&&typeof e.default=="object"?e.default:e}const za={class:"flex flex-col p-3",role:"alert"},Ha={class:"flex flex-col gap-2 overflow-hidden rounded-lg border border-phantom-danger/25 bg-phantom-danger/10 px-3 py-2.5"},Va={class:"flex items-start gap-2"},Wa={class:"min-w-0 flex-1"},Ga={class:"text-xs font-medium text-phantom-danger"},Ka={class:"mt-0.5 break-words text-2xs text-phantom-text-soft"},Xa=["textContent"],Ya={key:1,class:"text-2xs text-phantom-subtle"},Ja=_n({__name:"ErrorCard",props:{error:{},development:{type:Boolean},kind:{}},emits:["dismiss"],setup(e,{emit:t}){const n=e,r=t,i=zn(()=>n.kind==="panel"?"This panel":n.kind==="page"?"This page":"This plugin");return(a,s)=>(we(),ve("div",za,[ne("div",Ha,[ne("div",Va,[s[1]||(s[1]=ne("span",{class:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-phantom-danger","aria-hidden":"true"},null,-1)),ne("div",Wa,[ne("p",Ga,$e(i.value)+" stopped with an error",1),ne("p",Ka,$e(e.error.message),1)]),e.development?(we(),ve("button",{key:0,type:"button",class:"shrink-0 rounded px-1.5 text-2xs text-phantom-muted transition-colors hover:bg-phantom-danger/10 hover:text-phantom-text",onClick:s[0]||(s[0]=o=>r("dismiss"))}," Dismiss ")):vt("",!0)]),e.development&&e.error.stack?(we(),ve("pre",{key:0,class:"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-md bg-phantom-canvas/60 px-2.5 py-2 font-mono text-3xs text-phantom-muted",textContent:$e(e.error.stack)},null,8,Xa)):e.development?vt("",!0):(we(),ve("p",Ya," More is in the plugin's log, in Plugins. "))])]))}});function Qa(e){let t=null,n=null,r=-1;const i=()=>{const o=Math.ceil(Math.max(e.content.scrollHeight,e.content.getBoundingClientRect().height));o!==r&&(r=o,e.onResize(o))},a=typeof ResizeObserver>"u"?null:new ResizeObserver(i);a==null||a.observe(e.content);function s(){n==null||n.unmount(),n=null,e.content.hidden=!1}return{mount(o,l){s(),t==null||t.unmount(),document.documentElement.dataset.kind=T.kind??"",t=bt({name:"PhantomPluginView",render:()=>It(o,{...T.props})}),t.provide(Wn,l),t.config.errorHandler=c=>e.onError(c),t.mount(e.content)},showError(o,l){n==null||n.unmount(),e.content.hidden=!0,n=bt({render:()=>It(Ja,{error:o,development:l,kind:T.kind,onDismiss:()=>s()})}),n.mount(e.errors),i()},unmount(){a==null||a.disconnect(),t==null||t.unmount(),n==null||n.unmount(),t=null,n=null}}}function Za(e){window.parent===window&&es();const t=nn("app"),n=nn("phantom-error");let r=null;function i(o){window.parent.postMessage(o,"*")}const a=Qa({content:t,errors:n,onError:o=>r==null?void 0:r.crash(o),onResize:o=>{document.documentElement.dataset.kind&&i({phantom:F,type:"resize",height:o})}});r=Ba({post:i,listen(o){const l=c=>{c.source===window.parent&&o(c.data)};return window.addEventListener("message",l),()=>window.removeEventListener("message",l)},root:document.documentElement,view:a,...e.loadStyles?{loadStyles:e.loadStyles}:{}},e);const s=r;return Xn(console,(o,l)=>s.log(o,l)),window.addEventListener("error",o=>{String(o.message).includes("ResizeObserver loop")||s.crash(o.error??o.message)}),window.addEventListener("unhandledrejection",o=>s.crash(o.reason)),window.addEventListener("pagehide",()=>{a.unmount(),s.stop()}),document.addEventListener("click",o=>{const l=o.target,c=l&&typeof l.closest=="function"?l.closest("a[href]"):null;if(!c)return;const d=c.getAttribute("href")??"";d.startsWith("#")||(o.preventDefault(),/^https:\/\//i.test(d)?s.ctx.openUrl(d).catch(()=>{}):s.log("warn",[`Only https links open from a plugin; this one goes to ${d}`]))}),s}function nn(e){const t=document.getElementById(e);if(t)return t;const n=document.createElement("div");return n.id=e,document.body.append(n),n}function es(){const e=document.createElement("p");e.className="m-6 max-w-md text-xs text-phantom-muted",e.textContent="This is a Phantom plugin frame. It runs inside Phantom: turn on Developer mode in Plugins, and a plugin served by phantom-plugin dev shows up there.",document.body.prepend(e)}const rn="/dist/plugin.js",ts="/dist/plugin.css";let an=null;function ns(){return an??=new Promise(e=>{const t=document.createElement("link");t.rel="stylesheet",t.href=ts,t.onload=t.onerror=()=>e(),document.head.append(t)}),an}async function rs(){const e=await import(rn);if(!e.default)throw new Error(`${rn} has no default export. Export definePlugin({ ... }) as default.`);return e.default}Za({definition:rs,loadStyles:ns});
|
|
1
|
+
import{c as Gt,a as Yt,b as Kt,s as Xt,j as Jt,S as Qt,i as Zt,d as en,e as tn,P as z,f as nn}from"./chunks/sdk-permissions-AYsXGgro.js";import{M as Lt,P as Ze,X as rn,a as an,b as sn,C as Ee,c as A,r as on}from"./chunks/api-DCkkcNDr.js";import{i as ln,t as cn,d as hn,o as ue,c as de,a as ee,b as Se,e as et,f as un,g as tt,h as nt}from"./chunks/runtime-dom.esm-bundler-Dcouf4CU.js";import{f as x,b as dn,r as fn,s as rt,P as gn}from"./chunks/state-CyERnsrb.js";class L extends Error{constructor(e,t,r=null){super(wn(t,r,e)),this.code=e,this.flash=r,this.name="BridgeError"}code;flash}function wn(n,e,t){if(typeof n=="string"&&n.trim()!=="")return mn(n,e);const r=yn(n);if(r)return r;const a=typeof(e==null?void 0:e.name)=="string"?e.name.trim():"";return a||`The game answered with no reason (${t})`}const pn={1006:"that member is not a method",1009:"something the call reached was null",1010:"that member is not there",1034:"a value was not of the type the member takes",1056:"that object has nowhere to put the value",1063:"the call was given the wrong number of arguments",1069:"the object has no member of that name",1502:"a script in the game ran for longer than the player allows",2007:"a value the call needs was null"};function mn(n,e){const t=typeof(e==null?void 0:e.errorId)=="number"?e.errorId:0,r=pn[t];return!r||!/^\s*Error #\d+\s*$/.test(n)?n:`${n.trim()}: ${r}`}function yn(n){if(n==null)return"";if(typeof n=="string")return n.trim();if(typeof n!="object")return String(n);const e=n;if(typeof e.message=="string"&&e.message.trim()!=="")return e.message;try{const t=JSON.stringify(n);return t&&t!=="{}"?t:""}catch{return""}}const at=2;function te(n){return encodeURIComponent(JSON.stringify(n))}function Nt(n){return JSON.parse(decodeURIComponent(n))}function bn(n){return typeof n=="object"&&n!==null&&"$handle"in n}function vn(n){switch(n.kind){case"result":return n.id;case"event":return n.listener;case"callback":return n.callback;case"hook":case"override":case"hook-dropped":case"hook-failed":return n.registration;case"watch":return n.watch;case"tick":return n.tick;case"overlay":return n.node;case"key":return n.key;case"drive-failed":return n.drive;case"track":return n.track;default:return null}}class ke{constructor(e,t=[]){this.className=e,this.args=t}className;args}class _{constructor(e,t,r){this.bridge=e,this.handle=t,this.className=r}bridge;handle;className;at(...e){return new J(this.bridge,{kind:"handle",handle:this.handle},e)}release(){return this.bridge.release([this])}}class J{constructor(e,t,r=[]){this.bridge=e,this.target=t,this.path=r}bridge;target;path;at(...e){return new J(this.bridge,this.target,[...this.path,...e])}get(){return this.bridge.request({op:"get",target:this.target,path:[...this.path]})}set(e){return this.bridge.request({op:"set",target:this.target,path:[...this.path],value:this.bridge.encode(e)}).then(()=>{})}call(...e){return this.bridge.request({op:"call",target:this.target,path:[...this.path],args:e.map(t=>this.bridge.encode(t))})}describe(){return this.bridge.request({op:"describe",target:this.target,path:[...this.path]})}listen(e,t){return this.bridge.listen(this,e,t)}get entry(){return{target:this.target,path:[...this.path]}}}const kn=new Set(["drive-failed","track","hook","override","hook-dropped","hook-failed","watch","tick","overlay","key"]);class xn{constructor(e,t={}){this.transport=e,this.timeoutMs=t.timeoutMs??5e3,this.firstId=t.firstId??1,this.nextId=this.firstId,this.batchOption=t.batch,this.stopReceiving=e.onMessage(r=>this.receive(r))}transport;stateValue="waiting";nextId;pending=new Map;listeners=new Map;callbacks=new Map;readyWaiters=[];clientListeners=new Set;uncaughtListeners=new Set;timeoutMs;stopReceiving;clientVersion=null;featureList=[];firstId;batchOption;queue=[];batches=new Map;subscriptions=new Map;ticks=new Map;get state(){return this.stateValue}get client(){return this.clientVersion}get features(){return this.featureList}allocate(){return this.nextId++}whenReady(){return this.stateValue==="ready"?Promise.resolve():this.stateValue==="closed"?Promise.reject(new L("CLOSED","The game is closed")):new Promise((e,t)=>this.readyWaiters.push({resolve:e,reject:t}))}definition(e){return new J(this,{kind:"definition",name:e})}gameClient(){return new J(this,{kind:"client"})}stage(){return new J(this,{kind:"stage"})}construct(e,...t){return this.request({op:"construct",className:e,args:t.map(r=>this.encode(r))})}onClient(e){return this.clientListeners.add(e),()=>this.clientListeners.delete(e)}onUncaught(e){return this.uncaughtListeners.add(e),()=>this.uncaughtListeners.delete(e)}async listen(e,t,r){const a=this.nextId++;this.listeners.set(a,r);try{await this.request({op:"listen",target:e.target,path:[...e.path],event:t,listener:a})}catch(i){throw this.listeners.delete(a),i}return async()=>{!this.listeners.delete(a)||this.stateValue==="closed"||await this.request({op:"unlisten",listener:a})}}async subscribe(e,t,r){const a=this.nextId++;this.subscriptions.set(a,r);try{await this.request(e(a))}catch(i){throw this.subscriptions.delete(a),i}return async()=>{!this.subscriptions.delete(a)||this.stateValue==="closed"||await this.request(t(a))}}onSubscription(e,t){return this.subscriptions.set(e,t),()=>{this.subscriptions.get(e)===t&&this.subscriptions.delete(e)}}async hookTable(e){return await this.request(e===void 0?{op:"hookTable"}:{op:"hookTable",url:e})}async hook(e,t,r){let a=0;const i=await this.subscribe(s=>(a=s,{op:"hook",registration:s,hook:e,rules:t}),s=>({op:"unhook",registration:s}),r);return{registration:a,stop:i}}watch(e,t,r){return this.subscribe(a=>({op:"watch",watch:a,entries:e.map(i=>({target:i.target,path:[...i.path]})),everyFrames:Math.max(1,Math.floor(t.everyFrames??1)),handles:t.handles??!1}),a=>({op:"unwatch",watch:a}),a=>{a.kind==="watch"&&r(a.values.map(i=>this.decode(i)),a.errors??null)})}async tick(e,t){const r=Math.max(1,Math.floor(e));let a=this.ticks.get(r);if(!a){const o=new Set,l=this.subscribe(c=>({op:"tick",tick:c,everyFrames:r}),c=>({op:"untick",tick:c}),c=>{if(c.kind==="tick")for(const h of[...o])h(c.frame,c.time)});a={listeners:o,started:l},this.ticks.set(r,a),l.catch(()=>{this.ticks.get(r)===a&&this.ticks.delete(r)})}const i=a;i.listeners.add(t);try{await i.started}catch(o){throw i.listeners.delete(t),o}let s=!1;return async()=>{s||(s=!0,i.listeners.delete(t),!(i.listeners.size>0||this.ticks.get(r)!==i)&&(this.ticks.delete(r),await(await i.started)()))}}highlight(e,t){return this.subscribe(r=>({op:"highlight",highlight:r,target:e.target,path:[...e.path],effect:t}),r=>({op:"unhighlight",highlight:r}),()=>{})}style(e,t){return this.subscribe(r=>({op:"style",style:r,target:e.target,path:[...e.path],format:t}),r=>({op:"unstyle",style:r}),()=>{})}invokeOriginal(e,t,r){return this.request({op:"invokeOriginal",registration:e,token:t,arguments:r===null?null:r.map(a=>this.encode(a))})}async overrideDone(e,t){this.stateValue!=="closed"&&await this.request({op:"overrideDone",registration:e,token:t})}onKey(e,t){return this.subscribe(r=>({op:"key",key:r,spec:e}),r=>({op:"unkey",key:r}),r=>{r.kind==="key"&&t(r)})}async draw(e,t){await this.request({op:"draw",node:e,spec:t})}async erase(e){if(!(e.length===0||this.stateValue==="closed")){for(const t of e)this.subscriptions.delete(t);await this.request({op:"erase",nodes:[...e]})}}drive(e,t){return this.subscribe(r=>({op:"drive",drive:r,spec:e}),r=>({op:"undrive",drive:r}),r=>{r.kind==="drive-failed"&&(t==null||t(r.error))})}async collect(e,t){const a=await this.request({op:"collect",target:e.target,path:[...e.path],spec:t});return{items:Array.isArray(a==null?void 0:a.items)?a.items:[],total:typeof(a==null?void 0:a.total)=="number"?a.total:0}}track(e,t,{mode:r="displayList",everyFrames:a=15}={},i){return this.subscribe(s=>({op:"track",track:s,target:e.target,path:[...e.path],className:t,mode:r,everyFrames:a}),s=>({op:"untrack",track:s}),s=>{s.kind==="track"&&i({added:s.added.map(o=>this.decode(o)),removed:s.removed.map(o=>this.decode(o))})})}async snapshot(e,{scale:t=1,background:r=null,maxSize:a=0}={}){const i=await this.request({op:"snapshot",target:e.target,path:[...e.path],scale:t,background:r,maxSize:a});if(typeof i!="string")throw new L("FLASH","The picture came back empty");return i}note(e,t,r,a){if(t==="keys"||t==="clear")return this.request({op:"note",table:e,verb:t});if(!r)throw new TypeError(`A note to ${t} is kept beside an object; name the place`);const i={target:r.target,path:[...r.path]};return t==="write"?this.request({op:"note",table:e,verb:t,...i,value:this.encode(a)}):this.request({op:"note",table:e,verb:t,...i})}async find(e,t){const r=await this.request({op:"find",target:e.target,path:[...e.path],spec:t});return(Array.isArray(r)?r:[]).filter(a=>a instanceof _)}async answer(e,t){this.stateValue!=="closed"&&await this.request({op:"answer",callback:e,...t===void 0?{}:{value:this.encode(t)}})}async release(e){e.length===0||this.stateValue==="closed"||await this.request({op:"release",handles:e.map(t=>t.handle)})}close(){if(this.stateValue==="closed")return;if(this.stateValue==="ready"&&this.featureList.includes("dispose")){const t=this.nextId++;try{this.transport.send(te({id:t,op:"dispose",from:this.firstId,to:this.nextId}))}catch{}}this.stateValue="closed",this.stopReceiving();const e=new L("CLOSED","The game was closed");for(const t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear();for(const t of this.batches.values())clearTimeout(t.timer);this.batches.clear(),this.queue=[],this.listeners.clear(),this.callbacks.clear(),this.subscriptions.clear(),this.ticks.clear(),this.readyWaiters.splice(0).forEach(t=>t.reject(e))}readyWithin(e){return new Promise((t,r)=>{const a=setTimeout(()=>r(new L("NOT_READY","The game has not started yet")),e);this.whenReady().then(()=>{clearTimeout(a),t()},i=>{clearTimeout(a),r(i)})})}encodeRequest(e){return te({...e,id:this.nextId++})}request(e){if(this.stateValue==="closed")return Promise.reject(new L("CLOSED","The game is closed"));if(this.stateValue!=="ready")return this.readyWithin(this.timeoutMs).then(()=>this.request(e));const t=this.nextId++;return new Promise((r,a)=>{const i=setTimeout(()=>{this.pending.delete(t),a(new L("TIMEOUT",`The game did not answer "${e.op}" in ${this.timeoutMs}ms`))},this.timeoutMs);this.pending.set(t,{resolve:r,reject:a,timer:i});const s={...e,id:t};if(!this.batching||s.op==="hookTable"||s.op==="batch"){this.transport.send(te(s));return}this.queue.push(s),this.queue.length===1&&queueMicrotask(()=>this.flush())})}get batching(){return this.batchOption??this.featureList.includes("batch")}flush(){const e=this.queue;if(this.queue=[],e.length===0||this.stateValue!=="ready")return;if(e.length===1){this.transport.send(te(e[0]));return}const t=this.nextId++,r=e.map(i=>i.id),a=setTimeout(()=>this.batches.delete(t),this.timeoutMs+1e3);this.batches.set(t,{ids:r,timer:a}),this.transport.send(te({id:t,op:"batch",requests:e}))}settle(e,t){const r=this.pending.get(e);r&&(this.pending.delete(e),clearTimeout(r.timer),t.ok?r.resolve(this.decode(t.value)):r.reject(new L("FLASH",t.error.message,t.error)))}encode(e){if(e===void 0)return{$undefined:!0};if(e===null||typeof e!="object"){if(typeof e=="function"){const t=this.nextId++;return this.callbacks.set(t,e),{$callback:t}}return e}return e instanceof _?{$handle:e.handle}:e instanceof ke?{$new:e.className,args:e.args.map(t=>this.encode(t))}:Array.isArray(e)?e.map(t=>this.encode(t)):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,this.encode(r)]))}decode(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(t=>this.decode(t));if(bn(e))return new _(this,e.$handle,e.className);if(!("$undefined"in e))return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,this.decode(r)]))}receive(e){var t,r,a;if(this.stateValue==="closed")return;let i;try{i=Nt(e)}catch{return}switch(i.kind){case"ready":if(i.version!==at){const s=new L("VERSION",`The loader speaks bridge ${i.version}; this Phantom speaks ${at}`);this.readyWaiters.splice(0).forEach(o=>o.reject(s)),this.close();return}this.stateValue="ready",this.clientVersion=i.client,this.featureList=Array.isArray(i.features)?[...i.features]:[],this.readyWaiters.splice(0).forEach(s=>s.resolve());return;case"client-loaded":this.clientListeners.forEach(s=>s(!0,null));return;case"client-failed":this.clientListeners.forEach(s=>s(!1,i.message));return;case"result":{const s=this.batches.get(i.id);if(s){this.batches.delete(i.id),clearTimeout(s.timer);const o=i.ok&&Array.isArray(i.value)?i.value:null;s.ids.forEach((l,c)=>{i.ok?o&&c<o.length&&this.settle(l,o[c]):this.settle(l,i)});return}this.settle(i.id,i.ok?{ok:!0,value:i.value}:i);return}case"event":(t=this.listeners.get(i.listener))==null||t(this.decode(i.event));return;case"callback":(r=this.callbacks.get(i.callback))==null||r(...i.args.map(s=>this.decode(s)));return;case"uncaught":{const s=new L("FLASH",i.error.message,i.error);this.uncaughtListeners.forEach(o=>o(s));return}default:if(kn.has(i.kind)){const s=vn(i);s!==null&&((a=this.subscriptions.get(s))==null||a(i))}}}}const Tn=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],_t={r:.3086,g:.6094,b:.082};function fe(n,e){const t=new Array(20).fill(0);for(let r=0;r<4;r++)for(let a=0;a<5;a++){let i=a===4?e[r*5+4]:0;for(let s=0;s<4;s++)i+=e[r*5+s]*n[s*5+a];t[r*5+a]=i}return t}function jt(n){const e=n,{r:t,g:r,b:a}=_t;return[t*(1-e)+e,r*(1-e),a*(1-e),0,0,t*(1-e),r*(1-e)+e,a*(1-e),0,0,t*(1-e),r*(1-e),a*(1-e)+e,0,0,0,0,0,1,0]}function On(n){const e=n*255;return[1,0,0,0,e,0,1,0,0,e,0,0,1,0,e,0,0,0,1,0]}function Mn(n){const e=n+1,t=128*(1-e);return[e,0,0,0,t,0,e,0,0,t,0,0,e,0,t,0,0,0,1,0]}function En(n){const e=n*Math.PI/180,t=Math.cos(e),r=Math.sin(e),{r:a,g:i,b:s}=_t;return[a+t*(1-a)+r*-a,i+t*-i+r*-i,s+t*-s+r*(1-s),0,0,a+t*-a+r*.143,i+t*(1-i)+r*.14,s+t*-s+r*-.283,0,0,a+t*-a+r*-.6914,i+t*-i+r*i,s+t*(1-s)+r*s,0,0,0,0,0,1,0]}const Sn={grayscale:jt(0),sepia:[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0],invert:[-1,0,0,0,255,0,-1,0,0,255,0,0,-1,0,255,0,0,0,1,0],night:[.45,0,0,0,0,0,.5,0,0,0,0,0,.8,0,20,0,0,0,1,0]};function zt(n){if(typeof n=="string"){const t=Sn[n];if(!t)throw new TypeError(`Unknown colour look "${String(n)}"`);return{matrix:[...t],colorTransform:null}}if("matrix"in n){if(n.matrix.length!==20)throw new TypeError("A colour matrix has twenty numbers");return{matrix:[...n.matrix],colorTransform:null}}if("tint"in n){const t=Math.max(0,Math.min(1,n.amount??.5)),r=a=>(n.tint>>a&255)*t;return{matrix:null,colorTransform:it({redMultiplier:1-t,greenMultiplier:1-t,blueMultiplier:1-t,redOffset:r(16),greenOffset:r(8),blueOffset:r(0)})}}if("transform"in n)return{matrix:null,colorTransform:it(n.transform)};let e=[...Tn];return n.saturation!==void 0&&(e=fe(e,jt(n.saturation))),n.hue!==void 0&&(e=fe(e,En(n.hue))),n.contrast!==void 0&&(e=fe(e,Mn(n.contrast))),n.brightness!==void 0&&(e=fe(e,On(n.brightness))),{matrix:e,colorTransform:null}}function it(n){return{redMultiplier:n.redMultiplier??1,greenMultiplier:n.greenMultiplier??1,blueMultiplier:n.blueMultiplier??1,alphaMultiplier:n.alphaMultiplier??1,redOffset:n.redOffset??0,greenOffset:n.greenOffset??0,blueOffset:n.blueOffset??0,alphaOffset:n.alphaOffset??0}}function ce(n={}){const e=n.recolor?zt(n.recolor):{matrix:null,colorTransform:null},r=n.glow??!(n.recolor||n.hide)?{color:n.color??9133302,alpha:n.alpha??1,blur:n.blur??8,strength:n.strength??2,inner:n.inner??!1,knockout:n.knockout??!1}:null;if(r&&e.matrix)throw new TypeError("A highlight is a glow or a colour matrix, not both: use two highlights");const a=n.pulse===void 0||n.pulse===!1?null:n.pulse===!0?{frames:60,from:.6,to:1}:{frames:n.pulse.frames??60,from:n.pulse.from??.6,to:n.pulse.to??1};return{glow:r,matrix:e.matrix,colorTransform:e.colorTransform,hide:n.hide??!1,pulse:a}}const xe=Symbol.for("phantom.typedFlash");function Ht(n){return typeof n=="function"&&n[xe]!==void 0}function C(n,e,t={}){const r={reference:e,handle:t.handle??null,className:t.className??null},a=o=>P(n,o),i={$get:()=>e.get().then(a),$set:async o=>e.set((await Q(n,[o]))[0]),$listen:(o,l)=>e.listen(o,c=>l(a(c))),$describe:()=>e.describe(),$at:(...o)=>C(n,e.at(...o)),$as:()=>C(n,e,{...r.handle?{handle:r.handle}:{}}),$release:()=>r.handle?r.handle.release():Promise.resolve(),$reference:e,$new:async(...o)=>{if(!r.className)throw new TypeError("Only a class can make objects with $new");return a(await n.construct(r.className,...await Q(n,o)))},toJSON:()=>`[Flash ${An(r)}]`},s=(()=>{});return new Proxy(s,{get:(o,l)=>{if(l===xe)return r;if(typeof l!="symbol"&&l!=="then")return Object.prototype.hasOwnProperty.call(i,l)?i[l]:C(n,e.at(l))},apply:async(o,l,c)=>a(await e.call(...await Q(n,c)))})}function ne(n){return Ht(n)?n[xe].reference:n instanceof _?n.at():n&&typeof n=="object"&&"target"in n&&"path"in n&&typeof n.at=="function"?n:null}function P(n,e){if(e instanceof _)return C(n,e.at(),{handle:e});if(Array.isArray(e))return e.map(t=>P(n,t));if(e&&typeof e=="object"){const t={};for(const[r,a]of Object.entries(e))t[r]=P(n,a);return t}return e}async function Q(n,e){return Promise.all(e.map(t=>qe(n,t)))}async function qe(n,e){if(Ht(e)){const t=e[xe];return t.handle&&t.reference.path.length===0?t.handle:t.reference.get()}if(typeof e=="function"){const t=e;return(...r)=>t(...r.map(a=>P(n,a)))}if(Array.isArray(e))return Promise.all(e.map(t=>qe(n,t)));if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const t={};for(const[r,a]of Object.entries(e))t[r]=await qe(n,a);return t}return e}function An({reference:n,className:e}){const t=n.target,r=t.kind==="definition"?t.name:t.kind==="handle"?`object ${t.handle}`:t.kind,a=n.path.join(".");return e??(a?`${r}.${a}`:r)}class Pn{constructor(e,t,r){this.bridge=e;const a=e.encode(t);this.callback=a.$callback,r!==void 0&&this.answers(r)}bridge;callback;stopped=!1;get argument(){return{$callback:this.callback}}async answers(e){if(this.stopped)return;await this.ready();const[t]=await Q(this.bridge,[e]);await this.bridge.answer(this.callback,t)}async answersNothing(){this.stopped||(await this.ready(),await this.bridge.answer(this.callback))}async stop(){this.stopped||(this.stopped=!0,await this.bridge.answer(this.callback))}async ready(){if(await this.bridge.whenReady(),!this.bridge.features.includes("answer"))throw new Error("This game is running a loader from before answers; a function of yours gives the game nothing back")}}function E(n){const e=ne(n);if(!e)throw new TypeError("Expected a place in Flash: a typed place, an object read from Flash, or a reference");return{target:e.target,path:[...e.path]}}function st(n){return ne(n)!==null}async function Rn(n,e,t,r){if(await n.whenReady(),!n.features.includes("collect"))throw new Error("This game is running a loader from before collects; read the items one by one");const a={fields:Cn(t)};r.skip!==void 0&&(a.skip=Math.max(0,Math.trunc(r.skip))),r.limit!==void 0&&(a.limit=Math.max(1,Math.trunc(r.limit))),r.handles!==void 0&&(a.handles=r.handles);const i=await n.collect(E(e),a);return{rows:i.items.map(s=>P(n,s)),total:i.total}}function Cn(n){const e=Array.isArray(n)?n.map(t=>[t,t]):Object.entries(n);if(e.length===0)throw new TypeError("A collect needs the members to read");return e.map(([t,r])=>({name:t,path:(Array.isArray(r)?r:String(r).split(".")).filter(a=>a.length>0)}))}function he(n){const e=`${n.className}.${n.member}`;return n.kind==="getter"?`${e}@get`:n.kind==="setter"?`${e}@set`:e}const Te=Symbol.for("phantom.hookRead"),Z=Symbol.for("phantom.hookTest");class $n{constructor(e){this.table=e;for(const t of e.hooks){this.byId.set(t.id,t);const r=he(t);this.byKey.has(r)||this.byKey.set(r,t)}}table;byKey=new Map;byId=new Map;get size(){return this.byId.size}names(){return[...this.byKey.keys()]}find(e){return e.startsWith("#")?this.byId.get(Number(e.slice(1)))??null:this.byKey.get(e)??this.byKey.get(`${e}@get`)??this.byKey.get(`${e}@set`)??null}}function X(n){return n.flatMap(e=>Array.isArray(e)?e:e.includes("::")?[e]:e.split(".").filter(Boolean))}function G(n){return Object.freeze({[Te]:n})}function j(n,e,t){return Object.freeze({[Z]:t===void 0&&n==="exists"?{test:n,left:e}:{test:n,left:e,right:t}})}const Fn={self:(...n)=>G({from:"self",path:X(n)}),arg:(n,...e)=>G({from:"arg",arg:n,path:X(e)}),returned:(...n)=>G({from:"return",path:X(n)}),fromClass:(n,...e)=>G({from:"class",name:n,path:X(e)}),place:(n,...e)=>G({from:"place",place:n,path:X(e)}),calls:()=>G({from:"calls"}),constant:n=>G({from:"constant",value:n}),equals:(n,e)=>j("equals",n,e),notEquals:(n,e)=>j("notEquals",n,e),less:(n,e)=>j("less",n,e),lessOrEqual:(n,e)=>j("lessOrEqual",n,e),greater:(n,e)=>j("greater",n,e),greaterOrEqual:(n,e)=>j("greaterOrEqual",n,e),contains:(n,e)=>j("contains",n,e),startsWith:(n,e)=>j("startsWith",n,e),endsWith:(n,e)=>j("endsWith",n,e),oneOf:(n,e)=>j("in",n,e),exists:n=>j("exists",n),all:(...n)=>Object.freeze({[Z]:{all:n}}),any:(...n)=>Object.freeze({[Z]:{any:n}}),not:n=>Object.freeze({[Z]:{not:n}})};function Dt(n){return typeof n=="object"&&n!==null&&Te in n}function Bt(n){return typeof n=="object"&&n!==null&&Z in n}function Ue(n,e,t,r){const a=u=>{if(typeof u=="number")return ot(e,u);const d=e.parameters.findIndex(w=>w.name===u);if(d>=0)return d;if(/^\d+$/.test(u))return ot(e,Number(u));const g=e.parameters.map(w=>w.name).join(", ")||"none";throw new TypeError(`${he(e)} has no argument "${u}" (its arguments: ${g})`)},i=u=>{if(!Dt(u))return ve(u)??{from:"constant",value:re(n,u)};const d=u[Te];switch(d.from){case"constant":return{from:"constant",value:re(n,d.value)};case"arg":return{from:"arg",index:a(d.arg),path:d.path};case"self":return{from:"self",path:d.path};case"return":return{from:"return",path:d.path};case"class":return{from:"class",name:d.name,path:d.path};case"calls":return{from:"calls"};case"place":{const g=ve(d.place,d.path);if(!g)throw new TypeError("rules.place takes a place in the game");return g}}},s=u=>{if(!Bt(u)){const g=Object.entries(u).map(([w,f])=>({test:"equals",left:{from:"arg",index:a(w),path:[]},right:i(f)}));if(g.length===0)throw new TypeError("A hook condition names nothing to compare");return g.length===1?g[0]:{all:g}}const d=u[Z];return"all"in d?{all:d.all.map(s)}:"any"in d?{any:d.any.map(s)}:"not"in d?{not:s(d.not)}:d.test==="exists"?{test:d.test,left:i(d.left)}:{test:d.test,left:i(d.left),right:i(d.right)}},o=t.phase??(r?"enter":"none"),l=t.capture??{},c=e.parameters.map((u,d)=>d),h=l.args===!0||l.args===void 0&&r?c:(l.args??[]).map(a);return{observe:o==="both"?["enter","exit"]:o==="none"?[]:[o],capture:{args:h,self:Ve(l.self).map(([,u])=>u),value:l.value??!1,handles:l.handles??!1},when:t.when===void 0?null:s(t.when),first:t.first??null,every:t.every??null,skip:t.skip===void 0||t.skip===!1?null:t.skip===!0?{from:"constant",value:{$undefined:!0}}:i(t.skip.returns),replaceArgs:Object.entries(t.replaceArgs??{}).map(([u,d])=>({index:a(u),value:i(d)})),replaceReturn:"replaceReturn"in t?i(t.replaceReturn):null,perFrame:t.perFrame??20}}function ot(n,e){if(!Number.isInteger(e)||e<0||n.parameters.length>0&&e>=n.parameters.length)throw new RangeError(`${he(n)} has no argument ${e}`);return e}function Ve(n){return n?Array.isArray(n)?n.map(e=>[e,X([e])]):Object.entries(n).map(([e,t])=>[e,X([t])]):[]}function Wt(n,e){const t=r=>{if(!Bt(r))throw new TypeError("A condition between calls has no call to read: compare with rules.equals and its like");const a=r[Z];return"all"in a?{all:a.all.map(t)}:"any"in a?{any:a.any.map(t)}:"not"in a?{not:t(a.not)}:a.test==="exists"?{test:a.test,left:oe(n,a.left)}:{test:a.test,left:oe(n,a.left),right:oe(n,a.right)}};return t(e)}function ve(n,e=[]){const t=ne(n);return t?{from:"place",target:t.target,path:[...t.path,...e]}:null}function oe(n,e){if(!Dt(e))return ve(e)??{from:"constant",value:re(n,e)};const t=e[Te];switch(t.from){case"constant":return{from:"constant",value:re(n,t.value)};case"class":return{from:"class",name:t.name,path:t.path};case"place":{const r=ve(t.place,t.path);if(!r)throw new TypeError("rules.place takes a place in the game");return r}default:throw new TypeError(`rules.${t.from} reads the call it is in; a value held between calls is a constant, rules.fromClass or a place`)}}function re(n,e){if(e===void 0)return{$undefined:!0};if(e instanceof _||e instanceof ke)return n.encode(e);const t=ne(e);if(t){if(t.target.kind==="handle"&&t.path.length===0)return{$handle:t.target.handle};throw new TypeError("A place inside a list or object in a rule cannot be read there: pass the place on its own, or read it first")}if(typeof e=="function")throw new TypeError("A hook rule cannot call a function");return Array.isArray(e)?e.map(r=>re(n,r)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,a])=>[r,re(n,a)])):e}async function In(n,e,t,r,a){var i;const s=e.find(t);if(!s)throw new TypeError(`There is no hook "${t}" in the hook table`);let o=r,l=Ve((i=r.capture)==null?void 0:i.self).map(([g])=>g),c=Ue(n,s,r,a!==void 0);const{registration:h,stop:u}=await n.hook(s.id,c,g=>{var w;switch(g.kind){case"hook":{if(!a)return;const f=(g.args??[]).map(y=>P(n,n.decode(y))),p={};c.capture.args.forEach((y,v)=>{var T;p[((T=s.parameters[y])==null?void 0:T.name)??String(y)]=f[v]});const m={};(g.self??[]).forEach((y,v)=>{m[l[v]??String(v)]=P(n,n.decode(y))}),a({phase:g.phase,call:g.call,args:p,argList:f,self:m,..."value"in g?{value:P(n,n.decode(g.value))}:{},skipped:g.skipped===!0,hook:s});return}case"hook-dropped":(w=o.onDropped)==null||w.call(o,g.dropped);return;case"hook-failed":{const f=new L("FLASH",`The hook on ${he(s)} failed and is off: ${g.error.message}`,g.error);o.onError?o.onError(f):console.error(f.message);return}}});return Object.assign(()=>u(),{registration:h,hook:s,update:async(g,w={})=>{var f;const p=Ue(n,s,g,a!==void 0);await n.request({op:"rehook",registration:h,rules:p,resetCounts:w.resetCounts??!1}),o=g,c=p,l=Ve((f=g.capture)==null?void 0:f.self).map(([m])=>m)},stats:async()=>(await n.request({op:"hookStats"})).find(w=>w.registration===h)??null})}async function Ln(n,e,t){if(await n.whenReady(),!n.features.includes("drive"))throw new Error("This game is running a loader from before repeated calls; call it yourself each frame");const r=E(e);if(r.path.length===0)throw new TypeError("A repeat calls a method, so name one: `place.method`, not the object");const a=t.while?Wt(n,t.while):null;return n.drive({writes:[],calls:[{target:r.target,path:r.path,args:(t.args??[]).map(i=>oe(n,i)),times:Math.max(1,Math.trunc(t.times??1))}],everyFrames:Math.max(1,Math.trunc(t.everyFrames??1)),while:a,restore:!1,once:t.once===!0},t.onFailed)}async function lt(n,e,t){if(await n.whenReady(),!n.features.includes("drive"))throw new Error("This game is running a loader from before held values; write it yourself each frame");if(e.length===0)throw new TypeError("A hold needs a value to keep");const r=e.map(({place:i,value:s})=>{const o=E(i);if(o.path.length===0)throw new TypeError("A hold writes to a member, so name one: `place.member`, not the object");return{target:o.target,path:o.path,value:oe(n,s)}}),a=t.while?Wt(n,t.while):null;return n.drive({writes:r,everyFrames:Math.max(1,Math.trunc(t.everyFrames??1)),while:a,restore:t.restore!==!1,once:t.once===!0},t.onFailed)}class Ae{constructor(e,t,r,a,i,s,o){this.host=e,this.kind=t,this.id=r,this.name=a,this.tagY=s,this.handle=o,this.place=i}host;kind;id;name;tagY;handle;place;highlight(e={}){return this.host.bridge.highlight(this.entry(),ce(e))}tag(e,t={}){const{anchorX:r,anchorY:a,...i}=t;return this.host.overlay.text(e,{centered:!0,font:{size:12,bold:!0,color:16777215},outline:0,...i,anchor:{place:this.place,x:r??0,y:a??this.tagY}})}onClick(e){const t=this.host.bridge;return this.kind!=="object"?this.place.$listen("mouseDown",()=>e(this)):t.stage().listen("mouseDown",r=>{const{stageX:a,stageY:i}=r??{};typeof a!="number"||typeof i!="number"||this.place.$reference.at("hitTestPoint").call(a,i,!0).then(s=>{s===!0&&e(this)}).catch(()=>{})})}async release(){this.handle&&await this.handle.release()}entry(){const e=this.place.$reference;return{target:e.target,path:[...e.path]}}}class Nn{constructor(e){this.host=e}host;async players(){const e=this.host.bridge,t=e.definition("avatar.AvatarManager").at("avatarViewList"),r=await t.get(),a=r&&typeof r=="object"&&!(r instanceof _)?Object.keys(r):[],i=a.map(s=>r[s]).filter(s=>s instanceof _);try{const s=await Promise.all(a.map(o=>q(t.at(o,"userName").get())));return a.map((o,l)=>new Ae(this.host,"player",o,typeof s[l]=="string"?s[l]:null,C(e,t.at(o)),-80,null))}finally{await e.release(i)}}async npcs(){const e=this.host.bridge,t=e.definition("quest.QuestManager").at("_questActors"),r=await q(t.at("length").get());if(typeof r!="number"||r<=0)return[];const a=Array.from({length:Math.min(r,500)},(c,h)=>String(h)),[i,s,o]=await Promise.all([Promise.all(a.map(c=>q(t.at(c).get()))),Promise.all(a.map(c=>q(t.at(c,"_actorId").get()))),Promise.all(a.map(c=>q(t.at(c,"currAvatar","avName").get())))]),l=[];return a.forEach((c,h)=>{const u=i[h];if(!(u instanceof _))return;const d=o[h];l.push(new Ae(this.host,"npc",typeof s[h]=="string"?s[h]:c,typeof d=="string"&&d?d:null,C(e,u.at(),{handle:u}),-90,u))}),l}async objects(){const e=this.host.bridge,t=e.definition("room.RoomManagerWorld").at("instance","volumeManager","_volumeActors");let r;try{r=await t.at("length").get()}catch(h){throw h instanceof L&&h.code==="FLASH"?new L("FLASH",`The room's objects are private to the client, and this client does not reach them: ${h.message}`,h.flash):h}if(typeof r!="number"||r<=0)return[];const a=Array.from({length:Math.min(r,500)},(h,u)=>String(u)),[i,s]=await Promise.all([Promise.all(a.map(h=>q(t.at(h,"name").get()))),Promise.all(a.map(h=>q(t.at(h,"interactiveObjs","length").get())))]),o=[];a.forEach((h,u)=>{const d=s[u],g=i[u];for(let w=0;typeof d=="number"&&w<Math.min(d,50);w++)o.push([h,String(w),typeof g=="string"?g:null])});const l=await Promise.all(o.map(([h,u])=>q(t.at(h,"interactiveObjs",u,"mc").get()))),c=[];return o.forEach(([h,u,d],g)=>{const w=l[g];w instanceof _&&c.push(new Ae(this.host,"object",`${d??h}#${u}`,d,C(e,w.at(),{handle:w}),0,w))}),c}}function q(n){return n.catch(()=>null)}async function _n(n,e,t){if(await n.whenReady(),!n.features.includes("find"))throw new Error("This game is running a loader from before searches; only a path reaches an object");const r=e===void 0?{target:{kind:"stage"},path:[]}:E(e);return(await n.find(r,jn(t))).map(i=>C(n,i.at(),{handle:i}))}function jn(n){const e={};return n.ofClass!==void 0&&(e.ofClass=n.ofClass),n.named!==void 0&&(e.named=n.named),n.containing!==void 0&&(e.containing=n.containing),n.visibleOnly!==void 0&&(e.visibleOnly=n.visibleOnly),n.through!==void 0&&(e.through=n.through),n.depth!==void 0&&(e.depth=n.depth),n.limit!==void 0&&(e.limit=n.limit),e}const ct={backspace:8,tab:9,enter:13,return:13,shift:16,control:17,ctrl:17,alt:18,pause:19,capslock:20,escape:27,esc:27,space:32,pageup:33,pagedown:34,end:35,home:36,left:37,arrowleft:37,up:38,arrowup:38,right:39,arrowright:39,down:40,arrowdown:40,insert:45,delete:46,";":186,"=":187,",":188,"-":189,".":190,"/":191,"`":192,"[":219,"\\":220,"]":221,"'":222};function zn(n){return n===!0?"always":n===!1?"never":n??"empty"}function Hn(n,e={}){const t={phase:e.phase??"down",consume:e.consume??!1,whileTyping:zn(e.whileTyping),repeat:e.repeat??!1};if(typeof n=="number")return{code:n,ctrl:null,shift:null,alt:null,...t};const r=n==="+"||n.endsWith("++"),a=(r?n.slice(0,-1):n).split("+").map(o=>o.trim()).filter(Boolean);r&&a.push("+");const i={ctrl:!1,shift:!1,alt:!1};let s=null;for(const o of a){const l=o.toLowerCase();l==="ctrl"||l==="control"||l==="cmd"||l==="meta"?i.ctrl=!0:l==="shift"?i.shift=!0:l==="alt"||l==="option"?i.alt=!0:l==="any"?s=null:s=Dn(o)}if(s===null&&!a.some(o=>o.toLowerCase()==="any"))throw new TypeError(`"${n}" names no key`);return{code:s,...i,...t}}function Dn(n){const e=n.toLowerCase();if(e in ct)return ct[e];if(/^[a-z0-9]$/i.test(n))return n.toUpperCase().charCodeAt(0);const t=/^f([1-9]|1[0-5])$/i.exec(n);if(t)return 111+Number(t[1]);const r=/^num(?:pad)?([0-9])$/i.exec(n);if(r)return 96+Number(r[1]);if(n==="+")return 187;throw new TypeError(`Unknown key "${n}"`)}class Bn{constructor(e){this.bridge=e}bridge;table=null;async set(e,t){const[r]=await Q(this.bridge,[t]);await this.bridge.note(await this.number(),"write",E(e),r)}async get(e){const t=await this.bridge.note(await this.number(),"read",E(e));return t==null?void 0:P(this.bridge,t)}async has(e){return await this.bridge.note(await this.number(),"has",E(e))===!0}async forget(e){return await this.bridge.note(await this.number(),"forget",E(e))===!0}async objects(){const e=await this.bridge.note(await this.number(),"keys");return Array.isArray(e)?e.filter(t=>t instanceof _).map(t=>C(this.bridge,t.at(),{handle:t})):[]}async clear(){this.table!==null&&await this.bridge.note(this.table,"clear")}async number(){if(await this.bridge.whenReady(),!this.bridge.features.includes("notes"))throw new Error("This game is running a loader from before notes; nothing can be kept beside its objects");return this.table??=this.bridge.allocate(),this.table}}const Wn=127;function qt(n){const e=[],t=[];let r="",a=0;const i=()=>{const o={};for(const l of t)Object.assign(o,l.look);return o},s=()=>{if(r==="")return;const o={text:r,...i()},l=e[e.length-1];l&&Kn(l,o)?l.text+=r:e.push(o),r=""};for(;a<n.length;){const o=n[a];if(o!=="["){r+=o,a++;continue}if(n[a+1]==="["){r+="[",a+=2;continue}const l=n.indexOf("]",a+1),c=l<0?null:qn(n.slice(a+1,l));if(c===null){r+=o,a++;continue}if(c.closing){const h=Yn(t,c.name);h<0?r+=n.slice(a,l+1):(s(),t.splice(h))}else s(),t.push({tag:c.name,look:c.look});a=l+1}return s(),e}function qn(n){if(n.startsWith("/")){const a=n.slice(1);return Un.has(a)?{name:a,closing:!0}:null}const e=n.indexOf("="),t=e<0?n:n.slice(0,e),r=e<0?null:n.slice(e+1);switch(t){case"b":return r===null?{name:t,closing:!1,look:{bold:!0}}:null;case"i":return r===null?{name:t,closing:!1,look:{italic:!0}}:null;case"u":return r===null?{name:t,closing:!1,look:{underline:!0}}:null;case"color":{const a=r===null?null:Gn(r);return a===null?null:{name:t,closing:!1,look:{color:a}}}case"size":{const a=r===null?NaN:Number(r);return Number.isInteger(a)&&a>=1&&a<=Wn?{name:t,closing:!1,look:{size:a}}:null}case"link":return r===null||r===""?null:{name:t,closing:!1,look:{link:r}};default:return null}}const Un=new Set(["b","i","u","color","size","link"]),Vn="0123456789abcdef";function Gn(n){const e=n.toLowerCase(),t=e.startsWith("#")?e.slice(1):e.startsWith("0x")?e.slice(2):null;if(t===null||t.length!==6)return null;let r=0;for(const a of t){const i=Vn.indexOf(a);if(i<0)return null;r=r*16+i}return r}function Yn(n,e){for(let t=n.length-1;t>=0;t--)if(n[t].tag===e)return t;return-1}function Kn(n,e){return["color","bold","italic","underline","size","font","link"].every(r=>n[r]===e[r])}const Pe={className:"avatar.AvatarManager",path:["playerAvatarWorldView","parent"]},ht=new Set(["click","down","up","over","out"]);class Xn{constructor(e){this.bridge=e}bridge;nodes=new Map;async draw(e,t={}){const{handle:r}=await this.make(e,t);return r}world(e={x:0,y:0},t={}){return{place:this.bridge.definition(Pe.className).at(Pe.path[0],Pe.path[1]),x:e.x,y:e.y,...t}}marker(e,t={}){const{kind:r="circle",...a}=t;return this.draw(r,{radius:8,...a,anchor:this.world(e)})}group(e={}){return this.draw("group",e)}text(e,t={}){return this.draw("text",{...t,text:e})}rich(e,t={}){return this.draw("text",{...t,rich:e})}rect(e){return this.draw("rect",e)}circle(e){return this.draw("circle",e)}line(e){return this.draw("line",e)}image(e,t={}){return this.draw("image",{...t,url:e})}async input(e={}){const{handle:t,state:r}=await this.make("input",{width:200,height:24,fill:16777215,stroke:10265519,padding:4,...e,font:{color:1120295,...e.font}});return r.value=e.value??"",Object.assign(t,{value:()=>r.value,setValue:async i=>{r.value=i,r.removed||await this.bridge.draw(t.node,{value:i})},focus:async()=>{r.removed||await this.bridge.draw(t.node,{focus:!0})}})}async button(e,t={}){const{handle:r,state:a}=await this.make("button",{width:72,height:24,fill:8141549,hoverFill:9133302,pressedFill:7153881,cornerRadius:4,...t,font:{color:16777215,bold:!0,...t.font},label:e});return Object.assign(r,{setLabel:i=>a.removed?Promise.resolve():this.bridge.draw(r.node,{label:i}),setDisabled:i=>a.removed?Promise.resolve():this.bridge.draw(r.node,{disabled:i})})}async panel(e={}){const{onMove:t,onResize:r,...a}=e,{handle:i}=await this.make("panel",{width:260,height:200,fill:{color:1120295,alpha:.92},stroke:3621201,titleFill:2042167,titleHeight:22,cornerRadius:6,...a,titleFont:{color:16777215,bold:!0,...a.titleFont}}),s=i;return t&&s.on("move",t),r&&s.on("resize",r),s}async list(e={}){const{handle:t,state:r}=await this.make("list",{width:240,height:160,fill:{color:0,alpha:.55},padding:4,...e,font:{color:16777215,...e.font}});return Object.assign(t,{append:(...a)=>r.removed||a.length===0?Promise.resolve():this.bridge.draw(t.node,{append:a.map(Re)}),setRows:a=>r.removed?Promise.resolve():this.bridge.draw(t.node,{rows:a.map(Re)})})}async replace(e,t){return await t.update({parent:null,host:null,replaces:e}),()=>t.remove()}async attach(e,t){return await t.update({parent:null,replaces:null,host:e}),()=>t.remove()}async focusGame(){await this.bridge.stage().at("focus").set(null)}async clear(){const e=[...this.nodes.entries()].filter(([,t])=>t.parent===null||!this.nodes.has(t.parent)).map(([t])=>t);await this.remove(e)}async make(e,t){var r;const a=this.bridge.allocate(),i={type:e,...this.specOf(t)},s={parent:t.parent?t.parent.node:null,children:new Set,listeners:new Map,failed:new Set,gone:new Set,stopHearing:()=>{},removed:!1,value:""};s.stopHearing=this.bridge.onSubscription(a,o=>{var l;if(o.kind==="overlay"){if(o.event==="failed"){s.failed.forEach(c=>c(o.message??"The image did not load"));return}(o.event==="change"||o.event==="submit")&&o.value!==void 0&&(s.value=o.value),(l=s.listeners.get(o.event))==null||l.forEach(c=>c(o))}}),this.nodes.set(a,s);try{await this.bridge.draw(a,i)}catch(o){throw s.stopHearing(),this.nodes.delete(a),o}return s.parent!==null&&((r=this.nodes.get(s.parent))==null||r.children.add(a)),{handle:this.handle(a,e,s),state:s}}handle(e,t,r){const a=()=>this.remove([e]);return Object.assign(a,{node:e,type:t,update:async s=>{var o,l;if(r.removed)return;const c=this.specOf(s);"parent"in s&&(r.parent!==null&&((o=this.nodes.get(r.parent))==null||o.children.delete(e)),r.parent=s.parent?s.parent.node:null,r.parent!==null&&((l=this.nodes.get(r.parent))==null||l.children.add(e))),await this.bridge.draw(e,c)},show:()=>r.removed?Promise.resolve():this.bridge.draw(e,{visible:!0}),hide:()=>r.removed?Promise.resolve():this.bridge.draw(e,{visible:!1}),remove:a,on:(s,o)=>{const l=o,c=w=>{switch(w.event){case"change":case"submit":case"link":l(w.value??"");return;case"focus":case"blur":l(void 0);return;case"row":l(w.index??-1);return;case"move":l({x:w.x,y:w.y});return;case"resize":l({width:w.width??0,height:w.height??0});return;default:l({x:w.x,y:w.y})}};let h=r.listeners.get(s);const u=!h||h.size===0;h||(h=new Set,r.listeners.set(s,h)),h.add(c);const d=ht.has(s);u&&d&&this.sendMouse(e,r);let g=!1;return async()=>{g||(g=!0,h.delete(c),d&&h.size===0&&!r.removed&&await this.sendMouse(e,r))}},onFailed:s=>(r.failed.add(s),()=>{r.failed.delete(s)}),onRemoved:s=>r.removed?(s(),()=>{}):(r.gone.add(s),()=>{r.gone.delete(s)})})}async sendMouse(e,t){const r=[...t.listeners.entries()].filter(([a,i])=>ht.has(a)&&i.size>0).map(([a])=>a);await this.bridge.draw(e,{mouse:r})}async remove(e){const t=[],r=[],a=s=>{var o;const l=this.nodes.get(s);!l||l.removed||(l.removed=!0,l.stopHearing(),this.nodes.delete(s),t.push(s),r.push(...l.gone),l.gone.clear(),l.children.forEach(a),l.parent!==null&&((o=this.nodes.get(l.parent))==null||o.children.delete(s)))};e.forEach(a);const i=e.filter(s=>t.includes(s));try{await this.bridge.erase(i)}finally{for(const s of r)try{s()}catch(o){console.error("phantom.flash.overlay: a removal listener failed",o)}}}specOf(e){const t={};for(const[r,a]of Object.entries(e))if(a!==void 0)switch(r){case"parent":t.parent=a===null?null:a.node;break;case"anchor":t.anchor=a===null?null:Qn(a);break;case"host":case"replaces":t[r]=a===null?null:Zn(a);break;case"fill":case"background":case"hoverFill":case"pressedFill":case"titleFill":t[r]=a===null?null:er(a);break;case"stroke":t.stroke=a===null?null:tr(a);break;case"font":case"titleFont":t[r]=Jn(a);break;case"rich":t.spans=a===null?null:typeof a=="string"?qt(a):a;break;case"rows":case"append":t[r]=a.map(Re);break;default:t[r]=a}return t}}function Jn(n){return{family:"_sans",size:12,color:16777215,bold:!1,italic:!1,...n}}function Re(n){if(typeof n=="string")return n||" ";const e=(Array.isArray(n)?n:qt(n.markup)).filter(t=>t.text.length>0);return e.length?e:" "}function Qn(n){const e=typeof n=="object"&&n!==null&&"place"in n?n:{place:n},t=E(e.place);return{target:t.target,path:t.path,x:e.x??0,y:e.y??0,refreshFrames:e.refreshFrames??12,hideWhenGone:e.hideWhenGone??!0}}function Zn(n){const e=typeof n=="object"&&n!==null&&"place"in n?n:{place:n},t=E(e.place);return{target:t.target,path:t.path,refreshFrames:e.refreshFrames??12}}function er(n){return typeof n=="number"?{color:n,alpha:1}:{color:n.color,alpha:n.alpha??1}}function tr(n){return typeof n=="number"?{color:n,alpha:1,width:1}:{color:n.color,alpha:n.alpha??1,width:n.width??1}}async function nr(n,e,t,r,a={}){const i=e.find(t);if(!i)throw new TypeError(`There is no hook "${t}" in the hook table`);const s={perFrame:a.perFrame??50};a.when!==void 0&&(s.when=a.when),a.first!==void 0&&(s.first=a.first),a.every!==void 0&&(s.every=a.every),a.replaceArgs!==void 0&&(s.replaceArgs=a.replaceArgs),"returns"in a&&(s.skip={returns:a.returns});const o={...Ue(n,i,s,!1),override:!0};let l=0,c=Promise.resolve();const h=he(i),u=async f=>{l++;let p=!1,m=!1;const y=f.args.map(O=>P(n,n.decode(O))),v={};y.forEach((O,H)=>{var b;v[((b=i.parameters[H])==null?void 0:b.name)??String(H)]=O});const T=i.isStatic?C(n,n.definition(i.className),{className:i.className}):P(n,n.decode(f.self)),R={hook:i,call:f.call,self:T,args:v,argList:y,original:async(...O)=>{if(m)throw new L("FLASH",`The call of ${h} has ended: its handler finished`);p=!0;const H=await n.invokeOriginal(d,f.token,O.length===0?null:await Q(n,O));return P(n,H)}};try{await r(R)}catch(O){if(console.error(`The override of ${h} failed: ${O instanceof Error?O.message:String(O)}`),!p&&(a.onError??"original")==="original")try{await n.invokeOriginal(d,f.token,null)}catch(H){console.error(`The original ${h} failed after its override did: ${H instanceof Error?H.message:String(H)}`)}}finally{m=!0,l--;try{await n.overrideDone(d,f.token)}catch{}}},{registration:d,stop:g}=await n.hook(i.id,o,f=>{var p;switch(f.kind){case"override":a.sequential?c=c.then(()=>u(f)):u(f);return;case"hook-dropped":(p=a.onDropped)==null||p.call(a,f.dropped);return;case"hook-failed":console.error(`The override of ${h} failed and is off: ${f.error.message}`);return}}),w=Object.assign(()=>g(),{registration:d,hook:i,stats:async()=>(await n.request({op:"hookStats"})).find(p=>p.registration===d)??null});return Object.defineProperty(w,"running",{get:()=>l,enumerable:!0}),w}const rr={fit:"showAll",stretch:"exactFit",fill:"noBorder",none:"noScale"};class ar{constructor(e){this.bridge=e}bridge;async zoom(e){await this.bridge.definition("room.RoomManagerWorld").at("instance","updateRoomZoom").call(Math.round(e))}async zoomLevel(){return await this.bridge.definition("gMainFrame").at("layerManager","bkg","scaleX").get()*100}async stretch(e){await this.bridge.stage().at("scaleMode").set(rr[e])}hideHud(e){return this.bridge.highlight({target:{kind:"definition",name:"gui.GuiManager"},path:e?["mainHud",e]:["mainHud"]},ce({hide:!0}))}hideLayer(e){return this.bridge.highlight({target:{kind:"definition",name:"gMainFrame"},path:["layerManager",e]},ce({hide:!0}))}async setQuality(e){await this.bridge.stage().at("quality").set(e)}async setFrameRate(e){const t=this.bridge.stage().at("frameRate"),r=await t.get();return await t.set(Math.max(1,Math.min(120,e))),r}}class Xe extends Lt{format="json";envelope;constructor(e,t){super(e,t),this.envelope=ir(e)}static create(e,t,r,a=-1,i="o"){const s=e==="toServer"?{t:"xt",b:{x:i,c:t,r:a,p:r}}:{t:"xt",b:{r:a,o:{_cmd:t,...r}}};return new Xe(JSON.stringify(s),e)}get type(){return this.envelope.t}get command(){var e;const t=this.direction==="toServer"?this.envelope.b.c:(e=this.envelope.b.o)==null?void 0:e._cmd;return typeof t=="string"?t:null}get room(){const e=this.envelope.b.r;return typeof e=="number"&&Number.isInteger(e)?e:null}get params(){if(this.direction==="toServer")return this.envelope.b.p??{};const{_cmd:e,...t}=this.envelope.b.o??{};return t}get value(){return this.envelope}edit(e){e(this.envelope),this.markModified()}serialize(){return JSON.stringify(this.envelope)}}function ir(n){let e;try{e=JSON.parse(n)}catch(t){throw new Ze(`Not JSON: ${t.message}`,"JSON_SYNTAX")}if(!ut(e)||typeof e.t!="string"||!ut(e.b))throw new Ze('A JSON message is an object with "t" and "b"',"JSON_SYNTAX");return e}function ut(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}class dt extends Lt{constructor(e,t,r=null){super(e,t),this.problem=r}problem;format="raw";get command(){return null}get room(){return null}serialize(){return this.raw}}function Ut(n,e){try{switch(n.charAt(0)){case"<":return new sn(n,e);case rn:return new an(n,e);case"{":return new Xe(n,e);default:return new dt(n,e)}}catch(t){return new dt(n,e,t)}}const Ge={send:"avatar.UserCommXtCommManager.onSendMessage",focusChat:"gui.ChatHistory.setFocusOnMsgText"};function sr(n,e){const t=new Map;for(const[s,o]of Object.entries(e))t.set(s.toLowerCase(),o);if(t.size===0)return n;let r="",a="";const i=()=>{r+=t.get(a.toLowerCase())??a,a=""};for(const s of n)s===" "||s===" "?(i(),r+=s):a+=s;return i(),r}function or(n,e){const t=n.toLowerCase();return e.some(r=>typeof r=="string"?r!==""&&t.includes(r.toLowerCase()):(r.lastIndex=0,r.test(n)))}async function lr(n,e={}){const{arg:t,fromClass:r,equals:a,exists:i,all:s}=n.flash.rules,o=e.shortcuts??{},l=e.blocked??[],c=r("avatar.UserCommXtCommManager","_mainHud","chatBar","text01_chat","text"),h=[],u=Je(async()=>{for(const d of h.splice(0).reverse())await d().catch(()=>{})});try{h.push(await n.flash.hook(Ge.send,{when:s(a(t("myMsg"),""),i(c)),replaceArgs:{myMsg:c}})),h.push(await n.flash.override(Ge.send,async d=>{var g;const[w,f]=d.argList,p=typeof f=="string"?f:"";if(p.trim()!==""&&or(p,l)){(g=e.onBlocked)==null||g.call(e,p);return}const m=sr(p,o);m===p?await d.original():await d.original(w,m)},{sequential:!0}))}catch(d){throw await u(),d}return u}async function cr(n,e={}){const t=e.style??{},r=n.flash.overlay,a=n.flash.use("gui.GuiManager").$at("mainHud"),i=e.maxLength??await n.flash.use("gui.GuiManager").$at("chatHist","chatMsgText","maxChars").$get().then(c=>typeof c=="number"&&c>0?c:70).catch(()=>70),s={family:t.font??"_sans",size:t.size??13},o=[],l=Je(async()=>{for(const c of o.splice(0).reverse())await c().catch(()=>{})});try{o.push(async()=>{await n.flash.use("gui.GuiManager").setFocusToChatText()});const c=await r.input({replaces:a.$at("chatBar"),placeholder:t.placeholderText??"Say something",maxLength:i,fill:t.background??16777215,stroke:t.border??8141549,cornerRadius:t.cornerRadius??6,padding:6,font:{...s,color:t.text??1120295}});o.push(()=>c.remove());const h=await r.button(t.buttonLabel??"Send",{replaces:a.$at("sendChatBtn"),fill:t.button??8141549,hoverFill:t.buttonHover??9133302,cornerRadius:t.cornerRadius??6,font:{...s,color:t.buttonText??16777215,bold:!0}});o.push(()=>h.remove());let u=!1;const d=async()=>{const g=c.value();if(!(u||g.trim()==="")){u=!0;try{await n.chat.say(g),await c.setValue(""),await c.focus()}finally{u=!1}}};return o.push(c.on("submit",()=>{d()})),o.push(h.on("click",()=>{d()})),o.push(await n.flash.hook(Ge.focusChat,{skip:!0,phase:"enter",capture:{args:[]}},()=>{c.focus()})),(e.focus??!0)&&await c.focus(),Object.assign(l,{input:c,send:d})}catch(c){throw await l(),c}}const hr=[16096779,1096065,3900150,15485081,9133302,15680580,1357990,15381256],Ce=22;async function ur(n,e={}){const t=e.style??{},r=n.flash.overlay,a=t.nameColors&&t.nameColors.length>0?t.nameColors:hr,i=e.width??280,s=e.height??200,o={family:t.font??"_sans",size:t.size??12},l=new Map,c=[],h=Je(async()=>{for(const u of c.splice(0).reverse())await Promise.resolve(u()).catch(()=>{})});try{const u=await r.panel({title:e.title??"Chat",x:e.x??12,y:e.y??60,width:i,height:s,resizable:!0,fill:{color:t.background??1120295,alpha:t.backgroundAlpha??.9},stroke:t.border??3621201,titleFill:t.titleBar??2042167,titleHeight:Ce,titleFont:{...o,color:t.titleText??16777215,bold:!0},...e.onMove?{onMove:e.onMove}:{}});c.push(()=>u.remove());const d=await r.list({parent:u,width:i,height:s-Ce,fill:null,maxRows:e.maxRows??200,font:{...o,color:t.text??15987958}});c.push(u.on("resize",m=>{var y;(y=e.onResize)==null||y.call(e,m),d.update({width:m.width,height:m.height-Ce})})),c.push(d.on("link",m=>{const y=l.get(m);if(y){if(e.onNameClick){e.onNameClick(y);return}dr(n,y.userId)}}));const g=async m=>{let y=null;if(m.kind===Ee.free||m.kind===Ee.freeSafeChat?y=m.text:m.kind===Ee.safeChat&&(y=await n.chat.phrase(m.text).catch(()=>null)??null),y===null)return null;const v=n.room.players.get(m.userId),T=(v==null?void 0:v.avatarName)||(v==null?void 0:v.userName)||`#${m.userId}`,R=String(m.userId);return l.set(R,{userId:m.userId,name:T}),[{text:T,bold:!0,color:a[Math.abs(m.userId)%a.length],link:R},{text:`: ${y}`}]},f=(await Promise.all(n.chat.recent.map(g))).filter(m=>m!==null);f.length>0&&await d.append(...f);let p=Promise.resolve();return c.push(n.chat.onMessage(m=>{p=p.then(async()=>{const y=await g(m);y&&await d.append(y)}).catch(()=>{})})),Object.assign(h,{panel:u,note:m=>d.append({markup:m})})}catch(u){throw await h(),u}}async function dr(n,e){const t=n.flash.use("avatar.AvatarManager").avatarViewList.$at(String(e)),r=await n.flash.highlight(t,{color:16436245,strength:3});setTimeout(()=>{r()},2e3)}function Je(n){let e=null;return()=>e??=n()}class fr{constructor(e){this.bridge=e,this.overlay=new Xn(e),this.entities=new Nn(this),this.view=new ar(e)}bridge;overlay;entities;view;rules=Fn;hookIndex=null;use(e){return C(this.bridge,this.bridge.definition(e),{className:e})}global(e){return C(this.bridge,this.bridge.definition(e))}stage(){return C(this.bridge,this.bridge.stage())}client(){return C(this.bridge,this.bridge.gameClient())}whenReady(){return this.bridge.whenReady()}hooks(e){if(e!==void 0||!this.hookIndex){const t=this.bridge.hookTable(e).then(r=>new $n(r));t.catch(()=>{this.hookIndex===t&&(this.hookIndex=null)}),this.hookIndex=t}return this.hookIndex}async hook(e,t={},r){return In(this.bridge,await this.hooks(),e,t,r)}async override(e,t,...[r]){return nr(this.bridge,await this.hooks(),e,t,r??{})}style(e,t){return this.bridge.style(E(e),t)}hold(e,t,r={}){return lt(this.bridge,[{place:e,value:t}],r)}holdAll(e,t={}){return lt(this.bridge,e,t)}repeat(e,t={}){return Ln(this.bridge,e,t)}collect(e,t,r={}){return Rn(this.bridge,e,t,r)}async track(e,t,r={}){if(await this.bridge.whenReady(),!this.bridge.features.includes("track"))throw new Error("This game is running a loader from before lists; look for them yourself");const a=r.where===void 0?{target:{kind:"stage"},path:[]}:E(r.where),i=s=>s.filter(o=>o instanceof _).map(o=>C(this.bridge,o.at(),{handle:o}));return this.bridge.track(a,e,{...r.mode!==void 0?{mode:r.mode}:{},...r.everyFrames!==void 0?{everyFrames:r.everyFrames}:{}},({added:s,removed:o})=>t({added:i(s),removed:i(o)}))}async snapshot(e,t={}){if(await this.bridge.whenReady(),!this.bridge.features.includes("snapshot"))throw new Error("This game is running a loader from before pictures; nothing can be drawn");return this.bridge.snapshot(E(e),t)}notes(){return new Bn(this.bridge)}async find(e,t){return await _n(this.bridge,t,e??{})}answering(e,t){return new Pn(this.bridge,e,t)}watch(e,t,r){const a=r;let i,s=[],o;if(Array.isArray(e))i="list",o=[...e];else if(wr(e))i="one",o=[e];else{i="record";const u=e;s=Object.keys(u),o=s.map(d=>u[d])}const l=o.map(E),c=u=>i==="one"?u[0]:i==="list"?u:Object.fromEntries(s.map((d,g)=>[d,u[g]]));let h=null;return this.bridge.watch(l,t,(u,d)=>{const g=u.map(p=>P(this.bridge,p)),w=c(g),f=l.map((p,m)=>(d==null?void 0:d[m])??null);a(w,h,i==="one"?f[0]:c(f)),h=w})}onTick(e,t={}){return this.bridge.tick(t.everyFrames??1,e)}highlight(e,t={}){return this.bridge.highlight(E(e),ce(t))}hide(e){return this.bridge.highlight(E(e),ce({hide:!0}))}recolor(e,t){const r=t?E(t):{target:{kind:"loader"},path:[]};return this.bridge.highlight(r,{glow:null,...zt(e),hide:!1,pulse:null})}onKey(e,t,r={}){return this.bridge.onKey(Hn(e,r),a=>gr(t)({code:a.code,char:a.char,ctrl:a.ctrl,shift:a.shift,alt:a.alt,phase:a.phase,consumed:a.consumed===!0}))}}function gr(n){return e=>{try{const t=n(e);t instanceof Promise&&t.catch(r=>ft(r))}catch(t){ft(t)}}}function ft(n){console.error("phantom.flash.onKey: a listener failed",n)}function wr(n){try{return E(n),!0}catch{return!1}}const pr={avatarManager:"avatar.AvatarManager"},mr="com.sbi.loader.LoaderCache.fetchCDNURL",yr=2e4;class br{channel;flash;hooks=new Map;constructor(e,t){this.channel=e.content??null,this.flash=t}get available(){return this.channel!==null}async replace(e,t){const r=this.reach(),a=gt(e);await this.unhook($e(a));const i=await r.replace(a,Fe(t)),s=[],o=await this.pointClientAt(a,i.url);return o&&(this.hooks.set($e(a),o),s.push("client")),s.push("proxy"),{...i,how:s,stop:()=>this.restore(a).then(()=>{})}}async restore(e){const t=this.reach(),r=gt(e);return await this.unhook($e(r)),t.restore(r)}replacements(){return this.reach().list()}onRequest(e){return this.reach().observe(e)}async replaceOnScreen(e,t,r={}){const{url:a,id:i}=await this.addressOf(t),{refreshFrames:s,...o}=r,l=await this.flash.overlay.image(a,{...o,replaces:s===void 0?e:{place:e,refreshFrames:s}});return{url:a,stop:async()=>{await l.remove(),i&&await this.reach().release(i)}}}async load(e,t={}){const r=this.flash.bridge,a=Fe(e),i=await r.construct("flash.display.Loader"),s=[];try{const o=await r.definition("flash.system.ApplicationDomain").at("currentDomain").get();s.push(()=>o.release());const l=await r.construct("flash.system.LoaderContext",!1,o);s.push(()=>l.release()),await l.at("allowCodeImport").set(t.allowCode===!0).catch(()=>{});const c=this.whenLoaded(i,t.timeoutMs??yr);if(a.kind==="data-url"){const u=await this.decodeInFlash(a.url);s.push(()=>u.release()),await i.at("loadBytes").call(u,l)}else{const u=await this.reach().hold(a);s.push(()=>this.reach().release(u.id)),await i.at("load").call(new ke("flash.net.URLRequest",[u.url]),l)}await c;const h=await i.at("content").get();if(!h)throw new Error("Nothing was loaded");return{content:h,loader:i,unload:async()=>{await i.at("unloadAndStop").call().catch(()=>{}),await h.release().catch(()=>{}),await i.release().catch(()=>{})}}}catch(o){throw await i.release().catch(()=>{}),o}finally{for(const o of s)await o().catch(()=>{})}}async pointClientAt(e,t){if(e.kind==="pattern")return null;const r=vr(e.value);if(!r)return null;const{arg:a,equals:i,startsWith:s,any:o}=this.flash.rules,l=e.kind==="prefix"?s:i;try{return await this.flash.hook(mr,{when:o(l(a("assetPath"),r),l(a("assetPath"),`/${r}`)),replaceReturn:t})}catch{return null}}async unhook(e){const t=this.hooks.get(e);t&&(this.hooks.delete(e),await t().catch(()=>{}))}async addressOf(e){const t=Fe(e);if(t.kind==="data-url")return{url:t.url,id:null};const r=await this.reach().hold(t);return{url:r.url,id:r.id}}async decodeInFlash(e){const t=e.indexOf(",");if(t===-1||e.slice(0,t).indexOf(";base64")===-1)throw new Error("Only base64 data: URLs can be loaded into the client");const r=await this.flash.bridge.definition("phantom.overlay.Base64").at("decode").call(e.slice(t+1));if(!r)throw new Error("The loader could not decode those bytes");return r}whenLoaded(e,t){const r=e.at("contentLoaderInfo");return new Promise((a,i)=>{const s=[],o=h=>{clearTimeout(l);for(const u of s.splice(0))u().catch(()=>{});h?i(h):a()},l=setTimeout(()=>o(new Error(`Flash did not load those bytes within ${t}ms`)),t),c=(h,u)=>r.listen(h,()=>o(u===null?null:new Error(u))).then(d=>s.push(d),d=>o(d));c("complete",null),c("ioError","Flash could not read those bytes"),c("securityError","Flash refused those bytes")})}reach(){if(!this.channel)throw new Error("This game cannot replace content: it was made without a content origin");return this.channel}}function $e(n){return`${n.kind}:${n.value}`}function vr(n){let e=n.charAt(0)==="/"?n.slice(1):n;const t=e.indexOf("?");t!==-1&&(e=e.slice(0,t)),e.slice(0,8)==="content/"&&(e=e.slice(8));const r=e.indexOf("/"),a=r===-1?e:e.slice(0,r);return r!==-1&&a.length>0&&kr(a)&&(e=e.slice(r+1)),e}function kr(n){for(const e of n)if(e<"0"||e>"9")return!1;return n.length>0}function gt(n){const e=typeof n=="string"?{kind:"path",value:n}:n;if(!e||typeof e.value!="string"||!e.value)throw new TypeError("A replacement matches a path, a prefix or a pattern");const t=e.kind;if(t!=="path"&&t!=="prefix"&&t!=="pattern")throw new TypeError(`${t} is not path, prefix or pattern`);const r=e.value.charAt(0)==="/"?e.value:`/${e.value}`;return{kind:t,value:r}}function Fe(n){if(typeof n=="string")return n.slice(0,5).toLowerCase()==="data:"?{kind:"data-url",url:n}:{kind:"file",path:n};if(n instanceof ArrayBuffer)return{kind:"bytes",bytes:new Uint8Array(n)};if(ArrayBuffer.isView(n)){const e=n;return{kind:"bytes",bytes:new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}}if(n&&typeof n=="object"){const e="contentType"in n&&n.contentType?n.contentType:null,t=e?{contentType:e}:{};if("bytes"in n){const r=n.bytes,a=r instanceof ArrayBuffer?new Uint8Array(r):r;if(!(a instanceof Uint8Array))throw new TypeError("bytes are a Uint8Array");return{kind:"bytes",bytes:a,...t}}if("dataUrl"in n&&typeof n.dataUrl=="string")return{kind:"data-url",url:n.dataUrl,...t};if("file"in n&&typeof n.file=="string")return{kind:"file",path:n.file,...t}}throw new TypeError("A source is bytes, a data: URL, or the path of a file on this computer")}const F={definitionByName:"GETDEFINITIONBYNAME",resourceStack:"com.sbi.loader.ResourceStack",guiManager:"gui.GuiManager",loadProgress:"loadProgress.LoadProgress",denEditor:"gui.DenEditor",fonts:"gui.Fonts",palette:"com.sbi.graphics.PaletteHelper",colorTable:"gui.ColorTable",avatarManager:"avatar.AvatarManager"},xr={message:"com.sbi.popup.SBMessage",ok:"com.sbi.popup.SBOkPopup",okCancel:"com.sbi.popup.SBOkCancelPopup",yesNo:"com.sbi.popup.SBYesNoPopup",titled:"com.sbi.popup.SBStandardTitlePopup",parchment:"com.sbi.popup.SBParchmentPopup"},Ye={ink:1118483,line:3816e3,light:15790322,muted:10000543,accent:8141549,danger:15680580,size:12,cornerRadius:4},Ke={ink:4403228,line:9071167,light:16643032,muted:9402972,accent:3123423,danger:13369344,size:11,cornerRadius:8},D={game:28,phantom:24},Ie=22,Le=4,wt={top:12,left:10,right:10,bottom:12},pt=4293980400,Tr=12e4,Or=500;function U(n){return(...e)=>{try{const t=n(...e);t instanceof Promise&&t.catch(B)}catch(t){B(t)}}}function B(n){console.error("phantom.ui: a listener failed",n)}function Ne(n,e){console.warn(`phantom.ui: the picture ${n} did not load: ${e}`)}const ge={game:110,phantom:96},V=2,mt=.5,ye="_sans";function Mr(n,e=ye){return{skin:n,font:e,...n==="game"?Ke:Ye}}const Er={PopupSkin:"The plain popup frame: `ba` (its `t`, `m` and `b` slices) and `c`, its content box.",PopupContent:"What a plain popup shows: a `text` field the popup sizes itself around.",OkPopupSkin:"The frame of a popup with one button.",OkPopupContent:"An OK button (`okBtn`) and the `text` above it.",YesNoPopupSkin:"The frame of a popup with two buttons.",YesNoPopupContent:"Yes (`yesBtn`) and No (`noBtn`), and the `text` above them.",okCancelPopupContent:"OK (`okCancelBtn`) and Cancel (`cancelBtn`).",ConfirmSkin:"The frame the client asks you to confirm something in.",Tooltip:"The client's own tooltip (`gui.ToolTipPopup`): `txt`, and `l`, `m` and `r`.",HelpTxtBubble:"The bubble the client points at something it is explaining.",closeBtn:"The round close button in the corner of the client windows.",scrollbar2:"A scrollbar: `track`, `handle`, `topBtn` and `botBtn`.",BuddyListPopup:"The buddy list window's frame.",BuddyListContent:"What the buddy list shows inside that frame.",BD_AvatarEditorSkin:"The frame of the avatar editor's own dialog.",BD_AvatarEditorContent:"What that dialog shows.",DenEditorAsset:"The whole den editor, as the client builds it.",MySettings:"The settings window.",MainHud:"The whole HUD.",FreeNameBar:"The name bar above a player who is not a member.",memberNameBar:"The name bar above a member.",AnimsTitleBanner:"The banner the client puts a title in.",ChatBalloonAsset:"A chat balloon.",Cursor:"The client's own mouse cursor.",QuestPickupIcon:"The icon an adventure shows over something to pick up.",MinigameLobbySkin:"A minigame lobby's frame.",MinigameLobbyContent:"What a minigame lobby shows.",BroadcastPopupSkin:"The frame an announcement is shown in.",BroadcastPopupContent:"What an announcement shows.",DenLockPopupSkin:"The frame of the den's lock settings.",DenLockPopupContent:"What the den lock settings show.",ReportRulesPopupSkin:"The frame of the report window's rules.",ReportRulesPopupContent:"What the report rules show."},Sr=/^[A-Za-z_][A-Za-z0-9_]*$/;function yt(n){if(!Sr.test(n))throw new TypeError(`"${n}" is not a symbol name: a symbol is named in letters, digits and underscores`);return n}const bt={gui:{className:F.guiManager,path:["guiLayer"]},hud:{className:F.guiManager,path:["mainHud"]},room:{className:F.avatarManager,path:["playerAvatarWorldView","parent"]},avatarEditor:{className:F.guiManager,path:["avatarEditor","avEditor"]},denEditor:{className:F.denEditor,path:["staticEditor"]}},vt="stage",kt={avatarEditor:{open:"gui.AvatarEditor.init",close:"gui.AvatarEditor.destroy",spot:"avatarEditor"},denEditor:{open:"gui.DenEditor.init",close:"gui.DenEditor.destroy",spot:"denEditor"},settings:{open:"gui.MySettings.init",close:"gui.MySettings.destroy",spot:null},buddyList:{open:"buddy.BuddyList.init",close:"buddy.BuddyList.destroy",spot:null},petCreator:{open:"gui.PetCreator.init",close:"gui.PetCreator.destroy",spot:null},achievements:{open:"gui.AchievementViewer.init",close:"gui.AchievementViewer.destroy",spot:null},bulletinBoard:{open:"gui.BulletinBoard.init",close:"gui.BulletinBoard.destroy",spot:null},playerSearch:{open:"gui.PlayerSearch.init",close:"gui.PlayerSearch.destroy",spot:null},recycle:{open:"gui.RecycleItems.init",close:"gui.RecycleItems.destroy",spot:null},trade:{open:"gui.TradeManager.init",close:"gui.TradeManager.destroy",spot:null},petInventory:{open:"gui.PetInventory.init",close:"gui.PetInventory.destroy",spot:null},reportPlayer:{open:"gui.ReportAPlayer.init",close:"gui.ReportAPlayer.destroy",spot:null},serverSelector:{open:"gui.ServerSelector.init",close:"gui.ServerSelector.destroy",spot:null}},Ar=5,Pr=18,ae=8,_e=16,Rr=240,je=20,Cr=48,$r=-80,xt={x:12,y:-10},M=8,ze=22,Tt={game:320,phantom:300},Fr={game:190,phantom:150},we={x:60,y:90},Ir={ok:0,yesNo:1,continueExit:2,continue:3};function Lr(n,e,t={}){const r={slot:"layer"},a={slot:"callback"},i=t.name??null,s=xr[n];switch(n){case"message":return{className:s,args:[r,{slot:"skin"},e,!0,!0,t.modal??!1,t.draggable??!0,t.darken??!1,i]};case"ok":return{className:s,args:[r,e,t.darken??!0,null,!0,!0,t.modal??!0,t.draggable??!1,i]};case"yesNo":return{className:s,args:[r,e,t.darken??!0,a,null,!0,!0,t.modal??!0,t.draggable??!1,i]};case"okCancel":return{className:s,args:[r,e,t.darken??!0,a,null]};case"titled":return{className:s,args:[r,e,t.title??null,t.mediaId??370,a,!0,t.darken??!0]};case"parchment":return{className:s,args:[r,Ir[t.buttons??"ok"],e,t.darken??!0,a,null]}}}function Ot(n){const e=Math.max(1,Math.floor(n.columns)),t=[];for(let r=0;r<Math.max(0,Math.floor(n.count));r++){const a=Math.floor(r/e),i=r%e;t.push({index:r,row:a,column:i,x:i*(n.tileWidth+n.gap),y:a*(n.tileHeight+n.gap),width:n.tileWidth,height:n.tileHeight})}return t}function Nr(n,e){const t=e.gap,r=n.length;if(r===0)return[];const a=(e.width+t)/r;return n.map((i,s)=>{const o=Math.round(s*a),l=s===r-1?e.width+t:Math.round((s+1)*a);return{index:s,value:i,x:o,width:Math.max(0,l-o-t)}})}function _r(n){const e=Math.max(0,n.contentHeight-n.viewHeight),t=Math.min(e,Math.max(0,n.offset)),r=n.minThumb??16,a=n.contentHeight>0?n.viewHeight/n.contentHeight:1,i=Math.max(Math.min(n.trackHeight,r),Math.min(n.trackHeight,Math.round(n.trackHeight*a))),s=n.trackHeight-i;return{offset:t,max:e,thumbY:e>0?Math.round(t/e*s):0,thumbHeight:i}}function jr(n,e,t){const r=Math.max(1,Math.round(n-e-t+1)),a=-Math.floor(r/2);return{middle:r,middleY:a,topY:a-e,bottomY:a+r-1}}function zr(n,e){const t=e?{top:e.y,left:e.x,right:n.width-e.x-e.width,bottom:n.height-e.y-e.height}:null,r=(s,o)=>{const l=t==null?void 0:t[s];return l!==void 0&&Number.isFinite(l)&&l>=2&&l<=o/4?Math.ceil(l):wt[s]},a={top:r("top",n.height),left:r("left",n.width),right:r("right",n.width),bottom:r("bottom",n.height)},i={x:a.left+Le,y:a.top,width:Math.max(0,Math.floor(n.width-a.left-a.right-2*Le)),height:Math.max(Ie,Math.floor(n.height-a.top-a.bottom-Le))};return{edge:a,measured:t!==null&&Object.keys(wt).every(s=>a[s]===Math.ceil(t[s])),panel:i,titleHeight:Ie,body:{width:i.width,height:i.height-Ie}}}class Hr{bridge;flash;drawn=new Set;popups=new Set;tags=new Map;symbolMaker=null;gameFont=null;defaultSkin="phantom";known={art:!1,palettes:!1};readyTimeoutMs=Tr;popup;constructor(e,t){this.bridge=e.flash,this.flash=t,this.popup=new Dr((r,a,i,s,o)=>this.openPopup(r,a,i,s,o),()=>this.clear())}get skin(){return this.defaultSkin}set skin(e){this.defaultSkin=e}async status(){const[e,t]=await Promise.all([this.artLoaded(),this.palettesLoaded()]);return{art:e,palettes:t}}async ready(e=this.readyTimeoutMs){const t=await this.waitFor({art:!0,palettes:!0},e);if(t.art&&t.palettes)return t;const r=[t.art?null:"its library art",t.palettes?null:"its colour palettes"].filter(Boolean);throw new Error(`The game has not loaded ${r.join(" or ")} yet: waited ${Math.round(e/1e3)} seconds`)}async theme(e){const t=e??this.defaultSkin;return Mr(t,t==="game"?await this.clientFont():ye)}symbols(){return Object.entries(Er)}async hasSymbol(e){const t=yt(e);try{return await this.bridge.definition(F.resourceStack).at("hudAssetsLoaderInfo","applicationDomain","hasDefinition").call(t)===!0}catch{return!1}}async symbol(e,t={}){const r=yt(e);await this.waitFor({art:!0});const a=await this.flash.overlay.group({x:t.x??0,y:t.y??0,...t.scale===void 0?{}:{scale:t.scale},...t.visible===void 0?{}:{visible:t.visible}});let i=null;try{i=await(await this.maker()).at("apply").call(null,[r,t.localize===!0]),await(await this.nodeObject(a)).at("addChild").call(i),await this.adopt(a,{...t.parent===void 0||t.parent===null?{}:{parent:S(t.parent)},...t.host===void 0?{}:{host:t.host===null?null:this.placeOf(t.host)},...t.replaces===void 0?{}:{replaces:t.replaces===null?null:this.placeOf(t.replaces)}})}catch(h){throw await a.remove(),i&&await this.bridge.release([i]).catch(()=>{}),h}const s=i,o=s.at(),l=new Set;return this.widget(a,t.skin??this.defaultSkin,{name:r,object:s,on:async(h,u)=>{const d=await o.listen(Mt[h],()=>u()),g=async()=>{l.delete(g),await d()};return l.add(g),g},size:async()=>({width:await s.at("width").get()??0,height:await s.at("height").get()??0})},async()=>{for(const h of[...l])await h().catch(()=>{});await this.bridge.release([s]).catch(()=>{})})}async window(e={}){const t=e.skin??this.defaultSkin,r=t==="game",a=r&&(await this.waitFor({art:!0})).art,i=await this.theme(t),s={width:e.width??280,height:e.height??200},o={x:e.x??40,y:e.y??40},l=r?30:24,c=await this.flash.overlay.panel({x:o.x,y:o.y,width:s.width,height:s.height,title:e.title??"",titleHeight:l,draggable:e.draggable!==!1,resizable:e.resizable===!0&&!r,cornerRadius:i.cornerRadius,fill:r?{color:i.light,alpha:0}:{color:i.ink,alpha:.94},stroke:r?null:i.line,titleFill:i.line,titleFont:{family:i.font,size:i.size+1,bold:!0,color:i.light},visible:!1});let h=null;if(a)try{h=await this.dressWindow(c,s.height)}catch(m){console.warn(`phantom.ui.window: the popup frame could not be drawn: ${Y(m)}`)}else r&&console.warn(`phantom.ui.window: the game has not loaded its popup art after ${Math.round(this.readyTimeoutMs/1e3)} seconds, so "${e.title??""}" is drawn in the game skin's colours instead`);const u=h?{x:h.layout.panel.x,y:h.layout.panel.y}:{x:0,y:0};if(h?await c.update({x:o.x+u.x,y:o.y+u.y,width:h.layout.panel.width,height:h.layout.panel.height,titleHeight:h.layout.titleHeight,titleFill:{color:i.line,alpha:.004},titleFont:{family:i.font,size:i.size+1,bold:!0,color:i.ink}}):r&&await c.update({fill:{color:Ke.light,alpha:.96},stroke:{color:Ke.line,width:2}}),e.parent)try{await this.adopt(c,{parent:S(e.parent)})}catch(m){throw await c.remove(),h&&await this.bridge.release(h.held).catch(()=>{}),m}const d=h?{width:h.width,height:h.height,bodyWidth:h.layout.body.width,bodyHeight:h.layout.body.height}:{...s,bodyWidth:s.width,bodyHeight:Math.max(0,s.height-l)},g=new Set,w=[],f=this.widget(c,t,{body:c,...d,framed:h!==null,move:(m,y)=>c.update({x:m+u.x,y:y+u.y}),setTitle:m=>c.update({title:m}),onClose:m=>(g.add(m),async()=>{g.delete(m)}),onMove:m=>{const y=c.on("move",({x:v,y:T})=>m({x:v-u.x,y:T-u.y}));return async()=>{await y()}}},async()=>{for(const m of w.splice(0))await m().catch(()=>{});h&&await this.bridge.release(h.held).catch(()=>{})}),p=()=>{f().then(()=>g.forEach(m=>m()))};if(e.closable!==!1&&(h!=null&&h.close)){const m=await h.close.at().listen(Mt.down,p);w.push(async()=>{await m()})}else e.closable!==!1&&(await this.flash.overlay.button("x",{parent:c,x:d.bodyWidth-(r?26:24),y:2,width:18,height:16,cornerRadius:i.cornerRadius,fill:i.line,hoverFill:{color:i.danger,alpha:.8},font:{family:i.font,size:i.size,bold:!0,color:i.light}})).on("click",p);return e.visible!==!1&&await c.show(),f}async button(e,t={}){const r=t.skin??this.defaultSkin,a=await this.theme(r),i=this.box(t,{width:ge[r],height:D[r]}),s=i.width??ge[r],o=i.height??D[r],l=t.image===void 0?null:await this.flash.overlay.group({x:i.x??0,y:i.y??0,...i.parent?{parent:i.parent}:{},...i.visible===void 0?{}:{visible:i.visible}});let c=e,h=l===null||t.imageOnly!==!0,u=t.disabled===!0;const d=await this.flash.overlay.button(h?c:"",{...l===null?i:{x:0,y:0,width:s,height:o,parent:l},...ie(a,t.primary===!0),cornerRadius:a.cornerRadius,...t.disabled===void 0?{}:{disabled:t.disabled},font:{family:a.font,size:a.size,bold:!0,color:t.primary===!0||r==="phantom"?a.light:a.ink}}),g=o-V*2,w=t.imageOnly===!0?{width:s-V*2,height:g}:{width:g,height:g};let f=null;const p=async()=>{h||(h=!0,await d.setLabel(c))},m=async y=>{if(f){await f.update({url:y});return}f=await this.picture(y,{parent:l,x:V,y:V,...w,...u?{alpha:mt}:{}},v=>{Ne("on a button",v),p().catch(B)})};return t.image!==void 0&&await m(t.image),this.widget(l??d,r,{label:()=>c,setLabel:async y=>{c=y,await d.setLabel(h?y:"")},setDisabled:async y=>{u=y,await d.setDisabled(y),f&&await f.update({alpha:y?mt:1})},setImage:async y=>{if(l===null)throw new TypeError("This button was drawn without a picture, so there is nowhere to put one: give it `image` when it is drawn");if(y===null){const v=f;f=null,await(v==null?void 0:v.remove()),await p();return}h=t.imageOnly!==!0,await d.setLabel(h?c:""),await m(y)},onClick:y=>{const v=d.on("click",U(y));return async()=>{await v()}}})}async label(e,t={}){const r=t.skin??this.defaultSkin,a=await this.theme(r),i=await this.flash.overlay.text(e,{x:t.x??0,y:t.y??0,...t.parent?{parent:S(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible},centered:t.centered===!0,font:{family:a.font,size:t.heading===!0?a.size+3:a.size,bold:t.heading===!0,color:t.muted===!0?a.muted:r==="game"?a.ink:a.light},...t.background===!0?{background:r==="game"?{color:a.light,alpha:.9}:{color:a.ink,alpha:.7},padding:4}:{}});return this.widget(i,r,{setText:s=>i.update({text:s})})}async input(e={}){const t=e.skin??this.defaultSkin,r=await this.theme(t),a=await this.flash.overlay.input({...this.box(e,{width:200,height:D[t]}),...e.value===void 0?{}:{value:e.value},...e.placeholder===void 0?{}:{placeholder:e.placeholder},...e.maxLength===void 0?{}:{maxLength:e.maxLength},...e.multiline===void 0?{}:{multiline:e.multiline},...e.disabled===void 0?{}:{disabled:e.disabled},fill:t==="game"?r.light:16777215,stroke:r.line,cornerRadius:r.cornerRadius,font:{family:r.font,size:r.size,color:t==="game"?r.ink:1120295}});return this.widget(a,t,{value:()=>a.value(),setValue:i=>a.setValue(i),focus:()=>a.focus(),onChange:i=>{const s=a.on("change",U(i));return async()=>{await s()}},onSubmit:i=>{const s=a.on("submit",U(i));return async()=>{await s()}}})}async checkbox(e,t={}){const r=t.skin??this.defaultSkin,a=await this.theme(r),i=await this.flash.overlay.group({x:t.x??0,y:t.y??0,...t.parent?{parent:S(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}});let s=t.checked===!0;const o=await this.flash.overlay.button(s?"x":"",{parent:i,width:14,height:14,cornerRadius:Math.min(3,a.cornerRadius),fill:r==="game"?a.light:{color:a.ink,alpha:.9},hoverFill:r==="game"?16777215:{color:a.line,alpha:.9},stroke:a.line,font:{family:a.font,size:a.size,bold:!0,color:a.accent}});await this.flash.overlay.text(e,{parent:i,x:20,y:0,font:{family:a.font,size:a.size,color:r==="game"?a.ink:a.light}});const l=new Set,c=async h=>{s=h,await o.setLabel(h?"x":"")};return o.on("click",()=>{c(!s).then(()=>l.forEach(h=>h(s)))}),this.widget(i,r,{checked:()=>s,setChecked:c,onChange:h=>(l.add(h),async()=>{l.delete(h)})})}async dropdown(e){var t;const r=e.skin??this.defaultSkin,a=await this.theme(r),i=e.width??140,s=e.height??D[r],o=await this.flash.overlay.group({x:e.x??0,y:e.y??0,...e.parent?{parent:S(e.parent)}:{},...e.visible===void 0?{}:{visible:e.visible}});let l=[...e.choices],c=e.value??((t=l[0])==null?void 0:t.value)??null;const h=f=>{var p;return((p=l.find(m=>m.value===f))==null?void 0:p.label)??e.placeholder??"Choose..."},u=await this.flash.overlay.button(h(c),{parent:o,width:i,height:s,cornerRadius:a.cornerRadius,...ie(a,!1),font:{family:a.font,size:a.size,color:r==="game"?a.ink:a.light}}),d=await this.flash.overlay.list({parent:o,y:s+2,width:i,height:Math.min(140,Math.max(20,l.length*16+8)),visible:!1,fill:r==="game"?a.light:{color:a.ink,alpha:.96},stroke:a.line,cornerRadius:a.cornerRadius,rows:l.map(f=>f.label),font:{family:a.font,size:a.size,color:r==="game"?a.ink:a.light}});let g=!1;const w=new Set;return u.on("click",()=>{g=!g,g?d.show():d.hide()}),d.on("row",f=>{const p=l[f];g=!1,d.hide(),p&&(c=p.value,u.setLabel(p.label).then(()=>w.forEach(m=>m(p.value))))}),this.widget(o,r,{value:()=>c,setValue:async f=>{c=f,await u.setLabel(h(f))},setChoices:async f=>{l=[...f],await d.setRows(l.map(p=>p.label)),await u.setLabel(h(c))},onChange:f=>(w.add(f),async()=>{w.delete(f)})})}async tabs(e){var t;const r=e.skin??this.defaultSkin,a=await this.theme(r),i=e.width??260,s=e.tabHeight??22,o=await this.flash.overlay.group({x:e.x??0,y:e.y??0,...e.parent?{parent:S(e.parent)}:{},...e.visible===void 0?{}:{visible:e.visible}}),l=Nr(e.tabs.map(w=>w.value),{width:i,gap:2});let c=e.value??((t=e.tabs[0])==null?void 0:t.value)??"";const h=new Map,u=new Map,d=new Set;for(const w of l){const f=e.tabs[w.index];u.set(f.value,await this.flash.overlay.button(f.label,{parent:o,x:w.x,width:w.width,height:s,cornerRadius:a.cornerRadius,...ie(a,f.value===c),font:{family:a.font,size:a.size,bold:f.value===c,color:f.value===c||r==="phantom"?a.light:a.ink}})),h.set(f.value,await this.flash.overlay.group({parent:o,y:s+4,visible:f.value===c}))}const g=async w=>{if(h.has(w)){c=w;for(const[f,p]of h)await(f===w?p.show():p.hide());for(const[f,p]of u)await p.update({...ie(a,f===w),font:{family:a.font,size:a.size,bold:f===w,color:f===w||r==="phantom"?a.light:a.ink}})}};for(const[w,f]of u)f.on("click",()=>{g(w).then(()=>d.forEach(p=>p(w)))});return this.widget(o,r,{current:()=>c,select:g,body:w=>{const f=h.get(w);if(!f)throw new TypeError(`There is no tab called "${w}"`);return f},onSelect:w=>(d.add(w),async()=>{d.delete(w)})})}async list(e={}){const t=e.skin??this.defaultSkin,r=await this.theme(t),a=await this.flash.overlay.list({...this.box(e,{width:240,height:160}),...e.rows===void 0?{}:{rows:[...e.rows]},...e.maxRows===void 0?{}:{maxRows:e.maxRows},fill:t==="game"?r.light:{color:r.ink,alpha:.85},stroke:r.line,cornerRadius:r.cornerRadius,font:{family:r.font,size:r.size,color:t==="game"?r.ink:r.light}});return this.widget(a,t,{setRows:i=>a.setRows([...i]),append:(...i)=>a.append(...i),onRow:i=>{const s=a.on("row",U(i));return async()=>{await s()}}})}async grid(e){const t=e.skin??this.defaultSkin,r=await this.theme(t),a={columns:e.columns??4,tileWidth:e.tileWidth??48,tileHeight:e.tileHeight??48,gap:e.gap??4},i=await this.flash.overlay.group({x:e.x??0,y:e.y??0,...e.parent?{parent:S(e.parent)}:{},...e.visible===void 0?{}:{visible:e.visible}}),s=new Set,o=[],l=async c=>{for(const u of o.splice(0))await u.remove();const h=Ot({count:c.length,...a});for(const u of h){const d=c[u.index],g=await this.flash.overlay.button(d.label??"",{parent:i,x:u.x,y:u.y,width:u.width,height:u.height,cornerRadius:r.cornerRadius,fill:d.color??(t==="game"?r.light:{color:r.ink,alpha:.9}),hoverFill:d.color??(t==="game"?16777215:r.line),pressedFill:d.color??r.accent,stroke:r.line,...d.disabled===void 0?{}:{disabled:d.disabled},font:{family:r.font,size:r.size-2,color:t==="game"?r.ink:r.light}});g.on("click",()=>s.forEach(w=>w(d.value,u.index))),o.push(g),d.image!==void 0&&o.push(await this.picture(d.image,{parent:i,x:u.x+V,y:u.y+V,width:u.width-V*2,height:u.height-V*2},w=>Ne(`on the grid tile ${d.value}`,w)))}};return await l(e.items),this.widget(i,t,{setItems:l,onSelect:c=>(s.add(c),async()=>{s.delete(c)})})}async image(e,t={}){const r=t.skin??this.defaultSkin,a=await this.theme(r),i=await this.flash.overlay.group({x:t.x??0,y:t.y??0,...t.parent?{parent:S(t.parent)}:{},...t.visible===void 0?{}:{visible:t.visible}}),s=new Set;let o=e,l=null,c=!1;const h=async()=>{if(c)return;c=!0;const d=t.width??D[r],g=t.height??D[r],w=await this.flash.overlay.group({parent:i,...t.centered===!0?{x:-Math.round(d/2),y:-Math.round(g/2)}:{}});l=w,await this.flash.overlay.rect({parent:w,width:d,height:g,cornerRadius:a.cornerRadius,fill:r==="game"?{color:a.light,alpha:.6}:{color:a.ink,alpha:.6},stroke:a.line}),!(t.alt===void 0||t.alt==="")&&await this.flash.overlay.text(t.alt,{parent:w,x:Math.round(d/2),y:Math.round(g/2),centered:!0,font:{family:a.font,size:a.size-1,color:a.muted}})},u=await this.picture(o,{parent:i,...t.width===void 0?{}:{width:t.width},...t.height===void 0?{}:{height:t.height},...t.centered===void 0?{}:{centered:t.centered},...t.alpha===void 0?{}:{alpha:t.alpha}},d=>{Ne(t.alt===void 0?"drawn on its own":`of ${t.alt}`,d),h().catch(B),s.forEach(g=>g(d))});return this.widget(i,r,{source:()=>o,setSource:async d=>{o=d;const g=l;l=null,c=!1,await(g==null?void 0:g.remove()),await u.update({url:d})},onFailed:d=>{const g=U(d);return s.add(g),async()=>{s.delete(g)}}})}async scroll(e={}){const t=e.skin??this.defaultSkin,r=await this.theme(t),a=e.width??220,i=e.height??120,s=e.step??32,o=await this.flash.overlay.panel({x:e.x??0,y:e.y??0,width:a,height:i,titleHeight:0,draggable:!1,cornerRadius:r.cornerRadius,fill:t==="game"?{color:r.light,alpha:.9}:{color:r.ink,alpha:.85},stroke:r.line,...e.parent?{parent:S(e.parent)}:{},...e.visible===void 0?{}:{visible:e.visible}}),l=await this.flash.overlay.group({parent:o,x:0,y:0});let c=e.contentHeight??i,h=0;const u=async d=>{h=_r({contentHeight:c,viewHeight:i,offset:d,trackHeight:i}).offset,await l.update({y:-h})};for(const[d,g,w]of[["^",-s,0],["v",s,i-16]])(await this.flash.overlay.button(d,{parent:o,x:a-16,y:w,width:14,height:14,cornerRadius:Math.min(3,r.cornerRadius),...ie(r,!1),font:{family:r.font,size:r.size-2,bold:!0,color:t==="game"?r.ink:r.light}})).on("click",()=>{u(h+g)});return this.widget(o,t,{body:l,offset:()=>h,scrollTo:u,setContentHeight:async d=>{c=d,await u(h)}})}async tooltip(e={}){const t=await this.bubble(e);return e.target&&this.explain(t,S(e.target)),t}async bubble(e){const t=e.skin??this.defaultSkin,r=e.text??"";if(t==="game"){const s=await this.clientTooltip(r,e);if(s)return s}const a=await this.theme(t),i=await this.flash.overlay.text(r,{x:e.x??0,y:e.y??0,visible:e.visible===!0,...e.parent?{parent:S(e.parent)}:{},background:t==="game"?{color:a.light,alpha:.95}:{color:a.ink,alpha:.92},padding:4,font:{family:a.font,size:a.size,color:t==="game"?a.ink:a.light}});return this.widget(i,t,{setText:s=>i.update({text:s}),showAt:async(s,o)=>{await i.update({x:s,y:o,visible:!0})}})}explain(e,t){const r=t.on("over",({x:s,y:o})=>{e.showAt(s+12,o-10).catch(B)}),a=t.on("out",()=>{e.hide().catch(B)}),i=t.onRemoved(()=>{e.remove().catch(B)});e.node.onRemoved(()=>{i(),r().catch(()=>{}),a().catch(()=>{})})}async progress(e={}){const t=e.skin??this.defaultSkin,r=await this.theme(t),a=e.width??200,i=e.height??16,s=await this.flash.overlay.group({x:e.x??0,y:e.y??0,...e.parent?{parent:S(e.parent)}:{},...e.visible===void 0?{}:{visible:e.visible}});await this.flash.overlay.rect({parent:s,width:a,height:i,cornerRadius:r.cornerRadius,fill:t==="game"?r.light:{color:r.ink,alpha:.9},stroke:r.line});let o=Et(e.value??0);const l=await this.flash.overlay.rect({parent:s,width:Math.round(a*o),height:i,cornerRadius:r.cornerRadius,fill:r.accent}),c=await this.flash.overlay.text(e.label??"",{parent:s,x:Math.round(a/2),y:Math.round(i/2),centered:!0,font:{family:r.font,size:r.size-1,bold:!0,color:t==="game"?r.ink:r.light}});return this.widget(s,t,{value:()=>o,setValue:async h=>{o=Et(h),await l.update({width:Math.round(a*o)})},setLabel:h=>c.update({text:h})})}async colors(e={}){const t=e.skin??this.defaultSkin,r=e.columns??10,a=e.swatchWidth??24,i=e.swatchHeight??30,{values:s,indexes:o}=await this.palette(e.palette??1),l=new Set;let c=e.value??o[0]??0;const h=g=>{c=g,l.forEach(w=>w(g,s[g]??0))},u=Math.max(1,Math.ceil(o.length/r)),d=t==="game"?await this.clientColorTable({columns:r,rows:u,width:r*a,height:u*i,values:s,indexes:o,current:c,options:e,tell:h}):await this.swatchGrid({columns:r,swatchWidth:a,swatchHeight:i,values:s,indexes:o,current:c,options:e,tell:h});return this.widget(d,t,{value:()=>c,onPick:g=>(l.add(g),async()=>{l.delete(g)})})}async paletteValues(e="game"){const{values:t,indexes:r}=await this.palette(e);return r.map(a=>t[a]??0)}prompt(e,t={}){let r=()=>{};const a=new Promise(c=>{r=c});let i=!1,s=null;const o=async c=>{if(i)return;i=!0,this.popups.delete(l);const h=s;s=null,h&&await h().catch(()=>{}),r(c)},l=()=>o(null);return this.popups.add(l),(async()=>{const c=t.skin??this.defaultSkin,h=t.width??Tt[c],u=await this.window({skin:c,title:t.title??"",x:t.x??we.x,y:t.y??we.y,width:h,height:Fr[c],closable:!0}),d=u.body,g=u.bodyWidth-2*M;await this.label(e,{skin:c,parent:d,x:M,y:M});const w=await this.input({skin:c,parent:d,x:M,y:M+ze,width:g,...t.value===void 0?{}:{value:t.value},...t.placeholder===void 0?{}:{placeholder:t.placeholder},...t.maxLength===void 0?{}:{maxLength:t.maxLength}}),f={width:Math.min(ge[c],Math.floor((g-M)/2))},p=u.bodyHeight-M-D[c],m=await this.button(t.cancelLabel??"Cancel",{skin:c,parent:d,x:M,y:p,width:f.width}),y=await this.button(t.okLabel??"OK",{skin:c,parent:d,x:u.bodyWidth-M-f.width,y:p,width:f.width,primary:!0});if(s=async()=>{await u(),await this.flash.overlay.focusGame().catch(()=>{})},i){const v=s;s=null,await v();return}w.onSubmit(v=>{o(v)}),y.onClick(()=>{o(w.value())}),m.onClick(()=>{o(null)}),u.onClose(()=>{o(null)}),await w.focus()})().catch(c=>{console.error(`phantom.ui.prompt could not be drawn: ${Y(c)}`),o(null)}),Object.assign(a,{close:l})}choose(e,t,r={}){const a=t.map(u=>typeof u=="string"?{value:u,label:u}:u);let i=()=>{};const s=new Promise(u=>{i=u});let o=!1,l=null;const c=async u=>{if(o)return;o=!0,this.popups.delete(h);const d=l;l=null,d&&await d().catch(()=>{}),i(u)},h=()=>c(null);return this.popups.add(h),(async()=>{const u=r.skin??this.defaultSkin,d=r.width??Tt[u],g=Math.max(1,r.rows??Ar),w=Math.min(a.length||1,g)*Pr+2*M,f=await this.window({skin:u,title:r.title??"",x:r.x??we.x,y:r.y??we.y,width:d,height:M*4+ze+w+D[u],closable:!0}),p=f.body,m=f.bodyWidth-2*M;await this.label(e,{skin:u,parent:p,x:M,y:M});const y=await this.list({skin:u,parent:p,x:M,y:M+ze,width:m,height:w,rows:a.map(R=>R.label)}),v={width:Math.min(ge[u],Math.floor((m-M)/2))},T=await this.button(r.cancelLabel??"Cancel",{skin:u,parent:p,x:f.bodyWidth-M-v.width,y:f.bodyHeight-M-D[u],width:v.width});if(l=async()=>{await f()},o){const R=l;l=null,await R();return}y.onRow(R=>{var O;c(((O=a[R])==null?void 0:O.value)??null)}),T.onClick(()=>{c(null)}),f.onClose(()=>{c(null)})})().catch(u=>{console.error(`phantom.ui.choose could not be drawn: ${Y(u)}`),c(null)}),Object.assign(s,{close:h})}async notice(e,t={}){const r=t.skin??this.defaultSkin,a=await this.theme(r),i=t.seconds??6,s=t.width??Rr,o=Math.max(_e,(r==="game"?s-Cr:s)-2*ae),l=De(e,At(o,a.size)),c=await this.stageSize(),h={x:t.x??(c.width?c.width-s-je:je),y:t.y??je},u=await this.window({skin:r,title:t.title??"",x:h.x,y:h.y,width:s,height:2*ae+(l.length+1)*_e+(r==="game"?30:24),closable:t.closable!==!1,...t.draggable===void 0?{}:{draggable:t.draggable}}),d=Math.max(_e,Math.min(o,u.bodyWidth-2*ae)),g=At(d,a.size),w=await this.label(De(e,g).join(`
|
|
2
|
+
`),{skin:r,parent:u.body,x:ae,y:ae}),f=new Set;let p=!1;const m=i>0?setTimeout(()=>{u().catch(()=>{})},i*1e3):null,y=()=>{if(!p){p=!0,m&&clearTimeout(m);for(const v of[...f])U(v)()}};return u.onClose(y),u.node.onRemoved(y),this.widget(u.node,r,{setText:async v=>{await w.setText(De(v,g).join(`
|
|
3
|
+
`))},onClose:v=>(f.add(v),async()=>{f.delete(v)})},async()=>y())}async tag(e,t,r={}){const a=r.skin??this.defaultSkin,i=await this.theme(a),s=await this.anchorOf(e);if(!s)throw new TypeError(typeof e=="number"?`No player with user id ${e} is in the room, so there is nothing to tag`:"Expected a player id, something from phantom.flash.entities, or a place in the client");const o=r.key??(typeof e=="number"?`player:${e}`:null),l=o?this.tags.get(o):void 0;l&&await l().catch(()=>{});const c=await this.flash.overlay.text(t,{anchor:{place:s,x:r.offsetX??0,y:r.offsetY??(typeof e=="number"?$r:0)},centered:!0,font:{family:i.font,size:r.heading===!0?i.size+3:i.size,bold:r.heading===!0,color:r.colour??(a==="game"?i.ink:i.light)},...r.background===!1?{outline:0}:{background:a==="game"?{color:i.light,alpha:.9}:{color:i.ink,alpha:.8},padding:4}}),h=r.seconds&&r.seconds>0?setTimeout(()=>{c.remove().catch(()=>{})},r.seconds*1e3):null,u=this.widget(c,a,{setText:d=>c.update({text:d})},async()=>{h&&clearTimeout(h),o&&this.tags.get(o)===u&&this.tags.delete(o)});return o&&this.tags.set(o,u),u}async tipOn(e,t,r={}){const a=r.skin??this.defaultSkin,i=await this.tooltip({skin:a,text:typeof t=="string"?t:""}),s=this.piece(e),o={x:r.offsetX??xt.x,y:r.offsetY??xt.y},l=async d=>{typeof t!="string"&&await i.setText(await t());const g=Ur(d)??await this.mouse();await i.showAt(g.x+o.x,g.y+o.y)},c=await s.on("rollOver",d=>{l(d).catch(g=>{console.error(`phantom.ui.tipOn could not show the tooltip: ${Y(g)}`)})}),h=await s.on("rollOut",()=>{i.hide().catch(()=>{})});let u=!1;return async()=>{u||(u=!0,await c().catch(()=>{}),await h().catch(()=>{}),await i.remove().catch(()=>{}))}}async stageSize(){const e=this.bridge.stage(),[t,r]=await Promise.all([e.at("stageWidth").get().catch(()=>null),e.at("stageHeight").get().catch(()=>null)]);return{width:me(t),height:me(r)}}onStageResize(e){let t=!0,r=null;return(async()=>{const i=await this.bridge.stage().listen("resize",()=>{this.stageSize().then(s=>U(e)(s)).catch(()=>{})});if(!t){await i();return}r=i})().catch(i=>{console.error(`phantom.ui.onStageResize could not hear the stage: ${Y(i)}`)}),()=>{t=!1;const i=r;r=null,i&&i().catch(()=>{})}}places(){const e=Object.keys(bt);return[vt,...e,...Wr]}place(e){if(e===vt)return this.bridge.stage();const t=bt[e];return t?this.bridge.definition(t.className).at(...t.path):this.bridge.definition(F.guiManager).at("mainHud",e)}async attach(e,t){const r=S(t);return await this.flash.overlay.attach(this.placeOf(e),r),()=>r.remove()}async replace(e,t){const r=S(t);return await this.flash.overlay.replace(this.placeOf(e),r),()=>r.remove()}async hide(e){const t=await this.flash.hide(this.placeOf(e)),r=async()=>{this.drawn.delete(r),await t()};return this.drawn.add(r),r}piece(e,...t){return this.pieceOf(this.placeOf(e),t)}async feed(e,t,r={}){return typeof t=="function"?this.deferredFeed(e,t,r):this.insideFeed(e,t,r)}async insideFeed(e,t,r){if(!Object.keys(t).length)throw new TypeError(`A feed of ${e} names no argument to change`);let a=null,i=0;const s=await this.flash.hook(e,{phase:"enter",capture:{args:!0},replaceArgs:t,...r.when===void 0?{}:{when:r.when},...r.first===void 0?{}:{first:r.first},...r.every===void 0?{}:{every:r.every},...r.perFrame===void 0?{}:{perFrame:r.perFrame}},o=>{i+=1,a={method:e,call:o.call,args:[...o.argList],named:{...o.args},on:this.pieceOf(this.bridge.stage(),[])}});return this.feedOf(e,!0,s,()=>i,()=>a)}async deferredFeed(e,t,r){if(r.deferred!==!0)throw new TypeError(`A feed of ${e} was given a function, which cannot run inside the call: the client's method is skipped and run again once the function answers. A builder whose result the client uses in the same breath comes up empty that way. Give the arguments themselves to change them inside the call, or set "deferred" to say the waiting is understood.`);let a=null,i=0;const s=async c=>{i+=1;const h={method:e,call:c.call,args:[...c.argList],named:{...c.args},on:this.pieceOf(ne(c.self)??this.bridge.stage(),[])};a=h;const u=await t(h);if(!u){await c.original();return}const d=[...h.args];for(const[g,w]of Object.entries(u)){const f=/^\d+$/.test(g)?Number(g):c.hook.parameters.findIndex(p=>p.name===g);if(f<0||f>=d.length){const p=c.hook.parameters.map(m=>m.name).join(", ");throw new TypeError(`${e} has no argument "${g}" (its arguments: ${p})`)}d[f]=w}await c.original(...d)},o={};r.when!==void 0&&(o.when=r.when),r.first!==void 0&&(o.first=r.first),r.every!==void 0&&(o.every=r.every),r.sequential!==void 0&&(o.sequential=r.sequential),r.perFrame!==void 0&&(o.perFrame=r.perFrame),r.returns!==void 0&&(o.returns=r.returns);const l=await this.flash.override(e,s,o);return this.feedOf(e,!1,l,()=>i,()=>a)}feedOf(e,t,r,a,i){const s=async()=>{this.drawn.delete(s),await r()};this.drawn.add(s);const o=s;return Object.defineProperty(o,"method",{value:e,enumerable:!0}),Object.defineProperty(o,"inside",{value:t,enumerable:!0}),Object.defineProperty(o,"calls",{get:a,enumerable:!0}),Object.defineProperty(o,"last",{value:i,enumerable:!0}),o}screens(){return Object.keys(kt)}onScreen(e,t){const r=kt[e];let a=!0;const i=[];return(async()=>{for(const[o,l]of[[r.open,!0],[r.close,!1]]){const c=await this.flash.hook(o,{phase:l?"exit":"enter",capture:{args:[]}},()=>t({name:e,open:l,spot:r.spot}));if(!a){await c();return}i.push(c)}})().catch(o=>{console.error(`phantom.ui.onScreen could not hook ${e}: ${Y(o)}`)}),()=>{a=!1;for(const o of i.splice(0))o().catch(()=>{})}}async clear(){for(const e of[...this.popups])await e().catch(()=>{});for(const e of[...this.drawn])await e().catch(()=>{})}pieceOf(e,t){const r=ne(e);if(!r)throw new TypeError("Expected a place in the client, or one of Phantom's spots");const a=r.at(...t);return{place:a,at:(...s)=>this.pieceOf(a,s),exists:async()=>{try{const s=await a.get();return s!=null}catch{return!1}},get:async(...s)=>{try{const o=await a.at(...s).get();return P(this.bridge,o)??null}catch{return null}},set:(s,o)=>a.at(...typeof s=="string"?[s]:s).set(o),read:async(...s)=>{const o=await Promise.all(s.map(c=>a.at(c).get().catch(()=>null))),l={};return s.forEach((c,h)=>{l[c]=P(this.bridge,o[h]??null)}),l},call:async(s,...o)=>{const l=await Q(this.bridge,o);return P(this.bridge,await a.at(s).call(...l))},on:async(s,o)=>{const l=await a.listen(s,h=>o(P(this.bridge,h))),c=async()=>{this.drawn.delete(c),await l()};return this.drawn.add(c),c},attach:s=>this.attach(a,s),replace:s=>this.replace(a,s),hide:()=>this.hide(a),use:()=>C(this.bridge,a)}}widget(e,t,r,a){let i=null;const s=()=>(i??=(async()=>{this.drawn.delete(o),a&&await a().catch(()=>{})})(),i),o=async()=>{await e.remove(),await s()};this.drawn.add(o),e.onRemoved(()=>{s()});const l={skin:t,node:e,move:(c,h)=>e.update({x:c,y:h}),show:()=>e.show(),hide:()=>e.hide(),remove:o,...r};for(const[c,h]of Object.entries(l))Object.defineProperty(o,c,{value:h,enumerable:!0,configurable:!0});return o}async picture(e,t,r){const a=await this.flash.overlay.image(e,t);return a.onFailed(U(r)),a}box(e,t){return{x:e.x??0,y:e.y??0,width:e.width??t.width,height:e.height??t.height,...e.parent?{parent:S(e.parent)}:{},...e.visible===void 0?{}:{visible:e.visible}}}async anchorOf(e){if(typeof e=="number"){const a=(await this.flash.entities.players()).find(i=>i.id===String(e));return a?a.place:null}if(typeof e=="string")return this.place(e);if(st(e))return e;const t=e.place;return st(t)?t:null}async mouse(){const e=this.bridge.stage(),[t,r]=await Promise.all([e.at("mouseX").get().catch(()=>null),e.at("mouseY").get().catch(()=>null)]);return{x:me(t),y:me(r)}}placeOf(e){return typeof e=="string"?this.place(e):e}maker(){if(!this.symbolMaker){const e=this.bridge.definition(F.definitionByName).get().then(t=>{if(!t)throw new TypeError("This client has no GETDEFINITIONBYNAME");return t});e.catch(()=>{this.symbolMaker===e&&(this.symbolMaker=null)}),this.symbolMaker=e}return this.symbolMaker}async nodeObject(e){const t=await new J(this.bridge,{kind:"overlay"},[]).at("getChildByName").call(`phantomNode${e.node}`);if(!t)throw new TypeError(`Overlay node ${e.node} is not drawn straight into the overlay, so it cannot be dressed`);return t}async adopt(e,t){const r=t.parent;if(r&&qr(r))throw new Error("What it was to be drawn in was taken off the screen before it could be put there");await e.update(t)}async waitFor(e,t=this.readyTimeoutMs){const r=Date.now()+Math.max(0,t);for(;;){const a=await this.status(),i=(!e.art||a.art)&&(!e.palettes||a.palettes),s=r-Date.now();if(i||s<=0||this.bridge.state==="closed")return a;await new Promise(o=>setTimeout(o,Math.min(Or,s)))}}async artLoaded(){return this.known.art||(this.known.art=await this.hasSymbol("PopupSkin")),this.known.art}async palettesLoaded(){if(!this.known.palettes)try{const e=await this.bridge.definition(F.palette).at("gamePalette").get();this.known.palettes=Array.isArray(e)&&e.length>0}catch{}return this.known.palettes}clientFont(){if(!this.gameFont){const e=this.bridge.definition(F.fonts),t=this.known.palettes,r=(async()=>{for(const a of[["defaultFontFormat","font"],["defaultFont","fontName"]])try{const i=await e.at(...a).get();if(typeof i=="string"&&i.length>0)return i}catch{}return ye})();r.then(a=>{a===ye&&!t&&this.gameFont===r&&(this.gameFont=null)},()=>{this.gameFont===r&&(this.gameFont=null)}),this.gameFont=r}return this.gameFont}async frameOnly(e){const t=await e.at("numChildren").get()??0;for(let r=0;r<Math.min(t,32);r+=1){const a=await e.at("getChildAt").call(r);try{await a.at("name").get()!=="ba"&&await a.at("visible").set(!1)}finally{await this.bridge.release([a]).catch(()=>{})}}}async dressWindow(e,t){const a=await(await this.maker()).at("apply").call(null,["PopupSkin",!1]),i=[a];try{const s=a.at("ba"),[o,l]=await Promise.all([pe(s.at("t","height")),pe(s.at("b","height"))]),c=jr(t,o,l);await Promise.all([s.at("m","height").set(c.middle),s.at("m","y").set(c.middleY),s.at("t","y").set(c.topY),s.at("b","y").set(c.bottomY)]),await this.frameOnly(a);const h=await this.boundsOf(s,a),u={width:Math.round(h.width),height:Math.round(h.height)},d=await this.parchmentOf(a,h).catch(()=>null),g=zr(u,d);await Promise.all([a.at("x").set(Math.round(-h.x-g.panel.x)),a.at("y").set(Math.round(-h.y-g.panel.y))]);const w=await this.nodeObject(e);i.push(w),await w.at("addChildAt").call(a,0);const f=await this.frameClose(w,g).catch(()=>null);return f&&i.push(f),{...u,layout:g,close:f,held:i}}catch(s){throw await this.bridge.release(i).catch(()=>{}),s}}async frameClose(e,t){const a=await(await this.maker()).at("apply").call(null,["closeBtn",!1]);try{const i=await this.boundsOf(a,a);if(i.width<=0||i.height<=0)throw new TypeError("The close button has no size");const s=Math.min(1,(t.titleHeight-2)/i.height);return await Promise.all([a.at("scaleX").set(s),a.at("scaleY").set(s),a.at("x").set(Math.round(t.panel.width-2-(i.x+i.width)*s)),a.at("y").set(Math.round((t.titleHeight-i.height*s)/2-i.y*s))]),await e.at("addChild").call(a),a}catch(i){throw await this.bridge.release([a]).catch(()=>{}),i}}async boundsOf(e,t){const r=await e.at("getBounds").call(t);try{const[a,i,s,o]=await Promise.all(["x","y","width","height"].map(l=>pe(r.at(l))));return{x:a,y:i,width:s,height:o}}finally{await this.bridge.release([r]).catch(()=>{})}}async parchmentOf(e,t){const r=Math.ceil(t.width),a=Math.ceil(t.height);if(r<=0||a<=0||r>2048||a>2048)return null;const i=await this.bridge.construct("flash.display.BitmapData",r,a,!0,0);try{await i.at("draw").call(e,new ke("flash.geom.Matrix",[1,0,0,1,-t.x,-t.y]));const s=await i.at("getPixel32").call(Math.floor(r/2),Math.floor(a/2));if(typeof s!="number"||s>>>24!==255)return null;const o=await i.at("getColorBoundsRect").call(pt,(s&pt)>>>0,!0);try{const[l,c,h,u]=await Promise.all(["x","y","width","height"].map(d=>pe(o.at(d))));return{x:l,y:c,width:h,height:u}}finally{await this.bridge.release([o]).catch(()=>{})}}finally{await i.at("dispose").call().catch(()=>{}),await this.bridge.release([i]).catch(()=>{})}}async clientTooltip(e,t){let r;try{r=await this.symbol("Tooltip",{skin:"game",x:t.x??0,y:t.y??0,visible:t.visible===!0,...t.parent?{parent:t.parent}:{}})}catch{return null}const a=async i=>{await r.object.at("setToolTipText").call(i)};try{e&&await a(e)}catch{return await r.remove(),null}return Object.assign(r,{setText:a,showAt:async(i,s)=>{await r.node.update({x:i,y:s,visible:!0})}})}async palette(e){const t=await this.waitFor({palettes:!0}),r=this.bridge.definition(F.palette),a=t.palettes?await r.at("gamePalette").get():null,i=St(a);if(!i.length)throw new Error(`The game has not loaded its colour palettes yet: waited ${Math.round(this.readyTimeoutMs/1e3)} seconds`);if(e==="game")return{values:i,indexes:i.map((o,l)=>l)};const s=St(await r.at(e===1?"avatarPalette1":"avatarPalette2").get());return{values:i,indexes:s.length?s:i.map((o,l)=>l)}}async clientColorTable(e){const t=await this.flash.overlay.group({x:e.options.x??0,y:e.options.y??0,visible:!1});try{const r=await this.bridge.construct(F.colorTable);await r.at("init").call(0,e.width,e.height,e.columns,e.rows,e.values,e.indexes,e.current,(i,s)=>e.tell(Number(s)),-1);const a=await this.nodeObject(t);await a.at("addChild").call(r),await this.bridge.release([a,r]).catch(()=>{}),await this.adopt(t,{...e.options.parent?{parent:S(e.options.parent)}:{},visible:e.options.visible!==!1})}catch(r){throw await t.remove(),r}return t}async swatchGrid(e){const t=await this.flash.overlay.group({x:e.options.x??0,y:e.options.y??0,...e.options.parent?{parent:S(e.options.parent)}:{},...e.options.visible===void 0?{}:{visible:e.options.visible}}),r=Ot({count:e.indexes.length,columns:e.columns,tileWidth:e.swatchWidth,tileHeight:e.swatchHeight,gap:1}),a={color:Ye.line,alpha:.6},i={color:Ye.light,width:2},s=new Map;let o=e.current;for(const l of r){const c=e.indexes[l.index],h=await this.flash.overlay.button("",{parent:t,x:l.x,y:l.y,width:l.width,height:l.height,cornerRadius:2,fill:e.values[c]??0,hoverFill:e.values[c]??0,stroke:c===o?i:a});s.set(c,h),h.on("click",()=>{var u;const d=o;o=c,d!==c&&((u=s.get(d))==null||u.update({stroke:a}).catch(B),h.update({stroke:i}).catch(B)),e.tell(c)})}return t}openPopup(e,t,r,a,i){let s=()=>{};const o=new Promise(f=>{s=f});let l=null,c=!1,h=null;const u=f=>{c||(c=!0,h&&clearTimeout(h),h=null,this.popups.delete(g),s(f))},d=()=>{c||h||(h=setTimeout(()=>u(i),Br))},g=async()=>{const f=l;l=null,u(i),f&&await f.at("destroy").call().catch(()=>{})};this.popups.add(g);const w=Lr(e,t,r);return(async()=>{await this.waitFor({art:!0});const f=this.bridge.definition(r.layer==="load"?F.loadProgress:F.guiManager).at(r.layer==="load"?"loadLayer":"guiLayer"),p=[];for(const y of w.args){if(y!==null&&typeof y=="object"){if(y.slot==="layer")p.push(await f.get());else if(y.slot==="callback")p.push((...v)=>u(a(v[0]??null)));else{const v=await this.maker();p.push(await v.at("apply").call(null,["PopupSkin",!1]))}continue}p.push(y)}const m=await this.bridge.construct(w.className,...p);l=m,await m.at("closeCallback").set(()=>d()).catch(()=>{})})().catch(f=>{this.popups.delete(g),c||(c=!0,s(i)),console.error(`phantom.ui.popup.${e} could not open: ${Y(f)}`)}),Object.assign(o,{close:g})}}class Dr{constructor(e,t){this.open=e,this.closeEverything=t}open;closeEverything;message(e,t={}){return this.open("message",e,t,()=>{},void 0)}ok(e,t={}){return this.open("ok",e,t,()=>{},void 0)}okCancel(e,t={}){return this.open("okCancel",e,t,He,null)}yesNo(e,t={}){return this.open("yesNo",e,t,He,null)}titled(e,t={}){return this.open("titled",e,t,()=>{},void 0)}parchment(e,t={}){return this.open("parchment",e,t,He,null)}async closeAll(){await this.closeEverything()}}const Br=50,Mt={click:"click",down:"mouseDown",up:"mouseUp",over:"rollOver",out:"rollOut"},Wr=["chatBar","chatHist","chatTxt","sendChatBtn","safeChatBtn","actionsBtn","emotesBtn","denBtn","worldMapBtn","buddyListBtn","newsBtn","partyBtn","mySettingsBtn","money","zoneName"];function S(n){if(!n)throw new TypeError("Expected a widget or an overlay node");return typeof n.node=="number"?n:n.node}function qr(n){let e=!1;return n.onRemoved(()=>{e=!0})(),e}function ie(n,e){return e?{fill:n.accent,hoverFill:{color:n.accent,alpha:.85},pressedFill:{color:n.accent,alpha:.7},stroke:n.line}:n.skin==="game"?{fill:n.light,hoverFill:16777215,pressedFill:n.line,stroke:n.line}:{fill:{color:n.ink,alpha:.92},hoverFill:n.line,pressedFill:{color:n.line,alpha:.7},stroke:n.line}}function He(n){if(n!==null&&typeof n=="object"&&!Array.isArray(n)){const e=n.status;if(typeof e=="boolean")return e}return null}function Et(n){return Number.isFinite(n)?Math.min(1,Math.max(0,n)):0}function Y(n){return n instanceof Error?n.message:String(n)}async function pe(n){const e=await n.get();if(typeof e!="number"||!Number.isFinite(e))throw new TypeError(`Expected a number at ${n.path.join(".")}, and read ${String(e)}`);return e}function St(n){return Array.isArray(n)?n.map(e=>typeof e=="number"?e:0):[]}function De(n,e){const t=[];for(const r of n.split(`
|
|
4
|
+
`)){let a="";for(const i of r.split(/\s+/).filter(Boolean))a?a.length+1+i.length<=e?a=`${a} ${i}`:(t.push(a),a=i):a=i;t.push(a)}return t.length?t:[""]}function At(n,e){return Math.max(8,Math.floor(n/Math.max(1,e*.55)))}function Ur(n){if(!n||typeof n!="object"||Array.isArray(n))return null;const{stageX:e,stageY:t}=n;return typeof e!="number"||typeof t!="number"?null:{x:e,y:t}}function me(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:0}function be(n){return n instanceof A?{code:n.code,message:n.message,...n.stack?{stack:n.stack}:{}}:n instanceof Error?{code:"FAILED",message:n.message||n.name,...n.stack?{stack:n.stack}:{}}:{code:"FAILED",message:N(n)}}function Vt(n){const e=n&&typeof n.code=="string"&&n.code?n.code:"FAILED";return new A(e,(n==null?void 0:n.message)||"Phantom could not do this")}function le(n){return K(n,new WeakMap)}function K(n,e){if(ln(n))return K(n.value,e);if(typeof n=="function"||typeof n=="symbol")return;if(typeof n!="object"||n===null)return n;const t=cn(n);if(e.has(t))return e.get(t);if(t instanceof Date||t instanceof RegExp||t instanceof ArrayBuffer||ArrayBuffer.isView(t))return t;if(Array.isArray(t)){const a=[];e.set(t,a);for(const i of t)a.push(K(i,e));return a}if(t instanceof Map){const a=new Map;e.set(t,a);for(const[i,s]of t)a.set(K(i,e),K(s,e));return a}if(t instanceof Set){const a=new Set;e.set(t,a);for(const i of t)a.add(K(i,e));return a}if(t instanceof Error)return be(t);const r={};e.set(t,r);for(const[a,i]of Object.entries(t)){const s=K(i,e);s!==void 0&&(r[a]=s)}return r}function N(n){if(typeof n=="string")return n;if(n instanceof Error)return n.stack||`${n.name}: ${n.message}`;if(n===void 0)return"undefined";if(typeof n=="function")return`[Function ${n.name||"anonymous"}]`;if(typeof n=="symbol"||typeof n=="bigint")return n.toString();try{const e=new WeakSet,t=JSON.stringify(le(n),(r,a)=>{if(typeof a=="object"&&a!==null){if(e.has(a))return"[Circular]";e.add(a)}return typeof a=="bigint"?`${a}n`:a});return Pt(t??String(n))}catch{return Pt(String(n))}}const Be=1e4;function Pt(n){return n.length>Be?`${n.slice(0,Be)}… (${n.length-Be} more)`:n}const Vr=["log","info","warn","error"];function Gr(n,e){const t=new Map;let r=!1;for(const a of Vr){const i=n[a].bind(n);t.set(a,i),n[a]=(...s)=>{if(i(...s),!r){r=!0;try{e(a,s.map(N))}finally{r=!1}}}}return()=>{for(const[a,i]of t)n[a]=i}}function Yr(n,e,t){return new fr(new xn(Kr(n,e),{firstId:t}))}function Kr(n,e){const t=new Set;let r=null;const a=i=>{for(const s of t)s(i)};return{send(i){n.call("flash.request",e,[i]).catch(s=>{const o=Xr(i,s);o?a(o):n.log("warn",[`A Flash request was refused: ${N(s)}`])})},onMessage(i){return t.add(i),r??=n.subscribe("flash.messages",e,{event(s){const[o]=s;typeof o=="string"&&a(o)},ended(s){r=null,s&&n.log("warn",[`Flash stopped answering: ${s.message}`])}}),()=>{t.delete(i),!t.size&&r&&(r(),r=null)}}}}function Xr(n,e){let t;try{t=Nt(n)}catch{return null}if(typeof(t==null?void 0:t.id)!="number")return null;const r=e instanceof A?e.code:"FAILED",a=e instanceof Error?e.message:N(e);return te({kind:"result",id:t.id,ok:!1,error:{name:r,message:a,errorId:0}})}function Jr(n){let e=null,t=null;const r=()=>{const a=n.flash();return e??=new br({flash:a.bridge,content:Qr(n.port,n.game)},a),e};return{avatar:{view:()=>n.flash().bridge.definition(pr.avatarManager).at("playerAvatarWorldView").get()},adventures:{record:()=>Zr(n.remote)},realtime:{join:(a,i)=>Jt(n.remote.realtime,a,i),stayIn:(a,i,s)=>Xt(n.remote.realtime,a,i,s)},customRooms:{prop:(a,i)=>Kt(n.remote.customRooms,a,i),object:(a,i)=>Yt(n.remote.customRooms,a,i),character:(a,i)=>Gt(n.remote.customRooms,a,i)},room:{surfaces:()=>on(n.flash().bridge)},content:{load:(a,i)=>r().load(a,i),replaceOnScreen:(a,i,s)=>r().replaceOnScreen(a,i,s)},ui:()=>{const a=n.flash();return t??=new Hr({flash:a.bridge},a),t},recipes:{chatShortcuts:async a=>lr(await We(n),a),customChatBox:async a=>cr(await We(n),a),chatHistoryPanel:async a=>ur(await We(n),a)}}}function Qr(n,e){const t=()=>{throw new A("NOT_SUPPORTED","Only holding and releasing content happen in a frame")};return{hold:r=>n.call("content.hold",e,[r]),release:r=>n.call("content.release",e,[r]),replace:t,restore:t,list:t,observe:t}}function Zr(n){const e=Date.now(),t=[];let r=null,a=null;const i=()=>{r===null&&n.adventures.current().then(o=>r??=(o==null?void 0:o.scriptDefId)??null).catch(()=>{}),a===null&&n.adventures.actor("diff_level").then(o=>a??=(o==null?void 0:o.state)??null).catch(()=>{})};i();const s=n.adventures.onStep(({time:o,...l})=>{i(),t.push({...l,at:o-e})});return{stop:()=>(s(),{version:1,scriptDefId:r,difficulty:a,steps:[...t]})}}async function We(n){const e=n.flash(),{remote:t}=n,r=[...await t.chat.recent()],a=new Map;for(const i of await t.room.players.list())a.set(i.userId,i);return t.room.players.onEnter(i=>a.set(i.userId,i)),t.room.players.onLeave(i=>a.delete(i.userId)),t.chat.onMessage(i=>r.push(i)),{flash:e,chat:{say:t.chat.say,phrase:t.chat.phrase,onMessage:t.chat.onMessage,recent:r},room:{players:{get:i=>a.get(i)??null}}}}function ea(n,e){const t={};for(const r of Object.keys(Qt)){const a=r.split(".");let i=t;for(const o of a.slice(0,-1))i=i[o]??={};const s=a[a.length-1];i[s]=Zt(r)?ra(n,e,r,tn(r)):na(n,e,r)}return Qe(t,"")}const ta=new Set(["then","toJSON","constructor","nodeType","tagName"]);function Qe(n,e){for(const[t,r]of Object.entries(Object.getOwnPropertyDescriptors(n))){const a=r.get||r.set?null:r.value;!a||typeof a!="object"||!r.writable||(n[t]=Qe(a,`${e}${t}.`))}return new Proxy(Object.freeze(n),{get(t,r,a){if(typeof r!="string"||r in t)return Reflect.get(t,r,a);if(!(ta.has(r)||r.startsWith("__v_")))throw new A("NOT_SUPPORTED",`phantom.${e}${r} is not in this Phantom's copy of the plugin SDK. Either the name is wrong, or Phantom is serving an older build of @phantomclient/plugin than this plugin was written against; building that package again gives every plugin the newer SDK.`)}})}function na(n,e,t){return(...r)=>n.call(`sdk:${t}`,e,r)}function ra(n,e,t,r){return(...a)=>{const i=a.findIndex(u=>typeof u=="function");if(i===-1&&en(t))throw new TypeError(`${t} takes a listener function`);const s=i===-1?null:a[i],o=i===-1?a:[...a.slice(0,i),...a.slice(i+1)];let l=null;const c=r==="awaited"?new Promise((u,d)=>{l=(g,w)=>{l=null,g?u(g):d(w)}}):null,h=n.subscribe(`sdk:${t}`,e,{event:u=>s==null?void 0:s(...u),started:()=>l==null?void 0:l(()=>h()),ended(u){if(l){l(null,Vt(u??{code:"FAILED",message:`${t} could not be started`}));return}u&&n.log("warn",[`${t} stopped: ${u.code}: ${N(u.message)}`])}},{args:o,...i===-1?{}:{listenerAt:i}});return c??h}}function Rt(n,e,t,r){const a=i=>({direction:r,...i==="*"?{}:{commands:[...i]}});return{send(i){return n.call("packets.send",e,[t,String(i)])},watch(i,s){return n.subscribe("packets.watch",e,{event(o){const l=ia(o,r);l&&s(Ut(l.text,l.direction))},ended:o=>{o&&n.log("warn",[`Watching the traffic stopped: ${o.message}`])}},{filter:a(i)})},on(i,s){return n.subscribe("packets.intercept",e,{event:()=>{},intercepted:o=>{aa(n,o,s)},ended:o=>{o&&n.log("warn",[`Hooking the traffic stopped: ${o.message}`])}},{filter:a(i)})}}}async function aa(n,e,t){let r;try{r=Ut(e.text,e.direction),await t(r)}catch(a){n.log("error",[`A traffic hook failed: ${N(a)}`]),n.verdict(e.requestId,!1,null);return}n.verdict(e.requestId,r.dropped,r.modified?r.encode():null)}function ia(n,e){const[t,r]=n;if(typeof t=="string")return{text:t,direction:Ct(r)?r:e};if(typeof t=="object"&&t!==null){const{text:a,direction:i}=t;if(typeof a=="string")return{text:a,direction:Ct(i)?i:e}}return null}function Ct(n){return n==="toServer"||n==="toClient"}function sa(n){const e=new Map,t=new Set;function r(i){var s,o;const l=i??dn(x.role);if(!l)throw new A("NO_GAME",((s=x.role)==null?void 0:s.kind)==="page"||((o=x.role)==null?void 0:o.kind)==="logic"?"This frame works with several games: name one, as ctx.phantom(id), from ctx.games()":"This frame is not bound to a game yet");let c=e.get(l);return c||(c=oa(n,l),e.set(l,c)),c}return{ctx:{get plugin(){return x.plugin},get granted(){return x.granted},get preferences(){return x.preferences},can:i=>la(x.granted.scopes,i),games:()=>[...x.games],onGames(i){return t.add(i),()=>t.delete(i)},phantom:r,storage:{get:i=>n.call("storage.get",null,[String(i)]),set:(i,s)=>n.call("storage.set",null,[String(i),s]),remove:i=>n.call("storage.remove",null,[String(i)]),keys:()=>n.call("storage.keys",null,[])},async fetch(i,s){const o=await n.call("fetch",null,[String(i),s??{}]);return ca(o)},copy:i=>n.call("copy",null,[String(i)]),notify:(i,s)=>n.call("notify",null,s===void 0?[String(i)]:[String(i),String(s)]),toast:(i,s)=>n.call("toast",null,[String(i),s??{}]),confirm:(i,s)=>n.call("confirm",null,[String(i),s??{}]),openUrl:i=>n.call("openUrl",null,[String(i)]),openPanel:(i,s)=>n.call("panel.open",(s==null?void 0:s.game)??null,[String(i)]),closePanel:(i,s)=>n.call("panel.close",(s==null?void 0:s.game)??null,[String(i)]),log:(...i)=>n.log("log",i.map(N))},notifyGames(i){for(const s of[...t])try{s([...i])}catch(o){n.log("error",[`An onGames listener failed: ${N(o)}`])}},dispose(){t.clear(),e.clear()}}}function oa(n,e){let t=null;const r=()=>{if(t)return t;if(x.flashIds===null)throw new A("PERMISSION_DENIED","game.flash needs the flash scope, which this plugin was not granted");return t=Yr(n,e,x.flashIds),t},a=ea(n,e),i=Jr({port:n,game:e,remote:a,flash:r}),s={...a,avatar:Object.freeze({...a.avatar,...i.avatar}),adventures:Object.freeze({...a.adventures,...i.adventures}),content:Object.freeze({...a.content,...i.content}),realtime:Object.freeze({...a.realtime,...i.realtime}),customRooms:Object.freeze({...a.customRooms,...i.customRooms}),room:Object.freeze({...a.room,...i.room}),recipes:Object.freeze(i.recipes),id:e,server:Rt(n,e,"toServer","toClient"),client:Rt(n,e,"toClient","toServer")};return Object.defineProperties(s,{flash:{enumerable:!0,get:r},ui:{enumerable:!0,get:i.ui}}),Qe(s,"")}function la(n,e){if(n.includes(e))return!0;if(!e.startsWith("network:"))return!1;const t=e.slice(8);return n.some(r=>{if(!r.startsWith("network:*."))return!1;const a=r.slice(9);return t.endsWith(a)&&t.length>a.length})}function ca(n){const e=n.body??"";return{status:n.status,ok:n.status>=200&&n.status<300,headers:n.headers??{},text:async()=>e,json:async()=>JSON.parse(e)}}const ha=6e4;function ua(n,e={}){const t=e.prefix??`f${Math.random().toString(36).slice(2,10)}-`,r=e.timeoutMs??ha;let a=0,i=!1;const s=new Map,o=new Map,l=()=>`${t}${a+=1}`;function c(f,p){if(!i)try{n({phantom:z,type:"log",level:f,values:p})}catch{}}function h(f,p,m){if(i)return Promise.reject(new A("FAILED","The frame was closed"));const y=l();return new Promise((v,T)=>{const R=setTimeout(()=>{s.delete(y),T(new A("TIMEOUT",`Phantom did not answer ${f} in ${r/1e3}s`))},r);s.set(y,{resolve:v,reject:T,timer:R});try{n({phantom:z,type:"call",id:y,method:f,game:p,args:le(m)})}catch(O){clearTimeout(R),s.delete(y),T(new A("FAILED",`${f} could not be sent: ${N(O)}`))}})}function u(f,p,m,y={}){if(i)return w(()=>{var T;return(T=m.ended)==null?void 0:T.call(m,{code:"FAILED",message:"The frame was closed"})}),()=>{};const v=l();o.set(v,m);try{n({phantom:z,type:"subscribe",id:v,topic:f,game:p,...y.filter?{filter:le(y.filter)}:{},...y.args?{args:le(y.args)}:{},...typeof y.listenerAt=="number"?{listenerAt:y.listenerAt}:{}})}catch(T){throw o.delete(v),new A("FAILED",`${f} could not be heard: ${N(T)}`)}return()=>{!o.delete(v)||i||n({phantom:z,type:"unsubscribe",id:v})}}function d(f,p,m){i||n({phantom:z,type:"verdict",requestId:f,drop:p,text:m})}function g(f){switch(f.type){case"call-result":{const p=s.get(f.id);return p?(s.delete(f.id),clearTimeout(p.timer),f.ok?p.resolve(f.value):p.reject(Vt(f.error)),!0):!1}case"event":{const p=o.get(f.subscription);return p?(w(()=>p.event(Array.isArray(f.args)?f.args:[])),!0):!1}case"subscribed":{const p=o.get(f.subscription);return p?(w(()=>{var m;return(m=p.started)==null?void 0:m.call(p)}),!0):!1}case"intercepted":{const p=o.get(f.subscription);return p!=null&&p.intercepted?(p.intercepted(f),!0):(d(f.requestId,!1,null),!!p)}case"subscription-ended":{const p=o.get(f.subscription);return p?(o.delete(f.subscription),w(()=>{var m;return(m=p.ended)==null?void 0:m.call(p,f.error)}),!0):!1}}}function w(f){try{f()}catch(p){c("error",[`A listener failed: ${N(p)}`])}}return{call:h,subscribe:u,verdict:d,log:c,receive:g,close(f){if(!i){i=!0;for(const p of s.values())clearTimeout(p.timer),p.reject(new A("FAILED",f));s.clear(),o.clear()}}}}function da(n,e,t=new Set){const r=new Set;for(const[i,s]of Object.entries((e==null?void 0:e.variables)??{}))!i.startsWith("--phantom-")||typeof s!="string"||(n.style.setProperty(i,s),r.add(i));for(const i of t)r.has(i)||n.style.removeProperty(i);const a=(e==null?void 0:e.mode)==="light"?"light":"dark";return n.dataset.theme=a,n.style.setProperty("color-scheme",a),r}const fa=2e3;function ga(n,e){fn(e.development??!1);let t=!1,r=new Set,a=null,i=null;function s(b){var k;t||(n.post(b),(k=e.tap)==null||k.call(e,b))}const o=ua(s),l=sa(o),c=l.ctx;rt(c);function h(b){var k;const $=be(b);try{s({phantom:z,type:"crash",error:$})}catch{}(k=n.view)==null||k.showError($,x.development)}let u;const g=new Promise(b=>u=b).then(async()=>{try{const b=e.definition,k=await(typeof b=="function"?b():b);return a=wa(k),!0}catch(b){return h(b),!1}}),w=g.then(async b=>{var k;if(!b||((k=x.role)==null?void 0:k.kind)!=="logic")return b;const $=se(a==null?void 0:a.widgets);if(s({phantom:z,type:"ready",implements:{pages:se(a==null?void 0:a.pages),panels:se(a==null?void 0:a.panels),commands:se(a==null?void 0:a.commands),commandViews:se(a==null?void 0:a.commandViews),...$.length?{widgets:$}:{}}}),!(a!=null&&a.setup))return!0;try{const I=await a.setup(c);typeof I=="function"&&(t?R(I):i=I)}catch(I){h(I)}return!0});function f(b){if(t||!nn(b))return;const k=b;switch(k.type){case"init":p(k);return;case"games":x.games=Array.isArray(k.games)?k.games:[],l.notifyGames(x.games);return;case"stop":H();return;case"mount":y(k);return;case"invoke":T(k);return;case"call-result":case"event":case"subscribed":case"subscription-ended":case"intercepted":o.receive(k);return}}function p(b){var k;n.root&&b.theme&&(r=da(n.root,b.theme,r)),Object.assign(x,{role:x.role??b.role??null,plugin:b.plugin??x.plugin,mode:((k=b.theme)==null?void 0:k.mode)==="light"?"light":"dark",granted:b.granted??{scopes:[]},preferences:b.preferences??{},games:Array.isArray(b.games)?b.games:[],flashIds:typeof b.flashIds=="number"?b.flashIds:null,development:x.development||!!b.development,initialized:!0}),l.notifyGames(x.games),u()}const m=n.listen(f);async function y(b){var k,$;const[I]=await Promise.all([g,((k=n.loadStyles)==null?void 0:k.call(n))??Promise.resolve()]);t||(($=x.role)==null?void 0:$.kind)==="logic"||(Object.assign(x,{kind:b.kind,contribution:b.contribution,props:b.props??{}}),I&&v())}function v(){var b;if(!x.kind||!x.contribution)return;const[k,$]=x.kind==="page"?[a==null?void 0:a.pages,"pages"]:x.kind==="panel"?[a==null?void 0:a.panels,"panels"]:x.kind==="widget"?[a==null?void 0:a.widgets,"widgets"]:[a==null?void 0:a.commandViews,"commandViews"],I=k==null?void 0:k[x.contribution];if(!I){h(new A("NOT_SUPPORTED",`definePlugin has no ${$}["${x.contribution}"], so there is nothing to show here`));return}try{(b=n.view)==null||b.mount(I,c)}catch(W){h(W)}}async function T(b){var k,$;const I=(W,Oe)=>{try{s({phantom:z,type:"result",id:b.id,ok:W,...Oe})}catch(Me){s({phantom:z,type:"result",id:b.id,ok:!1,error:be(new A("FAILED",`The answer could not be sent to Phantom: ${N(Me)}`))})}};try{if(!await w||!a)throw new A("FAILED","The plugin did not load");if(b.kind!=="commands")throw new A("NOT_SUPPORTED",`Phantom asked for an unknown kind, "${b.kind}"`);const W=(k=a.commands)==null?void 0:k[b.contribution];if(typeof W!="function")throw new A("NOT_SUPPORTED",`definePlugin has no commands["${b.contribution}"] function`);const Oe={arguments:(($=b.input)==null?void 0:$.arguments)??{}},Me=await W(Oe,c.phantom(b.game),c);I(!0,{value:le(Me??null)})}catch(W){I(!1,{error:be(W)})}}function R(b){try{const k=b();k instanceof Promise&&k.catch($=>O($))}catch(k){O(k)}}function O(b){o.log("error",[`setup's cleanup failed: ${N(b)}`])}async function H(){const b=i;if(i=null,b)try{await Promise.race([Promise.resolve(b()),new Promise(k=>setTimeout(k,fa))])}catch(k){O(k)}s({phantom:z,type:"stopped"})}return{ctx:c,crash:h,log:(b,k)=>o.log(b,k),replaceDefinition(b){var k;a=b,((k=x.role)==null?void 0:k.kind)!=="logic"&&v()},stop(){t||(i&&(R(i),i=null),t=!0,m(),o.close("The frame was closed"),l.dispose(),rt(null))}}}function se(n){return Object.keys(n??{})}function wa(n){return!n||typeof n!="object"?{}:"default"in n&&n.default&&typeof n.default=="object"?n.default:n}const pa={class:"flex flex-col p-3",role:"alert"},ma={class:"flex flex-col gap-2 overflow-hidden rounded-lg border border-phantom-danger/25 bg-phantom-danger/10 px-3 py-2.5"},ya={class:"flex items-start gap-2"},ba={class:"min-w-0 flex-1"},va={class:"text-xs font-medium text-phantom-danger"},ka={class:"mt-0.5 break-words text-2xs text-phantom-text-soft"},xa=["textContent"],Ta={key:1,class:"text-2xs text-phantom-subtle"},Oa=hn({__name:"ErrorCard",props:{error:{},development:{type:Boolean},kind:{}},emits:["dismiss"],setup(n,{emit:e}){const t=n,r=e,a=un(()=>t.kind==="panel"?"This panel":t.kind==="page"?"This page":"This plugin");return(i,s)=>(ue(),de("div",pa,[ee("div",ma,[ee("div",ya,[s[1]||(s[1]=ee("span",{class:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-phantom-danger","aria-hidden":"true"},null,-1)),ee("div",ba,[ee("p",va,Se(a.value)+" stopped with an error",1),ee("p",ka,Se(n.error.message),1)]),n.development?(ue(),de("button",{key:0,type:"button",class:"shrink-0 rounded px-1.5 text-2xs text-phantom-muted transition-colors hover:bg-phantom-danger/10 hover:text-phantom-text",onClick:s[0]||(s[0]=o=>r("dismiss"))}," Dismiss ")):et("",!0)]),n.development&&n.error.stack?(ue(),de("pre",{key:0,class:"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-md bg-phantom-canvas/60 px-2.5 py-2 font-mono text-3xs text-phantom-muted",textContent:Se(n.error.stack)},null,8,xa)):n.development?et("",!0):(ue(),de("p",Ta," More is in the plugin's log, in Plugins. "))])]))}});function Ma(n){let e=null,t=null,r=-1;const a=()=>{const o=Math.ceil(Math.max(n.content.scrollHeight,n.content.getBoundingClientRect().height));o!==r&&(r=o,n.onResize(o))},i=typeof ResizeObserver>"u"?null:new ResizeObserver(a);i==null||i.observe(n.content);function s(){t==null||t.unmount(),t=null,n.content.hidden=!1}return{mount(o,l){s(),e==null||e.unmount(),document.documentElement.dataset.kind=x.kind??"",e=tt({name:"PhantomPluginView",render:()=>nt(o,{...x.props})}),e.provide(gn,l),e.config.errorHandler=c=>n.onError(c),e.mount(n.content)},showError(o,l){t==null||t.unmount(),n.content.hidden=!0,t=tt({render:()=>nt(Oa,{error:o,development:l,kind:x.kind,onDismiss:()=>s()})}),t.mount(n.errors),a()},unmount(){i==null||i.disconnect(),e==null||e.unmount(),t==null||t.unmount(),e=null,t=null}}}function Ea(n){window.parent===window&&Sa();const e=$t("app"),t=$t("phantom-error");let r=null;function a(o){window.parent.postMessage(o,"*")}const i=Ma({content:e,errors:t,onError:o=>r==null?void 0:r.crash(o),onResize:o=>{document.documentElement.dataset.kind&&a({phantom:z,type:"resize",height:o})}});r=ga({post:a,listen(o){const l=c=>{c.source===window.parent&&o(c.data)};return window.addEventListener("message",l),()=>window.removeEventListener("message",l)},root:document.documentElement,view:i,...n.loadStyles?{loadStyles:n.loadStyles}:{}},n);const s=r;return Gr(console,(o,l)=>s.log(o,l)),window.addEventListener("error",o=>{String(o.message).includes("ResizeObserver loop")||s.crash(o.error??o.message)}),window.addEventListener("unhandledrejection",o=>s.crash(o.reason)),window.addEventListener("pagehide",()=>{i.unmount(),s.stop()}),document.addEventListener("click",o=>{const l=o.target,c=l&&typeof l.closest=="function"?l.closest("a[href]"):null;if(!c)return;const h=c.getAttribute("href")??"";h.startsWith("#")||(o.preventDefault(),/^https:\/\//i.test(h)?s.ctx.openUrl(h).catch(()=>{}):s.log("warn",[`Only https links open from a plugin; this one goes to ${h}`]))}),s}function $t(n){const e=document.getElementById(n);if(e)return e;const t=document.createElement("div");return t.id=n,document.body.append(t),t}function Sa(){const n=document.createElement("p");n.className="m-6 max-w-md text-xs text-phantom-muted",n.textContent="This is a Phantom plugin frame. It runs inside Phantom: turn on Developer mode in Plugins, and a plugin served by phantom-plugin dev shows up there.",document.body.prepend(n)}const Ft="/dist/plugin.js",Aa="/dist/plugin.css";let It=null;function Pa(){return It??=new Promise(n=>{const e=document.createElement("link");e.rel="stylesheet",e.href=Aa,e.onload=e.onerror=()=>n(),document.head.append(e)}),It}async function Ra(){const n=await import(Ft);if(!n.default)throw new Error(`${Ft} has no default export. Export definePlugin({ ... }) as default.`);return n.default}Ea({definition:Ra,loadStyles:Pa});
|