for-any-project-min
for-any-projectをこのURLでbundleしたもの
code:script.js
var E0=Object.defineProperty;var Bo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)r}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Xi=(e,t)=>{for(var r in t)E0(e,r,{get:tr,enumerable:!0})};function Te(e){if(e)return w0(e)}function w0(e){for(var t in Te.prototype)et=Te.prototypet;return e}Te.prototype.on=Te.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks"$"+e=this._callbacks"$"+e||[]).push(t),this};Te.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};Te.prototype.off=Te.prototype.removeListener=Te.prototype.removeAllListeners=Te.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks"$"+e;if(!r)return this;if(arguments.length==1)return delete this._callbacks"$"+e,this;for(var o,n=0;n<r.length;n++)if(o=rn,o===t||o.fn===t){r.splice(n,1);break}return r.length===0&&delete this._callbacks"$"+e,this};Te.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks"$"+e,o=1;o<arguments.length;o++)to-1=argumentso;if(r){r=r.slice(0);for(var o=0,n=r.length;o<n;++o)ro.apply(this,t)}return this};Te.prototype.emitReserved=Te.prototype.emit;Te.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks"$"+e||[]};Te.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Nr=Object.create(null);Nr.open="0";Nr.close="1";Nr.ping="2";Nr.pong="3";Nr.message="4";Nr.upgrade="5";Nr.noop="6";var Zi=Object.create(null);Object.keys(Nr).forEach(e=>{Zi[Nre]=e});var op={type:"error",data:"parser error"},Ud=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="object BlobConstructor",$d=typeof ArrayBuffer=="function",jd=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ea=({type:e,data:t},r,o)=>Ud&&t instanceof Blob?r?o(t):Ad(t,o):$d&&(t instanceof ArrayBuffer||jd(t))?r?o(t):Ad(new Blob(t),o):o(Nre+(t||"")),Ad=(e,t)=>{let r=new FileReader;return r.onload=function(){let o=r.result.split(",")1;t("b"+(o||""))},r.readAsDataURL(e)};function Fd(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var tp;function R0(e,t){if(Ud&&e.data instanceof Blob)return e.data.arrayBuffer().then(Fd).then(t);if($d&&(e.data instanceof ArrayBuffer||jd(e.data)))return t(Fd(e.data));ea(e,!1,r=>{tp||(tp=new TextEncoder),t(tp.encode(r))})}var Dd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Is=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Dd.length;e++)IsDd.charCodeAt(e)=e;var v0=e=>{let t=e.length*.75,r=e.length,o,n=0,s,i,a,c;ee.length-1==="="&&(t--,ee.length-2==="="&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(o=0;o<r;o+=4)s=Ise.charCodeAt(o),i=Ise.charCodeAt(o+1),a=Ise.charCodeAt(o+2),c=Ise.charCodeAt(o+3),un++=s<<2|i>>4,un++=(i&15)<<4|a>>2,un++=(a&3)<<6|c&63;return l},k0=typeof ArrayBuffer=="function",ta=(e,t)=>{if(typeof e!="string")return{type:"message",data:Bd(e,t)};let r=e.charAt(0);return r==="b"?{type:"message",data:T0(e.substring(1),t)}:Zir?e.length>1?{type:Zir,data:e.substring(1)}:{type:Zir}:op},T0=(e,t)=>{if(k0){let r=v0(e);return Bd(r,t)}else return{base64:!0,data:e}},Bd=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob(e);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Hd="",Wd=(e,t)=>{let r=e.length,o=new Array(r),n=0;e.forEach((s,i)=>{ea(s,!1,a=>{oi=a,++n===r&&t(o.join(Hd))})})},qd=(e,t)=>{let r=e.split(Hd),o=[];for(let n=0;n<r.length;n++){let s=ta(rn,t);if(o.push(s),s.type==="error")break}return o};function Gd(){return new TransformStream({transform(e,t){R0(e,r=>{let o=r.length,n;if(o<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,o);else if(o<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,o)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(o))}e.data&&typeof e.data!="string"&&(n0|=128),t.enqueue(n),t.enqueue(r)})}})}var rp;function Ji(e){return e.reduce((t,r)=>t+r.length,0)}function Qi(e,t){if(e0.length===t)return e.shift();let r=new Uint8Array(t),o=0;for(let n=0;n<t;n++)rn=e0o++,o===e0.length&&(e.shift(),o=0);return e.length&&o<e0.length&&(e0=e0.slice(o)),r}function zd(e,t){rp||(rp=new TextDecoder);let r=[],o=0,n=-1,s=!1;return new TransformStream({transform(i,a){for(r.push(i);;){if(o===0){if(Ji(r)<1)break;let c=Qi(r,1);s=(c0&128)===128,n=c0&127,n<126?o=3:n===126?o=1:o=2}else if(o===1){if(Ji(r)<2)break;let c=Qi(r,2);n=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),o=3}else if(o===2){if(Ji(r)<8)break;let c=Qi(r,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(op);break}n=u*Math.pow(2,32)+l.getUint32(4),o=3}else{if(Ji(r)<n)break;let c=Qi(r,n);a.enqueue(ta(s?c:rp.decode(c),t)),o=0}if(n===0||n>e){a.enqueue(op);break}}}})}var np=4;var As=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),ar=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),_0="arraybuffer";function Kd(e,...t){return t.reduce((r,o)=>(e.hasOwnProperty(o)&&(ro=eo),r),{})}var P0=ar.setTimeout,O0=ar.clearTimeout;function Fs(e,t){t.useNativeTimers?(e.setTimeoutFn=P0.bind(ar),e.clearTimeoutFn=O0.bind(ar)):(e.setTimeoutFn=ar.setTimeout.bind(ar),e.clearTimeoutFn=ar.clearTimeout.bind(ar))}var S0=1.33;function L0(e){return typeof e=="string"?N0(e):Math.ceil((e.byteLength||e.size)*S0)}function N0(e){let t=0,r=0;for(let o=0,n=e.length;o<n;o++)t=e.charCodeAt(o),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(o++,r+=4);return r}function Yd(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function M0(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(er));return t}function C0(e){let t={},r=e.split("&");for(let o=0,n=r.length;o<n;o++){let s=ro.split("=");t[decodeURIComponent(s0)]=decodeURIComponent(s1)}return t}var I0=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},ap=class extends Te{constructor(e){super(),this.writable=!1,Fs(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new I0(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=ta(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:""+e+""}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=M0(e);return t.length?"?"+t:""}},A0=class extends ap{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||t()})),this.writable||(r++,this.once("drain",function(){--r||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};qd(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write({type:"close"})};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Wd(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(tthis.opts.timestampParam=Yd()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},Xd=!1;try{Xd=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var F0=Xd;function D0(){}var U0=class extends A0{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(o,n)=>{this.onError("xhr post error",o,n)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},Ln=class ra extends Te{constructor(t,r,o){super(),this.createRequest=t,Fs(this,o),this._opts=o,this._method=o.method||"GET",this._uri=r,this._data=o.data!==void 0?o.data:null,this._create()}_create(){var t;let r=Kd(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let o=this._xhr=this.createRequest(r);try{o.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){o.setDisableHeaderCheck&&o.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&o.setRequestHeader(n,this._opts.extraHeadersn)}}catch{}if(this._method==="POST")try{o.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{o.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(o),"withCredentials"in o&&(o.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(o.timeout=this._opts.requestTimeout),o.onreadystatechange=()=>{var n;o.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(o.getResponseHeader("set-cookie"))),o.readyState===4&&(o.status===200||o.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof o.status=="number"?o.status:0)},0))},o.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=ra.requestsCount++,ra.requeststhis._index=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=D0,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ra.requeststhis._index,this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};Ln.requestsCount=0;Ln.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Vd);else if(typeof addEventListener=="function"){let e="onpagehide"in ar?"pagehide":"unload";addEventListener(e,Vd,!1)}}function Vd(){for(let e in Ln.requests)Ln.requests.hasOwnProperty(e)&&Ln.requestse.abort()}var $0=function(){let e=Jd({xdomain:!1});return e&&e.responseType!==null}(),cp=class extends U0{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=$0&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ln(Jd,this.uri(),e)}};function Jd(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||F0))return new XMLHttpRequest}catch{}if(!t)try{return new ar["Active".concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Qd=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",j0=class extends ap{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Qd?{}:Kd(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=et,o=t===e.length-1;ea(r,this.supportsBinary,n=>{try{this.doWrite(r,n)}catch{}o&&As(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(tthis.opts.timestampParam=Yd()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},sp=ar.WebSocket||ar.MozWebSocket,lp=class extends j0{createSocket(e,t,r){return Qd?new sp(e,t,r):t?new sp(e,t):new sp(e)}doWrite(e,t){this.ws.send(t)}},Zd=class extends ap{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptionsthis.name)}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=zd(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),o=Gd();o.readable.pipeTo(e.writable),this._writer=o.writable.getWriter();let n=()=>{r.read().then(({done:i,value:a})=>{i||(this.onPacket(a),n())}).catch(i=>{})};n();let s={type:"open"};this.query.sid&&(s.data={"sid":"${this.query.sid}"}),this._writer.write(s).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=et,o=t===e.length-1;this._writer.write(r).then(()=>{o&&As(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}},B0={websocket:lp,webtransport:Zd,polling:cp},H0=/^(?:(?!^:@\/?#+:^:@\/*@)(http|https|ws|wss):\/\/)?((?:((^:@\/?#*)(?::(^:@\/?#*))?)?@)?((?:a-f0-9{0,4}:){2,7}a-f0-9{0,4}|^:\/?#*)(?::(\d*))?)(((\/(?:^?#(?!^?#\/*\.^?#\/.+(?:?#|$)))*\/?)?(^?#\/*))(?:\?(^#*))?(?:#(.*))?)/,W0="source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor";function ia(e){if(e.length>8e3)throw"URI too long";let t=e,r=e.indexOf(""),o=e.indexOf("");r!=-1&&o!=-1&&(e=e.substring(0,r)+e.substring(r,o).replace(/:/g,";")+e.substring(o,e.length));let n=H0.exec(e||""),s={},i=14;for(;i--;)s[W0i]=ni||"";return r!=-1&&o!=-1&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("","").replace("","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=q0(s,s.path),s.queryKey=G0(s,s.query),s}function q0(e,t){let r=/\/{2,9}/g,o=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&o.splice(0,1),t.slice(-1)=="/"&&o.splice(o.length-1,1),o}function G0(e,t){let r={};return t.replace(/(?:^|&)(^&=*)=?(^&*)/g,function(o,n,s){n&&(rn=s)}),r}var ip=typeof addEventListener=="function"&&typeof removeEventListener=="function",oa=[];ip&&addEventListener("offline",()=>{oa.forEach(e=>e())},!1);var na=class sa extends Te{constructor(t,r){if(super(),this.binaryType=_0,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let o=ia(t);r.hostname=o.host,r.secure=o.protocol==="https"||o.protocol==="wss",r.port=o.port,o.query&&(r.query=o.query)}else r.host&&(r.hostname=ia(r.host).host);Fs(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(o=>{let n=o.prototype.name;this.transports.push(n),this._transportsByNamen=o}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=C0(this.opts.query)),ip&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},oa.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){let r=Object.assign({},this.opts.query);r.EIO=np,r.transport=t,this.id&&(r.sid=this.id);let o=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptionst);return new this._transportsByNamet(o)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&sa.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports0;this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){this.readyState="open",sa.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let o=this.writeBufferr.data;if(o&&(t+=L0(o)),r>0&&t>this._maxPayload)return this.writeBuffer.slice(0,r);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,As(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,o){return this._sendPacket("message",t,r,o),this}send(t,r,o){return this._sendPacket("message",t,r,o),this}_sendPacket(t,r,o,n){if(typeof r=="function"&&(n=r,r=void 0),typeof o=="function"&&(n=o,o=null),this.readyState==="closing"||this.readyState==="closed")return;o=o||{},o.compress=o.compress!==!1;let s={type:t,data:r,options:o};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let t=()=>{this._onClose("forced close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},o=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?o():t()}):this.upgrading?o():t()),this}_onError(t){if(sa.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ip&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let o=oa.indexOf(this._offlineEventListener);o!==-1&&oa.splice(o,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};na.protocol=np;var z0=class extends na{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgradese)}_probe(e){let t=this.createTransport(e),r=!1;na.priorWebsocketSuccess=!1;let o=()=>{r||(t.send({type:"ping",data:"probe"}),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;na.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send({type:"upgrade"}),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let p=new Error("probe error");p.transport=t.name,this.emitReserved("upgradeError",p)}}))};function n(){r||(r=!0,l(),t.close(),t=null)}let s=u=>{let p=new Error("probe error: "+u);p.transport=t.name,n(),this.emitReserved("upgradeError",p)};function i(){s("transport closed")}function a(){s("socket closed")}function c(u){t&&u.name!==t.name&&n()}let l=()=>{t.removeListener("open",o),t.removeListener("error",s),t.removeListener("close",i),this.off("close",a),this.off("upgrading",c)};t.once("open",o),t.once("error",s),t.once("close",i),this.once("close",a),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(er)&&t.push(er);return t}},pp=class extends z0{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports0=="string")&&(r.transports=(r.transports||"polling","websocket","webtransport").map(o=>B0o).filter(o=>!!o)),super(e,r)}};var UD=pp.protocol;var dp={};Xi(dp,{Decoder:()=>e_,Encoder:()=>Z0,PacketType:()=>ne,isPacketValid:()=>i_,protocol:()=>rh});var V0=typeof ArrayBuffer=="function",K0=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,eh=Object.prototype.toString,Y0=typeof Blob=="function"||typeof Blob<"u"&&eh.call(Blob)==="object BlobConstructor",X0=typeof File=="function"||typeof File<"u"&&eh.call(File)==="object FileConstructor";function fp(e){return V0&&(e instanceof ArrayBuffer||K0(e))||Y0&&e instanceof Blob||X0&&e instanceof File}function aa(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,o=e.length;r<o;r++)if(aa(er))return!0;return!1}if(fp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return aa(e.toJSON(),!0);for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&aa(er))return!0;return!1}function J0(e){let t=[],r=e.data,o=e;return o.data=up(r,t),o.attachments=t.length,{packet:o,buffers:t}}function up(e,t){if(!e)return e;if(fp(e)){let r={_placeholder:!0,num:t.length};return t.push(e),r}else if(Array.isArray(e)){let r=new Array(e.length);for(let o=0;o<e.length;o++)ro=up(eo,t);return r}else if(typeof e=="object"&&!(e instanceof Date)){let r={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(ro=up(eo,t));return r}return e}function Q0(e,t){return e.data=mp(e.data,t),delete e.attachments,e}function mp(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return te.num;throw new Error("illegal attachments")}else if(Array.isArray(e))for(let r=0;r<e.length;r++)er=mp(er,t);else if(typeof e=="object")for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(er=mp(er,t));return e}var th="connect","connect_error","disconnect","disconnecting","newListener","removeListener",rh=5,ne;(function(e){ee.CONNECT=0="CONNECT",ee.DISCONNECT=1="DISCONNECT",ee.EVENT=2="EVENT",ee.ACK=3="ACK",ee.CONNECT_ERROR=4="CONNECT_ERROR",ee.BINARY_EVENT=5="BINARY_EVENT",ee.BINARY_ACK=6="BINARY_ACK"})(ne||(ne={}));var Z0=class{constructor(e){this.replacer=e}encode(e){return(e.type===ne.EVENT||e.type===ne.ACK)&&aa(e)?this.encodeAsBinary({type:e.type===ne.EVENT?ne.BINARY_EVENT:ne.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):this.encodeAsString(e)}encodeAsString(e){let t=""+e.type;return(e.type===ne.BINARY_EVENT||e.type===ne.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=J0(e),r=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(r),o}},e_=class oh extends Te{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let o=r.type===ne.BINARY_EVENT;o||r.type===ne.BINARY_ACK?(r.type=o?ne.EVENT:ne.ACK,this.reconstructor=new t_(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(fp(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,o={type:Number(t.charAt(0))};if(neo.type===void 0)throw new Error("unknown packet type "+o.type);if(o.type===ne.BINARY_EVENT||o.type===ne.BINARY_ACK){let s=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let i=t.substring(s,r);if(i!=Number(i)||t.charAt(r)!=="-")throw new Error("Illegal attachments");o.attachments=Number(i)}if(t.charAt(r+1)==="/"){let s=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););o.nsp=t.substring(s,r)}else o.nsp="/";let n=t.charAt(r+1);if(n!==""&&Number(n)==n){let s=r+1;for(;++r;){let i=t.charAt(r);if(i==null||Number(i)!=i){--r;break}if(r===t.length)break}o.id=Number(t.substring(s,r+1))}if(t.charAt(++r)){let s=this.tryParse(t.substr(r));if(oh.isPayloadValid(o.type,s))o.data=s;else throw new Error("invalid payload")}return o}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case ne.CONNECT:return ca(r);case ne.DISCONNECT:return r===void 0;case ne.CONNECT_ERROR:return typeof r=="string"||ca(r);case ne.EVENT:case ne.BINARY_EVENT:return Array.isArray(r)&&(typeof r0=="number"||typeof r0=="string"&&th.indexOf(r0)===-1);case ne.ACK:case ne.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},t_=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=Q0(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function r_(e){return typeof e=="string"}var o_=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function n_(e){return e===void 0||o_(e)}function ca(e){return Object.prototype.toString.call(e)==="object Object"}function s_(e,t){switch(e){case ne.CONNECT:return t===void 0||ca(t);case ne.DISCONNECT:return t===void 0;case ne.EVENT:return Array.isArray(t)&&(typeof t0=="number"||typeof t0=="string"&&th.indexOf(t0)===-1);case ne.ACK:return Array.isArray(t);case ne.CONNECT_ERROR:return typeof t=="string"||ca(t);default:return!1}}function i_(e){return r_(e.nsp)&&n_(e.id)&&s_(e.type,e.data)}function a_(e,t="",r){let o=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),o=ia(e)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";let n=o.host.indexOf(":")!==-1?""+o.host+"":o.host;return o.id=o.protocol+"://"+n+":"+o.port+t,o.href=o.protocol+"://"+n+(r&&r.port===o.port?"":":"+o.port),o}function wr(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var c_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),nh=class extends Te{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=wr(e,"open",this.onopen.bind(this)),wr(e,"packet",this.onpacket.bind(this)),wr(e,"error",this.onerror.bind(this)),wr(e,"close",this.onclose.bind(this))}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,o,n;if(c_.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let s={type:ne.EVENT,data:t};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof tt.length-1=="function"){let c=this.ids++,l=t.pop();this._registerAckCallback(c,l),s.id=c}let i=(o=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||o===void 0?void 0:o.writable,a=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!i||(a?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(e,t){var r;let o=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(o===void 0){this.ackse=t;return}let n=this.io.setTimeoutFn(()=>{delete this.ackse;for(let i=0;i<this.sendBuffer.length;i++)this.sendBufferi.id===e&&this.sendBuffer.splice(i,1);t.call(this,new Error("operation has timed out"))},o),s=(...i)=>{this.io.clearTimeoutFn(n),t.apply(this,i)};s.withError=!0,this.ackse=s}emitWithAck(e,...t){return new Promise((r,o)=>{let n=(s,i)=>s?o(s):r(i);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof ee.length-1=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((o,...n)=>(this._queue0,o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(o)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue0;t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:ne.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.ackse;delete this.ackse,t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case ne.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ne.EVENT:case ne.BINARY_EVENT:this.onevent(e);break;case ne.ACK:case ne.BINARY_ACK:this.onack(e);break;case ne.DISCONNECT:this.ondisconnect();break;case ne.CONNECT_ERROR:this.destroy();let t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof ee.length-1=="string"&&(this._lastOffset=ee.length-1)}ack(e){let t=this,r=!1;return function(...o){r||(r=!0,t.packet({type:ne.ACK,id:e,data:o}))}}onack(e){let t=this.ackse.id;typeof t=="function"&&(delete this.ackse.id,t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ne.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===tr)return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===tr)return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}};function Mn(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Mn.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};Mn.prototype.reset=function(){this.attempts=0};Mn.prototype.setMin=function(e){this.ms=e};Mn.prototype.setMax=function(e){this.max=e};Mn.prototype.setJitter=function(e){this.jitter=e};var hp=class extends Te{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Fs(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Mn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let o=t.parser||dp;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new pp(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let o=wr(t,"open",function(){r.onopen(),e&&e()}),n=i=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",i),e?e(i):this.maybeReconnectOnOpen()},s=wr(t,"error",n);if(this._timeout!==!1){let i=this._timeout,a=this.setTimeoutFn(()=>{o(),n(new Error("timeout")),t.close()},i);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}return this.subs.push(o),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(wr(e,"ping",this.onping.bind(this)),wr(e,"data",this.ondata.bind(this)),wr(e,"error",this.onerror.bind(this)),wr(e,"close",this.onclose.bind(this)),wr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){As(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nspse;return r?this._autoConnect&&!r.active&&r.connect():(r=new nh(this,e,t),this.nspse=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nspsr.active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(tr,e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(o=>{o?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",o)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}},Ds={};function Nn(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};let r=a_(e,t.path||"/socket.io"),o=r.source,n=r.id,s=r.path,i=Dsn&&s in Dsn.nsps,a=t.forceNew||t"force new connection"||t.multiplex===!1||i,c;return a?c=new hp(o,t):(Dsn||(Dsn=new hp(o,t)),c=Dsn),r.query&&!t.query&&(t.query=r.queryKey),c.socket(r.path,t)}Object.assign(Nn,{Manager:hp,Socket:nh,io:Nn,connect:Nn});var sh=" must not return ",l_="transformer",p_="recoverer",u_="defaultValue",Cn=l_+sh,Kr="called with ",In=u_+" must not be ",An=p_+sh;var m_="Ok",ih="Err",ah=Kr+ih,ch=Kr+m_,lh="Carrying E in "+ih+" instead of throwing it directly. See .cause",gp="an instance of Error of the current realm.",TU="The thrown value is not "+gp,_U="The contained E should be "+gp,ph="This .cause is not "+gp;function K(e){return e.ok}function L(e){return{ok:!0,val:e,err:null}}function O(e){return!e.ok}function M(e){return{ok:!1,val:null,err:e}}function S(e){return yp(e,ah)}function Z(e){return xp(e,ch)}function yp(e,t){if(O(e))throw new TypeError(t);return e.val}function xp(e,t){if(K(e))throw new TypeError(t);return e.err}function ue(e){return e.val}function ye(e){return e.err}function Us(e,t){if(O(e))return e;let r=ue(e);return t(r)}async function $s(e,t){if(O(e))return e;let r=ue(e);return await t(r)}function f_(e){return e}function bp(e){return Us(e,f_)}function Ep(e){let t=e.status;switch(t){case"fulfilled":{let r=e.value;return L(r)}case"rejected":{let r=e.reason;return M(r)}default:{let r=\`PromiseSettledResult.status=${String(t)}\` is not supported;throw new TypeError(r)}}}function wp(e,t){if(K(e)){let r=ue(e);t(r)}return e}function Rp(e,t){if(O(e)){let r=ye(e);t(r)}return e}function vp(e,t,r){if(K(e)){let o=ue(e);t(o)}else{let o=ye(e);r(o)}return e}function la(e,t){if(K(e))return!1;let r=ye(e);return t(r)}function kp(e,t){return la(e,t)}function pa(e,t){if(O(e))return!1;let r=ue(e);return t(r)}function Tp(e,t){return pa(e,t)}function Yr(e,t){if(O(e))return e;let r=ue(e),o=t(r);return L(o)}async function ae(e,t){if(O(e))return e;let r=ue(e),o=await t(r);return L(o)}function _p(e,t){if(K(e))return e;let r=ye(e),o=t(r);return M(o)}async function Ae(e,t){if(K(e))return e;let r=ye(e),o=await t(r);return M(o)}function Pp(e,t,r){if(K(e)){let o=ue(e);return r(o)}return t}async function Op(e,t,r){if(O(e))return t;let o=ue(e);return await r(o)}function js(e,t,r){if(K(e)){let n=ue(e);return r(n)}let o=ye(e);return t(o)}async function Sp(e,t,r){if(K(e)){let n=ue(e);return await r(n)}let o=ye(e);return await t(o)}function Lp(e,t){if(K(e))return e;let r=ye(e);return t(r)}async function ua(e,t){if(K(e))return e;let r=ye(e);return await t(r)}function ma(e,t){return K(e)?t:ye(e)}function Ho(e,t){return K(e)?ue(e):t}function Np(e){return Ho(e,null)}function Mp(e){return ma(e,null)}function Cp(e){return Ho(e,void 0)}function Ip(e){return ma(e,void 0)}var fa="null",cr=Cn+fa,d_=Kr+fa,Fn=In+fa,yo=An+fa;function je(e){return e!==null}function tt(e){return e===null}function rt(e,t){if(je(e))return e;throw new TypeError(t)}var da="undefined",lr=Cn+da,h_=Kr+da,Dn=In+da,xo=An+da;function ot(e){return e!==void 0}function nt(e){return e===void 0}function st(e,t){if(ot(e))return e;throw new TypeError(t)}function Ap(e){if(O(e))return e;let t=ue(e);return tt(t)?null:L(t)}function Fp(e){if(O(e))return e;let t=ue(e);if(!nt(t))return L(t)}function uh(e){return e instanceof Error}var g_="UnknownCausalError",y_=class extends Error{constructor(e){super(ph,{cause:e}),this.name=g_}};function ha(e){return uh(e)?e:new y_(e)}function ga(e){try{let t=e();return L(t)}catch(t){return M(t)}}function Dp(e){let t=ga(e);if(K(t))return t;let r=ye(t),o=ha(r);return M(o)}async function ya(e){let t;try{t=await e()}catch(r){return M(r)}return L(t)}async function Up(e){let t=await ya(e);if(K(t))return t;let r=ye(t),o=ha(r);return M(o)}function $p(e,t){if(K(e))return ue(e);let r=ye(e);return t(r)}async function jp(e,t){if(K(e))return ue(e);let r=ye(e);return await t(r)}var x_="CausalCarrierError",b_=class extends Error{constructor(e){super(lh,{cause:e}),this.name=x_}};function Bp(e){if(K(e))return ue(e);let t=ye(e);throw new b_(t)}var Be=e=>e.ok?L(e):M({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var mh=async(e,t)=>{let r=new Request(e,t);try{return L(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return M({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return M({name:"NetworkError",message:o.message,request:r});throw o}};var Ee=e=>{let{fetch:t=mh,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var fh=e=>{let{sid:t,hostName:r}=Ee(e??{});return new Request(https://${r}/api/users/me,t?{headers:{Cookie:we(t)}}:void 0)},dh=e=>ae(Be(e),async t=>await t.json()),xa=(()=>{let e=async t=>{let{fetch:r,...o}=Ee(t??{}),n=await r(fh(o));return O(n)?n:dh(S(n))};return e.toRequest=fh,e.fromResponse=dh,e})();var we=e=>connect.sid=${e},Un=async e=>{let t=e?.csrf??globalThis._csrf;return t?L(t):Yr(await xa(e),r=>r.csrfToken)};var It=(e,t)=>{if(e?.connected)return Promise.resolve(L(e));e??=Nn("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"],...t?{rejectUnauthorized:!1,extraHeaders:{Cookie:we(t),Host:"scrapbox.io",Referer:"https://scrapbox.io/"}}:{}});let r=new Promise(o=>{let n=s=>o(M(s));e.once("connect",()=>{e.off("disconnect",n),o(L(e))}),e.once("disconnect",n)});return e.connect(),r},At=e=>{if(e.disconnected)return Promise.resolve(L(void 0));let t=new Promise(r=>{let o=n=>{if(n!=="io client disconnect"){r(M(n));return}r(L(void 0)),e.off("disconnect",o)};e.on("disconnect",o)});return e.disconnect(),t};var hh=e=>E_.includes(e.name),E_="SocketIOError","DuplicateTitleError","NotFastForwardError";var gh=(e,t,r,o)=>{if(t==="cursor")return e.emit(t,r),Promise.resolve(L(void 0));let{resolve:n,promise:s,reject:i}=Promise.withResolvers(),a=()=>{e.off("disconnect",c),clearTimeout(u)},c=f=>{if(f==="io client disconnect"){a(),i(new Error("io client disconnect"));return}if(f==="io server disconnect"){a(),n(M({name:"SocketIOError"}));return}};e.on("disconnect",c);let l=o?.timeout??9e4,u=setTimeout(()=>{a(),n(M({name:"TimeoutError",message:exceeded ${l} (ms)}))},l),p=t==="commit"?{method:"commit",data:r}:{method:"room:join",data:r};return e.emit("socket.io-request",p,f=>{if(a(),"error"in f){n(M(hh(f.error)?f.error:{name:"UnexpectedRequestError",...f}));return}n(L(f.data))}),s};function ba(e,t={}){if(e===null)return"null";if(Array.isArray(e))return w_(e,t);switch(typeof e){case"string":return JSON.stringify(e);case"bigint":return${e}n;case"object":return e.constructor?.name!=="Object"?e.constructor?.name:R_(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function w_(e,t){let{threshold:r=20}=t,o=e.map(i=>ba(i,t)),n=o.join(", ");if(n.length<=r)return[${n}];let s=o.join(`,
);return[
${yh(2,s)}
]}function R_(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(i=>${i.toString()}: ${ba(ei,t)}),n=o.join(", ");if(n.length<=r)return{${n}};let s=o.join(,
);return{
${yh(2,s)}
}}function yh(e,t){let r=" ".repeat(e);return t.split(
).map(o=>${r}${o}).join(
)}function ut(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=${t}(${r.map(n=>ba(n)).join(", ")}),o)}})}function Rr(e){return Array.isArray(e)}function Bs(e){return ut(t=>Rr(t)&&t.every(r=>e(r)),"isArrayOf",e)}function Wo(e){let t=new Set(e);return ut(r=>t.has(r),"isLiteralOneOf",e)}function bo(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function Re(e){return typeof e=="string"}var mt=async(e,t)=>{let r=e.response.clone(),o=Wo(t);try{let n=await r.json();if(!bo(n))return;if(r.status===422){if(!Re(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!Re(n.message)?void 0:n.name==="NotLoggedInError"?!bo(n.detals)||!Re(n.detals.project)||!Bs(v_)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},v_=Wo(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var ce=e=>e.replaceAll(" ","_").toLowerCase();var se=e=>[...e].map((t,r)=>t===" "?"_":!k_.includes(t)||r===e.length-1&&T_.includes(t)?encodeURIComponent(t):t).join(""),k_='@$&+=:;",',T_=':;",';var Ea="null or undefined",pr=Cn+Ea,__=Kr+Ea,$n=In+Ea,Eo=An+Ea;function Ve(e){return e!=null}function Ke(e){return e==null}function Ye(e,t){if(Ve(e))return e;throw new TypeError(t)}function Hp(e,t){return Ke(e)?e:t(e)}async function Wp(e,t){return Ke(e)?e:await t(e)}function qp(e,t){return Ve(e)&&t(e),e}function Gp(e,t){if(Ke(e))return e;let r=t(e);return Ye(r,pr)}async function zp(e,t){if(Ke(e))return e;let r=await t(e);return Ye(r,pr)}function Vp(e,t,r){let o,n;return e!=null?(o=r(e),n=pr):(o=t,n=$n),Ye(o,n)}async function Kp(e,t,r){if(Ke(e))return Ye(t,$n);let o=await r(e);return Ye(o,pr)}function Yp(e,t,r){let o,n;return e!=null?(o=r(e),n=pr):(o=t(),n=Eo),Ye(o,n)}async function Xp(e,t,r){let o,n;return Ve(e)?(o=await r(e),n=pr):(o=await t(),n=Eo),Ye(o,n)}function Jp(e,t){return Ve(e)?L(e):M(t)}function Hs(e,t){if(Ve(e))return L(e);let r=t();return M(r)}async function Qp(e,t){if(Ve(e))return L(e);let r=await t();return M(r)}function Zp(e,t){return e??t()}async function eu(e,t){return Ve(e)?e:await t()}function tu(e){return Ke(e)?null:e}function wa(e){return Ke(e)?M(void 0):L(e)}function ru(e){return Ke(e)?L(void 0):M(e)}function ou(e){if(!Ke(e))return e}function Ws(e,t){return Ve(e)?e:Ye(t,$n)}function nu(e,t){if(Ve(e))return e;let r=t();return Ye(r,Eo)}async function su(e,t){if(Ve(e))return e;let r=await t();return Ye(r,Eo)}var xh=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=Ee(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(https://${n}/api/pages/${e}/${se(t)}?${a},o?{headers:{Cookie:we(o)}}:void 0)},bh=async e=>Ae(await ae(Be(e),t=>t.json()),async t=>t.response.status===414?{name:"TooLongURIError",message:"project ids may be too much."}:Ws(await mt(t,["NotFoundError","NotLoggedInError","NotMemberError"]),t)),ur=(()=>{let e=async(t,r,o)=>$s(await Ee(o??{}).fetch(xh(t,r,o)),n=>bh(n));return e.toRequest=xh,e.fromResponse=bh,e})();var Eh=(e,t)=>{let{sid:r,hostName:o}=Ee(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:we(r)}}:void 0)},wh=async e=>ae(await Ae(Be(e),async t=>await mt(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),qo=(()=>{let e=async(t,r)=>{let{fetch:o}=Ee(r??{}),n=Eh(t,r),s=await o(n);return O(s)?s:wh(S(s))};return e.toRequest=Eh,e.fromResponse=wh,e})(),Rh=(e,t)=>{let{sid:r,hostName:o}=Ee(t??{}),n=new URLSearchParams(e.map(s=>["ids",s]));return new Request(https://${o}/api/projects?${n},r?{headers:{Cookie:we(r)}}:void 0)},vh=async e=>ae(await Ae(Be(e),async t=>await mt(t,["NotLoggedInError"])??t),t=>t.json()),Ra=(()=>{let e=async(t,r)=>{let{fetch:o}=Ee(r??{}),n=await o(Rh(t,r));return O(n)?n:vh(S(n))};return e.toRequest=Rh,e.fromResponse=vh,e})();var au=async(e,t,r)=>{let[o,n,s]=await Promise.all([ur(e,t,r),O_(r),S_(e,r)]);return O(o)?o:O(n)?n:O(s)?s:L({...S(o),projectId:S(s),userId:S(n)})},iu,O_=async e=>{if(iu)return L(iu);let t=await xa(e);if(O(t))return t;let r=S(t);return"id"in r?(iu=r.id,L(r.id)):M({name:"NotLoggedInError",message:"This script cannot be used without login"})},kh=new Map,S_=async(e,t)=>{let r=kh.get(e);return r?L(r):Yr(await qo(e,t),({id:o})=>(kh.set(e,o),o))};function Se(e,t={}){let{signal:r,persistent:o=!0}=t;return r?.aborted?Promise.reject(r.reason):new Promise((n,s)=>{let i=()=>{clearTimeout(+c),s(r?.reason)},c=L_(()=>{r?.removeEventListener("abort",i),n()},e);if(r?.addEventListener("abort",i,{once:!0}),o===!1)try{Deno.unrefTimer(+c)}catch(l){if(!(l instanceof ReferenceError))throw clearTimeout(+c),l;console.error("persistent option is only available in Deno")}})}var cu=2**31-1;function L_(e,t){if(t=Math.trunc(Math.max(t,0)||0),t<=cu){let s=Number(setTimeout(e,t));return{valueOf:()=>s}}let r=Date.now(),o,n=()=>{let s=t-(Date.now()-r);o=s>cu?Number(setTimeout(n,cu)):Number(setTimeout(e,s))};return n(),{valueOf:()=>o}}var Go=async(e,t,r,o)=>{let n=await It(o?.socket,o?.sid);if(O(n))return M({name:"UnexpectedRequestError",error:Z(n)});let s=S(n),i=await au(e,t,o);if(O(i))return i;let a=S(i);try{let c=0,l=[],u;for(;o?.maxAttempts===void 0||c<o.maxAttempts;){let p=r(a,c,l,u);if(l=p instanceof Promise?await p:p,c++,l.length===0)return L(a.commitId);let f={kind:"page",projectId:a.projectId,pageId:a.id,parentId:a.commitId,userId:a.userId,changes:l,cursor:null,freeze:!0};for(;;){let m=await gh(s,"commit",f);if(K(m))return a.commitId=S(m).commitId,L(a.commitId);let h=Z(m),g=h.name;if(g==="SocketIOServerDisconnectError"||g==="UnexpectedRequestError")return M(h);if(g==="TimeoutError"||g==="SocketIOError"){await Se(3e3);continue}if(g==="NotFastForwardError"){await Se(1e3);let y=await au(e,t,o);if(O(y))return y;a=S(y)}u=g;break}}return M({name:"RetryError",attempts:c,message:Retrying exceeded the maxAttempts (${c}).})}finally{o?.socket||await At(s)}};var lu=(e,t)=>{let r=e.length>t.length,o=r?t:e,n=r?e:t,s=o.length+1,i=o.length+n.length+3,a=new Array(i);a.fill(-1);let c=[];function l(g,y,x){let w=Math.max(y,x),R=w-g;for(;R<o.length&&w<n.length&&o[R]===n[w];)++R,++w;return a[g+s]=c.length,c.push([{x:R,y:w},a[g+(y>x?-1:1)+s]]),w}let u=new Array(i);u.fill(-1);let p=-1,f=n.length-o.length;do{++p;for(let g=-p;g<=f-1;++g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);for(let g=f+p;g>=f+1;--g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);u[f+s]=l(f,u[f-1+s]+1,u[f+1+s])}while(u[f+s]!==n.length);let m=[],h=a[f+s];for(;h!==-1;)m.push(c[h][0]),h=c[h][1];return{from:e,to:t,editDistance:f+p*2,buildSES:function*(){let g=0,y=0;for(let{x,y:w}of N_(m))for(;g<x||y<w;)w-x>y-g?(yield{value:n[y],type:r?"deleted":"added"},++y):w-x<y-g?(yield{value:o[g],type:r?"added":"deleted"},++g):(yield{value:o[g],type:"common"},++g,++y)}}};function*pu(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield Th(t[n],r[n]);for(let n=r.length;n<t.length;n++)yield t[n]}else{for(let n=0;n<t.length;n++)yield Th(t[n],r[n]);for(let n=t.length;n<r.length;n++)yield r[n]}t=[],r=[]}for(let n of e)switch(n.type){case"added":t.push(n);break;case"deleted":r.push(n);break;case"common":yield*o(),yield n;break}yield*o()}var Th=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*N_(e){for(let t=e.length-1;t>=0;t--)yield e[t]}var _h=e=>e.padStart(8,"0"),uu=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${_h(t).slice(-8)}${e.slice(-6)}0000${_h(r)}};function*mu(e,t,{userId:r}){let{buildSES:o}=lu(e.map(({text:i})=>i),t),n=0,s=e[0].id;for(let i of pu(o())){switch(i.type){case"added":yield{_insert:s,lines:{id:uu(r),text:i.value}};continue;case"deleted":yield{_delete:s,lines:-1};break;case"replaced":yield{_update:s,lines:{text:i.value}};break}n++,s=e[n]?.id??"_end"}}var Ph=e=>{let{rows:[{indent:t,text:r},...o]}=e,n=r.replace(/^\s*code:/,"");return{indent:t,type:"codeBlock",fileName:n,content:o.map(s=>s.text.substring(t+1)).join(
)}};var pe=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested||!r&&s.quoted)return i();for(let a of o){let c=a.exec(n);if(c===null)continue;let l=n.substring(0,c.index),u=n.substring(c.index+c[0].length),p=e(c,s);return[...Ht(l,s),...p,...Ht(u,s)]}return i()};var me=e=>[{type:"plain",raw:e,text:e}],Oh=me;var M_=/\[\s+\]/,C_=([e],t)=>t.context==="table"?me(e):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Sh=pe(C_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[M_]});var I_=/.*?/,A_=([e],t)=>t.context==="table"?me(e):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Lh=pe(A_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[I_]});var F_=/^[$%] .+$/,D_=([e],t)=>{if(t.context==="table")return me(e);let r=e.charAt(0),o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},Nh=pe(D_,{parseOnNested:!1,parseOnQuoted:!1,patterns:[F_]});var U_=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,$_=([e],t)=>{if(t.context==="table")return me(e);let r=e.indexOf(" "),o=e.substring(1,r),n=e.substring(r+1,e.length-1),s=new Set(o);if(s.has("*")){let i=o.split("*").length-1;s.delete("*"),s.add(*-${Math.min(i,10)})}return[{type:"decoration",raw:e,rawDecos:o,decos:Array.from(s),nodes:Ht(n,{...t,nested:!0})}]},Mh=pe($_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[U_]});var j_=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,B_=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,H_=/\[https?:\/\/[^\s\]]+\]/,W_=/https?:\/\/[^\s]+/,q_=([e],t)=>{if(t.context==="table")return me(e);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,o=/^https?:\/\/[^\s\]]/.test(r),n=(o?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(n===null)return[];let s=o?r.substring(n[0].length):r.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},Ch=pe(q_,{parseOnNested:!0,parseOnQuoted:!0,patterns:[j_,B_,H_,W_]});var G_=/\[\$ .+? \]/,z_=/\[\$ [^\]]+\]/,V_=([e],t)=>t.context==="table"?me(e):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],Ih=pe(V_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[G_,z_]});var K_=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Y_=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,X_=e=>{let[t="",r="",o=""]=e.split(","),n=Number.parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=Number.parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),i=/^Z\d+$/.test(o)?Number.parseInt(o.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:i}},J_=(e,t)=>{let r=e[0];if(t.context==="table")return me(r);let o=r.startsWith("[N")||r.startsWith("[S"),[,n="",s=""]=o?e:[e[0],e[2],e[1]],{latitude:i,longitude:a,zoom:c}=X_(n),l=s!==""?https://www.google.com/maps/place/${encodeURIComponent(s)}/@${i},${a},${c}z:https://www.google.com/maps/@${i},${a},${c}z;return[{type:"googleMap",raw:r,latitude:i,longitude:a,zoom:c,place:s,url:l}]},Ah=pe(J_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[K_,Y_]});var Q_=/(?:^|\s)#\S+/,Z_=([e],t)=>{if(t.context==="table")return me(e);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...me(r),{type:"hashTag",raw:o,href:o.substring(1)}]},Fh=pe(Z_,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Q_]});var eP=/^\? .+$/,tP=([e],t)=>t.context==="table"?me(e):[{type:"helpfeel",raw:e,text:e.substring(2)}],Dh=pe(tP,{parseOnNested:!1,parseOnQuoted:!1,patterns:[eP]});var rP=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,oP=([e])=>{let t=e.substring(1,e.length-1),r=t.lastIndexOf(".icon"),o=t.substring(0,r),n=o.startsWith("/")?"root":"relative",s=t.substring(r+5,t.length),i=s.startsWith("*")?Number.parseInt(s.substring(1),10):1;return new Array(i).fill({}).map(()=>({path:o,pathType:n,type:"icon",raw:e}))},Uh=pe(oP,{parseOnNested:!0,parseOnQuoted:!0,patterns:[rP]});var nP=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,sP=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,iP=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,aP=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,cP=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||lP(e),lP=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),pP=([e],t)=>{if(t.context==="table")return me(e);let r=e.search(/\s/),o=r!==-1?e.substring(1,r):e.substring(1,e.length-1),n=r!==-1?e.substring(r,e.length-1).replace(/^\s+/,""):"",[s,i]=cP(n)?[n,o]:[o,n];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?${s}/thumb/1000:s,link:i}]},$h=pe(pP,{parseOnNested:!0,parseOnQuoted:!0,patterns:[nP,sP,iP,aP]});var uP=/\[\/?[^[\]]+\]/,mP=([e])=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},jh=pe(mP,{parseOnNested:!0,parseOnQuoted:!0,patterns:[uP]});var fP=/^[0-9]+\. .*$/,dP=([e],t)=>{if(t.context==="table")return me(e);let r=e.indexOf(" "),o=e.substring(0,r-1),n=Number.parseInt(o,10),s=e.substring(r+1,e.length);return[{type:"numberList",raw:e,rawNumber:o,number:n,nodes:Ht(s,{...t,nested:!1})}]},Bh=pe(dP,{parseOnNested:!1,parseOnQuoted:!1,patterns:[fP]});var hP=/^>.*$/,gP=([e],t)=>t.context==="table"?me(e):[{type:"quote",raw:e,nodes:Ht(e.substring(1),{...t,quoted:!0})}],Hh=pe(gP,{parseOnNested:!1,parseOnQuoted:!1,patterns:[hP]});var yP=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,xP=([e],t)=>{if(t.context==="table")return me(e);let r=e.substring(2,e.length-2),o=r.lastIndexOf(".icon"),n=r.substring(0,o),s=n.startsWith("/")?"root":"relative",i=r.substring(o+5,r.length),a=i.startsWith("*")?Number.parseInt(i.substring(1),10):1;return new Array(a).fill({}).map(()=>({path:n,pathType:s,type:"strongIcon",raw:e}))},Wh=pe(xP,{parseOnNested:!1,parseOnQuoted:!0,patterns:[yP]});var bP=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,EP=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,wP=([e],t)=>{if(t.context==="table")return me(e);let r=e.substring(2,e.length-2),o=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:o?${r}/thumb/1000:r}]},qh=pe(wP,{parseOnNested:!1,parseOnQuoted:!0,patterns:[bP,EP]});var RP=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,vP=([e],t)=>t.context==="table"?me(e):[{type:"strong",raw:e,nodes:Ht(e.substring(2,e.length-2),{...t,nested:!0})}],Gh=pe(vP,{parseOnNested:!1,parseOnQuoted:!0,patterns:[RP]});var kP=(e,t,r)=>e!==""?r():[],TP=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>Oh(t,r))(),Ht=TP(kP,Hh,Dh,Bh,Lh,Nh,Sh,Mh,Ih,qh,Wh,Gh,$h,Ch,Uh,Ah,jh,Fh);var zh=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:Ht(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var Vh=e=>{let{rows:[{indent:t,text:r},...o]}=e,n=r.replace(/^\s*table:/,"");return{indent:t,type:"table",fileName:n,cells:o.map(s=>s.text.substring(t+1)).map(s=>s.split(" ").map(i=>Ht(i,{nested:!1,quoted:!1,context:"table"})))}};var Kh=e=>({type:"title",text:e.rows[0].text});var Yh=e=>{switch(e.type){case"title":return Kh(e);case"codeBlock":return Ph(e);case"table":return Vh(e);case"line":return zh(e)}};var _P=({type:e,rows:[t]},r)=>(e==="codeBlock"||e==="table")&&r.indent>t.indent,Xh=(e,t)=>{let r=e[e.length-1];return r!==void 0&&_P(r,t)?r.rows.push(t):e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e},Jh=(e,{hasTitle:t=!0})=>{if(t){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(Xh,[])]}return e.reduce(Xh,[])};var Qh=e=>e.split(
).map(t=>({indent:/^\s+/.exec(t)?.[0].length??0,text:t}));var it=(e,{hasTitle:t=!0}={})=>{let r=Qh(e);return Jh(r,{hasTitle:t}).map(Yh)},Zh=e=>/^\s*\S.*$/m.exec(e)?.[0].trim()??"Untitled";var PP=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,OP=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,SP=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,LP=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,va=e=>{if(PP.test(e)){let t=new URL(e).searchParams,r=t.get("v");if(r)return{pathType:"com",videoId:r,params:t}}{let t=e.match(OP);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(SP);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match(LP);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};var rg=e=>{let t=it(e,{hasTitle:!0}),r="",o=new Map,n=[],s=new Set,i=[],a=new Set,c=[],l=null,u=[],p=new Set,f=new Set,m=new RegExp(${globalThis.location?.origin??"https://scrapbox.io"}/files/([a-z0-9]{24})(?:|\\.[a-zA-Z0-9]+)(?:|\\?[^\\s]*)$),h=x=>{switch(x.type){case"hashTag":if(o.has(ce(x.href)))return;o.set(ce(x.href),!1),n.push(x.href);return;case"link":switch(x.pathType){case"relative":{let w=tg(x.href);if(o.get(ce(w)))return;o.set(ce(w),!0),n.push(w);return}case"root":{let w=tg(x.href);if(/^\/[\w\d-]+\/?$/.test(w)||s.has(ce(w)))return;s.add(ce(w)),i.push(w);return}case"absolute":{if(x.content)return;let w=va(x.href);if(w&&w.pathType!=="list"){l??=https://i.ytimg.com/vi/${w.videoId}/mqdefault.jpg;return}let R=x.href.match(m)?.[1];R&&p.add(R);return}default:return}case"icon":case"strongIcon":{if(x.pathType==="root"||a.has(ce(x.path)))return;a.add(ce(x.path)),c.push(x.path);return}case"image":case"strongImage":{l??=x.src.endsWith("/thumb/1000")?x.src.replace(/\/thumb\/1000$/,"/raw"):x.src;{let w=x.src.match(m)?.[1];w&&p.add(w)}if(x.type==="image"){let w=x.link.match(m)?.[1];w&&p.add(w)}return}case"helpfeel":f.add(x.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let w of x.nodes)h(w);return}default:return}},g=[];for(let x of t)switch(x.type){case"title":{r=x.text;continue}case"line":u.length<5&&x.nodes.length>0&&u.push(x.nodes[0].type==="helpfeel"||x.nodes[0].type==="commandLine"?eg(x.nodes[0].raw):x.nodes.map(w=>w.raw).join("").trim().slice(0,200));for(let w of x.nodes)h(w);continue;case"codeBlock":u.length<5&&u.push(eg(x.content));continue;case"table":{for(let w of x.cells)for(let R of w)for(let b of R)h(b);if(!["infobox","cosense"].includes(x.fileName))continue;g.push(...x.cells.map(w=>w.map(R=>R.map(b=>b.raw).join("")).join(" ").trim()));continue}}let y=e.split(
);return[r,n,i,c,l,u,[...p],[...f],g,y.length,y.reduce((x,w)=>x+[...w].length,0)]},eg=e=>\${e.trim().replaceAll("","\\").slice(0,198)}\`,tg=e=>e.replace(/#a-f\d{24,32}$/,"");var wo=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));var og=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?t.trimStart().slice(2):[]);function*ng(e,t,r){let o=t.flatMap(g=>(Re(g)?g:g.text).split(`
));for(let g of mu(e.lines,o,{userId:r}))yield g;let[n,s,i,a,c,l,u,p,f,m,h]=rg(o.join(
));(e.title!==n||!e.persistent)&&(yield{title:n}),wo(e.links,s)||(yield{links:s}),wo(e.projectLinks,i)||(yield{projectLinks:i}),wo(e.icons,a)||(yield{icons:a}),e.image!==c&&(yield{image:c}),wo(e.descriptions,l)||(yield{descriptions:l}),wo(e.files,u)||(yield{files:u}),wo(og(e.lines),p)||(yield{helpfeels:p}),wo(e.infoboxDefinition,f)||(yield{infoboxDefinition:f}),yield{linesCount:m},yield{charsCount:h}}var sg=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,o=t?.[2]?parseInt(t[2])+1:2;return${r}_${o}};var ig=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);var Le=(e,t,r,o)=>Go(e,t,async(n,s,i,a)=>{if(a==="DuplicateTitleError"){let m=sg(t);return i.map(h=>("title"in h&&(h.title=m),h))}let c=r(n.lines,{...n,attempts:s}),l=c instanceof Promise?await c:c;if(l===void 0)return[];let[u,p]=Array.isArray(l)?[l,void 0]:[l.lines,l.pin];if(u.length===0)return[{deleted:!0}];let f=n.lines===u?[]:[...ng(n,u,n.userId)];return p!==void 0&&(p&&n.pin===0||!p&&n.pin>0)&&f.push({pin:p?ig():0}),f},o);var ag=(e,t,r)=>Go(e,t,o=>o.persistent?[{deleted:!0}]:[],r);var ka=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i}=Ee(o??{}),a=await Un(o);if(O(a))return a;let c=new Request(https://${s}/api/pages/${e}/replace/links,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":S(a),...n?{Cookie:we(n)}:{}},body:JSON.stringify({from:t,to:r})}),l=await i(c);return O(l)?l:ae(await Ae(Be(S(l)),async u=>await mt(u,["NotFoundError","NotLoggedInError","NotMemberError"])??u),async u=>{let{message:p}=await u.json();return parseInt(p.match(/\d+/)?.[0]??"0")})};var cg=(e,t)=>{let{sid:r,hostName:o,followingId:n}=Ee(t??{});return new Request(https://${o}/api/pages/${e}/search/titles${n??followingId=${n}:""},r?{headers:{Cookie:we(r)}}:void 0)},lg=async e=>ae(await Ae(Be(e),async t=>t.response.status===422?{name:"InvalidFollowingIdError",message:await t.response.text()}:await mt(t,["NotFoundError","NotLoggedInError"])??t),t=>t.json().then(r=>({pages:r,followingId:t.headers.get("X-following-id")??""}))),CP=(()=>{let e=async(t,r)=>{let o=await Ee(r??{}).fetch(cg(t,r));return O(o)?o:lg(S(o))};return e.toRequest=cg,e.fromResponse=lg,e})();async function*pg(e,t){let r;do{let o=await CP(e,{followingId:r,...t});if(O(o)){yield o;return}let n=S(o);yield L(n.pages),r=n.followingId}while(r)}var ug=async(e,t,r)=>{let{sid:o,hostName:n,fetch:s}=Ee(r??{}),i=new Request(https://${n}/api/pages/${t}/search/query?q=${encodeURIComponent(e)},o?{headers:{Cookie:we(o)}}:void 0),a=await s(i);return O(a)?a:ae(await Ae(Be(S(a)),async c=>await mt(c,["NotFoundError","NotLoggedInError","NotMemberError","NoQueryError"])??c),c=>c.json())};var mg=(e,t,r,o)=>{let{sid:n,hostName:s}=Ee(o??{});return new Request(https://${s}/api/code/${e}/${se(t)}/${se(r)},n?{headers:{Cookie:we(n)}}:void 0)},fg=async e=>ae(await Ae(Be(e),async t=>t.response.status===404&&t.response.headers.get("Content-Type")?.includes?.("text/plain")?{name:"NotFoundError",message:"Code block is not found"}:await mt(t,["NotLoggedInError","NotMemberError"])??t),t=>t.text()),Ta=(()=>{let e=async(t,r,o,n)=>{let s=mg(t,r,o,n),i=await Ee(n??{}).fetch(s);return O(i)?i:fg(S(i))};return e.toRequest=mg,e.fromResponse=fg,e})();var du=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=[1732584193,4023233417,2562383102,271733878],o=new Uint8Array(fu),n=0,s=0,i=0;[r,o,n,s,i]=hg(r,o,n,s,i,t);let a=fu-n;a<9&&(a+=fu);let c=new Uint8Array(a);c[0]=128,[s,i]=[s<<3,i<<3|s>>>29],c[c.length-8]=s&255,c[c.length-7]=s>>>8&255,c[c.length-6]=s>>>16&255,c[c.length-5]=s>>>24&255,c[c.length-4]=i&255,c[c.length-3]=i>>>8&255,c[c.length-2]=i>>>16&255,c[c.length-1]=i>>>24&255,[r,o,n,s,i]=hg(r,o,n,s,i,new Uint8Array(c.buffer));let l=new ArrayBuffer(16),u=new DataView(l);return u.setUint32(0,r[0],!0),u.setUint32(4,r[1],!0),u.setUint32(8,r[2],!0),u.setUint32(12,r[3],!0),l},fu=64,z=(e,t)=>e<<t|e>>>32-t,Ft=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,dg=(e,t)=>{let[r,o,n,s]=e,i=Ft(t,0),a=Ft(t,4),c=Ft(t,8),l=Ft(t,12),u=Ft(t,16),p=Ft(t,20),f=Ft(t,24),m=Ft(t,28),h=Ft(t,32),g=Ft(t,36),y=Ft(t,40),x=Ft(t,44),w=Ft(t,48),R=Ft(t,52),b=Ft(t,56),E=Ft(t,60);return r=o+z(((n^s)&o^s)+r+i+3614090360,7),s=r+z(((o^n)&r^n)+s+a+3905402710,12),n=s+z(((r^o)&s^o)+n+c+606105819,17),o=n+z(((s^r)&n^r)+o+l+3250441966,22),r=o+z(((n^s)&o^s)+r+u+4118548399,7),s=r+z(((o^n)&r^n)+s+p+1200080426,12),n=s+z(((r^o)&s^o)+n+f+2821735955,17),o=n+z(((s^r)&n^r)+o+m+4249261313,22),r=o+z(((n^s)&o^s)+r+h+1770035416,7),s=r+z(((o^n)&r^n)+s+g+2336552879,12),n=s+z(((r^o)&s^o)+n+y+4294925233,17),o=n+z(((s^r)&n^r)+o+x+2304563134,22),r=o+z(((n^s)&o^s)+r+w+1804603682,7),s=r+z(((o^n)&r^n)+s+R+4254626195,12),n=s+z(((r^o)&s^o)+n+b+2792965006,17),o=n+z(((s^r)&n^r)+o+E+1236535329,22),r=o+z(((o^n)&s^n)+r+a+4129170786,5),s=r+z(((r^o)&n^o)+s+f+3225465664,9),n=s+z(((s^r)&o^r)+n+x+643717713,14),o=n+z(((n^s)&r^s)+o+i+3921069994,20),r=o+z(((o^n)&s^n)+r+p+3593408605,5),s=r+z(((r^o)&n^o)+s+y+38016083,9),n=s+z(((s^r)&o^r)+n+E+3634488961,14),o=n+z(((n^s)&r^s)+o+u+3889429448,20),r=o+z(((o^n)&s^n)+r+g+568446438,5),s=r+z(((r^o)&n^o)+s+b+3275163606,9),n=s+z(((s^r)&o^r)+n+l+4107603335,14),o=n+z(((n^s)&r^s)+o+h+1163531501,20),r=o+z(((o^n)&s^n)+r+R+2850285829,5),s=r+z(((r^o)&n^o)+s+c+4243563512,9),n=s+z(((s^r)&o^r)+n+m+1735328473,14),o=n+z(((n^s)&r^s)+o+w+2368359562,20),r=o+z((o^n^s)+r+p+4294588738,4),s=r+z((r^o^n)+s+h+2272392833,11),n=s+z((s^r^o)+n+x+1839030562,16),o=n+z((n^s^r)+o+b+4259657740,23),r=o+z((o^n^s)+r+a+2763975236,4),s=r+z((r^o^n)+s+u+1272893353,11),n=s+z((s^r^o)+n+m+4139469664,16),o=n+z((n^s^r)+o+y+3200236656,23),r=o+z((o^n^s)+r+R+681279174,4),s=r+z((r^o^n)+s+i+3936430074,11),n=s+z((s^r^o)+n+l+3572445317,16),o=n+z((n^s^r)+o+f+76029189,23),r=o+z((o^n^s)+r+g+3654602809,4),s=r+z((r^o^n)+s+w+3873151461,11),n=s+z((s^r^o)+n+E+530742520,16),o=n+z((n^s^r)+o+c+3299628645,23),r=o+z((n^(o|~s))+r+i+4096336452,6),s=r+z((o^(r|~n))+s+m+1126891415,10),n=s+z((r^(s|~o))+n+b+2878612391,15),o=n+z((s^(n|~r))+o+p+4237533241,21),r=o+z((n^(o|~s))+r+w+1700485571,6),s=r+z((o^(r|~n))+s+l+2399980690,10),n=s+z((r^(s|~o))+n+y+4293915773,15),o=n+z((s^(n|~r))+o+a+2240044497,21),r=o+z((n^(o|~s))+r+h+1873313359,6),s=r+z((o^(r|~n))+s+E+4264355552,10),n=s+z((r^(s|~o))+n+f+2734768916,15),o=n+z((s^(n|~r))+o+R+1309151649,21),r=o+z((n^(o|~s))+r+u+4149444226,6),s=r+z((o^(r|~n))+s+x+3174756917,10),n=s+z((r^(s|~o))+n+c+718787259,15),o=n+z((s^(n|~r))+o+g+3951481745,21),[e[0]+r>>>0,e[1]+o>>>0,e[2]+n>>>0,e[3]+s>>>0]},hg=(e,t,r,o,n,s)=>{let i=64-r;if(s.length<i)t.set(s,r),r+=s.length;else{t.set(s.slice(0,i),r),e=dg(e,t);let a=i;for(;a+64<=s.length;)e=dg(e,s.slice(a,a+64)),a+=64;t.fill(0).set(s.slice(a),0),r=s.length-a}return[o,n]=IP(o,n,s.length),[e,t,r,o,n]},IP=(e,t,r)=>(e+=r,e>4294967295&&(t+=1),[e>>>0,t]);var AP=new TextEncoder().encode("0123456789abcdef"),gg=new Uint8Array(128).fill(16);AP.forEach((e,t)=>gg[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>gg[e]=t+10);function yg(e){return e*2}function xg(e,t,r,o){for(;t<e.length;++t){let n=e[t];e[r++]=o[n>>4],e[r++]=o[n&15]}return r}function bg(e,t){let r=e.length;if(e.byteOffset){let o=new Uint8Array(e.buffer);o.set(e),e=o.subarray(0,r)}return e=new Uint8Array(e.buffer.transfer(t)),e.set(e.subarray(0,r),t-r),[e,t-r]}var Eg=new TextEncoder().encode("0123456789abcdef"),wg=new Uint8Array(128).fill(16);Eg.forEach((e,t)=>wg[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>wg[e]=t+10);function hu(e){typeof e=="string"?e=new TextEncoder().encode(e):e instanceof ArrayBuffer?e=new Uint8Array(e).slice():e=e.slice();let[t,r]=bg(e,yg(e.length));return xg(t,r,0,Eg),new TextDecoder().decode(t)}var Rg=async e=>{let t=e.title??".watchlistrc",r="projectsLastAccessed.json",o=await Ta(e.project,t,r),n=O(o)?{}:JSON.parse(S(o)||"{}"),s=JSON.parse(localStorage.getItem("projectsLastAccessed")??"{}"),i=new Set([...Object.keys(n),...Object.keys(s)]),a=Object.fromEntries([...i].map(l=>[l,Math.max(n[l]??0,s[l]??0)]).sort((l,u)=>u[1]-l[1])),c=JSON.stringify(a);localStorage.setItem("projectsLastAccessed",c),await Le(e.project,t,()=>[t,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","",code:${r}, ${c},""])};var rr=!1,_a=e=>{rr=typeof e=="boolean"?e:new Set(e)},jn=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(%c${e},gu,...o)];case"log":case"info":case"debug":return[t,(...o)=>{rr!==!0&&(!rr||!rr.has(e))||r(%c${e},gu,...o)}];case"assert":return[t,(o,...n)=>{rr!==!0&&(!rr||!rr.has(e))||r(o,%c${e},gu,...n)}];case"time":case"timeEnd":return[t,o=>{rr!==!0&&(!rr||!rr.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(rr!==!0&&(!rr||!rr.has(e))))return r(...o)}]}})),gu="color: gray";var Xr=globalThis.scrapbox;var qs=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}};var vg=e=>{let{accessToken:t,fetch:r,page:o,per:n}=qs(e??{}),i=https://api.gyazo.com/api/images?${new URLSearchParams({access_token:t,...n!==void 0?{per_page:${Math.max(1,Math.min(100,Math.round(n)))}}:{},...o!==void 0?{page:${o}}:{}})};return r(i)};var kg=(e,t)=>{let{title:r,description:o,metadataIsPublic:n,collectionId:s,refererURL:i,accessToken:a,created:c,app:l,fetch:u}=qs(t),p=new FormData;return p.append("imagedata",e),p.append("access_token",a),i&&p.append("referer_url",i.toString()),l!==void 0&&p.append("app",l),r!==void 0&&p.append("title",r),o!=null&&p.append("desc",o),s&&p.append("collection_id",s),n&&p.append("metadata_is_public","true"),c!==void 0&&p.append("created_at",${c}),u("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:p})};var Bn="Gyazo Viewer",Tg=e=>{let t=Promise.resolve(),r=globalThis.GM_fetch;Xr.PageMenu.addMenu({title:r?Bn:"Open Gyazo",icon:"kamon kamon-gyazo",onClick:r?()=>{t=t.then(()=>FP({per:e.maxCount??10,accessToken:e.accessToken,fetch:r,onClick:e.onClick}))}:()=>globalThis.open("https://gyazo.com/captures")})},FP=async e=>{let t;try{let r=vg({page:0,...e});t=setTimeout(()=>{Xr.PageMenu(Bn).addItem({title:"Loading...",icon:"fas fa-spinner",onClick:()=>{}})},100);let o=await r;if(!o.ok)throw new Error(${o.status} ${o.statusText});let n=await o.json();clearTimeout(t),Xr.PageMenu(Bn).removeAllItems();for(let s of n)s.image_id&&Xr.PageMenu(Bn).addItem({title:s.metadata?.title||"Untitled",image:s.url,onClick:i=>e.onClick?.(s,i)??navigator?.clipboard?.writeText?.(s.permalink_url)?.catch?.(a=>{alert(${a}),console.error(a)})})}catch(r){clearTimeout(t),Xr.PageMenu(Bn).removeAllItems(),Xr.PageMenu(Bn).addItem({title:"Failed to load the image list.",icon:"fas fa-exclamation-triangle",onClick:()=>{}}),console.error("Failed to load the image list",r)}};import{GYAZO_ACCESS_TOKEN as ED}from"https://scrapbox.io/api/code/takker-memex/GYAZO_ACCESS_TOKEN/auth.js";var Ca,re,Sg,DP,Ro,_g,Lg,Ng,yu,Oa,Gs,Mg,Ru,xu,bu,Cg,La={},Na=[],UP=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,zs=Array.isArray;function Jr(e,t){for(var r in t)e[r]=t[r];return e}function vu(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Qr(e,t,r){var o,n,s,i={};for(s in t)s=="key"?o=t[s]:s=="ref"?n=t[s]:i[s]=t[s];if(arguments.length>2&&(i.children=arguments.length>3?Ca.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)i[s]===void 0&&(i[s]=e.defaultProps[s]);return Sa(e,i,o,n,null)}function Sa(e,t,r,o,n){var s={type:e,props:t,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:n??++Sg,__i:-1,__u:0};return n==null&&re.vnode!=null&&re.vnode(s),s}function ee(e){return e.children}function vr(e,t){this.props=e,this.context=t}function Hn(e,t){if(t==null)return e.__?Hn(e.__,e.__i+1):null;for(var r;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null)return r.__e;return typeof e.type=="function"?Hn(e):null}function $P(e){if(e.__P&&e.__d){var t=e.__v,r=t.__e,o=[],n=[],s=Jr({},t);s.__v=t.__v+1,re.vnode&&re.vnode(s),ku(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[r]:null,o,r??Hn(t),!!(32&t.__u),n),s.__v=t.__v,s.__.__k[s.__i]=s,Dg(o,s,n),t.__e=t.__=null,s.__e!=r&&Ig(s)}}function Ig(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Ig(e)}function Eu(e){(!e.__d&&(e.__d=!0)&&Ro.push(e)&&!Ma.__r++||_g!=re.debounceRendering)&&((_g=re.debounceRendering)||Lg)(Ma)}function Ma(){try{for(var e,t=1;Ro.length;)Ro.length>t&&Ro.sort(Ng),e=Ro.shift(),t=Ro.length,$P(e)}finally{Ro.length=Ma.__r=0}}function Ag(e,t,r,o,n,s,i,a,c,l,u){var p,f,m,h,g,y,x,w=o&&o.__k||Na,R=t.length;for(c=jP(r,t,w,c,R),p=0;p<R;p++)(m=r.__k[p])!=null&&(f=m.__i!=-1&&w[m.__i]||La,m.__i=p,y=ku(e,m,f,n,s,i,a,c,l,u),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Tu(f.ref,null,m),u.push(m.ref,m.__c||h,m)),g==null&&h!=null&&(g=h),(x=!!(4&m.__u))||f.__k===m.__k?(c=Fg(m,c,e,x),x&&f.__e&&(f.__e=null)):typeof m.type=="function"&&y!==void 0?c=y:h&&(c=h.nextSibling),m.__u&=-7);return r.__e=g,c}function jP(e,t,r,o,n){var s,i,a,c,l,u=r.length,p=u,f=0;for(e.__k=new Array(n),s=0;s<n;s++)(i=t[s])!=null&&typeof i!="boolean"&&typeof i!="function"?(typeof i=="string"||typeof i=="number"||typeof i=="bigint"||i.constructor==String?i=e.__k[s]=Sa(null,i,null,null,null):zs(i)?i=e.__k[s]=Sa(ee,{children:i},null,null,null):i.constructor===void 0&&i.__b>0?i=e.__k[s]=Sa(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):e.__k[s]=i,c=s+f,i.__=e,i.__b=e.__b+1,a=null,(l=i.__i=BP(i,r,c,p))!=-1&&(p--,(a=r[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(n>u?f--:n<u&&f++),typeof i.type!="function"&&(i.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,i.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<u;s++)(a=r[s])!=null&&!(2&a.__u)&&(a.__e==o&&(o=Hn(a)),$g(a,a));return o}function Fg(e,t,r,o){var n,s;if(typeof e.type=="function"){for(n=e.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=e,t=Fg(n[s],t,r,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=Hn(e)),r.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function vo(e,t){return t=t||[],e==null||typeof e=="boolean"||(zs(e)?e.some(function(r){vo(r,t)}):t.push(e)),t}function BP(e,t,r,o){var n,s,i,a=e.key,c=e.type,l=t[r],u=l!=null&&(2&l.__u)==0;if(l===null&&a==null||u&&a==l.key&&c==l.type)return r;if(o>(u?1:0)){for(n=r-1,s=r+1;n>=0||s<t.length;)if((l=t[i=n>=0?n--:s++])!=null&&!(2&l.__u)&&a==l.key&&c==l.type)return i}return-1}function Pg(e,t,r){t[0]=="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||UP.test(t)?r:r+"px"}function Pa(e,t,r,o,n){var s,i;e:if(t=="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)r&&t in r||Pg(e.style,t,"");if(r)for(t in r)o&&r[t]==o[t]||Pg(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(Mg,"$1")),i=t.toLowerCase(),t=i in e||t=="onFocusOut"||t=="onFocusIn"?i.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=r,r?o?r[Gs]=o[Gs]:(r[Gs]=Ru,e.addEventListener(t,s?bu:xu,s)):e.removeEventListener(t,s?bu:xu,s);else{if(n=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=r??"";break e}catch{}typeof r=="function"||(r==null||r===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&r==1?"":r))}}function Og(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t[Oa]==null)t[Oa]=Ru++;else if(t[Oa]<r[Gs])return;return r(re.event?re.event(t):t)}}}function ku(e,t,r,o,n,s,i,a,c,l){var u,p,f,m,h,g,y,x,w,R,b,E,T,I,F,A=t.type;if(t.constructor!==void 0)return null;128&r.__u&&(c=!!(32&r.__u),s=[a=t.__e=r.__e]),(u=re.__b)&&u(t);e:if(typeof A=="function")try{if(x=t.props,w=A.prototype&&A.prototype.render,R=(u=A.contextType)&&o[u.__c],b=u?R?R.props.value:u.__:o,r.__c?y=(p=t.__c=r.__c).__=p.__E:(w?t.__c=p=new A(x,b):(t.__c=p=new vr(x,b),p.constructor=A,p.render=WP),R&&R.sub(p),p.state||(p.state={}),p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),w&&p.__s==null&&(p.__s=p.state),w&&A.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Jr({},p.__s)),Jr(p.__s,A.getDerivedStateFromProps(x,p.__s))),m=p.props,h=p.state,p.__v=t,f)w&&A.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),w&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(w&&A.getDerivedStateFromProps==null&&x!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,b),t.__v==r.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,b)===!1){t.__v!=r.__v&&(p.props=x,p.state=p.__s,p.__d=!1),t.__e=r.__e,t.__k=r.__k,t.__k.some(function(N){N&&(N.__=t)}),Na.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&i.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,b),w&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,h,g)})}if(p.context=b,p.props=x,p.__P=e,p.__e=!1,E=re.__r,T=0,w)p.state=p.__s,p.__d=!1,E&&E(t),u=p.render(p.props,p.state,p.context),Na.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,E&&E(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++T<25);p.state=p.__s,p.getChildContext!=null&&(o=Jr(Jr({},o),p.getChildContext())),w&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),I=u!=null&&u.type===ee&&u.key==null?Ug(u.props.children):u,a=Ag(e,zs(I)?I:[I],t,r,o,n,s,i,a,c,l),p.base=t.__e,t.__u&=-161,p.__h.length&&i.push(p),y&&(p.__E=p.__=null)}catch(N){if(t.__v=null,c||s!=null)if(N.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,t.__e=a}else{for(F=s.length;F--;)vu(s[F]);wu(t)}else t.__e=r.__e,t.__k=r.__k,N.then||wu(t);re.__e(N,t,r)}else s==null&&t.__v==r.__v?(t.__k=r.__k,t.__e=r.__e):a=t.__e=HP(r.__e,t,r,o,n,s,i,c,l);return(u=re.diffed)&&u(t),128&t.__u?void 0:a}function wu(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(wu))}function Dg(e,t,r){for(var o=0;o<r.length;o++)Tu(r[o],r[++o],r[++o]);re.__c&&re.__c(t,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(s){s.call(n)})}catch(s){re.__e(s,n.__v)}})}function Ug(e){return typeof e!="object"||e==null||e.__b>0?e:zs(e)?e.map(Ug):e.constructor!==void 0?null:Jr({},e)}function HP(e,t,r,o,n,s,i,a,c){var l,u,p,f,m,h,g,y=r.props||La,x=t.props,w=t.type;if(w=="svg"?n="http://www.w3.org/2000/svg":w=="math"?n="http://www.w3.org/1998/Math/MathML":n||(n="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((m=s[l])&&"setAttribute"in m==!!w&&(w?m.localName==w:m.nodeType==3)){e=m,s[l]=null;break}}if(e==null){if(w==null)return document.createTextNode(x);e=document.createElementNS(n,w,x.is&&x),a&&(re.__m&&re.__m(t,s),a=!1),s=null}if(w==null)y===x||a&&e.data==x||(e.data=x);else{if(s=w=="textarea"&&x.defaultValue!=null?null:s&&Ca.call(e.childNodes),!a&&s!=null)for(y={},l=0;l<e.attributes.length;l++)y[(m=e.attributes[l]).name]=m.value;for(l in y)m=y[l],l=="dangerouslySetInnerHTML"?p=m:l=="children"||l in x||l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x||Pa(e,l,null,m,n);for(l in x)m=x[l],l=="children"?f=m:l=="dangerouslySetInnerHTML"?u=m:l=="value"?h=m:l=="checked"?g=m:a&&typeof m!="function"||y[l]===m||Pa(e,l,m,y[l],n);if(u)a||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),Ag(t.type=="template"?e.content:e,zs(f)?f:[f],t,r,o,w=="foreignObject"?"http://www.w3.org/1999/xhtml":n,s,i,s?s[0]:r.__k&&Hn(r,0),a,c),s!=null)for(l=s.length;l--;)vu(s[l]);a&&w!="textarea"||(l="value",w=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[l]||w=="progress"&&!h||w=="option"&&h!=y[l])&&Pa(e,l,h,y[l],n),l="checked",g!=null&&g!=e[l]&&Pa(e,l,g,y[l],n))}return e}function Tu(e,t,r){try{if(typeof e=="function"){var o=typeof e.__u=="function";o&&e.__u(),o&&t==null||(e.__u=e(t))}else e.current=t}catch(n){re.__e(n,r)}}function $g(e,t,r){var o,n;if(re.unmount&&re.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||Tu(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){re.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(n=0;n<o.length;n++)o[n]&&$g(o[n],t,r||typeof e.type!="function");r||vu(e.__e),e.__c=e.__=e.__e=void 0}function WP(e,t,r){return this.constructor(e,r)}function vt(e,t,r){var o,n,s,i;t==document&&(t=document.documentElement),re.__&&re.__(e,t),n=(o=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],ku(t,e=(!o&&r||t).__k=Qr(ee,null,[e]),n||La,La,t.namespaceURI,!o&&r?[r]:n?null:t.firstChild?Ca.call(t.childNodes):null,s,!o&&r?r:n?n.__e:t.firstChild,o,i),Dg(s,e,i)}function Vs(e){function t(r){var o,n;return this.getChildContext||(o=new Set,(n={})[t.__c]=this,this.getChildContext=function(){return n},this.componentWillUnmount=function(){o=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&o.forEach(function(i){i.__e=!0,Eu(i)})},this.sub=function(s){o.add(s);var i=s.componentWillUnmount;s.componentWillUnmount=function(){o&&o.delete(s),i&&i.call(s)}}),r.children}return t.__c="__cC"+Cg++,t.__=e,t.Provider=t.__l=(t.Consumer=function(r,o){return r.children(o)}).contextType=t,t}Ca=Na.slice,re={__e:function(e,t,r,o){for(var n,s,i;t=t.__;)if((n=t.__c)&&!n.__)try{if((s=n.constructor)&&s.getDerivedStateFromError!=null&&(n.setState(s.getDerivedStateFromError(e)),i=n.__d),n.componentDidCatch!=null&&(n.componentDidCatch(e,o||{}),i=n.__d),i)return n.__E=n}catch(a){e=a}throw e}},Sg=0,DP=function(e){return e!=null&&e.constructor===void 0},vr.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Jr({},this.state),typeof e=="function"&&(e=e(Jr({},r),this.props)),e&&Jr(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),Eu(this))},vr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Eu(this))},vr.prototype.render=ee,Ro=[],Lg=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ng=function(e,t){return e.__v.__b-t.__v.__b},Ma.__r=0,yu=Math.random().toString(8),Oa="__d"+yu,Gs="__a"+yu,Mg=/(PointerCapture)$|Capture$/i,Ru=0,xu=Og(!1),bu=Og(!0),Cg=0;var zo,Me,_u,jg,Ks=0,Kg=[],Xe=re,Bg=Xe.__b,Hg=Xe.__r,Wg=Xe.diffed,qg=Xe.__c,Gg=Xe.unmount,zg=Xe.__;function Ys(e,t){Xe.__h&&Xe.__h(Me,e,Ks||t),Ks=0;var r=Me.__H||(Me.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function Q(e){return Ks=1,ko(Yg,e)}function ko(e,t,r){var o=Ys(zo++,2);if(o.t=e,!o.__c&&(o.__=[r?r(t):Yg(void 0,t),function(a){var c=o.__N?o.__N[0]:o.__[0],l=o.t(c,a);c!==l&&(o.__N=[l,o.__[1]],o.__c.setState({}))}],o.__c=Me,!Me.__f)){var n=function(a,c,l){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(f){return f.__c});if(u.every(function(f){return!f.__N}))return!s||s.call(this,a,c,l);var p=o.__c.props!==a;return u.some(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(p=!0)}}),s&&s.call(this,a,c,l)||p};Me.__f=!0;var s=Me.shouldComponentUpdate,i=Me.componentWillUpdate;Me.componentWillUpdate=function(a,c,l){if(this.__e){var u=s;s=void 0,n(a,c,l),s=u}i&&i.call(this,a,c,l)},Me.shouldComponentUpdate=n}return o.__N||o.__}function te(e,t){var r=Ys(zo++,3);!Xe.__s&&Ou(r.__H,t)&&(r.__=e,r.u=t,Me.__H.__h.push(r))}function Aa(e,t){var r=Ys(zo++,4);!Xe.__s&&Ou(r.__H,t)&&(r.__=e,r.u=t,Me.__h.push(r))}function ft(e){return Ks=5,H(function(){return{current:e}},[])}function H(e,t){var r=Ys(zo++,7);return Ou(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function D(e,t){return Ks=8,H(function(){return e},t)}function Zr(e){var t=Me.context[e.__c],r=Ys(zo++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(Me)),t.props.value):e.__}function qP(){for(var e;e=Kg.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Ia),t.__h.some(Pu),t.__h=[]}catch(r){t.__h=[],Xe.__e(r,e.__v)}}}Xe.__b=function(e){Me=null,Bg&&Bg(e)},Xe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),zg&&zg(e,t)},Xe.__r=function(e){Hg&&Hg(e),zo=0;var t=(Me=e.__c).__H;t&&(_u===Me?(t.__h=[],Me.__h=[],t.__.some(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})):(t.__h.some(Ia),t.__h.some(Pu),t.__h=[],zo=0)),_u=Me},Xe.diffed=function(e){Wg&&Wg(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Kg.push(t)!==1&&jg===Xe.requestAnimationFrame||((jg=Xe.requestAnimationFrame)||GP)(qP)),t.__H.__.some(function(r){r.u&&(r.__H=r.u),r.u=void 0})),_u=Me=null},Xe.__c=function(e,t){t.some(function(r){try{r.__h.some(Ia),r.__h=r.__h.filter(function(o){return!o.__||Pu(o)})}catch(o){t.some(function(n){n.__h&&(n.__h=[])}),t=[],Xe.__e(o,r.__v)}}),qg&&qg(e,t)},Xe.unmount=function(e){Gg&&Gg(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.some(function(o){try{Ia(o)}catch(n){t=n}}),r.__H=void 0,t&&Xe.__e(t,r.__v))};var Vg=typeof requestAnimationFrame=="function";function GP(e){var t,r=function(){clearTimeout(o),Vg&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(r,35);Vg&&(t=requestAnimationFrame(r))}function Ia(e){var t=Me,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),Me=t}function Pu(e){var t=Me;e.__c=e.__(),Me=t}function Ou(e,t){return!e||e.length!==t.length||t.some(function(r,o){return r!==e[o]})}function Yg(e,t){return typeof t=="function"?t(e):t}function Je(e){return typeof e=="number"}var zP=(e,t,r)=>{let o=t.name||"anonymous predicate",n=typeof e,s=JSON.stringify(e,null,2);returnExpected ${r??"a value"} that satisfies the predicate ${o}, got ${n}: ${s}},VP=zP,Su=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name=this.constructor.name}};function Xg(e,t,r={}){if(!t(e))throw new Su(r.message??VP(e,t,r.name))}function Lu(e,t,r={}){return Xg(e,t,r),e}function Kt(e){return typeof e>"u"}var Fa=!1,Jg=null,Qg=()=>{scrapbox.addListener("lines:changed",()=>Fa=!1),scrapbox.addListener("layout:changed",()=>Fa=!1),Qg=void 0},Zg=()=>(Qg?.(),Fa||(Jg=scrapbox.Page.lines,Fa=!0),Jg);var ey=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var ty=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var ry=()=>Da(document.getElementById("editor"),"div#editor"),Xs=()=>Da(document.getElementsByClassName("lines").item(0),"div.lines");var dt=()=>{let e=document.getElementById("text-input");if(e)return ty(e,"textarea#text-input"),e};var oy=()=>Da(document.getElementsByClassName("popup-menu")?.[0],"div.popup-menu");var ny=()=>Da(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),Da=(e,t)=>{if(e)return ey(e,t),e};var Dt=()=>{let e=Xs();if(!e)throw Error("div.lines is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.lines must has the property whose name starts with "__reactFiber"');return e[t].return.stateNode.props.lines};var or=e=>e.match(/^(\s*)/)?.[1]?.length??0,Vo=(e,t)=>{let r=or(sy(e,t)),o=0;for(;e+o+1<t.length&&or(sy(e+o+1,t))>r;)o++;return o},sy=(e,t)=>{let r=t[e];return Re(r)?r:r.text};var Nu=e=>{if(Kt(e))return;if(Je(e))return Ua(e)?.id;if(Re(e))return e.startsWith("L")?e.slice(1):e;if(e.classList.contains("line"))return e.id.slice(1);let t=e.closest(".line");if(t)return t.id.slice(1)},iy=e=>{if(Kt(e))return;if(Je(e))return e;let t=Nu(e);return t?Dt().findIndex(r=>r.id===t):-1};var Ua=e=>{if(Kt(e))return;if(Je(e))return Dt()[e];let t=Nu(e);return t?Dt().find(r=>r.id===t):void 0},eo=e=>{if(ay(e))return e;let t=Nu(e);if(Kt(t))return t;let r=document.getElementById(L${t});if(!Kt(r))return r},ay=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var To=()=>Lu(Zg(),Rr),kt=e=>{if(Kt(e))return;if(Je(e)||Re(e))return Ua(e)?.text;if(!(e instanceof HTMLElement))return;if(ay(e))return Ua(e)?.text;if(e.classList.contains("char-index"))return e.textContent??void 0;if(e.classList.contains("line")||e.getElementsByClassName("lines")?.[0])return Dt().map(({text:o})=>o).join(
);let t=[],r=Ua(e);if(!Kt(r)){for(let o of YP(e))t.push(XP(o));return r.text.slice(Math.min(...t),Math.max(...t)+1)}};var cy=()=>{let e=Xs()?.firstElementChild;if(!Kt(e))return e},ly=()=>{let e=Xs()?.lastElementChild;if(!Kt(e))return e};var Mu=e=>{let t=iy(e);if(!Kt(t))return Vo(t,To())};function*YP(e){let t=e.getElementsByClassName("char-index");for(let r=0;r<t.length;r++)yield t[0]}var Cu=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index"),XP=e=>{if(!Cu(e))throw Error("A char DOM is required.");let t=e.className.match(/c-(\d+)/)?.[1];if(Kt(t))throw Error('.char-index must have ".c-{\\d}"');return parseInt(t)},py=e=>{let t=e?.getElementsByClassName?.("c-0")?.[0];return Cu(t)?t:void 0};var Js=(e,t)=>{let r=eo(e)?.getElementsByClassName?.(c-${t})?.[0];return Cu(r)?r:void 0};var Tt=(e,t)=>{let{noModifiedKeys:r=!1,...o}=t??{},n={bubbles:!0,cancelable:!0,keyCode:JP[e],...r?{}:{...o}},s=dt();if(!s)throw Error("#text-input must exist.");s.dispatchEvent(new KeyboardEvent("keydown",n)),s.dispatchEvent(new KeyboardEvent("keyup",n))},JP={Backspace:8,Tab:9,Enter:13,Delete:46,Escape:27," ":32,PageUp:33,PageDown:34,End:35,Home:36,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,a:65,A:65,b:66,B:66,c:67,C:67,d:68,D:68,e:69,E:69,f:70,F:70,g:71,G:71,h:72,H:72,i:73,I:73,j:74,J:74,k:75,K:75,l:76,L:76,m:77,M:77,n:78,N:78,o:79,O:79,p:80,P:80,q:81,Q:81,r:82,R:82,s:83,S:83,t:84,T:84,u:85,U:85,v:86,V:86,w:87,W:87,x:88,X:88,y:89,Y:89,z:90,Z:90,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,F1:113,F2:114,F3:115,F4:116,F5:117,F6:118,F7:119,F8:120,F9:121,F10:122,F11:123,F12:124,":":186,"*":186,";":187,"+":187,"-":189,"=":189,".":190,">":190,"/":191,"?":191,"@":192,"":192,"":219,"{":219,"\\":220,"|":220,"":221,"}":221,"^":222,"~":222,_:226};var Iu=async(e,t)=>{let r={button:t.button??0,clientX:t.X,clientY:t.Y,bubbles:!0,cancelable:!0,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,view:window};e.dispatchEvent(new MouseEvent("mousedown",r)),e.dispatchEvent(new MouseEvent("mouseup",r)),e.dispatchEvent(new MouseEvent("click",r)),await Se(10)};var ht=()=>{let e=dt();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.cursor must has the property whose name starts with "__reactFiber"');return et.return.return.stateNode.props};var Au=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=globalThis.innerHeight};function Ut(e,t,r){if(r??=e>t?-1:1,!Number.isFinite(e))throw new RangeError(start must be finite, but got ${e}.);if(!Number.isFinite(r))throw new RangeError(step must be finite, but got ${r}.);if(r===0)throw new RangeError("step must not be 0.");if(!Number.isFinite(t))throw new RangeError(stop must be finite, but got ${t}.);if(r>0&&e>t)throw new RangeError("start must be less than stop for positive step.");if(r<0&&e<t)throw new RangeError("start must be greater than stop for negative step.");return function*(){if(r>=0)for(let o=e;o<=t;o+=r)yield o;else for(let o=e;o>=t;o+=r)yield o}()}var uy=()=>{Tt("Home"),Tt("Home")};var my=async()=>{let e=cy();if(!e)throw Error(".line:first-of-type can't be found.");Au(e)||e.scrollIntoView({block:"center"});let t=py(e);if(!t)throw Error(".line:first-of-type .c-0 can't be found.");let{left:r,top:o}=t.getBoundingClientRect();await Iu(e,{X:r,Y:o})},fy=async()=>{await hy(ly())},dy=async e=>{await hy(eo(e))},hy=async e=>{if(!e)throw Error("The target line DOM is failed to find.");Au(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:o}=e.getElementsByClassName("text")0.getBoundingClientRect();await Iu(e,{X:t+1,Y:r+o/2})};var gy=(e=1)=>{for(let t of Ut(1,e))Tt("z",{ctrlKey:!0})},yy=(e=1)=>{for(let t of Ut(1,e))Tt("z",{shiftKey:!0,ctrlKey:!0})};var xy=async(e,t,r)=>{await dy(e),uy();for(let o of Ut(e,t))Tt("ArrowDown",{shiftKey:!0});Tt("End",{shiftKey:!0}),await at(r)};var $a=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowRight",{ctrlKey:!0})},ja=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowLeft",{ctrlKey:!0})};var Ba=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowUp",{ctrlKey:!0})},Ha=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowDown",{ctrlKey:!0})},Wa=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowRight",{altKey:!0})},qa=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowLeft",{altKey:!0})};var Ga=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowUp",{altKey:!0})},za=(e=1)=>{for(let t of Ut(1,e))Tt("ArrowDown",{altKey:!0})},at=e=>{let t=dt();if(!t)throw Error("#text-input is not ditected.");t.focus(),t.value=e;let r=new InputEvent("input",{bubbles:!0});return t.dispatchEvent(r),scrapbox.Page.waitForSave()};var Fe=()=>{let e=ny();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let o=by(...r);o&&t.append(o)},dispose:()=>t.remove(),Symbol.dispose:()=>t.remove()}},by=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":returnZP();case"check-circle":returneO();case"exclamation-triangle":returntO();case"text":returnVa(o.text);case"group":{let n=by(...o.items);return n?n:[]}}});if(t.length===0)return;if(t.length===1)return t0;let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},Va=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},ZP=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Va(e)},eO=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Va(e)},tO=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Va(e)};var Wn=e=>{let t=JSON.parse(localStorage.getItem("pageTransitionContext")??""),r=e.type==="page"?e.from.project===e.to.project?e.from.title===e.to.title?{titleHint:e.to.title}:{linkFrom:e.from.title}:{linkFrom:/${e.from.project}/${e.from.title}}:{searchQuery:e.query};t[page_${ce(e.to.title)}]=r,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var rO=(e,t,r)=>{let o=new URL(/${e}/${se(t)},location.href);if(r?.body&&(o.search=?body=${encodeURIComponent(r.body)}),r?.id&&(o.hash=#${r.id}),r?.context&&Wn({...r?.context,to:{project:e,title:t}}),r?.newTab!==!1&&(r?.newTab===!0||e!==scrapbox.Project.name)){globalThis.open(o);return}if(r?.reload!==!1&&(r?.reload===!0||e!==scrapbox.Project.name)){globalThis.open(o,"_self");return}let n=document.createElement("a");n.href=o.toString(),document.body.append(n),n.click(),n.remove()},Fu=(e,t,r)=>rO(e,t,{newTab:!1,reload:!1,body:r});var _o=async(e,t)=>{let r=await globalThis.caches.keys();for(let o of r.sort().reverse()){let s=await(await caches.open(o)).match(e,t);if(s)return s}},Ka=async(e,t)=>{let r=t.clone();return await(await caches.open(oO(new Date))).put(e,r)},oO=e=>api-${e.getFullYear()}-${${e.getMonth()+1}.padStart(2,"0")}-${${e.getDate()}.padStart(2,"0")};var Wt=()=>{let e=dt();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(s=>s.startsWith("__reactFiber"));if(!t)throw Error('#text-input must has the property whose name starts with "__reactFiber"');let r=et.return.return.stateNode._stores,o=r.find(s=>s.constructor.name==="Cursor");if(!o)throw Error('#text-input must has a "Cursor" store.');let n=r.find(s=>s.constructor.name==="Selection");if(!n)throw Error('#text-input must has a "Selection" store.');return{cursor:o,selection:n}};var Po=()=>Wt().cursor;var Ya=()=>Wt().selection;var Qs=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),Ey=e=>{if(e===0)return;let t={};return e&1&&(t.capture=!0),e&2&&(t.once=!0),e&4&&(t.passive=!0),t};var Xa=new Map,Du=new Map,Uu=()=>{scrapbox.on("layout:changed",()=>{let e=dt();if(e)for(lett,rof Xa)for(leto,nof r)for(let s of n)e.addEventListener(t,o,Ey(s))}),Uu=void 0},wy=(e,t,r)=>{Uu?.();let o=Xa.get(e)??new Map,n=o.get(t)??new Set;if(n.has(Qs(r)))return;if(n.add(Qs(r)),o.set(t,n),Xa.set(e,o),typeof r=="object"&&r?.once){let i=Du.get(t)??new Map,a=Qs(r),c=function(u){return $u(e,t,r),i.delete(a),t.call(this,u)};i.set(a,c),Du.set(t,i);let l=dt();if(!l)return;l.addEventListener(e,c,r)}let s=dt();s&&s.addEventListener(e,t,r)},$u=(e,t,r)=>{Uu?.();let o=Xa.get(e);if(!o)return;let n=o.get(t);if(!n)return;let s=Qs(r);if(n.delete(s),typeof r=="object"&&r?.once){let a=Du.get(t);if(!a)return;let c=a.get(s);if(!c)return;let l=dt();if(!l)return;l.removeEventListener(e,c,r),a.delete(s);return}let i=dt();i&&i.removeEventListener(e,t,r)};var Ry={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\[","]":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},nO=new RegExp(${Object.values(Ry).join("")},"gu");function vy(e){return e.replaceAll(nO,t=>Ry[t]).replace(/^[0-9a-zA-Z]/,t=>\\x${t.codePointAt(0).toString(16)})}var sO=0,y5=Array.isArray;function d(e,t,r,o,n,s){t||(t={});var i,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?i=t[a]:c[a]=t[a];var l={type:e,props:c,key:r,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--sO,__i:-1,__u:0,__source:n,__self:s};if(typeof e=="function"&&(i=e.defaultProps))for(a in i)c[a]===void 0&&(c[a]=i[a]);return re.vnode&&re.vnode(l),l}var ky=({project:e,title:t,words:r,lines:o,query:n,close:s})=>{let i=D(c=>{Wn({type:"search",query:n,to:{project:e,title:t}}),!(c.metaKey||c.ctrlKey||c.altKey||c.shiftKey)&&s()},[e,t,n,s]),a=H(()=>{let c=new RegExp((${r.map(l=>vy(l)).join("|")}),"i");return o.flatMap(l=>{let u=l.split(c);return d("span",{children:u.map((p,f)=>f%2===0?p:d("strong",{children:p}))})})},[o,r]);return d("a",{href:/${e}/${se(t)},target:${e===scrapbox.Project.name?"":"_blank"},rel:${e===scrapbox.Project.name?"route":"noopener noreferrer"},onClick:i,children:[t,d("div",{className:"description",children:a})]})};var Ty=e=>{let[t,r]=Q(e),o=D(()=>r(!0),[]),n=D(()=>r(!1),[]),s=D(()=>r(i=>!i),[]);return[t,{open:o,close:n,toggle:s}]};var _y=(e,t)=>{let[r,o]=Q(),[n,s]=Q(!1),i=ft(Promise.resolve());return te(()=>{if(t===""){o(void 0);return}let a=!1;return i.current=(async()=>{if(await i.current,!a){s(!0);try{let c=await ug(t,e);if(a)return;o(K(c)?S(c):void 0)}finally{s(!1)}}})(),()=>a=!0},[t,e]),{loading:n,result:r}};var Py=()=>d("style",{children:.modal {
position:fixed;
inset:0;
z-index:1050;
background-color:#000c;
display: flex;
flex-direction: column;
align-items: center;
row-gap: 10px;
padding: 10px;
}
.closed {
display: none;
}
.modal > * {
color: var(--page-text-color, #4a4a4a);
background-color: var(--page-bg, #fefefe);
border: 2px solid var(--body-bg, #dcdde0);
border-radius: 4px;
padding: 5px;
width: calc(var(--item-width, 100%) - 10px);
}
@media (min-width: 768px) {
.modal {
padding: 30px;
}
}
.controller {
display: flex;
gap: 0.2em;
flex-direction: column;
}
input {
border-radius: 5px;
padding: 0 10px;
height: 32px;
border: transparent;
box-shadow: none;
color: var(--search-form-text-color, rgba(255, 255, 255, 0.35));
background-color: var(--search-form-bg, rgba(255, 255, 255, 0.15))
}
.result {
flex-direction: column;
width: 100%;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
font-weight: normal;
line-height: 28px;
text-align: left;
border: 1px solid rgba(0,0,0,0.15);
border-radius: 4px;
background-clip: padding-box;
white-space: nowrap;
overflow-x: hidden;
overflow-y: auto;
}
a {
display: block;
padding: 3px 20px;
clear: both;
align-items: center;
user-select: none;
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
color: inherit;
}
.description {
margin-top: 0.5em;
color: var(--incremental-fulltext-search-description-text-color, #c4c4c4);
font-size: 12px;
line-height: 14px;
max-height: 28px;
overflow: hidden;
text-overflow: ellipsis;
}
.description strong {
background-color: #ff0;
color: #666;
}
.spinner::before {
display: inline-block;
font-style: normal;
font-variant: normal;
text-rendering: auto;
line-height: 1;
content: "\f110";
font-family: "Font Awesome 5 Free";
font-weight: 900;
margin: 0;
padding: 0;
box-sizing: border-box;
animation: fa-spin 2s linear infinite;
}});var iO=()=>d("i",{className:"spinner"}),Oy=({exportOps:e})=>{let[t,r]=Q(""),o=scrapbox.Project.name,{loading:n,result:s}=_y(o,t),i=D(m=>{r(m.currentTarget.value)},[]),[a,{open:c,close:l,toggle:u}]=Ty(!1),p=ft({open:c,close:l,toggle:u});te(()=>{Object.assign(p.current,{open:c,close:l,toggle:u})},[]),te(()=>e(p.current),[e]);let f=D(m=>{m.target instanceof HTMLElement&&m.target.id==="background"&&l()},[]);return d(ee,{children:[d(Py,{}),d("div",{id:"background",className:modal${a?"":" closed"},onClick:f,children:[d("div",{className:"controller",children:[d("input",{type:"text",value:t,onInput:i}),d("div",{className:"info",children:[n&&d(iO,{}),${s?.pages?.length??0} pages]})]}),s?.pages&&s.pages.length>0&&d("ul",{className:"result",children:s.pages.map(m=>d("li",{children:d(ky,{...m,project:o,query:t,close:l})},m.title))})]})]})};var Sy=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>{vt(d(Oy,{exportOps:r}),t)})};var Ja=(e,t)=>Object.hasOwn(e,t),Ly={left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown",bs:"Backspace",menu:"ContextMenu",apps:"ContextMenu",del:"Delete",return:"Enter",cr:"Enter",esc:"Escape",pgup:"PageUp",pgdn:"PageDown",lt:"<",less:"<",lesser:"<",gt:">",greater:">"},Iy=e=>{let t=e.toLowerCase();return Ja(Ly,t)?Ly[t]:e},Ny={Backquote:["","~"],Digit1:"1","!",Digit2:"2","@",Digit3:"3","#",Digit4:"4","$",Digit5:"5","%",Digit6:"6","^",Digit7:"7","&",Digit8:"8","*",Digit9:"9","(",Digit0:"0",")",Minus:"-","_",Equal:"=","+",Backslash:"\\","|",BracketLeft:["","{",BracketRight:"","}"],Semicolon:";",":",Quote:"'",'"',Comma:",","<",Period:".",">",Slash:"/","?"},aO=(e,t)=>{if(e.startsWith("Key")){let r=e.slice(3);return t||(r=r.toLowerCase()),r}return Ja(Ny,e)?Nyet?1:0:e},My={"<":"lt",">":"gt"},cO=/^($|Unidentified$|Process$|Dead$|Alt|Control|Hyper|Meta|Shift|Super|OS)/,ju=e=>{let t=e.shiftKey,r=e.key||"Unidentified";if(r==="Unidentified"?r=aO(e.code||"",t):(r=Iy(r),r===" "&&(r="Space")),cO.test(r))return"";r.length===1?t=!1:r=r.toLowerCase();let o="";return e.altKey&&(o+="a-"),e.ctrlKey&&(o+="c-"),e.metaKey&&(o+="m-"),t&&(o+="s-"),Ja(My,r)&&(r=Myr),o||r.length>1?<${o}${r}>:r},Cy={a:"altKey",c:"ctrlKey",m:"metaKey",s:"shiftKey"},lO=e=>{if(e.length===1)return/\s/.test(e)?{ok:!1,value:{name:"InvalidKeyError",key:e,message:Invalid key: ${e}}}:{ok:!0,value:{key:e}};let t=e.match(/^<((?:a-z-)*)(a-z\d+|^<>\s)>$/i);if(!t)return{ok:!1,value:{name:"InvalidKeyError",key:e,message:Invalid key: ${e}}};let,r,o=t,n={key:Iy(o)};for(let s of r.split("-").slice(0,-1)){let i=s.toLowerCase();if(!Ja(Cy,i))return{ok:!1,value:{name:"UnknownModifierError",modifier:s,context:e,message:${e}: Unknown modifier: ${s}}};let a=Cyi;if(na!==void 0)return{ok:!1,value:{name:"DuplicateModifierError",modifier:s,context:e,message:${e}: Duplicate modifier: ${s}}};if(na=!0,n.key.length===1&&n.shiftKey)return{ok:!1,value:{name:"DisallowedModifierError",modifier:s,context:e,message:${e}: Unusable modifier with single-character keys: ${s}}}}return{ok:!0,value:n}},Ay=e=>{let t=lO(e);return t.ok?{ok:!0,value:ju(t.value)}:t},Fy=e=>e.match(/<^<>\s+>|\s\S|^$/g);var mr=!1;var Dy=e=>Object.fromEntries(...Object.entries(console).map((t,r)=>{if(typeof r!="function")returnt,r;switch(t){case"warn":case"error":return[t,(...o)=>r(%c${e},"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{mr!==!0&&(!mr||!mr.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{mr!==!0&&(!mr||!mr.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{mr!==!0&&(!mr||!mr.has(e))||r(${e} ${o})}];default:returnt,(...o)=>{if(!(mr!==!0&&(!mr||!mr.has(e))))return r(...o)}}}));var Ko=Dy("ScrapBindings:mod.ts"),Qa=class{constructor(t,r){this.target=t;this.onSequenceUpdate=r?.onSequenceUpdate,this.flushInterval=r?.flushInterval??1e3}bind(t,r){let o=new Map,n=[];for(lets,iof t instanceof Map?t.entries():typeof t=="string"?t,r:Object.entries(t)){let a=Uy(s);if(!a.ok){for(let l of a.value)Ko.error(${s}: ${l.message});o.set(s,a.value);continue}let c=a.value;this.bindings.set(c,i),c.startsWith(this.currentSequence)&&this.filtered.add(c),n.push(c)}return Ko.debug("Binded the following commands:",n),this.emitChange(),o}unbind(...t){for(let r of t){let o=Uy(r);if(!o.ok)continue;let n=o.value;this.bindings.delete(n),this.filtered.delete(n)}this.emitChange()}reset(){this.bindings.clear(),this.emitChange()}bindings=new Map;onSequenceUpdate;flushInterval;_sequence="";set currentSequence(t){let r=this._sequence!==t;this._sequence=t,r&&this.onSequenceUpdate?.(t)}get currentSequence(){return this._sequence}prevBestMatchCommand;filtered=new Set;timer;backToInitial=()=>{clearTimeout(this.timer),this.currentSequence="",this.prevBestMatchCommand=void 0,this.filtered=new Set(this.bindings.keys()),Ko.debug("reset the sequence")};handleKeydown=t=>{if(!t.isTrusted)return;let r=ju(t);if(!r)return;if(clearTimeout(this.timer),t.isComposing){this.backToInitial();return}this.currentSequence+=r,Ko.debug("sequence",this.currentSequence);let o;for(let s of this.filtered){if(s.startsWith(this.currentSequence)||this.filtered.delete(s),this.currentSequence!==s)continue;let i=this.bindings.get(s);if(!i){this.filtered.delete(s);continue}o=()=>{Ko.debug(run ${s});try{i(t)}catch(a){Ko.error(a)}finally{this.backToInitial()}}}let n=this.filtered.size;if(Ko.debug(${n} candidates: ${[...this.filtered.keys()].join(", ")}),n>0&&(this.prevBestMatchCommand=o),this.prevBestMatchCommand&&n<2){if(this.prevBestMatchCommand(),n===0){this.handleKeydown(t);return}return}if(n===0){this.backToInitial();return}t.preventDefault(),t.stopPropagation(),this.timer=setTimeout(this.prevBestMatchCommand??this.backToInitial,this.flushInterval)};emitChange=()=>{if(this.bindings.size===0){this.backToInitial(),this.target.removeEventListener("keydown",this.handleKeydown);return}this.target.addEventListener("keydown",this.handleKeydown)}},pO={name:"InvalidSequenceError",message:"cannot parse the sequence"},Uy=e=>{let t=Fy(e);if(!t)return{ok:!1,value:pO};let r="",o=[];for(let n of t){let s=Ay(n);if(!s.ok){o.push(s.value);continue}r+=s.value}return o.length>0?{ok:!1,value:o}:{ok:!0,value:r}};var $y=()=>{if(scrapbox.Layout!=="page")return{selectionRange:{start:{line:0,char:0},end:{line:0,char:0}},selectedText:""};let{selectionRange:e,selectedText:t,position:r}=ht();if(!t){let u=Mu(r.line)??0,p={start:{line:r.line,char:0},end:{line:r.line+u,char:kt(r.line+u)?.length??0}};return{selectionRange:p,selectedText:scrapbox.Page.lines.slice(p.start.line,p.end.line+1).map(f=>f.text).join(`
)}}let{start:o,end:n}=e,s=o.line>n.line,i=s?n.line:o.line,a=s?n.char:o.char,c=s?o.line:n.line,l=s?o.char:n.char;return{selectedText:t,selectionRange:{start:{line:i,char:a},end:{line:c,char:l}}}};var Bu=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=n.replaceAll("[","").replaceAll("]","").trim(),a=Math.min(...[n,...s].map(l=>or(l))),c=[from ${t},n.slice(a),...s.map(l=>l.slice(a))];return{text:${i},pages:[{project:r,title:i,lines:c,mode:o}]}};Bu.hookName="default-hook";var to=e=>{let{project:t=scrapbox.Project.name,mode:r="newtab"}=e??{},o=[...e?.hooks??[],Bu],{selectionRange:{start:n,end:s},selectedText:i}=$y();if(!i||scrapbox.Layout!=="page")return;let a=(()=>{for(let p of o){let f=p(i,{title:scrapbox.Page.title,projectFrom:scrapbox.Project.name,projectTo:t,lines:Dt().slice(n.line,s.line+1),mode:r});if(f)return[p.hookName,f]}})();if(!a)return;let[c,l]=a,u=async()=>{let p=l instanceof Promise?await l:l;if(p.pages.length===0&&p.text===i)return;let f,{render:m,dispose:h}=Fe();try{if(p.pages.length>0){let y=p.pages.length;m({type:"spinner"},{type:"text",text:Create new ${y} pages...});let x=await It(e?.socket);if(O(x))throw Z(x);f=S(x);let w=0;await Promise.all(p.pages.map(async R=>{let b=Array.isArray(R.lines)?E=>[...E.map(T=>T.text),...R.lines]:R.lines;await Le(R.project,R.title,b,{socket:f}),m({type:"spinner"},{type:"text",text:Create ${y-++w} pages...})}))}m({type:"spinner"},{type:"text",text:${p.pages.length>0?"Created. ":""}Removing cut text...});let g=p.text;if(i===g)return;await Le(scrapbox.Project.name,scrapbox.Page.title,y=>{let x=y.map(w=>w.text);return[...x.slice(0,n.line),...${xn.line.slice(0,n.char)}${g}${x.slice(s.line).join(`
).slice(s.char)}.split(`
)]}),m({type:"check-circle"},{type:"text",text:"Removed."});for(let y of p.pages)switch(y.mode){case"self":y.project===scrapbox.Project.name?Fu(y.project,y.title):globalThis.open(https://scrapbox.io/${y.project}/${se(y.title)},"_self");break;case"newtab":globalThis.open(https://scrapbox.io/${y.project}/${se(y.title)});break}}catch(g){m({type:"exclamation-triangle"},{type:"text",text:"Failed to create new pages (see console)."}),console.error(g)}finally{let g=Se(1e3);f&&await At(f),await g,h()}};return u.hookName=c,u};var uO=Math.pow(10,8)*24*60*60*1e3,K8=-uO;var mO=3600;var jy=mO*24,Y8=jy*7,fO=jy*365.2425,dO=fO/12,X8=dO*3,Hu=Symbol.for("constructDateFrom");function Mr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Hu in e?e[Hu](t):e instanceof Date?new e.constructor(t):new Date(t)}function De(e,t){return Mr(t||e,e)}function ro(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var Hy={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return ro(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):ro(r+1,2)},d(e,t){return ro(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return ro(e.getHours()%12||12,t.length)},H(e,t){return ro(e.getHours(),t.length)},m(e,t){return ro(e.getMinutes(),t.length)},s(e,t){return ro(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return ro(n,t.length)}};function Wy(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function qy(e){return!(!Wy(e)&&typeof e!="number"||isNaN(+De(e)))}var gO=/(\w)\1*|''|'(''|[^'])+('|$)|./g,yO=/^'([^]*?)'?$/,xO=/''/g,bO=/[a-zA-Z]/;function qt(e,t){let r=De(e);if(!qy(r))throw new RangeError("Invalid time value");let o=t.match(gO);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return EO(n);let i=Hy[s];if(i)return i(r,n);if(s.match(bO))throw new RangeError("Format string contains an unescaped latin alphabet character "+s+"");return n}).join(""):""}function EO(e){let t=e.match(yO);return t?t[1].replace(xO,"'"):e}function zy(e,t){return De(e,t?.in).getDate()}function Ky(e,t){return De(e,t?.in).getMonth()}function Yy(e,t){return De(e,t?.in).getFullYear()}var Xy=e=>{let t=new Map;for(let r of e){let o=${Yy(r)}-${Ky(r)}-${zy(r)},n=t.get(o);n&&n.getTime()>r.getTime()||t.set(o,r)}return[...t.values()]};var wO=Math.pow(10,8)*24*60*60*1e3,R7=-wO,Yo=6048e5,Wu=864e5,Cr=6e4,Oo=36e5,Za=1e3;var ec=3600;var qu=ec*24,RO=qu*7,Jy=qu*365.2425,Qy=Jy/12,vO=Qy*3,Gu=Symbol.for("constructDateFrom");function U(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Gu in e?e[Gu](t):e instanceof Date?new e.constructor(t):new Date(t)}function v(e,t){return U(t||e,e)}function ve(e,t,r){let o=v(e,r?.in);return isNaN(t)?U(r?.in||e,NaN):(t&&o.setDate(o.getDate()+t),o)}function Zs(e,t,r){let o=v(e,r?.in);if(isNaN(t))return U(r?.in||e,NaN);if(!t)return o;let n=o.getDate(),s=U(r?.in||e,o.getTime());s.setMonth(o.getMonth()+t+1,0);let i=s.getDate();return n>=i?s:(o.setFullYear(s.getFullYear(),s.getMonth(),n),o)}function zu(e,t,r){let{years:o=0,months:n=0,weeks:s=0,days:i=0,hours:a=0,minutes:c=0,seconds:l=0}=t,u=v(e,r?.in),p=n||o?Zs(u,n+o*12):u,f=i||s?ve(p,i+s*7):p,m=c+a*60,h=(l+m*60)*1e3;return U(r?.in||e,+f+h)}function Zy(e,t){let r=v(e,t?.in),o=r.getFullYear(),n=r.getMonth(),s=U(r,0);return s.setFullYear(o,n+1,0),s.setHours(0,0,0,0),s.getDate()}function Vu(e,t,r){let o=v(e,r?.in),n=o.getFullYear(),s=o.getDate(),i=U(r?.in||e,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);let a=Zy(i);return o.setMonth(t,Math.min(s,a)),o}function ex(e,t,r){let o=v(e,r?.in);return isNaN(+o)?U(r?.in||e,NaN):(t.year!=null&&o.setFullYear(t.year),t.month!=null&&(o=Vu(o,t.month)),t.date!=null&&o.setDate(t.date),t.hours!=null&&o.setHours(t.hours),t.minutes!=null&&o.setMinutes(t.minutes),t.seconds!=null&&o.setSeconds(t.seconds),t.milliseconds!=null&&o.setMilliseconds(t.milliseconds),o)}function ei(e,t,r){return U(r?.in||e,+v(e)+t)}function ti(e,t,r){return ei(e,t*1e3,r)}function tx(e,t){return v(e,t?.in).getMinutes()}function Ir(e,t,r){let o=v(e,r?.in);return o.setTime(o.getTime()+t*Cr),o}function Ar(e){return t=>{let r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function tc(e,t){return+v(e)-+v(t)}function So(e,t,r){let o=tc(e,t)/Cr;return Ar(r?.roundingMethod)(o)}function rx(e,t){return v(e,t?.in).getHours()}function Ku(e,t,r){return ei(e,t*Oo,r)}function Yu(e,t){return v(e,t?.in).getDate()}function Yt(e,t,r){return ve(e,-t,r)}function kr(e,t){let r=v(e,t?.in);return r.setHours(0,0,0,0),r}function rc(e,t){let r=v(e,t?.in);return r.setHours(23,59,59,999),r}function fe(e,...t){let r=U.bind(null,e||t.find(o=>typeof o=="object"));return t.map(r)}function gt(e,t,r){let[o,n]=fe(r?.in,e,t);return+kr(o)==+kr(n)}function Tr(e,t){let[r,o]=fe(e,t.start,t.end);return{start:r,end:o}}function ri(e,t){let{start:r,end:o}=Tr(t?.in,e),n=+r>+o,s=n?+r:+o,i=n?o:r;i.setHours(0,0,0,0);let a=t?.step??1;if(!a)return[];a<0&&(a=-a,n=!n);let c=[];for(;+i<=s;)c.push(U(r,i)),i.setDate(i.getDate()+a),i.setHours(0,0,0,0);return n?c.reverse():c}function fr(e){let t=v(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function oo(e,t,r){let[o,n]=fe(r?.in,e,t),s=kr(o),i=kr(n),a=+s-fr(s),c=+i-fr(i);return Math.round((a-c)/Wu)}var kO={};function yt(){return kO}function Ne(e,t){let r=yt(),o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=v(e,t?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function Xo(e,t){let r=v(e,t?.in),o=r.getFullYear(),n=yt(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=U(t?.in||e,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=Ne(i,t),c=U(t?.in||e,0);c.setFullYear(o,0,s),c.setHours(0,0,0,0);let l=Ne(c,t);return+r>=+a?o+1:+r>=+l?o:o-1}function Xu(e,t){let r=yt(),o=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=Xo(e,t),s=U(t?.in||e,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),Ne(s,t)}function Lo(e,t){let r=v(e,t?.in),o=+Ne(r,t)-+Xu(r,t);return Math.round(o/Yo)+1}function Jo(e,t,r){return ve(e,t*7,r)}function ox(e,t,r){return Jo(e,-t,r)}function oc(e,t,r){let o=v(e,r?.in),n=Lo(o,r)-t;return o.setDate(o.getDate()-n*7),v(o,r?.in)}function nx(e,t){let{start:r,end:o}=Tr(t?.in,e),n=+r>+o,s=n?Ne(o,t):Ne(r,t),i=n?Ne(r,t):Ne(o,t);s.setHours(15),i.setHours(15);let a=+i.getTime(),c=s,l=t?.step??1;if(!l)return[];l<0&&(l=-l,n=!n);let u=[];for(;+c<=a;)c.setHours(0),u.push(U(r,c)),c=Jo(c,l),c.setHours(15);return n?u.reverse():u}function nc(e,t,r){let[o,n]=fe(r?.in,e,t),s=o.getFullYear()-n.getFullYear(),i=o.getMonth()-n.getMonth();return s*12+i}function oi(e,t){return v(e,t?.in).getFullYear()}function Qo(e,t){let r=+v(e)-+v(t);return r<0?-1:r>0?1:r}function Zo(e,t){return+v(e)>+v(t)}function sx(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Xt(e){return!(!sx(e)&&typeof e!="number"||isNaN(+v(e)))}function Jt(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var Ju={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return Jt(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):Jt(r+1,2)},d(e,t){return Jt(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h(e,t){return Jt(e.getHours()%12||12,t.length)},H(e,t){return Jt(e.getHours(),t.length)},m(e,t){return Jt(e.getMinutes(),t.length)},s(e,t){return Jt(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return Jt(n,t.length)}};var TO=/(\w)\1*|''|'(''|[^'])+('|$)|./g,_O=/^'([^]*?)'?$/,PO=/''/g,OO=/[a-zA-Z]/;function ct(e,t){let r=v(e);if(!Xt(r))throw new RangeError("Invalid time value");let o=t.match(TO);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return SO(n);let i=Ju[s];if(i)return i(r,n);if(s.match(OO))throw new RangeError("Format string contains an unescaped latin alphabet character "+s+"");return n}).join(""):""}function SO(e){let t=e.match(_O);return t?t[1].replace(PO,"'"):e}var ix=e=>e==null,No=e=>typeof e=="string";async function*ax(e){let t=[],r,o=i=>{if(!r){t.push(i);return}r(i),r=void 0},n=()=>t.length>0?Promise.resolve(t.pop()):new Promise(i=>r=i),s=0;for(let i of e)i.then(a=>o({state:"fulfilled",value:a})).catch(a=>o({state:"rejected",reason:a})),s++;for(let i=0;i<s;i++)yield await n()}var _t=e=>{let t=e.match(/^(\d{4})-(\d{2})-(\d{2}) (?: {5}|(\d{2}):(\d{2})) (?: {4}|(\d{4})) (?: {8}|(\d{2}):(\d{2}):(\d{2})) (?: {8}|(\d{2}):(\d{2}):(\d{2}))([^\n]*)$/);if(!t)return;let[,r,o,n,s,i,a,c,l,u,p,f,m,h]=t,g={title:h,base:new Date(parseInt(r),parseInt(o)-1,parseInt(n)),plan:{},record:{}};if(s){let y=new Date(g.base);y.setHours(parseInt(s)),y.setMinutes(parseInt(i)),g.plan.start=y}if(a&&(g.plan.duration=parseInt(a)*60),c){let y=new Date(g.base);y.setHours(parseInt(c)),y.setMinutes(parseInt(l)),y.setSeconds(parseInt(u)),g.record.start=y}if(p){let y=new Date(g.base);y.setHours(parseInt(p)),y.setMinutes(parseInt(f)),y.setSeconds(parseInt(m)),g.record.start&&Zo(g.record.start,y)&&y.setDate(y.getDate()+1),g.record.end=y}return g};var qn=e=>e.record?.start??e.plan?.start??e.base,cx=e=>e.record?.end??(ix(e.plan?.duration)?e.base:ti(qn(e),e.plan.duration));var _e=({title:e,base:t,plan:r,record:o})=>["",ct(t,"yyyy-MM-dd")," ",r?.start?ct(r.start,"HH:mm"):" ".repeat(5)," ",r?.duration?${r.duration/60}.padStart(4,"0"):" ".repeat(4)," ",o?.start?ct(o?.start,"HH:mm:ss"):" ".repeat(8)," ",o?.end?ct(o?.end,"HH:mm:ss"):" ".repeat(8),"",e].join("");function*lx(e){for(let t of en(e))No(t)||(yield t)}function*en(e){for(let t=0;t<e.length;t++){let r=e[t],o=No(r)?r:r.text,n=Vo(t,e),s=_t(o);if(!s){yield o;continue}yield{...s,lines:e.slice(t+1,t+1+n).map(i=>No(i)?i:i.text)},t+=n}}var LO=5*60,Qu=async()=>{let e=ht().position.line,t=_t(kt(e)??""),r=t?.base??new Date,o={start:t?.plan?.start?ti(t.plan.start,LO+(t.plan.duration??0)):void 0,duration:t?.plan?.duration};scrapbox.Page.insertLine(_e({title:"",base:r,plan:o,record:{}}),e+1),await scrapbox.Page.waitForSave()};var sc=async()=>{let e=ht().position.line,t=_t(kt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;o||(scrapbox.Page.updateLine(_e({record:{start:r?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var Gn=async()=>{let e=ht().position.line,t=_t(kt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;r&&(scrapbox.Page.updateLine(_e({record:{start:r,end:o?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var Zu=async()=>{let e=ht().position.line,t=_t(kt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(r){if(o)return;await Gn();return}if(o)return;let s;for(let{text:a}of To().slice(0,(e??0)+1).reverse()){let{record:c}=_t(a)??{};if(c?.end){s=c.end;break}}let i=new Date;scrapbox.Page.updateLine(_e({record:{start:s??i,end:i},...n}),e),await scrapbox.Page.waitForSave()};var tn=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=ht();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var em=(e,t=7)=>new Date((e+2592e3*((t+1)**1.5-1)/5221.154823442138)*1e3);var tm=(e,t)=>{let r,o,n,s,i=null;if(i=e.match(/^(.*?)(s|e):([^\s]+)\s+d:(\d+)/))[,o,s,n,r]=i;else if(i=e.match(/^(.*?)d:(\d+)\s+(s|e):([^\s]+)/))[,o,r,s,n]=i;else if(i=e.match(/^(.*?)(s|e):([^\s]+)/))[,o,s,n]=i;else return(i=e.match(/^(.*?)d:(\d+)/))?([,o,r]=i,{name:o.trimEnd(),duration:parseInt(r)*60}):void 0;for(let{test:a,parse:c}of NO){let l=n.match(a);if(!l)continue;let u=c(l),p=u.isDuration?zu(t,u):ex(t,u);return s==="s"?{name:o.trimEnd(),start:p,...r!==void 0?{duration:parseInt(r)*60}:{}}:{name:o.trimEnd(),start:em(t.getTime()/1e3,(p.getTime()-t.getTime())/(24*60*60*1e3)),...r!==void 0?{duration:parseInt(r)*60}:{}}}},NO=[{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4])})},{test:/(\d{4})-(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2])})},{test:/(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2])})},{test:/T?(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/T?(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4])})},{test:/P(\d+)Y(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3])})},{test:/P(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/P(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3])})},{test:/P(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2])})},{test:/P(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/P(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2])})},{test:/P(\d+)D$/i,parse:e=>({isDuration:!0,days:parseInt(e[1])})},{test:/PT?(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/PT?(\d+)H$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1])})},{test:/PT?(\d+)M$/i,parse:e=>({isDuration:!0,minutes:parseInt(e[1])})},{test:/P(\d+)W$/i,parse:e=>({isDuration:!0,weeks:parseInt(e[1])})}];var ni=async()=>{let e=new Date,[t,r]=tn(),o=To().slice(t,r+1).map(s=>s.text),n=o.flatMap(s=>{let i=s.trimEnd();if(i==="")return s;let{name:a,start:c,duration:l}=tm(i,e)??{};return!a||!c&&!l?s:[_e({title:a.trim(),base:c??e,plan:{start:c,duration:l},record:{}})]});if(o.join(
)!==n.join(
)){for(let s=t;s<=r;s++)scrapbox.Page.updateLine(n[s-t],s);await scrapbox.Page.waitForSave()}};var ic=async(e,t,r)=>{let o=[];for(let n=e;n<=t;n++){let s=kt(n)??"",i=_t(s);if(!i){o.push(s);continue}o.push(_e(r(i,n)))}for(let n=e;n<=t;n++)scrapbox.Page.updateLine(o[n-e],n);await scrapbox.Page.waitForSave()};var rm=async(e=1)=>{let[t,r]=tn();await ic(t,r,o=>(o.base=ve(o.base,e),o))};var om=async()=>{let[e,t]=tn(),r=new Date;await ic(e,t,o=>(gt(o.base,r)||(o.base=r),o))};var MO="日刊記録sheet",CO=/日刊記録sheet (\d{4})-(\d{2})-(\d{2})/,si=["[** 00:00 - 03:00] 未明","[** 03:00 - 06:00] 明け方","[** 06:00 - 09:00] 朝","[** 09:00 - 12:00] 昼前","[** 12:00 - 15:00] 昼過ぎ","[** 15:00 - 18:00] 夕方","[** 18:00 - 21:00] 夜のはじめ頃","[** 21:00 - 00:00] 夜遅く"];var nm=e=>{let t=e.match(CO);if(!t)return;let[,r,o,n]=t,s=new Date(parseInt(r),parseInt(o)-1,parseInt(n));return Xt(s)?s:void 0},_r=e=>ct(e,'${MO}' yyyy-MM-dd),rn=e=>{let t=nm(e[0]);if(!t)return e;let r=IO(t),o=[],n=[];for(let a of en(e.slice(1))){if(typeof a=="string"){if(si.includes(a)||r!==""&&r===a)continue;n.push(a);continue}o.push(a)}let s=o.sort((a,c)=>Qo(qn(a),qn(c)));if(s.length===0)return[e[0],r,...si,...n];let i=[0,0,0,0,0,0,0,0];for(let a=1;a<si.length;a++){let c=Ku(new Date(t.getFullYear(),t.getMonth(),t.getDate()),3*a),l=s.findIndex(m=>Zo(qn(m),c));if(l<0){i[a]=-1;continue}if(l===0)continue;let u=s[l-1],p=qn(u),f=cx(u);i[a]=(f.getTime()-p.getTime())/2<c.getTime()-p.getTime()?l:l-1}return[e[0],r,...s.flatMap((a,c)=>[...i.flatMap((l,u)=>l===c?[si[u]]:[]),_e(a),...a.lines]),...i.flatMap((a,c)=>a===-1?[si[c]]:[]),...n]},IO=e=>yesterday: ${_r(Yt(e,1))};var sm=async(e,t)=>{let r=()=>{},o=setTimeout(()=>{let{render:n,dispose:s}=Fe();r=s,n({type:"spinner"},{type:"text",text:"formatting..."})},500);await Le(e,t,n=>rn(n.map(s=>s.text))),clearTimeout(o),r()};async function*im(e,t,r){let o=[...t],n=[];for(;o.length>0;){let s=o.shift();if(!s)break;let i=s.base,a=[s];for(let c=0;c<o.length;c++)gt(o[c].base,i)&&(a.push(...o.splice(c,1)),c--);n.push((async()=>(await Le(e,_r(i),c=>rn([...c.map(l=>l.text),...a.flatMap(l=>[_e(l),...l.lines??[]])]),r),{date:i,size:a.length}))())}yield*ax(n)}var ii=async({from:{project:e,title:t},to:r})=>{let o=await ur(e,t);if(O(o))throw Z(o);let n=nm(t),{lines:s}=S(o),i=[];for(let p of lx(s))n&&gt(p.base,n)||i.push(p);let{render:a,dispose:c}=Fe();a({type:"spinner"},{type:"text",text:copying ${i.length} tasks...});let l=await It();if(O(l))throw Z(l);let u=S(l);try{let p=0,f=!1;for await(let m of im(r,i,{socket:u})){if(m.state!=="fulfilled"){console.error(m.reason),f=!0;continue}p+=m.value.size,a({type:"spinner"},{type:"text",text:copying ${i.length-p} tasks...})}if(f){a({type:"exclamation-triangle"},{type:"text",text:"Some tasks failed to be written"});return}a({type:"spinner"},{type:"text",text:Copied. removing ${i.length} original tasks...}),await Le(e,t,m=>{let h=[];for(let g of en(m)){if(No(g)){h.push(g);continue}n&&gt(g.base,n)&&h.push(_e(g),...g.lines)}return h},{socket:u}),a({type:"check-circle"},{type:"text",text:"Moved"})}finally{await At(u),await Se(1e3),c()}};var Pr=e=>${e}.padStart(2,"0");var on=e=>"hours"in e,dr=(e,t)=>e.year!==t.year?e.year<t.year:e.month!==t.month?e.month<t.month:e.date!==t.date?e.date<t.date:"hours"in t?"hours"in e?e.hours*60+e.minutes<t.hours*60+t.minutes:0<t.hours*60+t.minutes:!1,Fr=e=>${${e.year}.padStart(4,"0")}-${Pr(e.month)}-${Pr(e.date)}${"hours"in e?T${Pr(e.hours)}:${Pr(e.minutes)}:""},he=e=>{let t=Fr(e);return new Date(t.includes("T")?t:${t}T00:00)},Gt=e=>({year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes()});var ux=e=>{switch(e.toLowerCase()){case"y":return"yearly";case"m":return"monthly";case"w":return"weekly";case"d":return"daily";default:return}};var mx=e=>{switch(e){case"+":return"todo";case"-":return"note";case"!":return"deadline";case".":return"done";case"~":return"up-down";default:return}},fx=e=>{switch(e){case"todo":return"+";case"note":return"-";case"deadline":return"!";case"done":return".";case"up-down":return"~"}};var Dr=e=>{let t=e.match(/(?:([\+\-!~.])(\d+)?)?@(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?(?:R([YMWD])?(\d+))?(?:@(?:(\d{2}):(\d{2})|(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?)?/i);if(!t)return;let[r,o,n,s,i,a,c,l,u,p,f,m,h,g,y,x,w,R,b,E,T,I,F,A,N,P,_,C,$,j,q,B,Y]=t,G=${e.slice(0,t.index).trim()}${e.slice((t.index??0)+r.length).trim()},X=dx(s,i,a,c,l);if(!Xt(he(X)))return M({name:"InvalidDateError",message:The reference point of the task "${Fr(X)}" is an invalid date.});let J=hx(X,f,m,h,u||g,p||y,x);if(J!==void 0){if(Je(J)&&isNaN(J)||!Je(J)&&!Xt(he(J)))return M({name:"InvalidDateError",message:The estimated end of the task${Je(J)?"": "${Fr(J)}"} is an invalid date.});if(Je(J)&&J<0||!Je(J)&&dr(J,X))return M({name:"TaskRangeError",message:The reference point of an task cannot be after its estimated end.
reference point:${Fr(X)}
estimated end:${Fr(Je(J)?Gt(Ir(he(X),J)):J)}})}let le=/^[\uFE00-\uFE0F]*[✅❌]/.test(e)?"done":mx(o),oe=le?{status:le,refDate:X}:void 0;oe&&n&&(oe.speed=parseInt(n));let Rt=dx(T||s,I||i,F||a,b||A||c,E||N||l);if(!Xt(he(Rt)))return M({name:"InvalidDateError",message:The start of the task/event "${Fr(Rt)}" is an invalid date.});let Oe=hx(Rt,C||f,$||m,j||h,P||q||u||g,_||B||p||y,Y||x),W=on(Rt)&&Je(Oe)?{start:Rt,duration:Oe}:void 0;if(W){let Ct={name:G,executed:W,generated:!1,raw:e};return oe&&(Ct.freshness=oe),(w||R)&&(Ct.recurrence={frequency:ux(w??"D")??"daily",count:R?parseInt(R):1}),L(Ct)}if(!oe)return M({name:"InvalidDateError",message:"Task requires freshness to be spec"});let be={name:G,freshness:oe,generated:!1,raw:e};return J&&(be.estimated=J),L(W?{...be,executed:W}:be)},Ur=e=>!("executed"in e),Mo=e=>"recurrence"in e,gx=e=>!("executed"in e||"freshness"in e&&on(e.freshness.refDate)&&e.estimated&&(Je(e.estimated)||on(e.estimated))),ci=e=>"executed"in e?e.executed.duration:Je(e.estimated)?e.estimated:void 0,$r=e=>Ur(e)?e.freshness.refDate:e.executed.start,yx=e=>{if(!Ur(e)){let r=he(e.executed.start);return Gt(Ir(r,e.executed.duration))}if(Je(e.estimated)&&on(e.freshness.refDate)){let r=he(e.freshness.refDate);return Gt(Ir(r,e.estimated))}let t=he(Je(e.estimated)?e.freshness.refDate:e.estimated??e.freshness.refDate);return t.setHours(0),t.setMinutes(0),Gt(ve(t,1))},jO=e=>{let t=e.freshness?${fx(e.freshness.status)}${e.freshness.speed??""}:"",r=${Fr($r(e))},o=ci(e);return${t}@${r}${o===void 0?"":D${o}}${e.name}},ac=(e,t)=>{let r=Gt(t),{recurrence:o,executed:n}=e;switch(o.frequency){case"yearly":{if(Math.abs(r.year-n.start.year)%(o.count??1)!==0||n.start.month!==r.month||n.start.date!==r.date)return;break}case"monthly":{if(nc(he(r),he(n.start))%(o.count??1)!==0)return;break}case"weekly":case"daily":{let a=o.frequency==="weekly"?7:1;if(oo(he(r),he(n.start))%((o.count??1)*a)!==0)return;break}}let s={...n.start};s.year=r.year,s.month=r.month,s.date=r.date;let i={name:e.name,executed:{start:s,duration:n.duration},generated:!0,raw:e.raw};return e.freshness&&(i.freshness=e.freshness),i},cc=e=>e.freshness?e.generated?jO(e):e.raw:e.generated?void 0:e.raw,dx=(e,t,r,o,n)=>{let s=parseInt(e),i=parseInt(t),a=parseInt(r),c=o?parseInt(o):void 0,l=n?parseInt(n):void 0;return c!==void 0&&l!==void 0?{year:s,month:i,date:a,hours:c,minutes:l}:{year:s,month:i,date:a}},hx=(e,t,r,o,n,s,i)=>{if(!t&&!r&&!o&&!n&&!s&&!i)return;if(i)return parseInt(i);let a=t?parseInt(t):e.year,c=r?parseInt(r):e.month,l=o?parseInt(o):e.date,u=n?parseInt(n):void 0,p=s?parseInt(s):void 0,f=u!==void 0&&p!==void 0?{year:a,month:c,date:l,hours:u,minutes:p}:{year:a,month:c,date:l};return!on(e)||!on(f)?f:Math.round((he(f).getTime()-he(e).getTime())/(60*1e3))};var li=(e,t)=>{if(!e.generated&&Mo(e)){let s=ac(e,t);return s?li(s,t):void 0}let r=he(Ur(e)?e.freshness.refDate:e.executed.start),o=ci(e),n=cc(e);return{title:n!==void 0?${n}:e.name,base:r,plan:{start:gx(e)?void 0:r,duration:o!==void 0?o*60:void 0},record:{}}};var am={あさごはん:"#log-breakfast",ひるごはん:"#log-lunch",よるごはん:"#log-dinner"},nn=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=_t(n);if(!i)return;if(s.length===0)return{text:e,pages:[]};let{title:a,base:c,record:l,...u}=i,p=BO(a,c,l),f=_e({title:${p},base:c,record:l,...u}),m=Math.min(...s.map(g=>or(g))),h=[.../[\[\]]/.test(a)&&a!==${p}?[a]:[],...t in am?[...s.map(g=>g.slice(m)),"",am[t],"#log-eatenfood"]:[...s.map(g=> ${g.slice(m)}),""]];return{text:f,pages:[{project:r,title:p,lines:xx(t,h,[l.start??c]),mode:o}]}};nn.hookName="task-hook";var BO=(e,t,r)=>{let o=qt(r.start??t,"yyyy-MM-dd");if(e in am)return${o} ${e};if(Dr(e.slice(1,-1)))return e.slice(1,-1);let n=e.replace(/[\[\]]/g,"").trim();return${n}${n.endsWith(o)?"": ${o}}},sn=(e,{title:t,projectTo:r,mode:o,lines:n})=>{let[s,...i]=e.split(
);if(i.length===0)return;let a=s.replace(/[\[\]]/g,"").trim(),c=Math.min(...i.map(p=>or(p))),l=r.startsWith("takker")?Xy([new Date,...n.map(({updated:p})=>new Date(p*1e3))]).sort((p,f)=>f.getTime()-p.getTime()):[],u=["",.../[\[\]]/.test(s)?[s.trimStart()]:[],...i.map(p=>p.slice(c))];return{text:${" ".repeat(or(s))}${a},pages:[{project:r,title:a,lines:xx(t,u,l),mode:o}]}};sn.hookName="new-page-hook";var an=(e,{projectTo:t,mode:r})=>{if(e.includes(
)||!/\[[^\]]+\]/.test(e))return;let[o,n]=e.match(/^(\s*)(.*)$/)?.slice?.(1)??["",e],s=[...n.matchAll(/\[([^\]])\]/g)].map(a=>ce(a[1])),i=n.replaceAll("[","").replaceAll("]","");return{text:${o}${i},pages:[{project:t,title:i,lines:(a,{links:c})=>{let l=c.map(u=>ce(u));if(!s.every(u=>l.includes(u)))return[...a.map(u=>u.text),n]},mode:r}]}};an.hookName="splitted-link-hook";var xx=(e,t,r)=>(o,{links:n})=>{let s=n.map(p=>ce(p)),i=s.includes(ce(e))?[]:[from ${e}],a=r.flatMap(p=>{let f=qt(p,"yyyy-MM-dd");if(s.includes(f))return[];let m=qt(p,"HH:mm:ss");return[#${f} ${m}]}),c=o.map(p=>p.text),l=c.findIndex(p=>/^#\d{4}-\d{2}-\d{2}/.test(p)),u=l<0?c.length:l;return[...c.slice(0,u),...i,...t,"",...a,...c.slice(u)]};var bx=e=>e.preventDefault(),Ex=e=>e.stopPropagation(),wx={"<A-a><A-t>":async e=>{bx(e),Ex(e);let[t,r]=HO(),o=To().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=Dr(i);if(!a||O(a))return s;let c=S(a);if(c.freshness?.status==="done")return s;let l=li(c,new Date);return l?(l.title=${i},_e(l)):s}).join(
);await xy(t,r,o),await ni()},"<A-a><A-m>":e=>{scrapbox.Layout==="page"&&(bx(e),Ex(e),ii({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"}))}},HO=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=ht();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var cn=e=>e.preventDefault(),ln=e=>e.stopPropagation(),cm={"<A-a><A-a>":e=>{cn(e),ln(e),Qu()},"<A-a><A-s>":e=>{cn(e),ln(e),sc()},"<A-a><A-e>":e=>{cn(e),ln(e),Gn()},"<A-a><A-0>":e=>{cn(e),ln(e),Zu()},"<A-a><A-1>":e=>{cn(e),ln(e),rm(1)},"<A-a><A-t>":e=>{cn(e),ln(e),om()},"<A-a><A-f>":e=>{scrapbox.Layout==="page"&&(cn(e),ln(e),sm(scrapbox.Project.name,scrapbox.Page.title))}};var xt=e=>e.preventDefault(),bt=e=>e.stopPropagation(),pn=(e,t)=>{let r=oy()?.getElementsByClassName?.("button");if(!r)return;let o=[...r].find(n=>t instanceof RegExp?t.test(n.textContent??""):n.textContent===t);o instanceof HTMLDivElement&&e.target===document.activeElement&&(xt(e),bt(e),o.click())},WO={"-":e=>pn(e,""),"]":e=>pn(e,""),c:e=>pn(e,"Copy plain"),$:e=>pn(e,""),"{":e=>pn(e,/{{c\d+}}/),"}":e=>pn(e,"reset cloze"),n:e=>pn(e,"make note")},qO={"<C-]>":e=>{let{position:{line:t,char:r}}=ht(),o=Js(t,r)?.closest("a.page-link")??eo(t)?.querySelector?.("a.page-link");o instanceof HTMLAnchorElement&&(xt(e),bt(e),o.click())},"<C-o>":e=>{xt(e),bt(e),history.back()}},GO={"<C-home>":e=>{xt(e),bt(e),my()},"<C-end>":e=>{xt(e),bt(e),fy()}},Rx=[nn,sn,an],zO={"<C-X>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(xt(e),bt(e),to({project:t,mode:"self",hooks:Rx})?.())},"<C-D>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(xt(e),bt(e),to({project:t,mode:"noopen",hooks:Rx})?.())},"<C-h>":e=>{xt(e),bt(e),ja()},"<C-j>":e=>{xt(e),bt(e),Ha()},"<C-k>":e=>{xt(e),bt(e),Ba()},"<C-l>":e=>{xt(e),bt(e),$a()},"<A-h>":e=>{xt(e),bt(e),qa()},"<A-j>":e=>{xt(e),bt(e),za()},"<A-k>":e=>{xt(e),bt(e),Ga()},"<A-l>":e=>{xt(e),bt(e),Wa()}};scrapbox.TimeStamp.removeAllFormats();var VO={"<A-t><A-t>":e=>{xt(e),bt(e),at(qt(new Date,"#yyyy-MM-dd HH:mm:ss "))},"<A-t><A-j>":e=>{xt(e),bt(e),at(qt(new Date,"yyyy-MM-dd HH:mm:ss "))},"<A-t><A-k>":e=>{xt(e),bt(e),at(qt(new Date,"HH:mm:ss "))},"<A-t><A-l>":e=>{xt(e),bt(e),at(qt(new Date,"yyyy-MM-dd"))}},vx={...WO,...qO,...GO,...zO,...VO,...wx};var{render:KO}=Fe(),lm,YO=e=>{lm!==void 0&&cancelAnimationFrame(lm),lm=requestAnimationFrame(()=>KO({type:"text",text:e}))},pm=new Qa({addEventListener:wy,removeEventListener:$u},{onSequenceUpdate:YO}),kx=pm.bind({...vx,...scrapbox.Project.name==="takker-memex"?cm:{}});kx.size>0&&alert([...kx.entries()].map(([e,t])=>${e}:
${t.map(r=>- ${r}).join(`
)}).join(`
));var XO=/https?:\/\/vimeo\.com\/([0-9]+)/i,Tx=e=>{let t=e.match(XO);if(t)return t[1]};var JO=/https?:\/\/open\.spotify\.com\/(track|artist|playlist|album|episode|show)\/([a-zA-Z\d_-]+)(?:\?[^\s]{0,100}|)/,_x=e=>{let t=e.match(JO);if(!t)return;let[,r,o]=t;return{videoId:o,pathType:r}};var QO=/https?:\/\/anchor\.fm\/[a-zA-Z\d_-]+\/episodes\/([a-zA-Z\d_-]+(?:\/[a-zA-Z\d_-]+)?)(?:\?[^\s]{0,100}|)/,Px=e=>{let t=e.match(QO);if(!t)return;let[,r]=t;return r};var Ox=e=>{let{type:t,pathType:r,content:o,href:n,...s}=e;if(o===""){let i=va(n);if(i)return{type:"youtube",href:n,...i,...s};let a=Tx(n);if(a)return{type:"vimeo",videoId:a,href:n,...s};let c=_x(n);if(c)return{type:"spotify",href:n,...c,...s};let l=Px(n);if(l)return{type:"anchor-fm",videoId:l,href:n,...s};if(eS(n))return{type:"video",href:n,...s}}return ZO(n)?{type:"audio",content:o,href:n,...s}:{type:"absoluteLink",content:o,href:n,...s}},ZO=e=>/\.(?:mp3|ogg|wav|aac)$/.test(e),eS=e=>/\.(?:mp4|webm)$/.test(e);var tS=Object.defineProperty,rS=(e,t)=>{for(var r in t)tS(e,r,{get:t[r],enumerable:!0})},oS={};rS(oS,{andThen:()=>Us,andThenAsync:()=>$s,flatten:()=>bp,fromPromiseSettledResult:()=>Ep,inspectBoth:()=>vp,inspectErr:()=>Rp,inspectOk:()=>wp,isErrAnd:()=>la,isErrAndWithEnsureType:()=>kp,isOkAnd:()=>pa,isOkAndWithEnsureType:()=>Tp,map:()=>Yr,mapAsync:()=>ae,mapErr:()=>_p,mapErrAsync:()=>Ae,mapOr:()=>Pp,mapOrAsync:()=>Op,mapOrElse:()=>js,mapOrElseAsync:()=>Sp,orElse:()=>Lp,orElseAsync:()=>ua,toNullableFromErr:()=>Mp,toNullableFromOk:()=>Np,toUndefinableFromErr:()=>Ip,toUndefinableFromOk:()=>Cp,transposeToNullable:()=>Ap,transposeToUndefinable:()=>Fp,tryCatchInto:()=>ga,tryCatchIntoAsync:()=>ya,tryCatchIntoWithEnsureError:()=>Dp,tryCatchIntoWithEnsureErrorAsync:()=>Up,unwrapOr:()=>Ho,unwrapOrElse:()=>$p,unwrapOrElseAsync:()=>jp,unwrapOrThrow:()=>Bp});var Sx=async()=>{let e=localStorage.getItem("projectsLastAccessed");if(!e)return[];try{let t=JSON.parse(e),r=Object.entries(t).sort(([,s],[,i])=>i-s).map(([s])=>s),o=await Ra([]);if(O(o))return r;let n=S(o).projects.map(s=>s.id);return r.filter(s=>!n.includes(s))}catch(t){if(!(t instanceof SyntaxError))throw t;return[]}};var nS;(e=>{})(nS||={});var lc="0.16.9",um,mm,Lx=e=>{let t=https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${e}/katex.min.js;if(mm)throw mm;if(!document.querySelector(scriptsrc="${t}")){let r=document.createElement("script");r.src=t,um=new Promise((o,n)=>{r.onload=()=>o(window.katex),r.onerror=s=>{mm=s,n(s)},document.head.append(r)})}return um||new Promise(r=>{let o=setInterval(()=>{window.katex&&(clearInterval(o),r(window.katex))},500)})};var pc=(e,t)=>{let[r,o]=Q("");return{ref:D(s=>{s&&Lx(lc).then(i=>{try{i.render(e,s,t),o("")}catch(a){if(a instanceof Error&&a.name==="ParseError")o(a.message.slice(19));else throw a}})},[e,...Object.values(t??{})]),error:r}};var Nx=e=>{let t=[],r=new Set,o=n=>{r.delete(n);let s=t.pop();if(!s)return;let i=s[0]().finally(()=>o(i)).then(a=>s[1](a)).catch(a=>s[2](a));r.add(i)};return n=>{if(r.size<e){let s=n().finally(()=>o(s));return r.add(s),s}return new Promise((s,i)=>{t.push([n,s,i])})}};var sS="0.6.5",Ix=ScrapBubble-${sS},Mx=await globalThis.caches.open(Ix);(async()=>{for(let e of await globalThis.caches.keys())e.startsWith("ScrapBubble-")&&e!==Ix&&(await globalThis.caches.delete(e),console.log(ScrapBubble deleted old cache :"${e}"))})();var Cx=Nx(3);async function*uc(e,t){let r=((t?.saveFailedResponse?Mx.match(e):void 0)??_o(e,t)).then(i=>["cache",i]);{let i=Se(1e3).then(()=>"timeout"),a=await Promise.race([r,i]);if(a!=="timeout"){a[1]&&(yield["cache",a[1]]);let c=await Cx(()=>fetch(e));!c.ok&&t?.saveFailedResponse&&await Mx.put(e,c.clone()),yield["network",c]}}let o=Cx(()=>fetch(e)).then(i=>["network",i]),[n,s]=await Promise.race([r,o]);if(n==="network"){yield[n,s];return}s&&(yield[n,s]),yield await o}var Ax=(e,t)=>new Date(e.headers.get("Date")??0).getTime()/1e3+t<new Date().getTime()/1e3;var mc=()=>{let e=new Map;return{dispatch:(t,r)=>{let o=e.get(t);if(o)for(let n of o)n(r)},on:(t,r)=>{let o=e.get(t)??new Set;o.add(r),e.set(t,o)},off:(t,r)=>{let o=e.get(t);o&&o.delete(r)}}};var nr=!1,Fx=e=>{nr=typeof e=="boolean"?e:new Set(e)},Co=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(%c${e},"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{nr!==!0&&(!nr||!nr.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{nr!==!0&&(!nr||!nr.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{nr!==!0&&(!nr||!nr.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(nr!==!0&&(!nr||!nr.has(e))))return r(...o)}]}}));var fm=mc(),fc=new Map,iS=Co("ScrapBubble:useProject.ts"),Dx=e=>{let[t,r]=Q();return te(()=>{fm.on(e,r);let o=fc.get(e);return o?r(o.loading?void 0:o.value):(fc.set(e,{loading:!0}),r(void 0),(async()=>{try{let n=qo.toRequest(e);for await(let[,s]of uc(n)){let i=await qo.fromResponse(s);fc.set(e,{loading:!1,value:i}),fm.dispatch(e,i);break}}catch(n){iS.error(n),fc.delete(e)}})()),()=>fm.off(e,r)},[e]),t};var aS=["default-light","default-dark","default-minimal"],cS=["paper-light","paper-dark-dark","paper-dark"],Ux=["blue","purple","green","orange","red"],lS=["hacker1","hacker2"],$x=["winter","spring","summer","automn"],jx=["tropical"],Bx=["kyoto","newyork","paris"],Hx=["mred","lgreen"],rue=["default-light","default-minimal","paper-light",...Ux,...$x,...jx,...Bx,...Hx];var pS=[...aS,...cS,...Ux,...lS,...$x,...jx,...Bx,...Hx];function Wx(e){return pS.includes(e)}var qx="default-light",un=e=>{let t=Dx(e);return H(()=>{if(!t||O(t))return qx;let r=S(t).theme;return Wx(r)?r:qx},[t])};var zn=(e,t)=>new Promise(r=>{let o=!1,n=()=>{o=!0,r(!1)};e.addEventListener("click",n),e.addEventListener("pointerleave",n),setTimeout(()=>{o||r(!0),e.removeEventListener("click",n),e.removeEventListener("pointerleave",n),r(!1)},t)});var Vn=e=>{let{top:t,right:r,left:o,bottom:n}=e.getBoundingClientRect(),s=document.body.getBoundingClientRect(),i=(o-s.left)/s.width>.5;return{top:Math.round(n-s.top),bottom:Math.round(globalThis.innerHeight-globalThis.scrollY-t),...i?{right:Math.round(s.right-r)}:{left:Math.round(o-s.left)},maxWidth:i?r-10:document.documentElement.clientWidth-o-10}};var Gx=({project:e,title:t,descriptions:r,thumbnail:o,linkTo:n,bubble:s,delay:i,prefetch:a})=>{let c=H(()=>o?[]:it(r.join(
),{hasTitle:!1}),[o,r]),l=un(e),u=D(async({currentTarget:f})=>{a(e,t),await zn(f,i)&&s({project:e,title:t,linkTo:n,type:"link",position:Vn(f)})},[e,t,i,n?.project,n?.titleLc]),p=H(()=>n?()=>{Wn({type:"page",from:{project:n.project??e,title:n.titleLc},to:{project:e,title:t}})}:()=>{},[e,t,n?.project,n?.titleLc]);return d("a",{className:"related-page-card page-link",type:"link","data-theme":l,href:/${e}/${se(t)},rel:e===scrapbox.Project.name?"route":"noopner noreferrer",target:e!==scrapbox.Project.name?"_blank":"",onPointerEnter:u,onClick:p,children:[d("div",{class:"hover"}),d("div",{class:"content",children:[d("div",{class:"header",children:d("div",{class:"title",children:t})}),o?d("div",{class:"thumbnail",children:d("img",{src:o})}):d("div",{class:"description",children:c.flatMap((f,m)=>f.type==="line"?[d("p",{children:f.nodes.map(h=>d(zx,{node:h,project:e}))},m)]:[])})]})]})},zx=({node:e,project:t})=>{switch(e.type){case"code":return d("code",{children:e.text});case"formula":return d(uS,{node:e});case"commandLine":return d("code",{children:[e.symbol," $",e.text]});case"helpfeel":return d("code",{children:["? ",e.text]});case"quote":case"strong":case"decoration":return d(ee,{children:e.nodes.map(r=>d(zx,{node:r,project:t}))});case"icon":case"strongIcon":return d(mS,{node:e,project:t});case"hashTag":return d(fS,{node:e});case"link":return d(dS,{node:e});case"plain":case"blank":return d(ee,{children:e.text});default:return}},uS=({node:{formula:e}})=>{let{ref:t,error:r}=pc(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},mS=({node:{pathType:e,path:t},project:r})=>{let[o,n]=e==="relative"?[r,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[r,t];return d("img",{class:"icon",src:/api/pages/${o}/${se(n)}/icon})},fS=({node:{href:e}})=>d("span",{class:"page-link",children:["#",e]}),dS=({node:{pathType:e,href:t,content:r}})=>e!=="absolute"?d("span",{class:"page-link",children:t}):d("span",{class:"link",children:r||t});var xe=(e,t)=>/${e.toLowerCase()}/${ce(t)},dc=e=>{let t=e.match("/([^/]+)/(.+)");if(!t)throw SyntaxError("${e}" cannnot match "/(^/+)/(.+)");return{project:t[1],titleLc:t[2]}};var Zx=Symbol.for("immer-nothing"),Vx=Symbol.for("immer-draftable"),ge=Symbol.for("immer-state");function hr(e,...t){throw new Error(Immer minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf)}var pi=Object.getPrototypeOf;function Kn(e){return!!e&&!!e[ge]}function so(e){return e?eb(e)||Array.isArray(e)||!!e[Vx]||!!e.constructor?.[Vx]||hi(e)||Ec(e):!1}var hS=Object.prototype.constructor.toString(),Kx=new WeakMap;function eb(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if(typeof r!="function")return!1;let o=Kx.get(r);return o===void 0&&(o=Function.toString.call(r),Kx.set(r,o)),o===hS}function ui(e,t,r=!0){bc(e)===0?(r?Reflect.ownKeys(e):Object.keys(e)).forEach(o=>{t(o,e[o],e)}):e.forEach((o,n)=>t(n,o,e))}function bc(e){let t=e[ge];return t?t.type_:Array.isArray(e)?1:hi(e)?2:Ec(e)?3:0}function gm(e,t){return bc(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function tb(e,t,r){let o=bc(e);o===2?e.set(t,r):o===3?e.add(r):e[t]=r}function gS(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function hi(e){return e instanceof Map}function Ec(e){return e instanceof Set}function Pt(e){return e.copy_||e.base_}function ym(e,t){if(hi(e))return new Map(e);if(Ec(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=eb(e);if(t===!0||t==="class_only"&&!r){let o=Object.getOwnPropertyDescriptors(e);delete o[ge];let n=Reflect.ownKeys(o);for(let s=0;s<n.length;s++){let i=n[s],a=o[i];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(o[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(pi(e),o)}else{let o=pi(e);if(o!==null&&r)return{...e};let n=Object.create(o);return Object.assign(n,e)}}function wm(e,t=!1){return wc(e)||Kn(e)||!so(e)||(bc(e)>1&&Object.defineProperties(e,{set:hc,add:hc,clear:hc,delete:hc}),Object.freeze(e),t&&Object.values(e).forEach(r=>wm(r,!0))),e}function yS(){hr(2)}var hc={value:yS};function wc(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var xm={};function mn(e){let t=xm[e];return t||hr(0,e),t}function xS(e,t){xm[e]||(xm[e]=t)}var mi;function gc(){return mi}function bS(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Yx(e,t){t&&(mn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function bm(e){Em(e),e.drafts_.forEach(ES),e.drafts_=null}function Em(e){e===mi&&(mi=e.parent_)}function Xx(e){return mi=bS(mi,e)}function ES(e){let t=e[ge];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Jx(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ge].modified_&&(bm(t),hr(4)),so(e)&&(e=yc(t,e),t.parent_||xc(t,e)),t.patches_&&mn("Patches").generateReplacementPatches_(r[ge].base_,e,t.patches_,t.inversePatches_)):e=yc(t,r,[]),bm(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Zx?e:void 0}function yc(e,t,r){if(wc(t))return t;let o=e.immer_.shouldUseStrictIteration(),n=t[ge];if(!n)return ui(t,(s,i)=>Qx(e,n,t,s,i,r),o),t;if(n.scope_!==e)return t;if(!n.modified_)return xc(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let s=n.copy_,i=s,a=!1;n.type_===3&&(i=new Set(s),s.clear(),a=!0),ui(i,(c,l)=>Qx(e,n,s,c,l,r,a),o),xc(e,s,!1),r&&e.patches_&&mn("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function Qx(e,t,r,o,n,s,i){if(n==null||typeof n!="object"&&!i)return;let a=wc(n);if(!(a&&!i)){if(Kn(n)){let c=s&&t&&t.type_!==3&&!gm(t.assigned_,o)?s.concat(o):void 0,l=yc(e,n,c);if(tb(r,o,l),Kn(l))e.canAutoFreeze_=!1;else return}else i&&r.add(n);if(so(n)&&!a){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[o]===n&&a)return;yc(e,n),(!t||!t.scope_.parent_)&&typeof o!="symbol"&&(hi(r)?r.has(o):Object.prototype.propertyIsEnumerable.call(r,o))&&xc(e,n)}}}function xc(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&wm(t,r)}function wS(e,t){let r=Array.isArray(e),o={type_:r?1:0,scope_:t?t.scope_:gc(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=o,s=Rm;r&&(n=[o],s=fi);let{revoke:i,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=i,a}var Rm={get(e,t){if(t===ge)return e;let r=Pt(e);if(!gm(r,t))return RS(e,r,t);let o=r[t];return e.finalized_||!so(o)?o:o===dm(e.base_,t)?(hm(e),e.copy_[t]=di(o,e)):o},has(e,t){return t in Pt(e)},ownKeys(e){return Reflect.ownKeys(Pt(e))},set(e,t,r){let o=rb(Pt(e),t);if(o?.set)return o.set.call(e.draft_,r),!0;if(!e.modified_){let n=dm(Pt(e),t),s=n?.[ge];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(gS(r,n)&&(r!==void 0||gm(e.base_,t)))return!0;hm(e),no(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return dm(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,hm(e),no(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Pt(e),o=Reflect.getOwnPropertyDescriptor(r,t);return o&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:o.enumerable,value:r[t]}},defineProperty(){hr(11)},getPrototypeOf(e){return pi(e.base_)},setPrototypeOf(){hr(12)}},fi={};ui(Rm,(e,t)=>{fi[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});fi.deleteProperty=function(e,t){return fi.set.call(this,e,t,void 0)};fi.set=function(e,t,r){return Rm.set.call(this,e[0],t,r,e[0])};function dm(e,t){let r=e[ge];return(r?Pt(r):e)[t]}function RS(e,t,r){let o=rb(t,r);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}function rb(e,t){if(!(t in e))return;let r=pi(e);for(;r;){let o=Object.getOwnPropertyDescriptor(r,t);if(o)return o;r=pi(r)}}function no(e){e.modified_||(e.modified_=!0,e.parent_&&no(e.parent_))}function hm(e){e.copy_||(e.copy_=ym(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var vS=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,r,o)=>{if(typeof t=="function"&&typeof r!="function"){let s=r;r=t;let i=this;return function(a=s,...c){return i.produce(a,l=>r.call(this,l,...c))}}typeof r!="function"&&hr(6),o!==void 0&&typeof o!="function"&&hr(7);let n;if(so(t)){let s=Xx(this),i=di(t,void 0),a=!0;try{n=r(i),a=!1}finally{a?bm(s):Em(s)}return Yx(s,o),Jx(n,s)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===Zx&&(n=void 0),this.autoFreeze_&&wm(n,!0),o){let s=[],i=[];mn("Patches").generateReplacementPatches_(t,n,s,i),o(s,i)}return n}else hr(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...i)=>this.produceWithPatches(s,a=>t(a,...i));let o,n;return[this.produce(t,r,(s,i)=>{o=s,n=i}),o,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof e?.useStrictIteration=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){so(e)||hr(8),Kn(e)&&(e=kS(e));let t=Xx(this),r=di(e,void 0);return r[ge].isManual_=!0,Em(t),r}finishDraft(e,t){let r=e&&e[ge];(!r||!r.isManual_)&&hr(9);let{scope_:o}=r;return Yx(o,t),Jx(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let o=mn("Patches").applyPatches_;return Kn(e)?o(e,t):this.produce(e,n=>o(n,t))}};function di(e,t){let r=hi(e)?mn("MapSet").proxyMap_(e,t):Ec(e)?mn("MapSet").proxySet_(e,t):wS(e,t);return(t?t.scope_:gc()).drafts_.push(r),r}function kS(e){return Kn(e)||hr(10,e),ob(e)}function ob(e){if(!so(e)||wc(e))return e;let t=e[ge],r,o=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=ym(e,t.scope_.immer_.useStrictShallowCopy_),o=t.scope_.immer_.shouldUseStrictIteration()}else r=ym(e,!0);return ui(r,(n,s)=>{tb(r,n,ob(s))},o),t&&(t.finalized_=!1),r}function nb(){class e extends Map{constructor(c,l){super(),this[ge]={type_:2,parent_:l,scope_:l?l.scope_:gc(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return Pt(this[ge]).size}has(c){return Pt(this[ge]).has(c)}set(c,l){let u=this[ge];return i(u),(!Pt(u).has(c)||Pt(u).get(c)!==l)&&(r(u),no(u),u.assigned_.set(c,!0),u.copy_.set(c,l),u.assigned_.set(c,!0)),this}delete(c){if(!this.has(c))return!1;let l=this[ge];return i(l),r(l),no(l),l.base_.has(c)?l.assigned_.set(c,!1):l.assigned_.delete(c),l.copy_.delete(c),!0}clear(){let c=this[ge];i(c),Pt(c).size&&(r(c),no(c),c.assigned_=new Map,ui(c.base_,l=>{c.assigned_.set(l,!1)}),c.copy_.clear())}forEach(c,l){let u=this[ge];Pt(u).forEach((p,f,m)=>{c.call(l,this.get(f),f,this)})}get(c){let l=this[ge];i(l);let u=Pt(l).get(c);if(l.finalized_||!so(u)||u!==l.base_.get(c))return u;let p=di(u,l);return r(l),l.copy_.set(c,p),p}keys(){return Pt(this[ge]).keys()}values(){let c=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let l=c.next();return l.done?l:{done:!1,value:this.get(l.value)}}}}entries(){let c=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let l=c.next();if(l.done)return l;let u=this.get(l.value);return{done:!1,value:[l.value,u]}}}}[Symbol.iterator](){return this.entries()}}function t(a,c){return new e(a,c)}function r(a){a.copy_||(a.assigned_=new Map,a.copy_=new Map(a.base_))}class o extends Set{constructor(c,l){super(),this[ge]={type_:3,parent_:l,scope_:l?l.scope_:gc(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return Pt(this[ge]).size}has(c){let l=this[ge];return i(l),l.copy_?!!(l.copy_.has(c)||l.drafts_.has(c)&&l.copy_.has(l.drafts_.get(c))):l.base_.has(c)}add(c){let l=this[ge];return i(l),this.has(c)||(s(l),no(l),l.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let l=this[ge];return i(l),s(l),no(l),l.copy_.delete(c)||(l.drafts_.has(c)?l.copy_.delete(l.drafts_.get(c)):!1)}clear(){let c=this[ge];i(c),Pt(c).size&&(s(c),no(c),c.copy_.clear())}values(){let c=this[ge];return i(c),s(c),c.copy_.values()}entries(){let c=this[ge];return i(c),s(c),c.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(c,l){let u=this.values(),p=u.next();for(;!p.done;)c.call(l,p.value,p.value,this),p=u.next()}}function n(a,c){return new o(a,c)}function s(a){a.copy_||(a.copy_=new Set,a.base_.forEach(c=>{if(so(c)){let l=di(c,a);a.drafts_.set(c,l),a.copy_.add(l)}else a.copy_.add(c)}))}function i(a){a.revoked_&&hr(3,JSON.stringify(Pt(a)))}xS("MapSet",{proxyMap_:t,proxySet_:n})}var zt=new vS,Rc=zt.produce,vue=zt.produceWithPatches.bind(zt),kue=zt.setAutoFreeze.bind(zt),Tue=zt.setUseStrictShallowCopy.bind(zt),_ue=zt.setUseStrictIteration.bind(zt),Pue=zt.applyPatches.bind(zt),Oue=zt.createDraft.bind(zt),Sue=zt.finishDraft.bind(zt);nb();var sb=e=>{let t=0;for(let r of e)if(r&&(r.exists||(t+=(r.linked?.length??0)+(r.projectLinked?.length??0),t>1)))return!1;return t<2},ib=(e,t)=>Rc(e,r=>{if(!r)return t;if(r.updated<t.updated){let{lines:o,linked:n,projectLinked:s,...i}=t;Object.assign(r,i),vm(t)||(r.lines=o),n&&(r.linked??=n),s&&(r.projectLinked??=s);return}vm(r)&&!vm(t)&&(r.lines=t.lines),t.linked&&(t.isLinkedCorrect||!r.isLinkedCorrect&&(r.linked?.length??0)<=t.linked.length)&&(r.linked=t.linked),t.projectLinked&&(r.projectLinked=t.projectLinked)}),vm=e=>e.lines[0].id==="dummy";var ab=(e,t)=>{let r=new Map,o=ce(t.title);for(let c of t.links){let l=km(e,c);l.linked=[o],r.set(xe(e,c),l)}let n=xe(e,o),s=t.projectLinks.map(c=>{let l=dc(c);return xe(l.project,l.titleLc)}),i={...vc(e,t),linked:[],projectLinked:[]};r.set(n,i);let a=t.links.map(c=>ce(c));for(let c of t.relatedPages.links1hop){c.linksLc.includes(o)&&i.linked.push(c.titleLc);for(let f of c.linksLc.filter(m=>a.includes(m))){let m=xe(e,f),h=r.get(m)??km(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=xe(e,c.titleLc),u=vc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}for(let c of t.relatedPages.projectLinks1hop){let l=xe(c.projectName,c.titleLc);s.includes(l)||i.projectLinked.push(l);let u=vc(c.projectName,c),p=r.get(l)?.projectLinked;p&&(u.projectLinked=p),r.set(l,u)}i.isLinkedCorrect=!0;for(let c of t.relatedPages.links2hop){for(let f of c.linksLc){let m=xe(e,f),h=r.get(m)??km(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=xe(e,c.titleLc),u=vc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}return r},vc=(e,t)=>({project:e,titleLc:"titleLc"in t?t.titleLc:ce(t.title),exists:"persistent"in t?t.persistent:!0,descriptions:"descriptions"in t?t.descriptions??[]:[],image:t.image,lines:"lines"in t?t.lines:[t.title,...t.descriptions??[]].map(r=>({text:r,id:"dummy",userId:"dummy",updated:t.updated,created:t.updated})),updated:t.updated,isLinkedCorrect:!1}),km=(e,t)=>({project:e,titleLc:ce(t),exists:!1,descriptions:[],image:null,lines:[{text:t,id:"dummy",userId:"dummy",updated:0,created:0}],updated:0,isLinkedCorrect:!1});var kc=Co("ScrapBubble:bubble.ts"),Tm=new Map,Tc=new Set,_m=mc();function*lb(e){for(let t of e)yield Tm.get(t)}var pb=(e,t)=>_m.on(e,t),ub=(e,t)=>_m.off(e,t),mb=async(e,t,r,o)=>{let n=[];for(let s of[...t].reverse()){let i=xe(s,e);Tc.has(i)||n.push(TS(s,e,r,o))}await Promise.all(n)},cb=0,TS=async(e,t,r,o)=>{let n=xe(e,t);if(Tc.has(n))return;Tc.add(n);let s=cb++,i=${s} Check update ${n};kc.time(i);try{let a=ur.toRequest(e,t,{followRename:!0,projects:[...r]});for await(let[c,l]of uc(a,{ignoreSearch:!0,saveFailedResponse:!0})){kc.debug(${s}${c} ${n});let u=await ur.fromResponse(l);if(K(u)){let p=ab(e,S(u));for(let[f,m]of p){let h=Tm.get(f),g=ib(h,m);g&&h!==g&&(Tm.set(f,g),_m.dispatch(f,m))}}if(o?.ignoreFetch===!0||c==="cache"&&!Ax(l,o?.maxAge??60))break}}catch(a){kc.error(a)}finally{Tc.delete(n),kc.timeEnd(i),cb--}};var fb=Co("ScrapBubble:useBubbleData.ts"),Yn=e=>{let[t,r]=Q(Pm(e));return te(()=>{r(Pm(e));let o,n=()=>{clearTimeout(o),o=setTimeout(()=>{fb.debug(Update ${e.length} pages),r(Pm(e))},10)};return e.forEach(s=>pb(s,n)),()=>e.forEach(s=>ub(s,n))},e),t},Pm=e=>{let t=[...lb(e)].flatMap(r=>r?[r]:[]);return fb.debug(Required: ${e.length} pages, ${t.length} found,t),t};var db=({source:e,linked:t,externalLinked:r,projectsForSort:o,...n})=>{let s=H(()=>[...t.keys(),...r.keys()],[t,r]),i=Yn(s),a=H(()=>[...o],[o]),c=H(()=>{let u=(p,f)=>{let m=a.indexOf(p.project),h=a.indexOf(f.project);return m===h?f.updated-p.updated:m<0?1:h<0?-1:m-h};return[...i].sort(u)},[i,a]),l=H(()=>({bottom:${e.position.bottom}px,maxWidth:${e.position.maxWidth}px,..."left"in e.position?{left:${e.position.left}px}:{right:${e.position.right}px}}),[e.position]);return d("ul",{className:"card-bubble",style:l,onClick:n.onClick,children:c.map(({project:u,titleLc:p,lines:[{text:f}],descriptions:m,image:h})=>{let g=xe(u,p),y=t.get(g)??r.get(g);return d("li",{children:d(Gx,{project:u,title:f,linkTo:y,descriptions:m,thumbnail:h??"",...n})},g)})})};var Xn=e=>{e:if(e.pathType==="root"){let[,r="",o=""]=e.href.match(/\/([\w\-]+)(?:\/?|\/(.*))$/)??["","",""];if(r==="")break e;let[,n]=o?.match?.(/#([a-f\d]{24,32})$/)??["",""];return o===""?{project:r}:n===""?{project:r,title:o}:{project:r,title:o.slice(0,-1-n.length),hash:n}}let[,t]=e.href.match(/#([a-f\d]{24,32})$/)??["",""];return t===""?{title:e.href}:{title:e.href.slice(0,-1-t.length),hash:t}};var Om=(e,t)=>t.some(r=>{let o=!e.project;switch(r.type){case"hashTag":return o&&ce(r.href)===e.titleLc;case"link":{if(r.pathType=="absolute"||r.pathType==="relative"!==o)return!1;let{project:n,title:s=""}=Xn({pathType:r.pathType,href:r.href});return o?!n&&ce(s)===e.titleLc:n===e.project&&ce(s)===e.titleLc}case"quote":case"strong":case"decoration":return Om(e,r.nodes)}});var Io=Vs({title:"",project:"",whiteList:new Set,bubble:()=>{},hide:()=>{},delay:0,prefetch:()=>{}}),gb=({lines:e,project:t,title:r,whiteList:o,noIndent:n,hash:s,linkTo:i,...a})=>{let c=H(()=>e.flatMap(m=>typeof m=="string"?[]:[m.id]),[e]),l=H(()=>{let m=0;return it(e.map(h=>typeof h=="string"?h:h.text).join(
),{hasTitle:!0}).map(h=>{switch(h.type){case"title":case"line":return{...h,id:c[m++]};case"codeBlock":{let g=m;return m+=h.content.split(
).length+1,{...h,ids:c.slice(g,m)}}case"table":{let g=m;return m+=h.cells.length+1,{...h,ids:c.slice(g,m)}}}})},[e,c]),u=H(()=>{if(s&&c.includes(s))return s;if(i)return l.find(m=>m.type!=="line"?!1:Om(i,m.nodes))?.id},[l,c,s,i?.project,i?.titleLc]),p=ft(null);te(()=>{if(!u)return;let m=p.current?.querySelector(data-id="${u}"),h=globalThis.scrollY;m?.scrollIntoView?.({block:"center"}),globalThis.scroll(0,h)},[u]);let f=un(t);return d("div",{className:"lines","data-theme":f,ref:p,children:d(Io.Provider,{value:{project:t,title:r,whiteList:o,...a},children:l.map(m=>{switch(m.type){case"title":return d(ee,{children:[d(Qn,{index:m.id,indent:0,noIndent:n,permalink:m.id===u,children:d("a",{className:"page-link",type:"link",href:/${t}/${se(m.text)},rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",children:m.text})},m.id),d("hr",{})]});case"codeBlock":return d(_S,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"table":return d(PS,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"line":return d(Qn,{index:m.id,indent:m.indent,noIndent:n,permalink:m.id===u,children:m.nodes.length>0?m.nodes.map(h=>d(Jn,{node:h},h.raw)):d("br",{})},m.id)}})})})},Qn=({index:e,indent:t,noIndent:r,children:o,permalink:n})=>d("div",{className:line${n?" permalink":""},"data-id":e,"data-indent":t,style:{"margin-left":r?"":${1*t}em},children:o}),_S=({block:{fileName:e,content:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=Zr(Io),[a,c]=Q(""),l=D(async u=>{u.preventDefault(),u.stopPropagation();try{await navigator.clipboard.writeText(t),c("Copied"),await Se(1e3),c("")}catch(p){alert(Failed to copy the code block
Error: ${p})}},[t]);return d(ee,{children:[d(Qn,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"code-block",children:[d("span",{className:"code-block-start",children:d("a",{href:/api/code/${s}/${se(i)}/${e},target:"_blank",children:e})}),d("span",{className:"copy",title:"Copy",onClick:l,children:a})]})}),d(ee,{children:t.split(
).map((u,p)=>d(Qn,{index:o[p+1],indent:r,permalink:o[p+1]===n,children:d("code",{className:"code-block",children:u})}))})]})},PS=({block:{fileName:e,cells:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=Zr(Io);return d(ee,{children:[d(Qn,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"table-block",children:d("span",{className:"table-block-start",children:d("a",{href:/api/table/${s}/${se(i)}/${e}.csv,target:"_blank",children:e})})})}),d(ee,{children:t.map((a,c)=>d(Qn,{index:o[c+1],indent:r,permalink:o[c+1]===n,children:d("span",{className:"table-block table-block-row",children:a.map((l,u)=>d("span",{className:cell col-${u},children:l.map(p=>d(Jn,{node:p},p.raw))}))})}))})]})},Jn=({node:e})=>{switch(e.type){case"code":return d("code",{className:"code",children:e.text});case"formula":return d(OS,{node:e});case"commandLine":return d(LS,{node:e});case"helpfeel":return d("code",{className:"helpfeel",children:[d("span",{className:"prefix",children:"?"})," ",d("span",{className:"entry",children:e.text})]});case"quote":return d("blockquote",{className:"quote",children:e.nodes.map(t=>d(Jn,{node:t},t.raw))});case"strong":return d("strong",{children:e.nodes.map(t=>d(Jn,{node:t},t.raw))});case"decoration":return d(SS,{node:e});case"plain":case"blank":return d(ee,{children:e.text});case"hashTag":return d(CS,{node:e});case"link":return d(IS,{node:e});case"googleMap":return d(NS,{node:e});case"icon":return d(hb,{node:e});case"strongIcon":return d(hb,{node:e,strong:!0});case"image":return d(MS,{node:e});case"strongImage":return d("img",{className:"image strong-image",src:e.src});case"numberList":return d(ee,{children:[${e.number}. ,e.nodes.map(t=>d(Jn,{node:t},t.raw))]})}},OS=({node:{formula:e}})=>{let{ref:t,error:r}=pc(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},SS=({node:{decos:e,nodes:t}})=>d("span",{className:e.map(r=>deco-${r}).join(" "),children:t.map(r=>d(Jn,{node:r},r.raw))}),LS=({node:e})=>{let[t,r]=Q(""),o=D(async n=>{n.preventDefault(),n.stopPropagation();try{await navigator.clipboard.writeText(e.text),r("Copied"),await Se(1e3),r("")}catch(s){alert(Failed to copy the code block
Error: ${s})}},[e.text]);return d(ee,{children:[d("code",{className:"cli",children:[d("span",{className:"prefix",children:e.symbol})," ",d("span",{className:"command",children:e.text})]}),d("span",{className:"tool-buttons",children:d("span",{title:"Copy",className:"copy",onClick:o,children:t})})]})},NS=({node:{place:e,latitude:t,longitude:r,zoom:o}})=>d("span",{className:"pointing-device-map",children:d("a",{href:https://www.google.com/maps/search/${e}/@${t},${r},${o}z,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"google-map",src:/api/google-map/static-map?center=${t}%2C${r}&markers=${e}&zoom=${o}&_csrf=${globalThis._csrf}})})}),hb=({node:{pathType:e,path:t},strong:r})=>{let{project:o}=Zr(Io),[n,s]=e==="relative"?[o,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[o,t],i=se(s);return d("a",{href:/${n}/${i},rel:n===scrapbox.Project.name?"route":"noopener noreferrer",target:n===scrapbox.Project.name?"":"_blank",children:d("img",{className:r?"icon strong-icon":"icon",alt:s,src:/api/pages/${n}/${i}/icon})})},MS=({node:{link:e,src:t}})=>{let r=e||(/https:\/\/gyazo\.com\/[^\/]+\/thumb\/1000/.test(t)?t.slice(0,-11):t);return d("a",{className:e?"link":"",href:r,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"image",src:t})})},CS=({node:{href:e}})=>{let{project:t}=Zr(Io),r=yb(t,e),o=xb(t,e,"hashtag");return d("a",{href:/${t}/${se(e)},className:page-link${r?" empty-page-link":""},type:"hashTag",rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",onPointerEnter:o,children:["#",e]})},IS=({node:{pathType:e,...t}})=>{switch(e){case"relative":case"root":return d(AS,{pathType:e,href:t.href});case"absolute":{let r=Ox({pathType:e,...t});switch(r.type){case"youtube":return d(FS,{...r});case"vimeo":return d(DS,{...r});case"spotify":return d(US,{...r});case"anchor-fm":return d($S,{...r});case"audio":return d(jS,{...r});case"video":return d(HS,{...r});case"absoluteLink":return d("a",{className:"link",href:r.href,rel:"noopener noreferrer",target:"_blank",children:r.content||r.href})}}}},AS=({pathType:e,href:t})=>{let{project:r}=Zr(Io),{project:o=r,title:n,hash:s=""}=Xn({pathType:e,href:t}),i=xb(o,n,"link",s),a=yb(o,n??"");return d("a",{className:page-link${n!==void 0&&a?" empty-page-link":""},type:"link",href:/${o}${n===void 0?"":/${se(n)}${s===""?"":#${s}}},rel:o===scrapbox.Project.name?"route":"noopener noreferrer",target:o===scrapbox.Project.name?"":"_blank",onPointerEnter:i,children:t})},FS=e=>{e.params.append("autoplay","0");let t=e.pathType==="list"?https://www.youtube.com/embed/?${e.params.toString()}&list=${e.listId}:https://www.youtube.com/embed/${e.videoId}?${e.params.toString()};return d("div",{className:"iframe-video-player",children:d("iframe",{src:t,allowFullScreen:!0})})},DS=({videoId:e})=>d("div",{className:"iframe-video-player",children:d("iframe",{src:https://player.vimeo.com/video/${e},allowFullScreen:!0})}),US=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:spotify type-${e.pathType},src:https://open.spotify.com/embed/${e.pathType}/${e.videoId},allowFullScreen:!0})}),$S=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:"anchor-fm",src:e.href.replace("/episodes/","/embed/episodes/"),allowFullScreen:!0})}),jS=e=>e.content===""?d("audio",{className:"audio-player",preload:"none",controls:!0,src:e.href}):d(BS,{...e}),BS=({href:e,content:t})=>{let r=ft(null),o=D(()=>{r.current?.paused?(r.current.currentTime=0,r.current.play()):r.current?.pause?.()},[]);return d("span",{className:"audio-link",children:[d("a",{href:e,rel:"noopener noreferrer",target:"_blank",children:t}),d("span",{className:"play",onClick:o,children:"♬"}),d("audio",{preload:"none",src:e,ref:r})]})},HS=({href:e})=>d("div",{className:"video-player",children:d("video",{class:"video",style:{display:"inline-block"},controls:!0,loop:!0,src:e})}),yb=(e,t)=>{let{whiteList:r}=Zr(Io),o=H(()=>(r.has(e)?[...r]:[e,...r]).map(s=>xe(s,t)),[r,e]),n=Yn(o);return H(()=>sb(n),n)},xb=(e,t,r,o)=>{let{delay:n,bubble:s,prefetch:i}=Zr(Io);return D(async({currentTarget:a})=>{t&&(i(e,t),await zn(a,n)&&s({project:e,title:t,hash:o,type:r,position:Vn(a)}))},[e,t,o,r,n,i,s])};var bb=({pages:e,onClick:t,source:r,whiteList:o,...n})=>{let[s,i]=Q(xe(e[0].project,e[0].titleLc)),a=H(()=>({top:${r.position.top}px,maxWidth:${r.position.maxWidth}px,..."left"in r.position?{left:${r.position.left}px}:{right:${r.position.right}px}}),[r.position]);return d("div",{className:"text-bubble",style:a,onClick:t,children:[e.length>1&&d("div",{role:"tablist",children:e.map(c=>d(WS,{project:c.project,titleLc:c.titleLc,selected:s===xe(c.project,c.titleLc),tabSelector:i},xe(c.project,c.titleLc)))}),e.map(c=>d(qS,{selected:s===xe(c.project,c.titleLc),...c,title:c.lines[0].text,hash:r.hash,linkTo:r.linkTo,whiteList:o,...n},xe(c.project,c.titleLc)))]})},WS=({project:e,titleLc:t,tabSelector:r,selected:o})=>{let n=D(()=>r(xe(e,t)),[e,t]),s=un(e);return d("button",{type:"button",role:"tab","aria-selected":o,"data-theme":s,tabIndex:-1,onClick:n,children:e})},qS=({selected:e,...t})=>{let r=un(t.project);return d("div",{role:"tabpanel","data-theme":r,hidden:!e,children:d(gb,{...t})})};var Eb=Co("ScrapBubble:Bubble.tsx"),wb=({source:e,parentTitles:t,whiteList:r,...o})=>{let n=H(()=>r.has(e.project)?new Set([e.project,...r]):new Set([e.project]),[r,e.project]),[s,i,a]=zS(e,n,r,t);return d(ee,{children:[GS(a)&&d(bb,{pages:a,source:e,whiteList:r,onClick:o.hide,...o}),d(db,{linked:s,externalLinked:i,onClick:o.hide,source:e,projectsForSort:n,...o})]})},GS=e=>e.length>0,zS=(e,t,r,o)=>{let[[n,s,i],a]=Q([new Map,new Map,[]]),c=H(()=>{let p=[...t].map(f=>xe(f,e.title));return Eb.debug("projects",p),p},[t,e.title]),l=Yn(c),u=H(()=>o.map(p=>ce(p)),[o]);return Aa(()=>{let p=new Map,f=new Map,m=[];for(let h of l){let g={project:h.project,titleLc:h.titleLc};for(let x of h.projectLinked??[]){let{project:w,titleLc:R}=dc(x);u.includes(R)&&r.has(w)||f.has(x)||f.set(x,g)}if(!r.has(h.project))continue;let y={titleLc:h.titleLc};for(let x of h.linked??[]){if(u.includes(x))continue;let w=xe(h.project,x);p.has(w)||p.set(w,y)}u.includes(h.titleLc)||h.exists&&m.push(h)}a(Rc(h=>{Eb.debug(depth: ${u.length}, bubbled from ${xe(e.project,e.title)}, bubbles,,l,"before",h[0],"internal cards,",p,"external cards",f);for(let g of h[0].keys())p.has(g)||h[0].delete(g);for(let[g,y]of p)h[0].set(g,y);for(let g of h[1].keys())f.has(g)||h[1].delete(g);for(let[g,y]of f)h[1].set(g,y);h[2]=m}))},[l,r,u]),[n,s,i]};var Rb=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var vb=e=>{let t=H(()=>Rb(e.style,import.meta.url),[e.style]);return d(ee,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var kb=String.raw*{box-sizing:border-box}a{background-color:transparent;text-decoration:none;cursor:pointer}img{display:inline-block;max-width:100%;max-height:100px}code{font-family:var(--code-text-font, Menlo, Monaco, Consolas, "Courier New", monospace);font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}blockquote{background-color:var(--quote-bg-color, rgba(0,0,0,.05));display:block;border-left:solid 4px #a0a0a0;padding-left:4px;margin:0}strong{font-weight:700}iframe{display:inline-block;margin:3px 0;vertical-align:middle;max-width:100%;width:640px;height:360px;border:0}audio{display:inline-block;vertical-align:middle;white-space:initial;max-width:100%}.formula{margin:auto 6px}.formula.error code{color:#fd7373}.katex-display{display:inline-block!important;margin:0!important;text-align:inherit!important}.error .katex-display{display:none}.cli{border-radius:4px}.cli .prefix{color:#9c6248}.helpfeel{background-color:#fbebdd;border-radius:4px;padding:3px!important}.helpfeel .prefix{color:#f17c00}.helpfeel .entry{color:#cc5020}.code-block{display:block;line-height:1.7em;background-color:var(--code-bg, rgba(0,0,0,.04))}.code-block-start{font-family:Menlo,Monaco,Consolas,Courier New,monospace;color:#342d9c;background-color:#ffcfc6;font-size:.9em;padding:1px 2px}.code-block-start a{color:#342d9c;text-decoration:underline}code.code-block,.table-block.table-block-row{padding-left:1em}.copy{font-family:"Font Awesome 5 Free";cursor:pointer}.table-block{white-space:nowrap}.table-block-start{padding:1px 2px;font-size:.9em;background-color:#ffcfc6}.table-block-start a{color:#342d9c;text-decoration:underline}.cell{margin:0;padding:0 2px 0 8px;box-sizing:content-box;display:inline-block;white-space:pre}.cell:nth-child(odd){background-color:#0000000a}.cell:nth-child(2n){background-color:#0000000f}.strong-image{max-height:100%}.icon{height:11px;vertical-align:middle}.strong-icon{height:13.2px}.tool-button{margin-left:1em;cursor:pointer;font-size:.9em}.deco-\/{font-style:italic}.deco-\*-1{font-weight:700}.deco-\*-2{font-weight:700;font-size:1.2em}.deco-\*-3{font-weight:700;font-size:1.44em}.deco-\*-4{font-weight:700;font-size:1.73em}.deco-\*-5{font-weight:700;font-size:2.07em}.deco-\*-6{font-weight:700;font-size:2.49em}.deco-\*-7{font-weight:700;font-size:3em}.deco-\*-8{font-weight:700;font-size:3.58em}.deco-\*-9{font-weight:700;font-size:4.3em}.deco-\*-10{font-weight:700;font-size:5.16em}.deco--{text-decoration:line-through}.deco-_{text-decoration:underline}.page-link{color:var(--page-link-color, #5e8af7)}a.page-link:hover{color:var(--page-link-hover-color, #2d67f5)}.empty-page-link{color:var(--empty-page-link-color, #fd7373)}a.empty-page-link:hover{color:var(--empty-page-link-hover-color, #fd7373)}.link{color:var(--page-link-color, #5e8af7);text-decoration:underline}a.link:hover{color:var(--page-link-color-hover-color, #2d67f5)}.link img{padding-bottom:3px;border-style:none none solid;border-width:1.5px;border-color:#8fadf9}.permalink{background-color:var(--line-permalink-color, rgba(234,218,74,.75))}.status-bar{display:inline-block;position:absolute;background-color:var(--page-bg, #fefefe);cursor:default}.status-bar>*{border:1px solid var(--status-bar-border-color, #a9aaaf)}.status-bar.top-left{top:0;left:0}.status-bar.top-left>*{border-top:none;border-left:none}.status-bar.top-left :last-of-type{border-bottom-right-radius:3px}.status-bar.top-right{top:0;right:0}.status-bar.top-right>*{border-top:none;border-right:none}.status-bar.top-right :last-of-type{border-bottom-left-radius:3px}.status-bar.bottom-right{bottom:0;right:0}.status-bar.bottom-right>*{border-bottom:none;border-right:none}.status-bar.bottom-right :last-of-type{border-top-left-radius:3px}.status-bar.bottom-left{bottom:0;left:0}.status-bar.bottom-left>*{border-bottom:none;border-left:none}.status-bar.bottom-left :last-of-type{border-top-right-radius:3px}.text-bubble{font-size:11px;line-height:1.42857;user-select:text;position:absolute;color:var(--page-text-color, #4a4a4a);box-shadow:0 6px 12px #0000002d;display:flex;flex-direction:column;z-index:9000;&.no-scroll{overflow-y:hidden}data-theme=default-dark{--text-bubble-border-color: hsl(0, 0%, 39%)}data-theme=default-minimal{--text-bubble-border-color: hsl(0, 0%, 89%)}data-theme=paper-light{--text-bubble-border-color: hsl(53, 8%, 58%)}data-theme=paper-dark-dark{--text-bubble-border-color: hsl(203, 42%, 17%)}data-theme=blue{--text-bubble-border-color: hsl(227, 68%, 62%)}data-theme=purple{--text-bubble-border-color: hsl(267, 39%, 60%)}data-theme=green{--text-bubble-border-color: hsl(136, 29%, 50%)}data-theme=orange{--text-bubble-border-color: hsl(43, 71%, 51%)}data-theme=red{--text-bubble-border-color: hsl(4, 58%, 56%)}data-theme=spring{--text-bubble-border-color: hsl(72, 64%, 57%)}data-theme=kyoto{--text-bubble-border-color: hsl(331, 21%, 26%)}data-theme=newyork{--text-bubble-border-color: hsl(176, 29%, 67%)}role=tabpanel{padding:5px 0 5px 5px;border-radius:4px;background-color:var(--page-bg, #fefefe);max-height:80vh;overflow-y:auto}role=tabpanel,button{border:1px solid var(--text-bubble-border-color, hsl(221, 15%, 25%))}button{cursor:default;color:inherit;font-size:inherit;line-height:inherit;background-color:var(--page-bg, #fefefe);border-radius:4px 4px 0 0}buttonaria-selected=true{background-color:var(--text-bubble-border-color, hsl(221, 15%, 25%))}}.project-badge{text-decoration:none;color:var(--tool-text-color, #363c49)}.related-page-carddata-theme=default-dark{--card-title-bg: hsl(0, 0%, 39%)}.related-page-carddata-theme=default-minimal{--card-title-bg: hsl(0, 0%, 89%)}.related-page-carddata-theme=paper-light{--card-title-bg: hsl(53, 8%, 58%)}.related-page-carddata-theme=paper-dark-dark{--card-title-bg: hsl(203, 42%, 17%)}.related-page-carddata-theme=blue{--card-title-bg: hsl(227, 68%, 62%)}.related-page-carddata-theme=purple{--card-title-bg: hsl(267, 39%, 60%)}.text-bubbledata-theme=green{--card-title-bg: hsl(136, 29%, 50%)}.related-page-carddata-theme=orange{--card-title-bg: hsl(43, 71%, 51%)}.related-page-carddata-theme=red{--card-title-bg: hsl(4, 58%, 56%)}.related-page-carddata-theme=spring{--card-title-bg: hsl(72, 64%, 57%)}.related-page-carddata-theme=kyoto{--card-title-bg: hsl(331, 21%, 26%)}.related-page-carddata-theme=newyork{--card-title-bg: hsl(176, 29%, 67%)}.related-page-card{display:block;position:relative;height:inherit;width:inherit;overflow:hidden;text-overflow:ellipsis;font-family:Roboto,Helvetica,Arial,Hiragino Sans,sans-serif;background-color:var(--card-bg, #fff);color:var(--card-title-color, #555);word-break:break-word;text-decoration:none}.related-page-card:hover{box-shadow:var(--card-box-hover-shadow, 0 2px 0 rgba(0,0,0,.23))}.related-page-card:focus{outline:0;box-shadow:0 0 0 3px #66afe999;border-color:#66afe9;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.related-page-card.hover{opacity:0;position:absolute;width:100%;height:100%;top:0;left:0;background-color:var(--card-hover-bg, rgba(0,0,0,.05));mix-blend-mode:multiply;z-index:1;transition:background-color .1s}.related-page-card:hover .hover{opacity:1}.related-page-card:active .hover{opacity:1;background-color:var(--card-active-bg, rgba(0,0,0,.1))}.related-page-card .content{height:calc(100% - 5px);width:inherit;display:flex;flex-direction:column;overflow:hidden}.related-page-card .content .header{width:100%;color:#396bdd;text-overflow:ellipsis;border-top:var(--card-title-bg, #f2f2f3) solid 10px;padding:8px 10px}.related-page-card .content .header .title{font-size:11px;line-height:16px;font-weight:700;max-height:48px;color:var(--card-title-color, #363c49);margin:0;overflow:hidden;display:block;-webkit-line-clamp:3;-webkit-box-orient:vertical;text-overflow:ellipsis}.related-page-card .content .description{line-height:16px;padding:8px 10px 0;font-size:10px;white-space:pre-line;column-count:1;column-gap:2em;column-width:10em;height:inherit;color:var(--card-description-color, gray);flex-shrink:16;overflow:hidden}.related-page-card .content .thumbnail{display:block;width:100%;margin:0 auto;padding:0 5px}.related-page-card .content .description p{margin:0;display:block}.related-page-card .content .description code{font-family:Menlo,Monaco,Consolas,Courier New,monospace;font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}.related-page-card .content .description .icon{height:9px;vertical-align:middle}.related-page-card .content .description .page-link{background-color:transparent;text-decoration:none;cursor:pointer;color:var(--page-link-color, #5e8af7)}.card-bubble{background-color:var(--page-bg, #FFF);box-shadow:0 2px 2px #00000024,0 3px 1px -2px #0003,0 1px 5px #0000001f;position:absolute;max-width:80vw;box-sizing:content-box;z-index:9000;font-size:11px;line-height:1.42857;display:flex;padding:0;margin:0;list-style:none;overflow-x:auto;overflow-y:visible}.card-bubble li{display:block;position:relative;float:none;margin:5px;box-sizing:border-box;box-shadow:var(--card-box-shadow, 0 2px 0 rgba(0,0,0,.12));border-radius:2px;width:120px;height:120px}
;var Tb=e=>e instanceof HTMLSpanElement&&e.matches(".line-title .text"),_c=e=>e instanceof HTMLAnchorElement&&e.classList.contains("page-link");var _b=()=>{let[e,t]=Q([{bubble:o=>r(0,o),hide:()=>r(0)}]),r=D((o,n)=>{t(([s,...i])=>[s,...n?[...i.slice(0,o),n===i.at(o)?.source?i.at(o):{source:n,parentTitles:[scrapbox.Page.title??"",...i.slice(0,o).map(a=>a.source.title)],bubble:a=>r(o+1,a),hide:()=>r(o+1)}]:[...i.slice(0,o)]])},[]);return e};var Sm=(e,t,r,o,n)=>{te(()=>(e.addEventListener(t,r,o),()=>e.removeEventListener(t,r,o)),[e,t,o,...n??[]])};var Lm="scrap-bubble",Pb=({delay:e,whiteList:t,watchList:r,style:o})=>{let[{bubble:n,hide:s},...i]=_b(),a=D((c,l)=>mb(l,t.has(c)?t:new Set([c]),r),[t,r]);return Sm(document,"pointerenter",async c=>{let l=c.target;if(!_c(l)&&!Tb(l))return;let{project:u=scrapbox.Project.name,title:p,hash:f=""}=_c(l)?Xn({pathType:"root",href:${new URL(l.href).pathname}${new URL(l.href).hash}}):{project:scrapbox.Project.name,title:scrapbox.Page.title};if(u==="")return;let m=decodeURIComponent(p??"");a(u,m),await zn(l,e)&&n({project:u,title:m,hash:f,position:Vn(l),type:VS(l)})},{capture:!0},[e,t,r]),Sm(document,"click",c=>{c.target.dataset.userscriptName!==Lm&&s()},{capture:!0},[s]),te(()=>(scrapbox.addListener("page:changed",s),()=>scrapbox.removeListener("page:changed",s)),[s]),d(ee,{children:[d("link",{rel:"stylesheet",href:https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${lc}/katex.min.css}),d("style",{children:kb}),d(vb,{style:o}),i.map(c=>d(wb,{...c,whiteList:t,delay:e,prefetch:a},xe(c.source.project,c.source.title)))]})},VS=e=>_c(e)?e.type==="link"?"link":"hashtag":"title";var Ob=async e=>{let{delay:t=500,whiteList:r=[],watchList:o=(await Sx()).slice(0,100),style:n="",debug:s=!1}=e??{};Fx(s);let i=document.createElement("div");i.dataset.userscriptName=Lm,document.body.append(i);let a=i.attachShadow({mode:"open"});vt(d(Pb,{delay:t,whiteList:new Set([scrapbox.Project.name,...r]),watchList:new Set(o),style:n}),a)};var KS=["takker-memex","takker-private","takker","takker-books","villagepump"],fn=[];switch(scrapbox.Project.name){case"hub":case"villagepump":case"verbalizing-community":fn.push("villagepump","hub","verbalizing-community");break;case"programming-notes":case"customize":case"scrapboxlab":fn.push("programming-notes","customize","scrapboxlab");break;case"sta":fn.push("sta-taskmanagement");break;case"sta-taskmanagement":case"taskmanagement":fn.push("sta-taskmanagement","taskmanagement");break;case"plurality-japanese":fn.push("nishio","tkgshn");case"takker-books":fn.push("work4ai");break}Ob({delay:/mobile/i.test(navigator.userAgent)?300:500,whiteList:[...KS,...fn],style:@import "/api/code/takker/kakeruの背景を白にするUserCSS/style.css";
@import "/api/code/takker/アイコン記法を画像記法っぽくするUserCSS/style2.css";});var Sb=e=>{{let r=e.match(/^([^(]+)\(([^)]+)\)$/);if(r)return{fileName:r[1],lang:r[2]}}let t=e.split(".").pop();return t===void 0?{fileName:e,lang:e}:{fileName:e,lang:t}};var Pc={};Xi(Pc,{getTitle:()=>Zh,parse:()=>it});var Lb=(e,t,r)=>{if(r.length===0)return[];let o=r.map(a=>a.text).join(
),n=it(o,{hasTitle:!0}),s=new Map,i=0;for(let a of n)switch(a.type){case"title":case"line":{i++;break}case"table":i+=a.cells.length+1;break;case"codeBlock":{let{fileName:c,lang:l}=Sb(a.fileName),u=s.get(c);s.set(c,{path:u?.path??https://scrapbox.io/api/code/${e}/${se(t)}/${se(c)},lang:u?.lang??l,startIds:[...u?.startIds??[],r[i].id]}),i+=a.content.split(
).length+1;break}}return s.values()};function Mm(e){let t=o=>{if(o===null)r.write8(0);else if(typeof o=="boolean")r.write8(1),r.write8(+o);else if(typeof o=="number")r.write8(2),r.write32(o|0);else if(typeof o=="string")r.write8(3),r.write(Or(o));else if(o instanceof Uint8Array)r.write8(4),r.write(o);else if(o instanceof Array){r.write8(5),r.write32(o.length);for(let n of o)t(n)}else{let n=Object.keys(o);r.write8(6),r.write32(n.length);for(let s of n)r.write(Or(s)),t(o[s])}},r=new Oc;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),Nm(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function Nb(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return Zn(r.read());case 4:return r.read();case 5:{let i=r.read32(),a=[];for(let c=0;c<i;c++)a.push(t());return a}case 6:{let i=r.read32(),a={};for(let c=0;c<i;c++)a[Zn(r.read())]=t();return a}default:throw new Error("Invalid packet")}},r=new Oc(e),o=r.read32(),n=(o&1)===0;o>>>=1;let s=t();if(r.ptr!==e.length)throw new Error("Invalid packet");return{id:o,isRequest:n,value:s}}var Oc=class{constructor(t=new Uint8Array(1024)){this.buf=t}len=0;ptr=0;_write(t){if(this.len+t>this.buf.length){let r=new Uint8Array((this.len+t)*2);r.set(this.buf),this.buf=r}return this.len+=t,this.len-t}write8(t){let r=this._write(1);this.buf[r]=t}write32(t){let r=this._write(4);Nm(this.buf,t,r)}write(t){let r=this._write(4+t.length);Nm(this.buf,t.length,r),this.buf.set(t,r+4)}_read(t){if(this.ptr+t>this.buf.length)throw new Error("Invalid packet");return this.ptr+=t,this.ptr-t}read8(){return this.buf[this._read(1)]}read32(){return Cm(this.buf,this._read(4))}read(){let t=this.read32(),r=new Uint8Array(t),o=this._read(r.length);return r.set(this.buf.subarray(o,o+t)),r}},Or,Zn,Mb;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;Or=r=>e.encode(r),Zn=r=>t.decode(r),Mb='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(Or("")instanceof Uint8Array))throw new Error(Invariant violation: "${Mb} instanceof Uint8Array" is incorrectly false
This indicates that your JavaScript environment is broken. You cannot use
esbuild in this environment because esbuild relies on this invariant. This
is not a problem with esbuild. You need to fix your environment instead.
);function Cm(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function Nm(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var gi="0.24.0";var lt=JSON.stringify,Cb="warning",Ib="silent";function Ab(e){if(Ot(e,"target"),e.indexOf(",")>=0)throw new Error(Invalid target: ${e});return e}var Nc=()=>null,Ue=e=>typeof e=="boolean"?null:"a boolean",V=e=>typeof e=="string"?null:"a string",Mc=e=>e instanceof RegExp?null:"a RegExp object",hn=e=>typeof e=="number"&&e===(e|0)?null:"an integer",Ub=e=>typeof e=="function"?null:"a function",He=e=>Array.isArray(e)?null:"an array",gr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",XS=e=>typeof e=="object"&&e!==null?null:"an array or an object";var Fb=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",$b=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",JS=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",QS=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",jb=e=>typeof e=="string"||e instanceof Uint8Array?null:"a string or a Uint8Array";function k(e,t,r,o){let n=e[r];if(t[r+""]=!0,n===void 0)return;let s=o(n);if(s!==null)throw new Error(${lt(r)} must be ${s});return n}function Et(e,t,r){for(let o in e)if(!(o in t))throw new Error(Invalid option ${r}: ${lt(o)})}function Bb(e){let t;if(e!==void 0){t=Object.create(null);for(let r in e){let o=e[r];if(typeof o=="string"||o===!1)t[r]=o;else throw new Error(Expected ${lt(r)} in mangle cache to map to either a string or false)}}return t}function Cc(e,t,r,o,n){let s=k(t,r,"color",Ue),i=k(t,r,"logLevel",V),a=k(t,r,"logLimit",hn);s!==void 0?e.push(--color=${s}):o&&e.push("--color=true"),e.push(--log-level=${i||n}),e.push(--log-limit=${a||0})}function Ot(e,t,r){if(typeof e!="string")throw new Error(Expected value for ${t}${r!==void 0?" "+lt(r):""} to be a string, got ${typeof e} instead);return e}function Hb(e,t,r){let o=k(t,r,"legalComments",V),n=k(t,r,"sourceRoot",V),s=k(t,r,"sourcesContent",Ue),i=k(t,r,"target",QS),a=k(t,r,"format",V),c=k(t,r,"globalName",V),l=k(t,r,"mangleProps",Mc),u=k(t,r,"reserveProps",Mc),p=k(t,r,"mangleQuoted",Ue),f=k(t,r,"minify",Ue),m=k(t,r,"minifySyntax",Ue),h=k(t,r,"minifyWhitespace",Ue),g=k(t,r,"minifyIdentifiers",Ue),y=k(t,r,"lineLimit",hn),x=k(t,r,"drop",He),w=k(t,r,"dropLabels",He),R=k(t,r,"charset",V),b=k(t,r,"treeShaking",Ue),E=k(t,r,"ignoreAnnotations",Ue),T=k(t,r,"jsx",V),I=k(t,r,"jsxFactory",V),F=k(t,r,"jsxFragment",V),A=k(t,r,"jsxImportSource",V),N=k(t,r,"jsxDev",Ue),P=k(t,r,"jsxSideEffects",Ue),_=k(t,r,"define",gr),C=k(t,r,"logOverride",gr),$=k(t,r,"supported",gr),j=k(t,r,"pure",He),q=k(t,r,"keepNames",Ue),B=k(t,r,"platform",V),Y=k(t,r,"tsconfigRaw",JS);if(o&&e.push(--legal-comments=${o}),n!==void 0&&e.push(--source-root=${n}),s!==void 0&&e.push(--sources-content=${s}),i&&(Array.isArray(i)?e.push(--target=${Array.from(i).map(Ab).join(",")}):e.push(--target=${Ab(i)})),a&&e.push(--format=${a}),c&&e.push(--global-name=${c}),B&&e.push(--platform=${B}),Y&&e.push(--tsconfig-raw=${typeof Y=="string"?Y:JSON.stringify(Y)}),f&&e.push("--minify"),m&&e.push("--minify-syntax"),h&&e.push("--minify-whitespace"),g&&e.push("--minify-identifiers"),y&&e.push(--line-limit=${y}),R&&e.push(--charset=${R}),b!==void 0&&e.push(--tree-shaking=${b}),E&&e.push("--ignore-annotations"),x)for(let G of x)e.push(--drop:${Ot(G,"drop")});if(w&&e.push(--drop-labels=${Array.from(w).map(G=>Ot(G,"dropLabels")).join(",")}),l&&e.push(--mangle-props=${l.source}),u&&e.push(--reserve-props=${u.source}),p!==void 0&&e.push(--mangle-quoted=${p}),T&&e.push(--jsx=${T}),I&&e.push(--jsx-factory=${I}),F&&e.push(--jsx-fragment=${F}),A&&e.push(--jsx-import-source=${A}),N&&e.push("--jsx-dev"),P&&e.push("--jsx-side-effects"),_)for(let G in _){if(G.indexOf("=")>=0)throw new Error(Invalid define: ${G});e.push(--define:${G}=${Ot(_G,"define",G)})}if(C)for(let G in C){if(G.indexOf("=")>=0)throw new Error(Invalid log override: ${G});e.push(--log-override:${G}=${Ot(CG,"log override",G)})}if($)for(let G in $){if(G.indexOf("=")>=0)throw new Error(Invalid supported: ${G});let X=$[G];if(typeof X!="boolean")throw new Error(Expected value for supported ${lt(G)} to be a boolean, got ${typeof X} instead);e.push(--supported:${G}=${X})}if(j)for(let G of j)e.push(--pure:${Ot(G,"pure")});q&&e.push("--keep-names")}function ZS(e,t,r,o,n){let s=[],i=[],a=Object.create(null),c=null,l=null;Cc(s,t,a,r,o),Hb(s,t,a);let u=k(t,a,"sourcemap",$b),p=k(t,a,"bundle",Ue),f=k(t,a,"splitting",Ue),m=k(t,a,"preserveSymlinks",Ue),h=k(t,a,"metafile",Ue),g=k(t,a,"outfile",V),y=k(t,a,"outdir",V),x=k(t,a,"outbase",V),w=k(t,a,"tsconfig",V),R=k(t,a,"resolveExtensions",He),b=k(t,a,"nodePaths",He),E=k(t,a,"mainFields",He),T=k(t,a,"conditions",He),I=k(t,a,"external",He),F=k(t,a,"packages",V),A=k(t,a,"alias",gr),N=k(t,a,"loader",gr),P=k(t,a,"outExtension",gr),_=k(t,a,"publicPath",V),C=k(t,a,"entryNames",V),$=k(t,a,"chunkNames",V),j=k(t,a,"assetNames",V),q=k(t,a,"inject",He),B=k(t,a,"banner",gr),Y=k(t,a,"footer",gr),G=k(t,a,"entryPoints",XS),X=k(t,a,"absWorkingDir",V),J=k(t,a,"stdin",gr),le=k(t,a,"write",Ue)??n,oe=k(t,a,"allowOverwrite",Ue),Rt=k(t,a,"mangleCache",gr);if(a.plugins=!0,Et(t,a,in ${e}() call),u&&s.push(--sourcemap${u===!0?"":=${u}}),p&&s.push("--bundle"),oe&&s.push("--allow-overwrite"),f&&s.push("--splitting"),m&&s.push("--preserve-symlinks"),h&&s.push("--metafile"),g&&s.push(--outfile=${g}),y&&s.push(--outdir=${y}),x&&s.push(--outbase=${x}),w&&s.push(--tsconfig=${w}),F&&s.push(--packages=${F}),R){let W=[];for(let be of R){if(Ot(be,"resolve extension"),be.indexOf(",")>=0)throw new Error(Invalid resolve extension: ${be});W.push(be)}s.push(--resolve-extensions=${W.join(",")})}if(_&&s.push(--public-path=${_}),C&&s.push(--entry-names=${C}),$&&s.push(--chunk-names=${$}),j&&s.push(--asset-names=${j}),E){let W=[];for(let be of E){if(Ot(be,"main field"),be.indexOf(",")>=0)throw new Error(Invalid main field: ${be});W.push(be)}s.push(--main-fields=${W.join(",")})}if(T){let W=[];for(let be of T){if(Ot(be,"condition"),be.indexOf(",")>=0)throw new Error(Invalid condition: ${be});W.push(be)}s.push(--conditions=${W.join(",")})}if(I)for(let W of I)s.push(--external:${Ot(W,"external")});if(A)for(let W in A){if(W.indexOf("=")>=0)throw new Error(Invalid package name in alias: ${W});s.push(--alias:${W}=${Ot(AW,"alias",W)})}if(B)for(let W in B){if(W.indexOf("=")>=0)throw new Error(Invalid banner file type: ${W});s.push(--banner:${W}=${Ot(BW,"banner",W)})}if(Y)for(let W in Y){if(W.indexOf("=")>=0)throw new Error(Invalid footer file type: ${W});s.push(--footer:${W}=${Ot(YW,"footer",W)})}if(q)for(let W of q)s.push(--inject:${Ot(W,"inject")});if(N)for(let W in N){if(W.indexOf("=")>=0)throw new Error(Invalid loader extension: ${W});s.push(--loader:${W}=${Ot(NW,"loader",W)})}if(P)for(let W in P){if(W.indexOf("=")>=0)throw new Error(Invalid out extension: ${W});s.push(--out-extension:${W}=${Ot(PW,"out extension",W)})}if(G)if(Array.isArray(G))for(let W=0,be=G.length;W<be;W++){let Ct=G[W];if(typeof Ct=="object"&&Ct!==null){let zr=Object.create(null),Vr=k(Ct,zr,"in",V),Lr=k(Ct,zr,"out",V);if(Et(Ct,zr,"in entry point at index "+W),Vr===void 0)throw new Error('Missing property "in" for entry point at index '+W);if(Lr===void 0)throw new Error('Missing property "out" for entry point at index '+W);i.push([Lr,Vr])}else i.push(["",Ot(Ct,"entry point at index "+W)])}else for(let W in G)i.push([W,Ot(G[W],"entry point",W)]);if(J){let W=Object.create(null),be=k(J,W,"contents",jb),Ct=k(J,W,"resolveDir",V),zr=k(J,W,"sourcefile",V),Vr=k(J,W,"loader",V);Et(J,W,'in "stdin" object'),zr&&s.push(--sourcefile=${zr}),Vr&&s.push(--loader=${Vr}),Ct&&(l=Ct),typeof be=="string"?c=Or(be):be instanceof Uint8Array&&(c=be)}let Oe=[];if(b)for(let W of b)W+="",Oe.push(W);return{entries:i,flags:s,write:le,stdinContents:c,stdinResolveDir:l,absWorkingDir:X,nodePaths:Oe,mangleCache:Bb(Rt)}}function eL(e,t,r,o){let n=[],s=Object.create(null);Cc(n,t,s,r,o),Hb(n,t,s);let i=k(t,s,"sourcemap",$b),a=k(t,s,"sourcefile",V),c=k(t,s,"loader",V),l=k(t,s,"banner",V),u=k(t,s,"footer",V),p=k(t,s,"mangleCache",gr);return Et(t,s,in ${e}() call),i&&n.push(--sourcemap=${i===!0?"external":i}),a&&n.push(--sourcefile=${a}),c&&n.push(--loader=${c}),l&&n.push(--banner=${l}),u&&n.push(--footer=${u}),{flags:n,mangleCache:Bb(p)}}function Wb(e){let t={},r={didClose:!1,reason:""},o={},n=0,s=0,i=new Uint8Array(16*1024),a=0,c=R=>{let b=a+R.length;if(b>i.length){let T=new Uint8Array(b*2);T.set(i),i=T}i.set(R,a),a+=R.length;let E=0;for(;E+4<=a;){let T=Cm(i,E);if(E+4+T>a)break;E+=4,h(i.subarray(E,E+T)),E+=T}E>0&&(i.copyWithin(0,E,a),a-=E)},l=R=>{r.didClose=!0,R&&(r.reason=": "+(R.message||R));let b="The service was stopped"+r.reason;for(let E in o)o[E](b,null);o={}},u=(R,b,E)=>{if(r.didClose)return E("The service is no longer running"+r.reason,null);let T=n++;o[T]=(I,F)=>{try{E(I,F)}finally{R&&R.unref()}},R&&R.ref(),e.writeToStdin(Mm({id:T,isRequest:!0,value:b}))},p=(R,b)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(Mm({id:R,isRequest:!1,value:b}))},f=async(R,b)=>{try{if(b.command==="ping"){p(R,{});return}if(typeof b.key=="number"){let E=t[b.key];if(!E)return;let T=E[b.command];if(T){await T(R,b);return}}throw new Error("Invalid command: "+b.command)}catch(E){let T=[dn(E,e,null,void 0,"")];try{p(R,{errors:T})}catch{}}},m=!0,h=R=>{if(m){m=!1;let E=String.fromCharCode(...R);if(E!==gi)throw new Error(Cannot start service: Host version "${gi}" does not match binary version ${lt(E)});return}let b=Nb(R);if(b.isRequest)f(b.id,b.value);else{let E=o[b.id];delete o[b.id],b.value.error?E(b.value.error,{}):E(null,b.value)}};return{readFromStdout:c,afterClose:l,service:{buildOrContext:({callName:R,refs:b,options:E,isTTY:T,defaultWD:I,callback:F})=>{let A=0,N=s++,P={},_={ref(){++A===1&&b&&b.ref()},unref(){--A===0&&(delete t[N],b&&b.unref())}};t[N]=P,_.ref(),tL(R,N,u,p,_,e,P,E,T,I,(C,$)=>{try{F(C,$)}finally{_.unref()}})},transform:({callName:R,refs:b,input:E,options:T,isTTY:I,fs:F,callback:A})=>{let N=qb(),P=_=>{try{if(typeof E!="string"&&!(E instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:C,mangleCache:$}=eL(R,T,I,Ib),j={command:"transform",flags:C,inputFS:_!==null,input:_!==null?Or(_):typeof E=="string"?Or(E):E};$&&(j.mangleCache=$),u(b,j,(q,B)=>{if(q)return A(new Error(q),null);let Y=es(B.errors,N),G=es(B.warnings,N),X=1,J=()=>{if(--X===0){let le={warnings:G,code:B.code,map:B.map,mangleCache:void 0,legalComments:void 0};"legalComments"in B&&(le.legalComments=B?.legalComments),B.mangleCache&&(le.mangleCache=B?.mangleCache),A(null,le)}};if(Y.length>0)return A(yi("Transform failed",Y,G),null);B.codeFS&&(X++,F.readFile(B.code,(le,oe)=>{le!==null?A(le,null):(B.code=oe,J())})),B.mapFS&&(X++,F.readFile(B.map,(le,oe)=>{le!==null?A(le,null):(B.map=oe,J())})),J()})}catch(C){let $=[];try{Cc($,T,{},I,Ib)}catch{}let j=dn(C,e,N,void 0,"");u(b,{command:"error",flags:$,error:j},()=>{j.detail=N.load(j.detail),A(yi("Transform failed",[j],[]),null)})}};if((typeof E=="string"||E instanceof Uint8Array)&&E.length>1024*1024){let _=P;P=()=>F.writeFile(E,_)}P(null)},formatMessages:({callName:R,refs:b,messages:E,options:T,callback:I})=>{if(!T)throw new Error(Missing second argument in ${R}() call);let F={},A=k(T,F,"kind",V),N=k(T,F,"color",Ue),P=k(T,F,"terminalWidth",hn);if(Et(T,F,in ${R}() call),A===void 0)throw new Error(Missing "kind" in ${R}() call);if(A!=="error"&&A!=="warning")throw new Error(Expected "kind" to be "error" or "warning" in ${R}() call);let _={command:"format-msgs",messages:io(E,"messages",null,"",P),isWarning:A==="warning"};N!==void 0&&(_.color=N),P!==void 0&&(_.terminalWidth=P),u(b,_,(C,$)=>{if(C)return I(new Error(C),null);I(null,$.messages)})},analyzeMetafile:({callName:R,refs:b,metafile:E,options:T,callback:I})=>{T===void 0&&(T={});let F={},A=k(T,F,"color",Ue),N=k(T,F,"verbose",Ue);Et(T,F,in ${R}() call);let P={command:"analyze-metafile",metafile:E};A!==void 0&&(P.color=A),N!==void 0&&(P.verbose=N),u(b,P,(_,C)=>{if(_)return I(new Error(_),null);I(null,C.result)})}}}}function tL(e,t,r,o,n,s,i,a,c,l,u){let p=qb(),f=e==="context",m=(y,x)=>{let w=[];try{Cc(w,a,{},c,Cb)}catch{}let R=dn(y,s,p,void 0,x);r(n,{command:"error",flags:w,error:R},()=>{R.detail=p.load(R.detail),u(yi(f?"Context failed":"Build failed",[R],[]),null)})},h;if(typeof a=="object"){let y=a.plugins;if(y!==void 0){if(!Array.isArray(y))return m(new Error('"plugins" must be an array'),"");h=y}}if(h&&h.length>0){if(s.isSync)return m(new Error("Cannot use plugins in synchronous API calls"),"");rL(t,r,o,n,s,i,a,h,p).then(y=>{if(!y.ok)return m(y.error,y.pluginName);try{g(y.requestPlugins,y.runOnEndCallbacks,y.scheduleOnDisposeCallbacks)}catch(x){m(x,"")}},y=>m(y,""));return}try{g(null,(y,x)=>x([],[]),()=>{})}catch(y){m(y,"")}function g(y,x,w){let R=s.hasFS,{entries:b,flags:E,write:T,stdinContents:I,stdinResolveDir:F,absWorkingDir:A,nodePaths:N,mangleCache:P}=ZS(e,a,c,Cb,R);if(T&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let _={command:"build",key:t,entries:b,flags:E,write:T,stdinContents:I,stdinResolveDir:F,absWorkingDir:A||l,nodePaths:N,context:f};y&&(_.plugins=y),P&&(_.mangleCache=P);let C=(q,B)=>{let Y={errors:es(q.errors,p),warnings:es(q.warnings,p),outputFiles:void 0,metafile:void 0,mangleCache:void 0},G=Y.errors.slice(),X=Y.warnings.slice();q.outputFiles&&(Y.outputFiles=q.outputFiles.map(nL)),q.metafile&&(Y.metafile=JSON.parse(q.metafile)),q.mangleCache&&(Y.mangleCache=q.mangleCache),q.writeToStdout!==void 0&&console.log(Zn(q.writeToStdout).replace(/\n$/,"")),x(Y,(J,le)=>{if(G.length>0||J.length>0){let oe=yi("Build failed",G.concat(J),X.concat(le));return B(oe,null,J,le)}B(null,Y,J,le)})},$,j;f&&(i["on-end"]=(q,B)=>new Promise(Y=>{C(B,(G,X,J,le)=>{let oe={errors:J,warnings:le};j&&j(G,X),$=void 0,j=void 0,o(q,oe),Y()})})),r(n,_,(q,B)=>{if(q)return u(new Error(q),null);if(!f)return C(B,(X,J)=>(w(),u(X,J)));if(B.errors.length>0)return u(yi("Context failed",B.errors,B.warnings),null);let Y=!1,G={rebuild:()=>($||($=new Promise((X,J)=>{let le;j=(Rt,Oe)=>{le||(le=()=>Rt?J(Rt):X(Oe))};let oe=()=>{r(n,{command:"rebuild",key:t},(Oe,W)=>{Oe?J(new Error(Oe)):le?le():oe()})};oe()})),$),watch:(X={})=>new Promise((J,le)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');Et(X,{},"in watch() call"),r(n,{command:"watch",key:t},Oe=>{Oe?le(new Error(Oe)):J(void 0)})}),serve:(X={})=>new Promise((J,le)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let oe={},Rt=k(X,oe,"port",hn),Oe=k(X,oe,"host",V),W=k(X,oe,"servedir",V),be=k(X,oe,"keyfile",V),Ct=k(X,oe,"certfile",V),zr=k(X,oe,"fallback",V),Vr=k(X,oe,"onRequest",Ub);Et(X,oe,"in serve() call");let Lr={command:"serve",key:t,onRequest:!!Vr};Rt!==void 0&&(Lr.port=Rt),Oe!==void 0&&(Lr.host=Oe),W!==void 0&&(Lr.servedir=W),be!==void 0&&(Lr.keyfile=be),Ct!==void 0&&(Lr.certfile=Ct),zr!==void 0&&(Lr.fallback=zr),r(n,Lr,(Id,y0)=>{if(Id)return le(new Error(Id));Vr&&(i["serve-request"]=(x0,b0)=>{Vr(b0.args),o(x0,{})}),J(y0)})}),cancel:()=>new Promise(X=>{if(Y)return X();r(n,{command:"cancel",key:t},()=>{X()})}),dispose:()=>new Promise(X=>{if(Y)return X();Y=!0,r(n,{command:"dispose",key:t},()=>{X(),w(),n.unref()})})};n.ref(),u(null,G)})}}var rL=async(e,t,r,o,n,s,i,a,c)=>{let l=[],u=[],p={},f={},m=[],h=0,g=0,y=[],x=!1;a=[...a];for(let b of a){let E={};if(typeof b!="object")throw new Error(Plugin at index ${g} must be an object);let T=k(b,E,"name",V);if(typeof T!="string"||T==="")throw new Error(Plugin at index ${g} is missing a name);try{let I=k(b,E,"setup",Ub);if(typeof I!="function")throw new Error("Plugin is missing a setup function");Et(b,E,on plugin ${lt(T)});let F={name:T,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};g++;let N=I({initialOptions:i,resolve:(P,_={})=>{if(!x)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof P!="string")throw new Error("The path to resolve must be a string");let C=Object.create(null),$=k(_,C,"pluginName",V),j=k(_,C,"importer",V),q=k(_,C,"namespace",V),B=k(_,C,"resolveDir",V),Y=k(_,C,"kind",V),G=k(_,C,"pluginData",Nc),X=k(_,C,"with",gr);return Et(_,C,"in resolve() call"),new Promise((J,le)=>{let oe={command:"resolve",path:P,key:e,pluginName:T};if($!=null&&(oe.pluginName=$),j!=null&&(oe.importer=j),q!=null&&(oe.namespace=q),B!=null&&(oe.resolveDir=B),Y!=null)oe.kind=Y;else throw new Error('Must specify "kind" when calling "resolve"');G!=null&&(oe.pluginData=c.store(G)),X!=null&&(oe.with=oL(X,"with")),t(o,oe,(Rt,Oe)=>{Rt!==null?le(new Error(Rt)):J({errors:es(Oe.errors,c),warnings:es(Oe.warnings,c),path:Oe.path,external:Oe.external,sideEffects:Oe.sideEffects,namespace:Oe.namespace,suffix:Oe.suffix,pluginData:c.load(Oe.pluginData)})})})},onStart(P){let _='This error came from the "onStart" callback registered here:',C=Sc(new Error(_),n,"onStart");l.push({name:T,callback:P,note:C}),F.onStart=!0},onEnd(P){let _='This error came from the "onEnd" callback registered here:',C=Sc(new Error(_),n,"onEnd");u.push({name:T,callback:P,note:C}),F.onEnd=!0},onResolve(P,_){let C='This error came from the "onResolve" callback registered here:',$=Sc(new Error(C),n,"onResolve"),j={},q=k(P,j,"filter",Mc),B=k(P,j,"namespace",V);if(Et(P,j,in onResolve() call for plugin ${lt(T)}),q==null)throw new Error("onResolve() call is missing a filter");let Y=h++;p[Y]={name:T,callback:_,note:$},F.onResolve.push({id:Y,filter:q.source,namespace:B||""})},onLoad(P,_){let C='This error came from the "onLoad" callback registered here:',$=Sc(new Error(C),n,"onLoad"),j={},q=k(P,j,"filter",Mc),B=k(P,j,"namespace",V);if(Et(P,j,in onLoad() call for plugin ${lt(T)}),q==null)throw new Error("onLoad() call is missing a filter");let Y=h++;f[Y]={name:T,callback:_,note:$},F.onLoad.push({id:Y,filter:q.source,namespace:B||""})},onDispose(P){m.push(P)},esbuild:n.esbuild});N&&await N,y.push(F)}catch(I){return{ok:!1,error:I,pluginName:T}}}s["on-start"]=async(b,E)=>{c.clear();let T={errors:[],warnings:[]};await Promise.all(l.map(async({name:I,callback:F,note:A})=>{try{let N=await F();if(N!=null){if(typeof N!="object")throw new Error(Expected onStart() callback in plugin ${lt(I)} to return an object);let P={},_=k(N,P,"errors",He),C=k(N,P,"warnings",He);Et(N,P,from onStart() callback in plugin ${lt(I)}),_!=null&&T.errors.push(...io(_,"errors",c,I,void 0)),C!=null&&T.warnings.push(...io(C,"warnings",c,I,void 0))}}catch(N){T.errors.push(dn(N,n,c,A&&A(),I))}})),r(b,T)},s["on-resolve"]=async(b,E)=>{let T={},I="",F,A;for(let N of E.ids)try{({name:I,callback:F,note:A}=p[N]);let P=await F({path:E.path,importer:E.importer,namespace:E.namespace,resolveDir:E.resolveDir,kind:E.kind,pluginData:c.load(E.pluginData),with:E.with});if(P!=null){if(typeof P!="object")throw new Error(Expected onResolve() callback in plugin ${lt(I)} to return an object);let _={},C=k(P,_,"pluginName",V),$=k(P,_,"path",V),j=k(P,_,"namespace",V),q=k(P,_,"suffix",V),B=k(P,_,"external",Ue),Y=k(P,_,"sideEffects",Ue),G=k(P,_,"pluginData",Nc),X=k(P,_,"errors",He),J=k(P,_,"warnings",He),le=k(P,_,"watchFiles",He),oe=k(P,_,"watchDirs",He);Et(P,_,from onResolve() callback in plugin ${lt(I)}),T.id=N,C!=null&&(T.pluginName=C),$!=null&&(T.path=$),j!=null&&(T.namespace=j),q!=null&&(T.suffix=q),B!=null&&(T.external=B),Y!=null&&(T.sideEffects=Y),G!=null&&(T.pluginData=c.store(G)),X!=null&&(T.errors=io(X,"errors",c,I,void 0)),J!=null&&(T.warnings=io(J,"warnings",c,I,void 0)),le!=null&&(T.watchFiles=Lc(le,"watchFiles")),oe!=null&&(T.watchDirs=Lc(oe,"watchDirs"));break}}catch(P){T={id:N,errors:[dn(P,n,c,A&&A(),I)]};break}r(b,T)},s["on-load"]=async(b,E)=>{let T={},I="",F,A;for(let N of E.ids)try{({name:I,callback:F,note:A}=f[N]);let P=await F({path:E.path,namespace:E.namespace,suffix:E.suffix,pluginData:c.load(E.pluginData),with:E.with});if(P!=null){if(typeof P!="object")throw new Error(Expected onLoad() callback in plugin ${lt(I)} to return an object);let _={},C=k(P,_,"pluginName",V),$=k(P,_,"contents",jb),j=k(P,_,"resolveDir",V),q=k(P,_,"pluginData",Nc),B=k(P,_,"loader",V),Y=k(P,_,"errors",He),G=k(P,_,"warnings",He),X=k(P,_,"watchFiles",He),J=k(P,_,"watchDirs",He);Et(P,_,from onLoad() callback in plugin ${lt(I)}),T.id=N,C!=null&&(T.pluginName=C),$ instanceof Uint8Array?T.contents=$:$!=null&&(T.contents=Or($)),j!=null&&(T.resolveDir=j),q!=null&&(T.pluginData=c.store(q)),B!=null&&(T.loader=B),Y!=null&&(T.errors=io(Y,"errors",c,I,void 0)),G!=null&&(T.warnings=io(G,"warnings",c,I,void 0)),X!=null&&(T.watchFiles=Lc(X,"watchFiles")),J!=null&&(T.watchDirs=Lc(J,"watchDirs"));break}}catch(P){T={id:N,errors:[dn(P,n,c,A&&A(),I)]};break}r(b,T)};let w=(b,E)=>E([],[]);u.length>0&&(w=(b,E)=>{(async()=>{let T=[],I=[];for(let{name:F,callback:A,note:N}of u){let P,_;try{let C=await A(b);if(C!=null){if(typeof C!="object")throw new Error(Expected onEnd() callback in plugin ${lt(F)} to return an object);let $={},j=k(C,$,"errors",He),q=k(C,$,"warnings",He);Et(C,$,from onEnd() callback in plugin ${lt(F)}),j!=null&&(P=io(j,"errors",c,F,void 0)),q!=null&&(_=io(q,"warnings",c,F,void 0))}}catch(C){P=[dn(C,n,c,N&&N(),F)]}if(P){T.push(...P);try{b.errors.push(...P)}catch{}}if(_){I.push(..._);try{b.warnings.push(..._)}catch{}}}E(T,I)})()});let R=()=>{for(let b of m)setTimeout(()=>b(),0)};return x=!0,{ok:!0,requestPlugins:y,runOnEndCallbacks:w,scheduleOnDisposeCallbacks:R}};function qb(){let e=new Map,t=0;return{clear(){e.clear()},load(r){return e.get(r)},store(r){if(r===void 0)return-1;let o=t++;return e.set(o,r),o}}}function Sc(e,t,r){let o,n=!1;return()=>{if(n)return o;n=!0;try{let s=(e.stack+"").split(
);s.splice(1,1);let i=Gb(t,s,r);if(i)return o={text:e.message,location:i},o}catch{}}}function dn(e,t,r,o,n){let s="Internal error",i=null;try{s=(e&&e.message||e)+""}catch{}try{i=Gb(t,(e.stack+"").split(
),"")}catch{}return{id:"",pluginName:n,text:s,location:i,notes:o?[o]:[],detail:r?r.store(e):-1}}function Gb(e,t,r){let o=" at ";if(e.readFileSync&&!t[0].startsWith(o)&&t[1].startsWith(o))for(let n=1;n<t.length;n++){let s=t[n];if(s.startsWith(o))for(s=s.slice(o.length);;){let i=/^(?:new |async )?\S+ \((.*)\)$/.exec(s);if(i){s=i[1];continue}if(i=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(s),i){s=i[1];continue}if(i=/^(\S+):(\d+):(\d+)$/.exec(s),i){let a;try{a=e.readFileSync(i[1],"utf8")}catch{break}let c=a.split(/\r\n|\r|\n|\u2028|\u2029/)[+i[2]-1]||"",l=+i[3]-1,u=c.slice(l,l+r.length)===r?r.length:0;return{file:i[1],namespace:"file",line:+i[2],column:Or(c.slice(0,l)).length,length:Or(c.slice(l,l+u)).length,lineText:c+
+t.slice(1).join(
),suggestion:""}}break}}return null}function yi(e,t,r){let o=5;e+=t.length<1?"": with ${t.length} error${t.length<2?"":"s"}:+t.slice(0,o+1).map((s,i)=>{if(i===o)return
...;if(!s.location)return
error: ${s.text};let{file:a,line:c,column:l}=s.location,u=s.pluginName?plugin: ${s.pluginName} :"";return
${a}:${c}:${l}: ERROR: ${u}${s.text}}).join("");let n=new Error(e);for(let[s,i]of[["errors",t],["warnings",r]])Object.defineProperty(n,s,{configurable:!0,enumerable:!0,get:()=>i,set:a=>Object.defineProperty(n,s,{configurable:!0,enumerable:!0,value:a})});return n}function es(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function Db(e,t,r){if(e==null)return null;let o={},n=k(e,o,"file",V),s=k(e,o,"namespace",V),i=k(e,o,"line",hn),a=k(e,o,"column",hn),c=k(e,o,"length",hn),l=k(e,o,"lineText",V),u=k(e,o,"suggestion",V);if(Et(e,o,t),l){let p=l.slice(0,(a&&a>0?a:0)+(c&&c>0?c:0)+(r&&r>0?r:80));!/[\x7F-\uFFFF]/.test(p)&&!/\n/.test(l)&&(l=p)}return{file:n||"",namespace:s||"",line:i||0,column:a||0,length:c||0,lineText:l||"",suggestion:u||""}}function io(e,t,r,o,n){let s=[],i=0;for(let a of e){let c={},l=k(a,c,"id",V),u=k(a,c,"pluginName",V),p=k(a,c,"text",V),f=k(a,c,"location",Fb),m=k(a,c,"notes",He),h=k(a,c,"detail",Nc),g=in element ${i} of "${t}";Et(a,c,g);let y=[];if(m)for(let x of m){let w={},R=k(x,w,"text",V),b=k(x,w,"location",Fb);Et(x,w,g),y.push({text:R||"",location:Db(b,g,n)})}s.push({id:l||"",pluginName:u||o,text:p||"",location:Db(f,g,n),notes:y,detail:r?r.store(h):-1}),i++}return s}function Lc(e,t){let r=[];for(let o of e){if(typeof o!="string")throw new Error(${lt(t)} must be an array of strings);r.push(o)}return r}function oL(e,t){let r=Object.create(null);for(let o in e){let n=e[o];if(typeof n!="string")throw new Error(key ${lt(o)} in object ${lt(t)} must be a string);r[o]=n}return r}function nL({path:e,contents:t,hash:r}){let o=null;return{path:e,contents:t,hash:r,get text(){let n=this.contents;return(o===null||n!==t)&&(t=n,o=Zn(n)),o}}}var Vb=gi,Ac=e=>Fc().build(e),Kb=(e,t)=>Fc().transform(e,t),Yb=(e,t)=>Fc().formatMessages(e,t),Xb=(e,t)=>Fc().analyzeMetafile(e,t);var gn,zb,Ic,Fc=()=>{if(Ic)return Ic;throw gn?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},Dc=e=>{let t=e.wasm,r=e.worker;if(gn)throw new Error('Cannot call "initialize" more than once');return gn=sL(t,r),gn.catch(()=>{gn=void 0}),gn},sL=async(e,t)=>{let r=new Worker(t.toString(),{type:"module"}),o,n,s=new Promise((c,l)=>{o=c,n=l});r.onmessage=({data:c})=>{r.onmessage=({data:l})=>i(l),c?n(c):o()},r.postMessage(e);let{readFromStdout:i,service:a}=Wb({writeToStdin(c){r.postMessage(c)},isSync:!1,hasFS:!1,esbuild:{build:Ac,transform:Kb,formatMessages:Yb,analyzeMetafile:Xb,version:Vb,initialize:Dc}});await s,zb=()=>{r.terminate(),gn=void 0,zb=void 0,Ic=void 0},Ic={build:c=>new Promise((l,u)=>a.buildOrContext({callName:"build",refs:null,options:c,isTTY:!1,defaultWD:"/",callback:(p,f)=>p?u(p):l(f)})),transform:(c,l)=>new Promise((u,p)=>a.transform({callName:"transform",refs:null,input:c,options:l||{},isTTY:!1,fs:{readFile(f,m){m(new Error("Internal error"),null)},writeFile(f,m){m(null)}},callback:(f,m)=>f?p(f):u(m)})),formatMessages:(c,l)=>new Promise((u,p)=>a.formatMessages({callName:"formatMessages",refs:null,messages:c,options:l,callback:(f,m)=>f?p(f):u(m)})),analyzeMetafile:(c,l)=>new Promise((u,p)=>a.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof c=="string"?c:JSON.stringify(c),options:l,callback:(f,m)=>f?p(f):u(m)}))}};self.Deno||(self.Deno={build:{os:"linux"},errors:{AlreadyExists:Error},env:{get:()=>{}},permissions:{query:()=>Promise.resolve("denied")},cwd:()=>location.href});function Jb(){let e=globalThis,t=e.process?.platform;if(typeof t=="string")return t.startsWith("win");let r=e.Deno?.build?.os;return typeof r=="string"?r==="windows":e.navigator?.platform?.startsWith("Win")??!1}var pt=Jb();function St(e){if(typeof e!="string")throw new TypeError(Path must be a string, received "${JSON.stringify(e)}")}function Im(e,t){if(t.length>=e.length)return e;let r=e.length-t.length;for(let o=t.length-1;o>=0;--o)if(e.charCodeAt(r+o)!==t.charCodeAt(o))return e;return e.slice(0,-t.length)}function Am(e,t,r=0){let o=!1,n=e.length;for(let s=e.length-1;s>=r;--s)if(t(e.charCodeAt(s))){if(o){r=s+1;break}}else o||(o=!0,n=s+1);return e.slice(r,n)}function Fm(e,t){if(St(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(Suffix must be a string, received "${JSON.stringify(t)}")}function Uc(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError(URL must be a file URL: received "${e.protocol}");return e}function ao(e){return e=Uc(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function ts(e,t){if(e.length<=1)return e;let r=e.length;for(let o=e.length-1;o>0&&t(e.charCodeAt(o));o--)r=o;return e.slice(0,r)}function yr(e){return e===47}function Dm(e,t=""){e instanceof URL&&(e=ao(e)),Fm(e,t);let r=Am(e,yr),o=ts(r,yr);return t?Im(o,t):o}function jr(e){return e===47||e===92}function co(e){return e>=97&&e<=122||e>=65&&e<=90}function yn(e){e=Uc(e);let t=decodeURIComponent(e.pathname.replace(/\//g,"\\").replace(/%(?![0-9A-Fa-f]{2})/g,"%25")).replace(/^\\*([A-Za-z]:)(\\|$)/,"$1\\");return e.hostname!==""&&(t=\\\\${e.hostname}${t}),t}var xi=pt?"\\":"/";function $m(e){e instanceof URL&&(e=ao(e)),St(e);let t=-1,r=0,o=-1,n=!0,s=0;for(let i=e.length-1;i>=0;--i){let a=e.charCodeAt(i);if(yr(a)){if(!n){r=i+1;break}continue}o===-1&&(n=!1,o=i+1),a===46?t===-1?t=i:s!==1&&(s=1):t!==-1&&(s=-1)}return t===-1||o===-1||s===0||s===1&&t===o-1&&t===r+1?"":e.slice(t,o)}function os(e){return pt?yn(e):ao(e)}function jm(e){return St(e),e.length>0&&yr(e.charCodeAt(0))}function Bm(e){St(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return jr(r)?!0:!!(co(r)&&t>2&&e.charCodeAt(1)===58&&jr(e.charCodeAt(2)))}var bL={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function jc(e){return e.replaceAll(/[\s]/g,t=>bL[t]??t)}function tE(e){if(!jm(e))throw new TypeError(Path must be absolute: received "${e}");let t=new URL("file:///");return t.pathname=jc(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}function rE(e){if(!Bm(e))throw new TypeError(Path must be absolute: received "${e}");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=jc(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError(Invalid hostname: "${o.hostname}");return o}function xn(e){return pt?rE(e):tE(e)}function Bc(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function Hc(e){let t={},r=Object.keys(e).sort((o,n)=>n.length-o.length);for(let o of r)t[o]=e[o];return t}function oE(e){return Bc(e)&&(e.imports!==void 0?Wm(e.imports):!0)&&(e.scopes!==void 0?qm(e.scopes):!0)}function Wm(e){return Bc(e)}function qm(e){return Bc(e)&&Object.values(e).every(t=>Gm(t))}function Gm(e){return Bc(e)}function Wc(e){try{return new URL(e),!0}catch{return!1}}function sE(e,t){let r={};for(let[o,n]of Object.entries(e)){let s=kL(o,t);if(s===null)continue;if(typeof n!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let i=zm(n,t);if(i===null){console.warn("the address was invalid."),r[s]=null;continue}if(o.endsWith("/")&&!Br(i).endsWith("/")){console.warn("an invalid address was given for the specifier key specifierKey; since specifierKey ended in a slash, the address needs to as well."),r[s]=null;continue}r[s]=Br(i)}return Hc(r)}function Br(e){return e.href}function vL(e,t){let r={};for(let[n,s]of Object.entries(e)){if(!Gm(s))throw new TypeError("the value of the scope with prefix scopePrefix needs to be an object.");let i;try{i=new URL(n,t)}catch{console.warn("the scope prefix URL was not parseable.");continue}let a=Br(i);r[a]=sE(s,t)}let o={};for(let n of Object.keys(r))o[n]=Hc(r[n]);return Hc(o)}function kL(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=zm(e,t);return r!==null?Br(r):e}function zm(e,t){if(t&&(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")))try{return new URL(e,t)}catch{return null}try{return new URL(e)}catch{return null}}var TL=["ftp","file","http","https","ws","wss"];function _L(e){return TL.some(t=>Br(e).startsWith(t))}function nE(e,t,r){for(let[o,n]of Object.entries(r))if(o===e){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Wc(n))throw new TypeError("resolutionResult must be an URL.");return n}else if(o.endsWith("/")&&e.startsWith(o)&&(t===null||_L(t))){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Wc(n))throw new TypeError("resolutionResult must be an URL.");let s=e.slice(o.length);if(!n.endsWith("/"))throw new TypeError('resolutionResult does not end with "/"');try{let i=new URL(s,n);if(!Wc(i))throw new TypeError("url must be an URL.");if(!Br(i).startsWith(n))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return Br(i)}catch{throw new TypeError("resolution of normalizedSpecifier was blocked since the afterPrefix portion could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.")}}return null}function Vm(e,t){let r={};if(!oE(e))throw new TypeError("the top-level value needs to be a JSON object.");let{imports:o,scopes:n}=e;if(o!==void 0){if(!Wm(o))throw new TypeError('"imports" top-level key needs to be an object.');r=sE(o,t)}let s={};if(n!==void 0){if(!qm(n))throw new TypeError('"scopes" top-level key needs to be an object.');s=vL(n,t)}return Object.keys(e).find(i=>i!=="imports"&&i!=="scopes")&&console.warn("an invalid top-level key was present in the import map."),{imports:r,scopes:s}}function iE(e,{imports:t={},scopes:r={}},o){let n=Br(o),s=zm(e,o),i=s!==null?Br(s):e;for(let[c,l]of Object.entries(r))if(c===n||c.endsWith("/")&&n.startsWith(c)){let u=nE(i,s,l);if(u!==null)return u}let a=nE(i,s,t);if(a!==null)return a;if(s!==null)return Br(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}var qc=class extends Error{constructor(t){super(t),this.name="AssertionError"}};function Km(e,t=""){if(!e)throw new qc(t)}function cE(e,{allowTrailingComma:t=!0}={}){if(new.target)throw new TypeError("parse is not a constructor");return new Ym(e,{allowTrailingComma:t}).parse()}var aE=globalThis.JSON.parse,Ym=class{#o=new Set( \r
);#r=new Set([..."[]{}:,/",...this.#o]);#t;#e;#i;#a;constructor(t,r){this.#t=${t},this.#e=this.#t.length,this.#i=this.#m(),this.#a=r}parse(){let t=this.#s(),r=this.#p(t),{done:o,value:n}=this.#i.next();if(!o)throw new SyntaxError(Fo(n));return r}#s(){let{done:t,value:r}=this.#i.next();if(t)throw new SyntaxError("Unexpected end of JSONC input");return r}*#m(){for(let t=0;t<this.#e;t++)if(!this.#o.has(this.#t[t])){if(this.#t[t]==="/"&&this.#t[t+1]==="*"){t+=2;let r=!1;for(;t<this.#e;t++)if(this.#t[t]==="*"&&this.#t[t+1]==="/"){r=!0;break}if(!r)throw new SyntaxError("Unexpected end of JSONC input");t++;continue}if(this.#t[t]==="/"&&this.#t[t+1]==="/"){for(t+=2;t<this.#e&&!(this.#t[t]===
||this.#t[t]==="\r");t++);continue}switch(this.#t[t]){case"{":yield{type:"BeginObject",position:t};break;case"}":yield{type:"EndObject",position:t};break;case"[":yield{type:"BeginArray",position:t};break;case"]":yield{type:"EndArray",position:t};break;case":":yield{type:"NameSeparator",position:t};break;case",":yield{type:"ValueSeparator",position:t};break;case'"':{let r=t,o=!1;for(t++;t<this.#e&&!(this.#t[t]==='"'&&!o);t++)o=this.#t[t]==="\\"&&!o;yield{type:"String",sourceText:this.#t.substring(r,t+1),position:r};break}default:{let r=t;for(;t<this.#e&&!this.#r.has(this.#t[t]);t++);t--,yield{type:"NullOrTrueOrFalseOrNumber",sourceText:this.#t.substring(r,t+1),position:r}}}}}#p(t){switch(t.type){case"BeginObject":return this.#f();case"BeginArray":return this.#n();case"NullOrTrueOrFalseOrNumber":return this.#g(t);case"String":return this.#h(t);default:throw new SyntaxError(Fo(t))}}#f(){let t={};for(let r=!0;;r=!1){let o=this.#s();if((r||this.#a.allowTrailingComma)&&o.type==="EndObject")return t;if(o.type!=="String")throw new SyntaxError(Fo(o));let n=this.#h(o),s=this.#s();if(s.type!=="NameSeparator")throw new SyntaxError(Fo(s));let i=this.#s();Object.defineProperty(t,n,{value:this.#p(i),writable:!0,enumerable:!0,configurable:!0});let a=this.#s();if(a.type==="EndObject")return t;if(a.type!=="ValueSeparator")throw new SyntaxError(Fo(a))}}#n(){let t=[];for(let r=!0;;r=!1){let o=this.#s();if((r||this.#a.allowTrailingComma)&&o.type==="EndArray")return t;t.push(this.#p(o));let n=this.#s();if(n.type==="EndArray")return t;if(n.type!=="ValueSeparator")throw new SyntaxError(Fo(n))}}#h(t){let r;try{r=aE(t.sourceText)}catch{throw new SyntaxError(Fo(t))}return Km(typeof r=="string"),r}#g(t){if(t.sourceText==="null")return null;if(t.sourceText==="true")return!0;if(t.sourceText==="false")return!1;let r;try{r=aE(t.sourceText)}catch{throw new SyntaxError(Fo(t))}return Km(typeof r=="number"),r}};function Fo({type:e,sourceText:t,position:r}){let o="";switch(e){case"BeginObject":o="{";break;case"EndObject":o="}";break;case"BeginArray":o="[";break;case"EndArray":o="]";break;case"NameSeparator":o=":";break;case"ValueSeparator":o=",";break;case"NullOrTrueOrFalseOrNumber":case"String":o=30<t.length?${t.slice(0,30)}...:t;break;default:throw new Error("unreachable")}returnUnexpected token ${o} in JSONC at position ${r}}function zc(e){if(e.protocol==="file:")return{path:os(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}}async function Xm(e){let t=await Deno.readTextFile(e),r=cE(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(Deno config at ${e} must be an object);if("imports"in r&&(typeof r.imports!="object"||r.imports===null||Array.isArray(r.imports)))throw new Error(Deno config at ${e} has invalid "imports" key);if("scopes"in r&&(typeof r.scopes!="object"||r.scopes===null||Array.isArray(r.scopes)))throw new Error(Deno config at ${e} has invalid "scopes" key);if("lock"in r&&typeof r.lock!="boolean"&&typeof r.lock!="string")throw new Error(Deno config at ${e} has invalid "lock" key);if("importMap"in r&&typeof r.importMap!="string")throw new Error(Deno config at ${e} has invalid "importMap" key);return r}function lE(e){if(e.imports!==void 0){let t=[];for(let[r,o]of Object.entries(e.imports))if(t.push([r,o]),!r.endsWith("/")&&o&&(o.startsWith("jsr:")||o.startsWith("npm:"))&&!e.imports[r+"/"]){let n=r+"/",s=o.slice(0,4)+"/"+o.slice(o[4]==="/"?5:4)+"/";t.push([n,s])}e.imports=Object.fromEntries(t)}}var OL=${xi}node_modules${xi},SL=${xi}node_modules;function Gc(e){return e.includes(OL)||e.endsWith(SL)}function Jm(e){return(e.namespace===""||e.namespace==="file")&&(Gc(e.resolveDir)||Gc(e.path)||Gc(e.importer))}function Qm(e={}){return{name:"deno-resolver",setup(t){let r=null,o=(t.initialOptions.external??[]).map(n=>new RegExp("^"+n.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*")+"$"));t.onStart(async function(){let s;if(e.importMapURL===void 0&&e.configPath!==void 0){let i=await Xm(e.configPath);if(i.imports!==void 0||i.scopes!==void 0){let a={imports:i.imports,scopes:i.scopes};lE(a),r=Vm(a,xn(e.configPath))}else i.importMap!==void 0&&(s=new URL(i.importMap,xn(e.configPath)).href)}else e.importMapURL!==void 0&&(s=e.importMapURL);if(s){let i=await fetch(s),a=await i.json();r=Vm(a,new URL(i.url))}}),t.onResolve({filter:/.*/},async function(s){if(Jm(s))return;let i;if(s.importer!==""){if(s.namespace==="")throw new Error("[assert] namespace is empty");i=new URL(${s.namespace}:${s.importer})}else if(s.resolveDir!=="")i=new URL(${xn(s.resolveDir).href}/);else return;let a;if(r!==null){let p=iE(s.path,r,new URL(i));a=new URL(p)}else a=new URL(s.path,i);for(let p of o)if(p.test(a.href))return{path:a.href,external:!0};let{path:c,namespace:l}=zc(a);return await t.resolve(c,{namespace:l,kind:s.kind})})}}}var nbe=new TextEncoder;var LL=[],NL=[],Zm="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";for(let e=0,t=Zm.length;e<t;++e)LL[e]=Zm[e],NL[Zm.charCodeAt(e)]=e;var Tbe=Deno.env.get("DENO_REGISTRY_URL")??"https://jsr.io";var $L=await Deno.permissions.query({name:"run"}).then(e=>e.state!=="granted")?"portable":"native";var pE=Qm;var uE=e=>!!(jL.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),jL=["i.gyazo.com","t.gyazo.com","scrapbox.io","api.openai.com","*.openai.azure.com","maps.googleapis.com","upload.gyazo.com","storage.googleapis.com","sentry.io"];var mE=e=>{if(e.protocol==="file:")return{path:os(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},ef=e=>e.namespace==="file"?xn(e.path):new URL(${e.namespace}:${e.path});var fE=(e,t)=>{let r=Hs(BL(e),()=>({name:"NotFoundError",message:"Source map URL is not found"}));if(O(r))return r;let{url:o,start:n,end:s}=S(r);return URL.canParse(o,t)?L({url:new URL(o,t),start:n,end:s}):M({name:"InvalidURLError",message:Invalid URL: ${o}})},BL=e=>{for(let t of e.matchAll(/\/([*/])[#@] *sourceMappingURL=/g)){let r=t.index+t[0].length,o=e.length,n=r;for(;n<o&&e.charCodeAt(n)>32;)n++;if(n!==r&&(t[1]==="/"||e.indexOf("*/",n)>0))return{url:e.slice(r,n),start:r,end:n}}};var HL=["base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx"],dE=e=>HL.includes(e),hE=e=>/^js|^ts|css$/.test(e),gE=e=>{let t=e.url,r=Dm(t);if(dE(r))return r;if(r==="mjs")return"js";let o=new URL(t);o.search="",o.hash="";let n=$m(o.href).slice(1);if(dE(n))return n;if(n==="mjs")return"js";let i=(e.headers.get("Content-Type")??"text/plain").split(";")[0]?.trim?.()??"text/plain";return WL(i)},WL=e=>{let t=e.split("/")[1]??"plain";if(/(?:^plain$|^xml|^svg|^x?html)/.test(t))return"text";if(t.startsWith("json"))return"json";switch(t){case"javascript":return"js";case"typescript":return"ts";case"css":return"css";default:return"text"}};function Vc(e,t){if(isNaN(e)||isNaN(t))throw new Error("Cannot compare against non-numbers");return e===t?0:e<t?-1:1}function bE(e=[],t=[]){return e.length&&!t.length?-1:!e.length&&t.length?1:0}function rf(e=[],t=[]){let r=Math.max(e.length,t.length);for(let o=0;o<r;o++){let n=e[o],s=t[o];if(n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(typeof n=="string"&&typeof s=="number")return 1;if(typeof n=="number"&&typeof s=="string"||n<s)return-1;if(n>s)return 1}return 0}var ns="0|[1-9]\\d*",qL="\\d*[a-zA-Z-][a-zA-Z0-9-]*",GL=(?<major>${ns})\\.(?<minor>${ns})\\.(?<patch>${ns}),yE=(?:${ns}|${qL}),EE=(?:-(?<prerelease>${yE}(?:\\.${yE})*)),xE="[0-9A-Za-z-]+",wE=(?:\\+(?<buildmetadata>${xE}(?:\\.${xE})*)),RE=v?${GL}${EE}?${wE}?,vE=new RegExp(^${RE}$),kE="(?:<|>)?=?",zL="x|X|\\*",tf=${ns}|${zL},Kc=v=\\s*(?<major>${tf})(?:\\.(?<minor>${tf})(?:\\.(?<patch>${tf})${EE}?${wE}?)?)?,TE=new RegExp(^(?<operator>~>?|\\^|${kE})\\s*${Kc}$),_E=new RegExp(^(?<operator>${kE})\\s*(${RE})$|^$);function of(e){return typeof e=="number"&&!Number.isNaN(e)&&(!Number.isFinite(e)||0<=e&&e<=Number.MAX_SAFE_INTEGER)}var nf=256;var VL=new RegExp(^${ns}$);function sr(e){return e.split(".").filter(Boolean).map(t=>{if(VL.test(t)){let r=Number(t);if(of(r))return r}return t})}function lo(e){return e.split(".").filter(Boolean)}function Yc(e,t){let r=Number(e);if(!of(r))throw new TypeError(t);return r}function bn(e){return Number.isNaN(e.major)&&Number.isNaN(e.minor)&&Number.isNaN(e.patch)&&(e.prerelease===void 0||e.prerelease.length===0)&&(e.build===void 0||e.build.length===0)}function xr(e,t){return e===t?0:Vc(e.major,t.major)||Vc(e.minor,t.minor)||Vc(e.patch,t.patch)||bE(e.prerelease,t.prerelease)||rf(e.prerelease,t.prerelease)}function sf(e){return e.toFixed(0)}function En(e){let t=sf(e.major),r=sf(e.minor),o=sf(e.patch),n=e.prerelease?.join(".")??"",s=e.build?.join(".")??"";return[[${t}.${r}.${o},n].filter(c=>c).join("-"),s].filter(c=>c).join("+")}function KL(e,t){if(bn(t))return!0;let r=xr(e,t);switch(t.operator){case"=":case void 0:return r===0;case"!=":return r!==0;case">":return r>0;case"<":return r<0;case">=":return r>=0;case"<=":return r<=0}}function Xc(e,t){for(let r of t)if(!KL(e,r))return!1;if(!e.prerelease?.length)return!0;for(let r of t){if(bn(r)||!r.prerelease?.length)continue;let{major:o,minor:n,patch:s}=r;if(e.major===o&&e.minor===n&&e.patch===s)return!0}return!1}function Jc(e,t){return t.some(r=>Xc(e,r))}var Qc={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},ss={operator:void 0,...Qc};function PE(e,t){return xr(e,t)>0}function bi(e,t){let r;for(let o of e)Jc(o,t)&&(r=r&&PE(r,o)?r:o);return r}function YL(e){let r=e.match(_E)?.groups;if(!r)return null;let{operator:o}=r;return{operator:o||void 0,...Qc}}function Pe(e){return!e||e.toLowerCase()==="x"||e==="*"}function XL(e){if(!Pe(e.major))return Pe(e.minor)?{operator:">=",major:+e.major,minor:0,patch:0,prerelease:[],build:[]}:Pe(e.patch)?{operator:">=",major:+e.major,minor:+e.minor,patch:0,prerelease:[],build:[]}:{operator:">=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:e.prerelease?sr(e.prerelease):[],build:[]}}function JL(e){if(!Pe(e.major))return Pe(e.minor)?{operator:"<",major:+e.major+1,minor:0,patch:0,prerelease:[],build:[]}:Pe(e.patch)?{operator:"<",major:+e.major,minor:+e.minor+1,patch:0,prerelease:[],build:[]}:e.prerelease?{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:sr(e.prerelease),build:[]}:{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:[],build:[]}}function QL(e){let t=e.match(new RegExp(^${Kc})),r=t?.groups;if(!r)return null;let o=t[0].length,n=e.slice(o).match(/^\s+-\s+/);if(!n)return null;let s=n[0].length,a=e.slice(o+s).match(new RegExp(^${Kc}\\s*$))?.groups,c=XL(r),l=JL(a);return[c,l].filter(Boolean)}function ZL(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ss];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return n===0?[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];let a=sr(e.prerelease??"");return n===0?s===0?[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s,patch:i+1}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n+1,minor:0,patch:0}]}function eN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ss];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=sr(e.prerelease??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]}function tN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return o?[{operator:"<",major:n,minor:0,patch:0}]:[{operator:"<",major:n,minor:0,patch:0}];if(o)return[{operator:"<",major:n,minor:s,patch:0}];let a=sr(e.prerelease??""),c=lo(e.build??"");return[{operator:"<",major:n,minor:s,patch:i,prerelease:a,build:c}]}function rN(e){let t=Pe(e.minor),r=Pe(e.patch),o=+e.major,n=+e.minor,s=+e.patch;if(t)return[{operator:"<",major:o+1,minor:0,patch:0}];if(r)return[{operator:"<",major:o,minor:n+1,patch:0}];let i=sr(e.prerelease??""),a=lo(e.build??"");return[{operator:"<=",major:o,minor:n,patch:s,prerelease:i,build:a}]}function oN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return[{operator:">=",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s+1,patch:0}];let a=sr(e.prerelease??""),c=lo(e.build??"");return[{operator:">",major:n,minor:s,patch:i,prerelease:a,build:c}]}function nN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ss];if(r)return[{operator:">=",major:n,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0}];let a=sr(e.prerelease??""),c=lo(e.build??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a,build:c}]}function sN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ss];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=sr(e.prerelease??""),c=lo(e.build??"");return[{operator:e.operator==="="?"=":void 0,major:n,minor:s,patch:i,prerelease:a,build:c}]}function iN(e){let t=e.match(TE)?.groups;if(!t)return YL(e);switch(t.operator){case"^":return ZL(t);case"~":case"~>":return eN(t);case"<":return tN(t);case"<=":return rN(t);case">":return oN(t);case">=":return nN(t);default:return sN(t)}}function aN(e){return e.split(/\s+/).flatMap(iN)}function OE(e){let t=e.replaceAll(/(?<=[<>=~^])(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>QL(r)||aN(r));if(t.some(r=>r.includes(null)))throw new TypeError(Cannot parse version range: range "${e}" is invalid);return t}function af(e){if(typeof e!="string")throw new TypeError(Cannot parse version as version must be a string: received ${typeof e});if(e.length>nf)throw new TypeError(Cannot parse version as version length is too long: length is ${e.length}, max length is ${nf});e=e.trim();let t=e.match(vE)?.groups;if(!t)throw new TypeError(Cannot parse version: ${e});let r=Yc(t.major,Cannot parse version ${e}: invalid major version),o=Yc(t.minor,Cannot parse version ${e}: invalid minor version),n=Yc(t.patch,Cannot parse version ${e}: invalid patch version),s=t.prerelease?sr(t.prerelease):[],i=t.buildmetadata?lo(t.buildmetadata):[];return{major:r,minor:o,patch:n,prerelease:s,build:i}}function cf(e){try{return OE(e)}catch{return}}function lf(e){try{return af(e)}catch{return}}var Ei={operator:void 0,major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]};var Do=async e=>{try{let t=await fetch(e);return t.ok?L([t,!1]):M({name:"HTTPError",message:${t.status} ${t.statusText},response:t})}catch(t){if(t instanceof TypeError)return M({name:"NetworkError",message:t.message,request:e});if(t instanceof DOMException)return M({name:"AbortError",message:t.message,request:e});throw t}};var pf="https://jsr.io",SE=async(e,t)=>{let r=await(t?.fetch??Do)(new Request(${t?.endpoint??pf}/${e}/meta.json),t?.cacheFirst);return ae(r,([o])=>o.json())};var LE=async(e,t,r)=>{let o=await(r?.fetch??Do)(new Request(${r?.endpoint??pf}/${e}/${t}_meta.json),r?.cacheFirst);return ae(o,([n])=>n.json())};var NE=async(e,t)=>{let r=await(t?.fetch??Do)(new Request(${t?.endpoint??"https://registry.npmjs.org"}/${e}),t?.cacheFirst);return ae(r,([o])=>o.json())};var IE=(e,t)=>({name:"InvalidPackageVersionError",message:No version of ${e.name} satisfies "${e.tag??"*"}" (available: ${t.slice(0,10).join(", ")}${t.length>10?, ... (${t.length-10} more versions):""}),packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableVersions:t}),Zc=(e,t)=>({name:"InvalidEntryPointError",message:${e.entryPoint} is not a valid entry point for ${e.name}@${e.tag??"*"} (available: ${t.join(", ")}),packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableEntryPoints:t}),AE=async(e,t)=>{if(t?.resolvedVersions){let c=new Map(t.resolvedVersions.get(e.name)??[]),l=bi([...c.keys()],e.range);if(l){let u=c.get(l)??wi,p=u[e.entryPoint];return typeof p!="string"&&console.log(p),p?L(ME(e.name,En(l),p)):M(Zc(e,Object.keys(u)))}}let r=await NE(e.name,t);if(O(r))return r;let o=S(r),n=new Map(Object.entries(o.versions).flatMap(([c,{exports:l}])=>{let u=lf(c);return u?[[u,l??wi]]:[]})),s=bi([...n.keys()],e.range);if(!s)return M(IE(e,Object.keys(o.versions)));let i={...wi};for(let c of Object.keys(n.get(s)??wi))i[c]=c;let a=i[e.entryPoint];return a?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[s,i]]),L(ME(e.name,En(s),a))):M(Zc(e,Object.keys(i)))},ME=(e,t,r)=>new URL(r,https://esm.sh/${e}@${t}/),FE=async(e,t)=>{if(t?.resolvedVersions){let a=new Map(t.resolvedVersions.get(e.name)??[]),c=bi([...a.keys()],e.range);if(c){let l=a.get(c)??wi,u=l[e.entryPoint];return u?L(CE(e.name,En(c),u)):M(Zc(e,Object.keys(l)))}}let r=await cN(e,t);if(O(r))return r;let o=S(r),n=await LE(e.name,En(o),t);if(O(n))return n;let s=S(n).exports,i=s[e.entryPoint];return i?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[o,s]]),L(CE(e.name,En(o),i))):M(Zc(e,Object.keys(S(n).exports)))},CE=(e,t,r)=>new URL(r,https://jsr.io/${e}/${t}/),cN=async(e,t)=>{let r=await SE(e.name,t);if(O(r))return r;let o=S(r),n=Object.keys(o.versions).flatMap(i=>{let a=lf(i);return a?[a]:[]}),s=bi(n,e.range);return s?L(s):M(IE(e,Object.keys(o.versions)))},wi={".":"./"};var lN=e=>({name:"OnlyScopeProvidedError",specifier:e}),DE=e=>({name:"PackageNotFoundError",specifier:e}),UE=e=>{if(e.protocol!=="npm:")return M({name:"NotNpmProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0,o,n;if(t[r]==="@"){let p=t.indexOf("/",r);if(p===-1)return M(lN(e));o=t.indexOf("/",p+1),n=t.indexOf("@",p+1)}else o=t.indexOf("/",r),n=t.indexOf("@",r);if(o===-1&&(o=t.length),n===-1&&(n=t.length),n=Math.min(n,o),r===n)return M(DE(e));let s=t.slice(r,n),i=decodeURIComponent(t.slice(n+1,o)),a=i?cf(i)??[[Ei]]:[[Ei]],c=t.slice(o+1),l=c?./${c}:".",u={name:s,range:a,entryPoint:l};return i&&(u.tag=i),L(u)},$E=e=>{if(e.protocol!=="jsr:")return M({name:"NotJsrProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0;if(t[r]!=="@")return M({name:"ScopeNotFoundError",specifier:e});let o=t.indexOf("/",r);if(o===-1)return M(DE(e));let n=t.indexOf("/",o+1),s=t.indexOf("@",o+1);n===-1&&(n=t.length),s===-1&&(s=t.length),s=Math.min(s,n);let i=t.slice(r,s),a=decodeURIComponent(t.slice(s+1,n)),c=a?cf(a)??[[Ei]]:[[Ei]],l=t.slice(n+1),u=l?./${l}:".",p={name:i,range:c,entryPoint:u};return a&&(p.tag=a),L(p)};var jE=e=>new Promise((t,r)=>{let o=new FileReader;o.addEventListener("load",()=>{let n=o.result,s=n.indexOf(";");n.startsWith("; charset=utf-8",s)?t(${n.slice(0,s)}${n.slice(s+15)}):t(n)}),o.addEventListener("error",()=>r(o.error)),o.readAsDataURL(e)});var WE=e=>{let t=new Map,r=async o=>{let n=o.namespace==="npm",s=(n?UE:$E)(ef(o));if(O(s)){let a=Z(s);return{errors:[{text:a.name,detail:a}]}}let i=await(n?AE:FE)(S(s),{resolvedVersions:t,...e});if(O(i)){let a=Z(i);return{errors:[{text:${a.name} ${a.message},detail:a}]}}return mE(S(i))};return{name:"remote-loader",setup({onLoad:o,onResolve:n,initialOptions:s}){for(let i of[...BE,...HE])n({filter:/.*/,namespace:i.slice(0,-1)},pN);n({filter:/.*/,namespace:"npm"},r),n({filter:/.*/,namespace:"jsr"},r);for(let i of BE)o({filter:/.*/,namespace:i.slice(0,-1)},a=>uN(ef(a),{...e,sourcemap:s.sourcemap!==!1&&s.sourcemap!==void 0}));for(let i of HE)o({filter:/.*/,namespace:i.slice(0,-1)},()=>{throw new Error(${i} import is not supported yet.)})}}},pN=e=>({path:e.path,namespace:e.namespace}),BE=["http:","https:","data:"],HE=["node:"],uN=async(e,t)=>{let r=t.reload?t.reload===!0?!1:!t.reload.some(l=>l.test(e)):!0,o=t.fetch??Do,n=await o(new Request(e),r);if(O(n))return{errors:[{text:${Z(n).message} Failed to fetch ${e},detail:Z(n)}]};let[s,i]=S(n),a=gE(s);t.onProgress?.({path:e,done:s.clone().blob().then(l=>({size:l.size,loader:a,isCache:i}))});let c=await s.blob();if(t.sourcemap&&hE(a)){let l=await c.text(),u=fE(l,e);if(K(u)){let{url:p,start:f,end:m}=S(u);if(p.protocol!=="data:"){let h=await o(new Request(p),r);if(O(h))return{contents:l,loader:a,warnings:[{text:${Z(h).message} Failed to fetch the source map URL,notes:[{text:Source map URL: ${p}},{text:Original URL: ${e}}],detail:Z(h)}]};let g=await S(h)[0].blob().then(jE);return{contents:l.slice(0,f)+g+l.slice(m),loader:a}}}}return{contents:new Uint8Array(await c.arrayBuffer()),loader:a}};var ki=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(e,t,r,o,n,s){this.type=e,this.name=t,this.prefix=r,this.value=o,this.suffix=n,this.modifier=s}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},mN=/[$_\p{ID_Start}]/u,fN=/[$_\u200C\u200D\p{ID_Continue}]/u,mf=".*";function dN(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function zE(e,t=!1){let r=[],o=0;for(;o<e.length;){let n=e[o],s=function(i){if(!t)throw new TypeError(i);r.push({type:"INVALID_CHAR",index:o,value:e[o++]})};if(n==="*"){r.push({type:"ASTERISK",index:o,value:e[o++]});continue}if(n==="+"||n==="?"){r.push({type:"OTHER_MODIFIER",index:o,value:e[o++]});continue}if(n==="\\"){r.push({type:"ESCAPED_CHAR",index:o++,value:e[o++]});continue}if(n==="{"){r.push({type:"OPEN",index:o,value:e[o++]});continue}if(n==="}"){r.push({type:"CLOSE",index:o,value:e[o++]});continue}if(n===":"){let i="",a=o+1;for(;a<e.length;){let c=e.substr(a,1);if(a===o+1&&mN.test(c)||a!==o+1&&fN.test(c)){i+=e[a++];continue}break}if(!i){s(Missing parameter name at ${o});continue}r.push({type:"NAME",index:o,value:i}),o=a;continue}if(n==="("){let i=1,a="",c=o+1,l=!1;if(e[c]==="?"){s(Pattern cannot start with "?" at ${c});continue}for(;c<e.length;){if(!dN(e[c],!1)){s(Invalid character '${ec}' at ${c}.),l=!0;break}if(e[c]==="\\"){a+=e[c++]+e[c++];continue}if(e[c]===")"){if(i--,i===0){c++;break}}else if(e[c]==="("&&(i++,e[c+1]!=="?")){s(Capturing groups are not allowed at ${c}),l=!0;break}a+=e[c++]}if(l)continue;if(i){s(Unbalanced pattern at ${o});continue}if(!a){s(Missing pattern at ${o});continue}r.push({type:"REGEX",index:o,value:a}),o=c;continue}r.push({type:"CHAR",index:o,value:e[o++]})}return r.push({type:"END",index:o,value:""}),r}function VE(e,t={}){let r=zE(e);t.delimiter??="/#?",t.prefixes??="./";let o=^${br(t.delimiter)}+?,n=[],s=0,i=0,a="",c=new Set,l=R=>{if(i<r.length&&r[i].type===R)return r[i++].value},u=()=>l("OTHER_MODIFIER")??l("ASTERISK"),p=R=>{let b=l(R);if(b!==void 0)return b;let{type:E,index:T}=r[i];throw new TypeError(Unexpected ${E} at ${T}, expected ${R})},f=()=>{let R="",b;for(;b=l("CHAR")??l("ESCAPED_CHAR");)R+=b;return R},m=R=>R,h=t.encodePart||m,g="",y=R=>{g+=R},x=()=>{g.length&&(n.push(new ki(3,"","",h(g),"",3)),g="")},w=(R,b,E,T,I)=>{let F=3;switch(I){case"?":F=1;break;case"*":F=0;break;case"+":F=2;break}if(!b&&!E&&F===3){y(R);return}if(x(),!b&&!E){if(!R)return;n.push(new ki(3,"","",h(R),"",F));return}let A;E?E==="*"?A=mf:A=E:A=o;let N=2;A===o?(N=1,A=""):A===mf&&(N=0,A="");let P;if(b?P=b:E&&(P=s++),c.has(P))throw new TypeError(Duplicate name '${P}'.);c.add(P),n.push(new ki(N,P,h(R),A,h(T),F))};for(;i<r.length;){let R=l("CHAR"),b=l("NAME"),E=l("REGEX");if(!b&&!E&&(E=l("ASTERISK")),b||E){let I=R??"";t.prefixes.indexOf(I)===-1&&(y(I),I=""),x();let F=u();w(I,b,E,"",F);continue}let T=R??l("ESCAPED_CHAR");if(T){y(T);continue}if(l("OPEN")){let I=f(),F=l("NAME"),A=l("REGEX");!F&&!A&&(A=l("ASTERISK"));let N=f();p("CLOSE");let P=u();w(I,F,A,N,P);continue}x(),p("END")}return n}function br(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function qE(e){return e&&e.ignoreCase?"ui":"u"}function hN(e,t,r){return KE(VE(e,r),t,r)}function is(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function KE(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let o=r.start?"^":"";for(let a of e){if(a.type===3){a.modifier===3?o+=br(a.value):o+=(?:${br(a.value)})${is(a.modifier)};continue}t&&t.push(a.name);let c=^${br(r.delimiter)}+?,l=a.value;if(a.type===1?l=c:a.type===0&&(l=mf),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?o+=(${l})${is(a.modifier)}:o+=((?:${l})${is(a.modifier)});continue}if(a.modifier===3||a.modifier===1){o+=(?:${br(a.prefix)}(${l})${br(a.suffix)}),o+=is(a.modifier);continue}o+=(?:${br(a.prefix)},o+=((?:${l})(?:,o+=br(a.suffix),o+=br(a.prefix),o+=(?:${l}))*)${br(a.suffix)}),a.modifier===0&&(o+="?")}let n=${br(r.endsWith)}|$,s=${br(r.delimiter)};if(r.end)return r.strict||(o+=${s}?),r.endsWith.length?o+=(?=${n}):o+="$",new RegExp(o,qE(r));r.strict||(o+=(?:${s}(?=${n}))?);let i=!1;if(e.length){let a=e[e.length-1];a.type===3&&a.modifier===3&&(i=r.delimiter.indexOf(a)>-1)}return i||(o+=(?=${s}|${n})),new RegExp(o,qE(r))}var $o={delimiter:"",prefixes:"",sensitive:!0,strict:!0},gN={delimiter:".",prefixes:"",sensitive:!0,strict:!0},yN={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function xN(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function YE(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function bN(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function XE(e){return!e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var JE=["ftp","file","http","https","ws","wss"];function QE(e){if(!e)return!0;for(let t of JE)if(e.test(t))return!0;return!1}function EN(e,t){if(e=YE(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function wN(e,t){if(e=YE(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function RN(e,t){return t||e===""?e:XE(e)?tw(e):ew(e)}function vN(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function kN(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function TN(e,t,r){if(r||e==="")return e;if(t&&!JE.includes(t))return new URL(${t}:${e}).pathname;let o=e[0]=="/";return e=new URL(o?e:"/-"+e,"https://example.com").pathname,o||(e=e.substring(2,e.length)),e}function _N(e,t,r){return ZE(t)===e&&(e=""),r||e===""?e:rw(e)}function PN(e,t){return e=bN(e,":"),t||e===""?e:ff(e)}function ZE(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function ff(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(Invalid protocol '${e}'.)}function ON(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function SN(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function ew(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(Invalid hostname '${e}');let t=new URL("https://example.com");return t.hostname=e,t.hostname}function tw(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(Invalid IPv6 hostname '${e}');return e.toLowerCase()}function rw(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(Invalid port '${e}'.)}function LN(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function NN(e){return e===""?e:new URL(data:${e}).pathname}function MN(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function CN(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var IN=class{#o;#r=[];#t={};#e=0;#i=1;#a=0;#s=0;#m=0;#p=0;#f=!1;constructor(e){this.#o=e}get result(){return this.#t}parse(){for(this.#r=zE(this.#o,!0);this.#e<this.#r.length;this.#e+=this.#i){if(this.#i=1,this.#r[this.#e].type==="END"){if(this.#s===0){this.#g(),this.#u()?this.#n(9,1):this.#d()?this.#n(8,1):this.#n(7,0);continue}else if(this.#s===2){this.#y(5);continue}this.#n(10,0);break}if(this.#m>0)if(this.#_())this.#m-=1;else continue;if(this.#T()){this.#m+=1;continue}switch(this.#s){case 0:this.#w()&&this.#y(1);break;case 1:if(this.#w()){this.#S();let e=7,t=1;this.#R()?(e=2,t=3):this.#f&&(e=2),this.#n(e,t)}break;case 2:this.#b()?this.#y(3):(this.#E()||this.#d()||this.#u())&&this.#y(5);break;case 3:this.#v()?this.#n(4,1):this.#b()&&this.#n(5,1);break;case 4:this.#b()&&this.#n(5,1);break;case 5:this.#P()?this.#p+=1:this.#O()&&(this.#p-=1),this.#k()&&!this.#p?this.#n(6,1):this.#E()?this.#n(7,0):this.#d()?this.#n(8,1):this.#u()&&this.#n(9,1);break;case 6:this.#E()?this.#n(7,0):this.#d()?this.#n(8,1):this.#u()&&this.#n(9,1);break;case 7:this.#d()?this.#n(8,1):this.#u()&&this.#n(9,1);break;case 8:this.#u()&&this.#n(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="")}#n(e,t){switch(this.#s){case 0:break;case 1:this.#t.protocol=this.#l();break;case 2:break;case 3:this.#t.username=this.#l();break;case 4:this.#t.password=this.#l();break;case 5:this.#t.hostname=this.#l();break;case 6:this.#t.port=this.#l();break;case 7:this.#t.pathname=this.#l();break;case 8:this.#t.search=this.#l();break;case 9:this.#t.hash=this.#l();break;case 10:break}this.#s!==0&&e!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(e)&&(this.#t.pathname??=this.#f?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&e===9&&(this.#t.search??="")),this.#h(e,t)}#h(e,t){this.#s=e,this.#a=this.#e+t,this.#e+=t,this.#i=0}#g(){this.#e=this.#a,this.#i=0}#y(e){this.#g(),this.#s=e}#x(e){return e<0&&(e=this.#r.length-e),e<this.#r.length?this.#r[e]:this.#r[this.#r.length-1]}#c(e,t){let r=this.#x(e);return r.value===t&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#w(){return this.#c(this.#e,":")}#R(){return this.#c(this.#e+1,"/")&&this.#c(this.#e+2,"/")}#b(){return this.#c(this.#e,"@")}#v(){return this.#c(this.#e,":")}#k(){return this.#c(this.#e,":")}#E(){return this.#c(this.#e,"/")}#d(){if(this.#c(this.#e,"?"))return!0;if(this.#r[this.#e].value!=="?")return!1;let e=this.#x(this.#e-1);return e.type!=="NAME"&&e.type!=="REGEX"&&e.type!=="CLOSE"&&e.type!=="ASTERISK"}#u(){return this.#c(this.#e,"#")}#T(){return this.#r[this.#e].type=="OPEN"}#_(){return this.#r[this.#e].type=="CLOSE"}#P(){return this.#c(this.#e,"[")}#O(){return this.#c(this.#e,"]")}#l(){let e=this.#r[this.#e],t=this.#x(this.#a).index;return this.#o.substring(t,e.index)}#S(){let e={};Object.assign(e,$o),e.encodePart=ff;let t=hN(this.#l(),void 0,e);this.#f=QE(t)}},uf=["protocol","username","password","hostname","port","pathname","search","hash"],Uo="*";function GE(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function po(e,t){return t?vi(e):e}function Ri(e,t,r){let o;if(typeof t.baseURL=="string")try{o=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=po(o.protocol.substring(0,o.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=po(o.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=po(o.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=po(o.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=po(o.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=po(o.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=po(o.search.substring(1,o.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=po(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(invalid baseURL '${t.baseURL}'.)}if(typeof t.protocol=="string"&&(e.protocol=PN(t.protocol,r)),typeof t.username=="string"&&(e.username=kN(t.username,r)),typeof t.password=="string"&&(e.password=vN(t.password,r)),typeof t.hostname=="string"&&(e.hostname=RN(t.hostname,r)),typeof t.port=="string"&&(e.port=_N(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,o&&!xN(e.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(e.pathname=po(o.pathname.substring(0,n+1),r)+e.pathname)}e.pathname=TN(e.pathname,e.protocol,r)}return typeof t.search=="string"&&(e.search=wN(t.search,r)),typeof t.hash=="string"&&(e.hash=EN(t.hash,r)),e}function vi(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function AN(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function FN(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",o=^${AN(t.delimiter)}+?,n=/[$_\u200C\u200D\p{ID_Continue}]/u,s="";for(let i=0;i<e.length;++i){let a=e[i];if(a.type===3){if(a.modifier===3){s+=vi(a.value);continue}s+={${vi(a.value)}}${is(a.modifier)};continue}let c=a.hasCustomName(),l=!!a.suffix.length||!!a.prefix.length&&(a.prefix.length!==1||!t.prefixes.includes(a.prefix)),u=i>0?e[i-1]:null,p=i<e.length-1?e[i+1]:null;if(!l&&c&&a.type===1&&a.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let f=p.value.length>0?p.value[0]:"";l=n.test(f)}else l=!p.hasCustomName();if(!l&&!a.prefix.length&&u&&u.type===3){let f=u.value[u.value.length-1];l=t.prefixes.includes(f)}l&&(s+="{"),s+=vi(a.prefix),c&&(s+=:${a.name}),a.type===2?s+=(${a.value}):a.type===1?c||(s+=(${o})):a.type===0&&(!c&&(!u||u.type===3||u.modifier!==3||l||a.prefix!=="")?s+="*":s+=(${r})),a.type===1&&c&&a.suffix.length&&n.test(a.suffix[0])&&(s+="\\"),s+=vi(a.suffix),l&&(s+="}"),a.modifier!==3&&(s+=is(a.modifier))}return s}var ow=class{#o;#r={};#t={};#e={};#i={};#a=!1;constructor(e={},t,r){try{let o;if(typeof t=="string"?o=t:r=t,typeof e=="string"){let a=new IN(e);if(a.parse(),e=a.result,o===void 0&&typeof e.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");e.baseURL=o}else{if(!e||typeof e!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let n={ignoreCase:r.ignoreCase===!0},s={pathname:Uo,protocol:Uo,username:Uo,password:Uo,hostname:Uo,port:Uo,search:Uo,hash:Uo};this.#o=Ri(s,e,!0),ZE(this.#o.protocol)===this.#o.port&&(this.#o.port="");let i;for(i of uf){if(!(i in this.#o))continue;let a={},c=this.#o[i];switch(this.#t[i]=[],i){case"protocol":Object.assign(a,$o),a.encodePart=ff;break;case"username":Object.assign(a,$o),a.encodePart=ON;break;case"password":Object.assign(a,$o),a.encodePart=SN;break;case"hostname":Object.assign(a,gN),XE(c)?a.encodePart=tw:a.encodePart=ew;break;case"port":Object.assign(a,$o),a.encodePart=rw;break;case"pathname":QE(this.#r.protocol)?(Object.assign(a,yN,n),a.encodePart=LN):(Object.assign(a,$o,n),a.encodePart=NN);break;case"search":Object.assign(a,$o,n),a.encodePart=MN;break;case"hash":Object.assign(a,$o,n),a.encodePart=CN;break}try{this.#i[i]=VE(c,a),this.#r[i]=KE(this.#i[i],this.#t[i],a),this.#e[i]=FN(this.#i[i],a),this.#a=this.#a||this.#i[i].some(l=>l.type===2)}catch{throw new TypeError(invalid ${i} pattern '${this.#oi}'.)}}}catch(o){throw new TypeError(Failed to construct 'URLPattern': ${o.message})}}test(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return!1;try{typeof e=="object"?r=Ri(r,e,!1):r=Ri(r,GE(e,t),!1)}catch{return!1}let o;for(o of uf)if(!this.#r[o].exec(r[o]))return!1;return!0}exec(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return;try{typeof e=="object"?r=Ri(r,e,!1):r=Ri(r,GE(e,t),!1)}catch{return null}let o={};t?o.inputs=[e,t]:o.inputs=[e];let n;for(n of uf){let s=this.#r[n].exec(r[n]);if(!s)return null;let i={};for(let[a,c]of this.#t[n].entries())if(typeof c=="string"||typeof c=="number"){let l=s[a+1];i[c]=l}o[n]={input:r[n]??"",groups:i}}return o}static compareComponent(e,t,r){let o=(a,c)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(a[l]<c[l])return-1;if(a[l]!==c[l])return 1}return 0},n=new ki(3,"","","","",3),s=new ki(0,"","","","",3),i=(a,c)=>{let l=0;for(;l<Math.min(a.length,c.length);++l){let u=o(a[l],c[l]);if(u)return u}return a.length===c.length?0:o(a[l]??n,c[l]??n)};return!t.#e[e]&&!r.#e[e]?0:t.#e[e]&&!r.#e[e]?i(t.#i[e],[s]):!t.#e[e]&&r.#e[e]?i([s],r.#i[e]):i(t.#i[e],r.#i[e])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#a}};globalThis.URLPattern||(globalThis.URLPattern=ow);var nw,sw=async(e,t)=>(nw??=Dc({wasm:e,worker:t}),await nw,async r=>{let{outputFiles:o}=await Ac({entryPoints:[r],format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[pE(),WE({fetch:DN,reload:[new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"})]})],write:!1});return{contents:o[0].text}}),DN=async(e,t)=>{let r=uE(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let o=await df(e);if(o)return o}try{let o=await r(e);return o.ok?(r===GM_fetch&&!e.url.startsWith("data:")&&await Ka(e,o),L([o,!1])):await df(e)??M({name:"HTTPError",message:${o.status} ${o.statusText},response:o})}catch(o){let n=await df(e);if(n)return n;if(o instanceof TypeError)return M({name:"NetworkError",message:o.message,request:e});if(o instanceof DOMException)return M({name:"AbortError",message:o.message,request:e});throw o}},df=async e=>{if(e.url.startsWith("data:"))return;let t=await _o(e);if(t)return t.url||Object.defineProperty(t,"url",{value:e.url}),L([t,!0])};var iw=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e);var aw=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},cw=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},lw=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},pw=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var uw=()=>{let e;return{show:(o,{x:n,y:s})=>{e=UN(),e.append($N(o)),e.style.visibility="hidden",document.body.append(e);let{height:i}=e.getBoundingClientRect();e.style.top=${s-i}px,e.style.left=${n}px,e.style.removeProperty("visibility")},hide:async()=>{e?.classList?.remove?.("in"),await new Promise(o=>setTimeout(o,150)),e?.remove?.()}}},UN=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},$N=e=>{let t=document.createElement("pre");return t.classList.add("tooltip-inner"),t.style.textAlign="unset",t.style.maxWidth="70vw",t.style.margin="unset",t.innerText=e,t};var mw=()=>{let e=document.createElement("a");e.classList.add("tool-btn"),e.type="button",e.setAttribute("aria-haspopup","true");let t=!1,{show:r,hide:o}=uw();return{component:e,setStatus:async(s,i)=>{switch(e.textContent="",await o(),s){case"loading":e.append(lw());break;case"pass":e.append(aw());break;case"fail":e.append(cw());break;case"none":break}i!==void 0&&s!=="none"?(e.style.removeProperty("pointer-events"),e.onclick=async()=>{if(t)await o();else{let{top:a,left:c}=e.getBoundingClientRect();r(i,{y:a+globalThis.scrollY,x:c})}t=!t}):e.style.pointerEvents="none"}}};var fw=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(pw()),t.addEventListener("click",e),t};var dw=e=>{let{component:t,setStatus:r}=mw(),o=document.createElement("div");return o.style.position="absolute",o.style.left="-2em",o.style.zIndex="1",o.style.display="flex",o.style.flexFlow="column",o.append(fw(e),t),{menu:o,setStatus:r}};function hw(e){return new Promise(t=>setTimeout(t,e))}function gw(e,t){let{trailing:r=!1,interval:o=0}=t??{},n,s=!1,i=l=>{n?.resolve?.({executed:!1}),n=l},a=()=>{let{...l}=n;return n=void 0,l},c=async()=>{if(s||!n)return;s=!0,o>0&&await hw(o);let{parameters:l,resolve:u,reject:p}=a();try{let f=await e(...l);s=!1,u({result:f,executed:!0})}catch(f){s=!1,p(f)}finally{r?await c():(i(),await Promise.resolve())}};return(...l)=>new Promise((u,p)=>{i({parameters:l,resolve:u,reject:p}),c()})}var yw,xw=async(e,t)=>{let r=[],n=gw(async()=>{r.forEach(({menu:i,setStatus:a})=>{a("none"),i.remove()});let s=Lb(scrapbox.Project.name,scrapbox.Page.title??"",Dt());for(let i of s){let a=i.lang.toLowerCase();if(iw(a))for(let c of i.startIds){let l=document.getElementById(L${c}),{menu:u,setStatus:p}=dw(async()=>{await p("loading");try{yw??=await sw(e,t);let{contents:f}=await yw(i.path);console.debug("execute:",f),await Function(return (async()=>{${f}})())(),await p("pass")}catch(f){console.error(f),await p("fail",${f})}});r.push({menu:u,setStatus:p}),l?.insertBefore?.(u,l?.firstElementChild)}}await Promise.resolve()},{interval:100,trailing:!0});return await n(),scrapbox.addListener("lines:changed",n),()=>{scrapbox.removeListener("lines:changed",n),r.forEach(({menu:s,setStatus:i})=>{i("none"),s.remove()})}};function BN(e,t){for(var r in t)e[r]=t[r];return e}function bw(e,t){for(var r in e)if(r!=="__source"&&!(r in t))return!0;for(var o in t)if(o!=="__source"&&e[o]!==t[o])return!0;return!1}function tl(e,t){var r=t(),o=Q({t:{__:r,u:t}}),n=o[0].t,s=o[1];return Aa(function(){n.__=r,n.u=t,hf(n)&&s({t:n})},[e,r,t]),te(function(){return hf(n)&&s({t:n}),e(function(){hf(n)&&s({t:n})})},[e]),r}function hf(e){try{return!((t=e.__)===(r=e.u())&&(t!==0||1/t==1/r)||t!=t&&r!=r)}catch{return!0}var t,r}function Ew(e,t){this.props=e,this.context=t}(Ew.prototype=new vr).isPureReactComponent=!0,Ew.prototype.shouldComponentUpdate=function(e,t){return bw(this.props,e)||bw(this.state,t)};var ww=re.__b;re.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),ww&&ww(e)};var ike=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;var HN=re.__e;re.__e=function(e,t,r,o){if(e.then){for(var n,s=t;s=s.__;)if((n=s.__c)&&n.__c)return t.__e==null&&(t.__e=r.__e,t.__k=r.__k),n.__c(e,t)}HN(e,t,r,o)};var Rw=re.unmount;function Ow(e,t,r){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(o){typeof o.__c=="function"&&o.__c()}),e.__c.__H=null),(e=BN({},e)).__c!=null&&(e.__c.__P===r&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(o){return Ow(o,t,r)})),e}function Sw(e,t,r){return e&&r&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(o){return Sw(o,t,r)}),e.__c&&e.__c.__P===t&&(e.__e&&r.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=r)),e}function gf(){this.__u=0,this.o=null,this.__b=null}function Lw(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function el(){this.i=null,this.l=null}re.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Rw&&Rw(e)},(gf.prototype=new vr).__c=function(e,t){var r=t.__c,o=this;o.o==null&&(o.o=[]),o.o.push(r);var n=Lw(o.__v),s=!1,i=function(){s||o.__z||(s=!0,r.__R=null,n?n(c):c())};r.__R=i;var a=r.__P;r.__P=null;var c=function(){if(!--o.__u){if(o.state.__a){var l=o.state.__a;o.__v.__k[0]=Sw(l,l.__c.__P,l.__c.__O)}var u;for(o.setState({__a:o.__b=null});u=o.o.pop();)u.__P=a,u.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(i,i)},gf.prototype.componentWillUnmount=function(){this.o=[]},gf.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=Ow(this.__b,r,o.__O=o.__P)}this.__b=null}var n=t.__a&&Qr(ee,null,e.fallback);return n&&(n.__u&=-33),[Qr(ee,null,t.__a?null:e.children),n]};var vw=function(e,t,r){if(++r[1]===r[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(r=e.i;r;){for(;r.length>3;)r.pop()();if(r[1]<r[0])break;e.i=r=r[2]}};(el.prototype=new vr).__a=function(e){var t=this,r=Lw(t.__v),o=t.l.get(e);return o[0]++,function(n){var s=function(){t.props.revealOrder?(o.push(n),vw(t,e,o)):n()};r?r(s):s()}},el.prototype.render=function(e){this.i=null,this.l=new Map;var t=vo(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var r=t.length;r--;)this.l.set(t[r],this.i=[1,0,this.i]);return e.children},el.prototype.componentDidUpdate=el.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,r){vw(e,r,t)})};var WN=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,qN=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,GN=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,zN=/[A-Z0-9]/g,VN=typeof document<"u",KN=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};vr.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(vr.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var kw=re.event;re.event=function(e){return kw&&(e=kw(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Nw,YN={configurable:!0,get:function(){return this.class}},Tw=re.vnode;re.vnode=function(e){typeof e.type=="string"&&function(t){var r=t.props,o=t.type,n={},s=o.indexOf("-")==-1;for(var i in r){var a=r[i];if(!(i==="value"&&"defaultValue"in r&&a==null||VN&&i==="children"&&o==="noscript"||i==="class"||i==="className")){var c=i.toLowerCase();i==="defaultValue"&&"value"in r&&r.value==null?i="value":i==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?i="ondblclick":c!=="onchange"||o!=="input"&&o!=="textarea"||KN(r.type)?c==="onfocus"?i="onfocusin":c==="onblur"?i="onfocusout":GN.test(i)&&(i=c):c=i="oninput":s&&qN.test(i)?i=i.replace(zN,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&n[i=c]&&(i="oninputCapture"),n[i]=a}}o=="select"&&(n.multiple&&Array.isArray(n.value)&&(n.value=vo(r.children).forEach(function(l){l.props.selected=n.value.indexOf(l.props.value)!=-1})),n.defaultValue!=null&&(n.value=vo(r.children).forEach(function(l){l.props.selected=n.multiple?n.defaultValue.indexOf(l.props.value)!=-1:n.defaultValue==l.props.value}))),r.class&&!r.className?(n.class=r.class,Object.defineProperty(n,"className",YN)):r.className&&(n.class=n.className=r.className),t.props=n}(e),e.$$typeof=WN,Tw&&Tw(e)};var _w=re.__r;re.__r=function(e){_w&&_w(e),Nw=e.__c};var Pw=re.diffed;re.diffed=function(e){Pw&&Pw(e);var t=e.props,r=e.__e;r!=null&&e.type==="textarea"&&"value"in t&&t.value!==r.value&&(r.value=t.value==null?"":t.value),Nw=null};var Mw=({title:e,projects:t,selected:r,confirm:o})=>d("div",{className:candidate${r?" selected":""},children:[d(XN,{title:e,confirm:o}),t.map(n=>d(JN,{project:n.name,title:e,mark:n.mark,confirm:n.confirm}))]}),XN=({title:e,confirm:t})=>d("a",{className:"button",tabIndex:0,role:"menuitem",href:./${se(e)},onClick:Cw(t),children:e}),JN=({project:e,title:t,mark:r,confirm:o})=>{let n=Cw(o);return r===""?null:d("a",{className:"mark",tabIndex:0,href:../${e}/${se(t)},onClick:n,title:/${e}/${se(t)},children:r instanceof URL?d("img",{src:r.href}):${r}})},Cw=e=>D(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var Iw=(e,t)=>{let[r,o]=Q(null),n=D(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[0]);let u=e.findIndex(p=>t(p)===l);return t(c?.cyclic?e[(u+1)%e.length]:e.at(u+1)??e[0])}),[e,t]),s=D(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[e.length-1]);let u=e.findIndex(p=>t(p)===l);return u<0?t(e[e.length-1]):t(c?.cyclic?e[(u-1+e.length)%e.length]:e.at(u-1)??e[e.length-1])}),[e,t]),i=D(()=>o(e.length===0?null:t(e[0])),[e,t]),a=D(()=>o(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:n,prev:s,selectFirst:i,selectLast:a}};var Aw=e=>{let[t,r]=Q(null),o=H(()=>{let n=t?.getBoundingClientRect?.(),i=Js(e.line,e.char)?.getBoundingClientRect?.();return!i||!n?{}:{top:${i.bottom-n.top}px,left:${i?.left??0-n.left}px,right:${n.right-(i?.left??0)}px}},[t,e.line,e.char]);return{updateStandardElement:r,...o}};var xf="enableProjectsOnSuggestion",Fw=(e,t)=>{let[r,o]=Q(rl([...e],t)),n=D((s,i)=>{QN(s,i,e,t),o(rl([...e],t))},[e,t.enableSelfProjectOnStart]);return te(()=>{let s=i=>{i.key===xf&&o(rl([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:n}},yf=!0,rl=(e,t)=>{try{let r=localStorage.getItem(xf);if(r===null)return ol(e),e;let o=JSON.parse(r);return Array.isArray(o)&&o.every(n=>typeof n=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?o:o.includes(scrapbox.Project.name)?yf?o:o.filter(n=>n!==scrapbox.Project.name):yf?[...o,scrapbox.Project.name]:o:(ol(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return ol(e),e}},QN=(e,t,r,o)=>{let n=rl([...r],o);o.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(yf=t),ol(t?[...n,e]:n.filter(s=>s!==e))},ol=e=>localStorage.setItem(xf,JSON.stringify(e));var Dw=()=>H(()=>document.documentElement.dataset.os??"",[]);var Ti=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var Uw=({progress:e})=>d("div",{className:"progress",style:background: linear-gradient(to right, var(--select-suggest-border-color, #eee) ${(e*100).toPrecision(3)}%, transparent ${(e*100).toPrecision(3)}%)});var jw=({position:e,start:t,enableSelfProjectOnStart:r,projects:o,...n})=>{let{projects:s,set:i}=Fw(o,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:c,left:l,right:u}=Aw({line:e.line,char:t}),p=Dw();return d(ee,{children:[d(e1,{itemCount:n.items.length,enableProjects:s,projects:o,top:c,right:u,set:i,os:p,...n}),d(ZN,{updateStandardElement:a,start:t,enableProjects:s,projects:o,top:c,left:l,os:p,...n})]})},ZN=({start:e,updateStandardElement:t,confirmAfter:r,cancel:o,query:n,enableProjects:s,projects:i,items:a,top:c,left:l,progress:u,callback:p,limit:f,mark:m,os:h})=>{let g=D((N,P,_)=>{let C=[${P?/${P}/${N}:N}${_?.icon?".icon":""}];r(($,{line:j})=>[${...$.slice(0,e).join("")}${C}${...$.slice(e+...n.length).join("")},{line:j,char:e+[...C].length}])},[e,n]),y=H(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),x=H(()=>{let N=[];for(let P of a){if(N.length===f)break;P.projects.some(_=>s.includes(_))&&N.push({title:P.title,projects:P.projects.flatMap(_=>s.includes(_)?[{name:_,mark:y?Ti(m[_]??"",import.meta.url)||_[0]:"",confirm:C=>g(P.title,_,C)}]:[]),confirm:_=>g(P.title,void 0,_)})}return N},[s,y,a,f,m,g]),{selectedId:w,next:R,prev:b,selectLast:E,selectFirst:T}=Iw(x,$w),I=D(N=>w===null?!1:(x.find(P=>$w(P)===w)?.confirm?.(N),!0),[w,x]);te(()=>p(x.length===0?void 0:{selectNext:N=>(R(N),!0),selectPrev:N=>(b(N),!0),selectFirst:()=>(T(),!0),selectLast:()=>(E(),!0),confirm:I,cancel:()=>(o(),!0)}),[p,x.length,R,b,T,E,I]);let F=H(()=>x.length>0&&c!=null&&l!=null?{top:c,left:l}:{display:"none"},[x.length,c,l]),A=D(N=>{if(!N){t(N);return}let P=N.parentNode;if(!(P instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(P.host.parentElement)},[t]);return d("div",{ref:A,className:"container candidates","data-os":h,style:F,children:[x.map(N=>d(Mw,{...N,selected:w===N.title},N.title)),a.length>f&&d("div",{className:"counter",children:${a.length-f} more links}),d(Uw,{progress:u})]})},e1=({enableProjects:e,projects:t,projectScore:r,mark:o,itemCount:n,top:s,right:i,set:a,os:c,freezeUntil:l})=>{let u=H(()=>[...t].sort((f,m)=>(r.get(m)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:Ti(o[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),dt().focus()})}]:[]),[t,r,e,o]),p=H(()=>n>0&&s!=null&&i!=null&&t.size>1?{top:s,right:i}:{display:"none"},[s,i,n,t.size]);return d("div",{className:"container projects","data-os":c,style:p,children:u.map(f=>d(t1,{...f},f.name))})},t1=e=>d("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name,children:e.mark instanceof URL?d("img",{src:e.mark.href}):${e.mark}}),$w=e=>e.title;var Bw=e=>{let t=H(()=>Ti(e.style,import.meta.url),[e.style]);return d(ee,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var Hw=()=>d("style",{children:.container {
position: absolute;
margin-top: 14px;
max-height: 80vh;
z-index: 301;
background-color: var(--select-suggest-bg, #111);
font-family: var(--select-suggest-font-family, "Open Sans", Helvetica, Arial, "Hiragino Sans", sans-serif);
font-size: 14px;
color: var(--select-suggest-text-color, #eee);
border-radius: 4px;
}
.candidates {
max-width: 80vw;
}
.candidates:not(data-os*="android"):not(data-os*="ios") {
font-size:11px;
}
.projects {
margin-right: 4px;
display: grid;
grid-template-rows: repeat(4, min-content);
grid-auto-flow: column;
direction: rtl;
}
.projects:is(data-os*="android", data-os*="ios") > * {
padding: 6px;
}
.candidates > :not(:first-child) {
border-top: 1px solid var(--select-suggest-border-color, #eee);
}
.candidates > *{
line-height: 1.2em;
padding: 0.5em 10px;
}
.candidate {
display: flex;
}
a {
display: block;
text-decoration: none;
color: inherit;
}
a:not(.mark) {
width: 100%;
}
.selected a {
background-color: var(--select-suggest-selected-bg, #222);
text-decoration: underline
}
img {
height: 1.3em;
width: 1.3em;
position: relative;
object-fit: cover;
object-position: 0% 0%;
}
.disabled {
filter: grayscale(1.0) opacity(0.5);
}
.counter {
color: var(--select-suggest-information-text-color, #aaa);
font-size: 80%;
font-style: italic;
}
.progressstyle {
padding: unset;
border: unset;
height: 0.5px;
transition: background 0.1s;
}});function*Ww(e){if(!("nodes"in e))return;let t=0;function*r(o){for(let n of Array.isArray(o)?o:[o]){if(typeof n=="string"){t+=[...n].length;continue}switch(n.type){case"link":yield{whole:n.unit.whole,start:t},t+=[...n.unit.whole].length;break;case"indent":case"quote":t+=[...n.unit.tag].length,yield*r(n.children);break;case"deco":t+=[...n.unit.deco].length+2,yield*r(n.children),t++;break;case"strong":t+=2,yield*r(n.children),t+=2;break;default:t+=[...n.unit.whole].length;break}}}yield*r(e.nodes)}var qw=(e,t)=>{if(t.type==="unlock"){if(!e.lock)return e;let{lock:i,...a}=e;return{...a}}if(e.lock)return e;switch(t.type){case"lock":{let{lock:i,...a}=e;return{lock:!0,...a}}case"enable":return e.type==="disabled"&&e.isManuallyDisabled?{type:"ready"}:e;case"disable":return e.type==="disabled"&&e.isManuallyDisabled?e:{type:"disabled",isManuallyDisabled:!0}}if(e.type==="disabled")return e.isManuallyDisabled||!t.lines?e:{type:"ready"};if(t.type==="cancel")return e.type==="completion"?{type:"cancelled",context:e.context}:e;if(!t.lines)return{type:"disabled"};let r=Math.min(t.range.start.char,t.range.end.char),o=Math.max(t.range.start.char,t.range.end.char),n=t.lines?t.range.start.line!==t.range.end.line?
:[...t.lines[t.range.start.line].text].slice(r,o).join(""):"";if(o1(t.lines[t.position.line],n)&&e.type!=="cancelled")return{type:"completion",context:"selection",query:n,start:r,position:t.position};if(n!=="")return e.type==="completion"?{type:"ready"}:e;let s=r1(t.lines[t.position.line],t.position.char);return s?e.type==="cancelled"&&e.context==="input"?e:e.type==="completion"||t.type==="lines:changed"?{type:"completion",context:"input",query:s.whole,start:s.start,position:t.position}:e.type==="ready"?e:{type:"ready"}:e.type==="ready"?e:{type:"ready"}},r1=(e,t)=>{for(let{whole:r,start:o}of Ww(e))if(!(t<=o||o+[...r].length<=t))return{whole:r,start:o}},o1=(e,t)=>!(t.trim()===""||t.includes(
)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var Gw=()=>{let e=ft(scrapbox.Page.lines),t=ft(!1);return te(()=>{let r=()=>{t.current=!0};return scrapbox.addListener("lines:changed",r),scrapbox.addListener("layout:changed",r),()=>{scrapbox.removeListener("lines:changed",r),scrapbox.removeListener("layout:changed",r)}},[]),D(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var n1=jn("scrapbox-select-suggestion:useLifecycle.ts"),zw=()=>{let[e,t]=ko(qw,{type:"ready"}),r=Gw(),o=H(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:c,selection:l}=Wt();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:c.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);te(()=>{let i=()=>{o("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{o("selection:changed")},c=Ya();return c.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),c.removeChangeListener(a)}},[]),te(()=>{if(e.context!=="input")return;let i=()=>{o("cursor:changed")},a=Po();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[n,s]=Q(e);return n!==e&&(s(e),n1.debug("Detect changes",e)),{state:e,setEnable:D(i=>t({type:i?"enable":"disable"}),[]),cancel:D(()=>t({type:"cancel"}),[]),freezeUntil:D(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:D(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:c,selection:l}=Wt(),u=c.getPosition().line,p=a[u].text,[f,m]=i(p,c.getPosition());l.setRange({start:{line:u,char:0},end:{line:u,char:[...p].length}}),await at(f),c.setPosition(m),c.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var Vw=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let o=e.matches.map(([i])=>i).sort(),n=t.matches.map(([i])=>i).sort();for(let i=0;i<o.length;i++){let a=o[i]-(n[i]??n.length);if(a!==0)return a}let s=e.title.length-t.title.length;return s!==0?s:t.updated-e.updated};var Yw=Symbol("Comlink.proxy"),s1=Symbol("Comlink.endpoint"),wf=Symbol("Comlink.releaseProxy"),bf=Symbol("Comlink.finalizer"),sl=Symbol("Comlink.thrown"),Xw=e=>typeof e=="object"&&e!==null||typeof e=="function",i1={canHandle:e=>Xw(e)&&e[Yw],serialize(e){let{port1:t,port2:r}=new MessageChannel;return Qw(e,t),[r,[r]]},deserialize(e){return e.start(),Rf(e)}},a1={canHandle:e=>Xw(e)&&sl in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Jw=new Map([["proxy",i1],["throw",a1]]);function c1(e,t){for(let r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function Qw(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(n){if(!n||!n.data)return;if(!c1(r,n.origin)){console.warn(Invalid origin '${n.origin}' for comlink proxy);return}let{id:s,type:i,path:a}=Object.assign({path:[]},n.data),c=(n.data.argumentList||[]).map(wn),l;try{let u=a.slice(0,-1).reduce((f,m)=>f[m],e),p=a.reduce((f,m)=>f[m],e);switch(i){case"GET":l=p;break;case"SET":u[a.slice(-1)[0]]=wn(n.data.value),l=!0;break;case"APPLY":l=p.apply(u,c);break;case"CONSTRUCT":{let f=new p(...c);l=vf(f)}break;case"ENDPOINT":{let{port1:f,port2:m}=new MessageChannel;Qw(e,m),l=f1(f,[f])}break;case"RELEASE":l=void 0;break;default:return}}catch(u){l={value:u,[sl]:0}}Promise.resolve(l).catch(u=>({value:u,[sl]:0})).then(u=>{let[p,f]=cl(u);t.postMessage(Object.assign(Object.assign({},p),{id:s}),f),i==="RELEASE"&&(t.removeEventListener("message",o),Zw(t),bf in e&&typeof e[bf]=="function"&&e[bf]())}).catch(u=>{let[p,f]=cl({value:new TypeError("Unserializable return value"),[sl]:0});t.postMessage(Object.assign(Object.assign({},p),{id:s}),f)})}),t.start&&t.start()}function l1(e){return e.constructor.name==="MessagePort"}function Zw(e){l1(e)&&e.close()}function Rf(e,t){let r=new Map;return e.addEventListener("message",function(o){let{data:n}=o;if(!n||!n.id)return;let s=r.get(n.id);if(s)try{s(n)}finally{r.delete(n.id)}}),Ef(e,r,[],t)}function nl(e){if(e)throw new Error("Proxy has been released and is not useable")}function eR(e){return as(e,new Map,{type:"RELEASE"}).then(()=>{Zw(e)})}var il=new WeakMap,al="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(il.get(e)||0)-1;il.set(e,t),t===0&&eR(e)});function p1(e,t){let r=(il.get(t)||0)+1;il.set(t,r),al&&al.register(e,t,e)}function u1(e){al&&al.unregister(e)}function Ef(e,t,r=[],o=function(){}){let n=!1,s=new Proxy(o,{get(i,a){if(nl(n),a===wf)return()=>{u1(s),eR(e),t.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>s};let c=as(e,t,{type:"GET",path:r.map(l=>l.toString())}).then(wn);return c.then.bind(c)}return Ef(e,t,[...r,a])},set(i,a,c){nl(n);let[l,u]=cl(c);return as(e,t,{type:"SET",path:[...r,a].map(p=>p.toString()),value:l},u).then(wn)},apply(i,a,c){nl(n);let l=r[r.length-1];if(l===s1)return as(e,t,{type:"ENDPOINT"}).then(wn);if(l==="bind")return Ef(e,t,r.slice(0,-1));let[u,p]=Kw(c);return as(e,t,{type:"APPLY",path:r.map(f=>f.toString()),argumentList:u},p).then(wn)},construct(i,a){nl(n);let[c,l]=Kw(a);return as(e,t,{type:"CONSTRUCT",path:r.map(u=>u.toString()),argumentList:c},l).then(wn)}});return p1(s,e),s}function m1(e){return Array.prototype.concat.apply([],e)}function Kw(e){let t=e.map(cl);return[t.map(r=>r[0]),m1(t.map(r=>r[1]))]}var tR=new WeakMap;function f1(e,t){return tR.set(e,t),e}function vf(e){return Object.assign(e,{[Yw]:!0})}function cl(e){for(let[t,r]of Jw)if(r.canHandle(e)){let[o,n]=r.serialize(e);return[{type:"HANDLER",name:t,value:o},n]}return[{type:"RAW",value:e},tR.get(e)||[]]}function wn(e){switch(e.type){case"HANDLER":return Jw.get(e.name).deserialize(e.value);case"RAW":return e.value}}function as(e,t,r,o){return new Promise(n=>{let s=d1();t.set(s,n),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),o)})}function d1(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var cs=jn("scrapbox-select-suggestion:cancelableSearch.ts"),rR=e=>{let t=Rf(e);return{load:async r=>{cs.debug("start loading source");let o=await t.load([...r]);return cs.debug(loaded ${o} candidates),o},search:(r,o)=>h1(r,o??5e3,t.search),[Symbol.dispose]:()=>{t[wf](),e instanceof MessagePort?e.close():e.terminate(),cs.debug("shared worker closed.")}}},h1=(e,t,r)=>{if(cs.debug("start searching: ",e),!e.trim())return new ReadableStream({start(s){s.close()}});let o=new Date,n=!1;return new ReadableStream({async start(s){try{await r(e,t,vf((i,a)=>(n||s.enqueue([i,a]),n))),s.close()}catch(i){s.error(i)}finally{n=!0;let a=new Date().getTime()-o.getTime();cs.debug(Comlink search completed for "${e}" in ${a}ms)}},cancel(){n=!0;let i=new Date().getTime()-o.getTime();cs.debug(Comlink search cancelled for "${e}" after ${i}ms)}})};var ll=(e,t)=>{let r=t?.interval??0,o=t?.maxQueued??1/0,n,s,i=[],a=(...c)=>{if(!n)return n=(async()=>{do{await new Promise(m=>{let h=setTimeout(m,r);s=()=>{for(clearTimeout(h);i.length>0;)i.shift()("discarded");m()}});let f=i.pop();if(!f)break;f("delayed")}while(i.length>0);n=void 0})(),new Promise(f=>f(e.call(a,...c,"immediate")));for(;i.length>Math.max(o,0);)i.shift()("discarded");let{promise:l,resolve:u,reject:p}=Promise.withResolvers();return i.push(f=>{try{u(e.call(a,...c,f))}catch(m){p(m)}}),l};return a.clear=()=>{s?.()},Object.defineProperty(a,"ready",{get:()=>n}),a};var _i=e=>e.query!=="",oR=e=>(t,r)=>{if("query"in r){if(r.query===t.query)return t;let i=_i(t)?t.job:void 0;if(!r.query)return i?.abort?.(),{query:""};let{run:a,abort:c}=e(r.query),l=i?.abort?.()?.then?.(a)??a();return{query:r.query,job:{done:l,abort:()=>(c(),l)},progress:0,candidates:_i(t)?t.candidates:[]}}if(!_i(t))return t;if(!r.candidates){let{progress:i,...a}=t;return i===r.progress?t:{progress:r.progress,...a}}let{candidates:o,progress:n,...s}=t;return o===r.candidates&&n===r.progress?t:{candidates:r.candidates??o,progress:r.progress,...s}};var g1=jn("scrapbox-select-suggestion:useSearch.ts"),nR=(e,t)=>{let r=H(()=>rR(new SharedWorker(t.workerUrl,{type:"module"}).port),[t.workerUrl]);te(()=>(r.load(t.projects),()=>{using i=r}),[r,t.projects]);let o=D(oR(i=>{let a=!1;return{run:async()=>{let c=ll((u,p)=>{p!=="discarded"&&(a||s(u))},{interval:500,maxQueued:0}),l=[];for await(let[u,p]of r.search(i,1e4)){if(a)return;l=[...l,...u],s({progress:p}),u.length!==0&&c({progress:p,candidates:l})}c({progress:1,candidates:l})},abort:()=>a=!0}}),[r]),[n,s]=ko(o,{query:""});return te(()=>s({query:e}),[e]),H(()=>{if(!_i(n))return;let[i,a]=y1(n.candidates);return g1.debug("Detect changes",{progress:n.progress,items:a}),{progress:n.progress,projectScore:i,items:a}},[n])},y1=e=>{let t=new Map,r=[];for(let o of e.sort(Vw)){let n=[...o.metadata.keys()];for(let s of n)t.set(s,(t.get(s)??0)+.5**o.dist);r.push({title:o.title,dist:o.dist,projects:n})}return[t,r]};var sR=(e,t)=>{let r=ft({...t});te(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),te(()=>{e(r.current)},[e])};var x1={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},iR=e=>{let{state:t,setEnable:r,...o}=zw(),n=nR(t.type==="completion"?t.context==="input"?t.query.slice(1,-1):t.query:"",e),[s,i]=Q(),{callback:a,style:c,...l}=e;return sR(a,{enable:D(()=>r(!0),[]),disable:D(()=>r(!1),[]),...t.type!=="completion"||!s?x1:s}),d(ee,{children:[d(Hw,{}),d(Bw,{style:c}),t.type==="completion"&&n&&d(jw,{callback:i,...n,...t,...o,...l})]})};var aR=e=>{let t=document.createElement("div");t.dataset.userscriptName="scrapbox-select-suggestion";let r=t.attachShadow({mode:"open"});document.body.append(t);let{limit:o=5,debug:n=!1,mark:s={},style:i="",enableSelfProjectOnStart:a=!0,workerUrl:c}=e,l=new Set([...a?[scrapbox.Project.name]:[],...e.projects??[scrapbox.Project.name]]);return _a(n),new Promise(u=>vt(d(iR,{limit:o,projects:l,mark:s,style:i,callback:u,enableSelfProjectOnStart:a,workerUrl:c}),r))};var ir=e=>e.flatMap(t=>{let r=t.slice(1),o=Math.min(...r.map(n=>n.text.length-n.text.trimStart().length));return r.map(n=>n.text.slice(o))}).join(
).trim();function*cR(e,t){for(let[r,o]of t.entries()){let n=e.get(r);if(n&&ir(n.blocks)===ir(o)){yield{changed:!1,filename:r};continue}yield{changed:!0,filename:r}}for(let r of e.keys())t.has(r)||(yield{changed:!0,filename:r})}var lR=e=>{let t=new Map;if(e.length===0)return t;let r=it(e.map(n=>n.text).join(
),{hasTitle:!0}),o=0;for(let n of r)switch(n.type){case"title":case"line":o++;break;case"table":o+=n.cells.length+1;break;case"codeBlock":{let s=t.get(n.fileName)??[],i=n.content.split(
).length+1;s.push(e.slice(o,o+i)),t.set(n.fileName,s),o+=i;break}}return t};var pR=e=>{let t,r,o=async()=>{for(;t;){let[n,s]=t;t=void 0;try{let i=await e(...n);s({type:"resolve",value:i})}catch(i){s({type:"reject",value:i})}}r=void 0};return(...n)=>{let{resolve:s,promise:i}=Promise.withResolvers();return t?.[1]?.({type:"cancel"}),t=[n,s],r??=o(),i}};var pl=class{constructor(t,r){this._filename=t;this._preview=pR(async(o,n,s)=>(this._dispose=await r(s?{filename:this.filename,before:o,after:n,render:(...i)=>{s.textContent="",s.append(...i)}}:{filename:this.filename,before:o}),!1))}get filename(){return this._filename}get blocks(){return this._blocks??[]}async update(t){if(await this._dispose?.(),!t||ir(t)===""){let a=await this._preview(this.blocks);if(a.type==="cancel")return a;if(a.type==="reject")throw a.value;return this._area?.remove?.(),this._style?.remove?.(),this._area=void 0,this._style=void 0,this._blocks=void 0,{type:"resolve",value:!0}}let r=this.blocks;this._blocks=t,this.makeStyle();let o=this.makeArea(),n=t.at(0)?.at?.(-1)?.id,s=eo(n);if(!s)throw new Error("div.lines#L${n}" could not be found.);s.insertAdjacentElement("afterend",o);let i=()=>{let a=s.getElementsByClassName("indent")[0];a instanceof HTMLElement&&(o.style.marginLeft=a.style.marginLeft)};return this._observer?.disconnect?.(),i(),this._observer=new MutationObserver(i),this._observer.observe(s,{childList:!0,subtree:!0}),this._preview(r,t,o)}makeArea(){if(this._area)return this._area;let t=document.createElement("div");return t.classList.add("scrap-run"),t.dataset.filename=this.filename,this._area=t,t}makeStyle(){let t=this.blocks.flatMap(o=>o.slice(1).map(({id:n})=>#L${n})),r=this.blocks.flatMap(o=>o.map(({id:n})=>#L${n}));this._style||(this._style=document.createElement("style"),document.head.append(this._style)),this._style.textContent=.lines:not(:has(:is(${...r.join(",")}).cursor-line)) :is(${...t.join(",")}){display:none}}_blocks;_dispose;_preview;_area;_observer;_style};var uR=({previewers:e})=>{let t=new Map,r=()=>{let s=lR(Dt());for(let{changed:i,filename:a}of cR(t,s)){if(!i)continue;let c=s.get(a),l=t.get(a);if(!l){if(!c)continue;let u=e.find(({when:p})=>p.test(a))?.preview;if(!u)continue;l=new pl(a,u),t.set(a,l)}l.update(c).then(u=>{switch(u.type){case"resolve":u.value&&t.delete(a);return;case"reject":throw u.value;case"cancel":return}})}},o=()=>{if(scrapbox.Layout!=="page"){scrapbox.off("lines:changed",r);return}r(),scrapbox.on("lines:changed",r)};o(),scrapbox.on("page:changed",o);let n=document.createElement("style");return n.textContent=".scrap-run{display:block;width:95%}",document.head.append(n),()=>{scrapbox.off("page:changed",o),n.remove()}};var Pi=e=>{let t=new FileReader,r=new Promise(o=>t.onload=()=>o(t.result));return t.readAsDataURL(e),r};var mR=async e=>{if(!("after"in e))return;let t=ir(e.after),o=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("parsererror");if(o){let i=document.createElement("pre"),a=document.createElement("code");a.innerText=o.innerHTML,i.append(a),e.render(i);return}let n=await Pi(new Blob([t],{type:"image/svg+xml"})),s=document.createElement("img");s.src=n,e.render(s)};var kf={};Xi(kf,{default:()=>hR});var K1=Object.create,dR=Object.defineProperty,Y1=Object.getOwnPropertyDescriptor,X1=Object.getOwnPropertyNames,J1=Object.getPrototypeOf,Q1=Object.prototype.hasOwnProperty,Z1=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),eM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of X1(t))!Q1.call(e,n)&&n!==r&&dR(e,n,{get:()=>t[n],enumerable:!(o=Y1(t,n))||o.enumerable});return e},tM=(e,t,r)=>(r=e!=null?K1(J1(e)):{},eM(t||!e||!e.__esModule?dR(r,"default",{value:e,enumerable:!0}):r,e)),rM=Z1((e,t)=>{t.exports=o;var r=Object.prototype.toString;function o(n){if(!n)return!1;var s=r.call(n);return s==="[object Function]"||typeof n=="function"&&s!=="[object RegExp]"||typeof window<"u"&&(n===window.setTimeout||n===window.alert||n===window.confirm||n===window.prompt)}}),fR=tM(rM()),hR=fR.default??fR;var Tf={};Xi(Tf,{default:()=>xR});var oM=Object.create,yR=Object.defineProperty,nM=Object.getOwnPropertyDescriptor,sM=Object.getOwnPropertyNames,iM=Object.getPrototypeOf,aM=Object.prototype.hasOwnProperty,cM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),lM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of sM(t))!aM.call(e,n)&&n!==r&&yR(e,n,{get:()=>t[n],enumerable:!(o=nM(t,n))||o.enumerable});return e},pM=(e,t,r)=>(r=e!=null?oM(iM(e)):{},lM(t||!e||!e.__esModule?yR(r,"default",{value:e,enumerable:!0}):r,e)),uM=cM((e,t)=>{var r=function(n){return n.replace(/^\s+|\s+$/g,"")},o=function(n){return Object.prototype.toString.call(n)==="[object Array]"};t.exports=function(n){if(!n)return{};for(var s=Object.create(null),i=r(n).split(
),a=0;a<i.length;a++){var c=i[a],l=c.indexOf(":"),u=r(c.slice(0,l)).toLowerCase(),p=r(c.slice(l+1));typeof s[u]>"u"?s[u]=p:o(s[u])?s[u].push(p):s[u]=[s[u],p]}return s}}),gR=pM(uM()),xR=gR.default??gR;var mM=(()=>{var e=globalThis;return{default:e}})(),fM=(()=>{var e=(...t)=>Object.assign({},...t);return{default:e}})(),ls=e=>{let t=o=>typeof o.default<"u"?o.default:o,r=o=>Object.assign({__esModule:!0},o);switch(e){case"npm:global/window":return t(mM);case"is-function":return t(kf);case"parse-headers":return t(Tf);case"npm:xtend":return t(fM);default:return console.error('module "'+e+'" not found'),null}},dM=Object.create,ER=Object.defineProperty,hM=Object.getOwnPropertyDescriptor,gM=Object.getOwnPropertyNames,yM=Object.getPrototypeOf,xM=Object.prototype.hasOwnProperty,ul=(e=>typeof ls<"u"?ls:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof ls<"u"?ls:t)[r]}):e)(function(e){if(typeof ls<"u")return ls.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),bM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),EM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of gM(t))!xM.call(e,n)&&n!==r&&ER(e,n,{get:()=>t[n],enumerable:!(o=hM(t,n))||o.enumerable});return e},wM=(e,t,r)=>(r=e!=null?dM(yM(e)):{},EM(t||!e||!e.__esModule?ER(r,"default",{value:e,enumerable:!0}):r,e)),RM=bM((e,t)=>{"use strict";var r=ul("npm:global/window"),o=ul("is-function"),n=ul("parse-headers"),s=ul("npm:xtend");t.exports=l,t.exports.default=l,l.XMLHttpRequest=r.XMLHttpRequest||f,l.XDomainRequest="withCredentials"in new l.XMLHttpRequest?l.XMLHttpRequest:r.XDomainRequest,i(["get","put","post","patch","head","delete"],function(m){l[m==="delete"?"del":m]=function(h,g,y){return g=c(h,g,y),g.method=m.toUpperCase(),u(g)}});function i(m,h){for(var g=0;g<m.length;g++)h(m[g])}function a(m){for(var h in m)if(m.hasOwnProperty(h))return!1;return!0}function c(m,h,g){var y=m;return o(h)?(g=h,typeof m=="string"&&(y={uri:m})):y=s(h,{uri:m}),y.callback=g,y}function l(m,h,g){return h=c(m,h,g),u(h)}function u(m){if(typeof m.callback>"u")throw new Error("callback argument missing");var h=!1,g=function(j,q,B){h||(h=!0,m.callback(j,q,B))};function y(){b.readyState===4&&setTimeout(R,0)}function x(){var j=void 0;if(b.response?j=b.response:j=b.responseText||p(b),_)try{j=JSON.parse(j)}catch{}return j}function w(j){return clearTimeout(C),j instanceof Error||(j=new Error(""+(j||"Unknown XMLHttpRequest Error"))),j.statusCode=0,g(j,$)}function R(){if(!T){var j;clearTimeout(C),m.useXDR&&b.status===void 0?j=200:j=b.status===1223?204:b.status;var q=$,B=null;return j!==0?(q={body:x(),statusCode:j,method:F,headers:{},url:I,rawRequest:b},b.getAllResponseHeaders&&(q.headers=n(b.getAllResponseHeaders()))):B=new Error("Internal XMLHttpRequest Error"),g(B,q,q.body)}}var b=m.xhr||null;b||(m.cors||m.useXDR?b=new l.XDomainRequest:b=new l.XMLHttpRequest);var E,T,I=b.url=m.uri||m.url,F=b.method=m.method||"GET",A=m.body||m.data,N=b.headers=m.headers||{},P=!!m.sync,_=!1,C,$={body:void 0,headers:{},statusCode:0,method:F,url:I,rawRequest:b};if("json"in m&&m.json!==!1&&(_=!0,N.accept||N.Accept||(N.Accept="application/json"),F!=="GET"&&F!=="HEAD"&&(N["content-type"]||N["Content-Type"]||(N["Content-Type"]="application/json"),A=JSON.stringify(m.json===!0?A:m.json))),b.onreadystatechange=y,b.onload=R,b.onerror=w,b.onprogress=function(){},b.onabort=function(){T=!0},b.ontimeout=w,b.open(F,I,!P,m.username,m.password),P||(b.withCredentials=!!m.withCredentials),!P&&m.timeout>0&&(C=setTimeout(function(){if(!T){T=!0,b.abort("timeout");var j=new Error("XMLHttpRequest timeout");j.code="ETIMEDOUT",w(j)}},m.timeout)),b.setRequestHeader)for(E in N)N.hasOwnProperty(E)&&b.setRequestHeader(E,N[E]);else if(m.headers&&!a(m.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in m&&(b.responseType=m.responseType),"beforeSend"in m&&typeof m.beforeSend=="function"&&m.beforeSend(b),b.send(A||null),b}function p(m){try{if(m.responseType==="document")return m.responseXML;var h=m.responseXML&&m.responseXML.documentElement.nodeName==="parsererror";if(m.responseType===""&&!h)return m.responseXML}catch{}return null}function f(){}}),bR=wM(RM()),ml=bR.default??bR;var fl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},aPe=function(){function e(r){this.value=r}function t(r){var o,n;function s(c,l){return new Promise(function(u,p){var f={key:c,arg:l,resolve:u,reject:p,next:null};n?n=n.next=f:(o=n=f,i(c,l))})}function i(c,l){try{var u=r[c](l),p=u.value;p instanceof e?Promise.resolve(p.value).then(function(f){i("next",f)},function(f){i("throw",f)}):a(u.done?"return":"normal",u.value)}catch(f){a("throw",f)}}function a(c,l){switch(c){case"return":o.resolve({value:l,done:!0});break;case"throw":o.reject(l);break;default:o.resolve({value:l,done:!1});break}o=o.next,o?i(o.key,o.arg):n=null}this._invoke=s,typeof r.return!="function"&&(this.return=void 0)}return typeof Symbol=="function"&&Symbol.asyncIterator&&(t.prototype[Symbol.asyncIterator]=function(){return this}),t.prototype.next=function(r){return this._invoke("next",r)},t.prototype.throw=function(r){return this._invoke("throw",r)},t.prototype.return=function(r){return this._invoke("return",r)},{wrap:function(r){return function(){return new t(r.apply(this,arguments))}},await:function(r){return new e(r)}}}(),vR=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},kR=function(){function e(t,r){for(var o=0;o<r.length;o++){var n=r[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),_f=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}else return Array.from(e)},Oi="";function vM(e){return
<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>
<td align="center">
<div style="display: table-cell; vertical-align: middle;">
<div style="">+e+</div>
</div>
</td></tr></table>
}var kM=
This page requires a browser that supports WebGL.<br/>
<a href="http://get.webgl.org">Click here to upgrade your browser.</a>
,TM=
It does not appear your computer can support WebGL.<br/>
<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>
,_M=1,PM=2;function OM(e,t,r){function o(i){var a=e.parentNode;a&&(a.innerHTML=vM(i))}function n(i,a){typeof r=="function"?r(i):o(a)}if(!window.WebGLRenderingContext)return n(_M,kM),null;var s=SM(e,t);return s?s.getExtension("OES_standard_derivatives"):n(PM,TM),s}function SM(e,t){for(var r=["webgl","experimental-webgl"],o=null,n=0;n<r.length;++n)try{o=e.getContext(r[n],t)}catch{if(o)break}return o}function ps(e,t,r,o){var n=e.gl,s=n.createShader(r);n.shaderSource(s,t),n.compileShader(s);var i=n.getShaderParameter(s,n.COMPILE_STATUS);return i?s:(Oi=n.getShaderInfoLog(s),console.error("*** Error compiling shader "+s+":"+Oi),e.trigger("error",{shader:s,source:t,type:r,error:Oi,offset:o||0}),n.deleteShader(s),null)}function wR(e,t,r,o){for(var n=e.gl,s=n.createProgram(),i=0;i<t.length;++i)n.attachShader(s,t[i]);if(r)for(var a=0;a<r.length;++a)n.bindAttribLocation(s,o?o[a]:a,r[a]);n.linkProgram(s);var c=n.getProgramParameter(s,n.LINK_STATUS);return c?s:(Oi=n.getProgramInfoLog(s),console.log("Error in program linking:"+Oi),n.deleteProgram(s),null)}function Pf(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=[];for(var o in e){var n=e[o],s=void 0;if(t&&(o=t+"."+o),typeof n=="number")r.push({type:"float",method:"1f",name:o,value:n});else if(Array.isArray(n)){if(typeof n[0]=="number")n.length===1?r.push({type:"float",method:"1f",name:o,value:n}):n.length>=2&&n.length<=4?r.push({type:"vec"+n.length,method:n.length+"fv",name:o,value:n}):n.length>4&&r.push({type:"float[]",method:"1fv",name:o+"[0]",value:n});else if(typeof n[0]=="string")r.push({type:"sampler2D",method:"1i",name:o,value:n});else if(Array.isArray(n[0])&&typeof n[0][0]=="number"){if(n[0].length>=2&&n[0].length<=4)for(s=0;s<n.length;s++)r.push({type:"vec"+n[0].length,method:n[s].length+"fv",name:o+"["+s+"]",value:n[s]})}else if(fl(n[0])==="object")for(s=0;s<n.length;s++)r.push.apply(r,_f(Pf(n[s],o+"["+s+"]")))}else typeof n=="boolean"?r.push({type:"bool",method:"1i",name:o,value:n}):typeof n=="string"?r.push({type:"sampler2D",method:"1i",name:o,value:n}):(typeof n>"u"?"undefined":fl(n))==="object"&&r.push.apply(r,_f(Pf(n,o)))}return r}function LM(e){var t=e.getBoundingClientRect();return t.top+t.height>0&&t.top<(window.innerHeight||document.documentElement.clientHeight)}function RR(e){return(e&e-1)===0}function NM(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function MM(e,t){return e&&t?e.toString()!==t.toString():!1}function CM(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(),t.status==200?t.responseText:""}function TR(e){var t=new Set;return Object.assign(e,{on:function(r,o){var n={};n[r]=o,t.add(n)},off:function(r,o){if(o){var n={};n[r]=o,t.delete(n)}else{var s=!0,i=!1,a=void 0;try{for(var c=t[Symbol.iterator](),l;!(s=(l=c.next()).done);s=!0){var u=l.value,p=!0,f=!1,m=void 0;try{for(var h=Object.keys(u)[Symbol.iterator](),g;!(p=(g=h.next()).done);p=!0){var y=g.value;if(y===r){t.delete(u);return}}}catch(x){f=!0,m=x}finally{try{!p&&h.return&&h.return()}finally{if(f)throw m}}}}catch(x){i=!0,a=x}finally{try{!s&&c.return&&c.return()}finally{if(i)throw a}}}},listSubscriptions:function(){var r=!0,o=!1,n=void 0;try{for(var s=t[Symbol.iterator](),i;!(r=(i=s.next()).done);r=!0){var a=i.value;console.log(a)}}catch(c){o=!0,n=c}finally{try{!r&&s.return&&s.return()}finally{if(o)throw n}}},subscribe:function(r){t.add(r)},unsubscribe:function(r){t.delete(r)},unsubscribeAll:function(){t.clear()},trigger:function(r){for(var o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];var i=!0,a=!1,c=void 0;try{for(var l=t[Symbol.iterator](),u;!(i=(u=l.next()).done);i=!0){var p=u.value;typeof p[r]=="function"&&p[r].apply(p,_f(n))}}catch(f){a=!0,c=f}finally{try{!i&&l.return&&l.return()}finally{if(a)throw c}}}})}var Of=function(){function e(t,r){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};vR(this,e),TR(this),this.gl=t,this.texture=t.createTexture(),this.texture&&(this.valid=!0),this.bind(),this.name=r,this.source=null,this.sourceType=null,this.loading=null,this.setData(1,1,new Uint8Array([0,0,0,255]),{filtering:"linear"}),this.setFiltering(o.filtering),this.load(o)}return kR(e,[{key:"destroy",value:function(){this.valid&&(this.gl.deleteTexture(this.texture),this.texture=null,delete this.data,this.data=null,this.valid=!1)}},{key:"bind",value:function(t){this.valid&&(typeof t=="number"&&e.activeUnit!==t&&(this.gl.activeTexture(this.gl.TEXTURE0+t),e.activeUnit=t),e.activeTexture!==this.texture&&(this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),e.activeTexture=this.texture))}},{key:"load",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.loading=null,typeof t.url=="string"?(this.url===void 0||t.url!==this.url)&&this.setUrl(t.url,t):t.element?this.setElement(t.element,t):t.data&&t.width&&t.height&&this.setData(t.width,t.height,t.data,t)}},{key:"setUrl",value:function(t){var r=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.valid)return this.url=t,this.source=this.url,this.sourceType="url",this.loading=new Promise(function(n,s){var i=t.split(".").pop().toLowerCase(),a=i==="ogv"||i==="webm"||i==="mp4",c=void 0;a?(c=document.createElement("video"),c.autoplay=!0,c.muted=!0,setTimeout(function(){c.play()},1),o.filtering="nearest"):c=new Image,c.onload=function(){try{r.setElement(c,o)}catch(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o)}n(r)},c.onerror=function(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o),n(r)},NM()&&r.source.slice(0,5)==="data:"||(c.crossOrigin="anonymous"),c.src=r.source,a&&r.setElement(c,o)}),this.loading}},{key:"setData",value:function(t,r,o){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.width=t,this.height=r,this.source=o,this.sourceType="data",this.update(n),this.setFiltering(n),this.loading=Promise.resolve(this),this.loading}},{key:"setElement",value:function(t,r){var o=this,n=t;if(typeof t=="string"&&(t=document.querySelector(t)),t instanceof HTMLCanvasElement||t instanceof HTMLImageElement||t instanceof HTMLVideoElement)this.source=t,this.sourceType="element",t instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight,t.addEventListener("canplaythrough",function(){o.intervalID=setInterval(function(){o.update(r)},15)},!0),t.addEventListener("ended",function(){t.currentTime=0,t.play()},!0)):this.update(r),this.setFiltering(r);else{var s="the 'element' parameter (element: "+JSON.stringify(n)+") must be a CSS ";s+="selector string, or a <canvas>, <image> or <video> object",console.log("Texture '"+this.name+"': "+s,r)}return this.loading=Promise.resolve(this),this.loading}},{key:"update",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.valid&&(this.bind(),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,t.UNPACK_FLIP_Y_WEBGL!==!1),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.UNPACK_PREMULTIPLY_ALPHA_WEBGL||!1),this.sourceType==="element"&&(this.source instanceof HTMLCanvasElement||this.source instanceof HTMLVideoElement||this.source instanceof HTMLImageElement&&this.source.complete)?(this.source instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight):(this.width=this.source.width,this.height=this.source.height),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source)):this.sourceType==="data"&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.width,this.height,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source),this.trigger("loaded",this))}},{key:"setFiltering",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.valid){this.powerOf2=RR(this.width)&&RR(this.height),this.filtering=t.filtering||"linear";var r=this.gl;this.bind(),this.powerOf2?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,t.TEXTURE_WRAP_S||r.REPEAT),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,t.TEXTURE_WRAP_T||r.REPEAT),this.filtering==="mipmap"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR_MIPMAP_LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.generateMipmap(r.TEXTURE_2D)):this.filtering==="linear"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)):this.filtering==="nearest"&&(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST))):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.filtering==="mipmap"&&(this.filtering="linear"),this.filtering==="nearest"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST)):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)))}}}]),e}();Of.getMaxTextureSize=function(e){return e.getParameter(e.MAX_TEXTURE_SIZE)};Of.activeUnit=-1;var _R=function(){function e(t,r,o){var n=this;vR(this,e),TR(this),r=r||{},o=o||{},t.hasAttribute("data-fullscreen")&&(t.getAttribute("data-fullscreen")=="1"||t.getAttribute("data-fullscreen")=="true")?(this.width=window.innerWidth,this.height=window.innerHeight,t.width=window.innerWidth,t.height=window.innerHeight):(this.width=t.clientWidth,this.height=t.clientHeight),this.canvas=t,this.gl=void 0,this.deps={},this.program=void 0,this.textures={},this.buffers={},this.uniforms={},this.vbo={},this.isValid=!1,this.animationFrameRequest=void 0,this.BUFFER_COUNT=0,this.vertexString=r.vertexString||
#ifdef GL_ES
precision mediump float;
#endif
attribute vec2 a_position;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
v_texcoord = a_texcoord;
}
,this.fragmentString=r.fragmentString||
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texcoord;
void main(){
gl_FragColor = vec4(0.0);
}
;var s=OM(t,r,o.onError);if(!s)return;if(this.gl=s,this.timeLoad=this.timePrev=performance.now(),this.timeDelta=0,this.forceRender=!0,this.paused=!1,this.realToCSSPixels=window.devicePixelRatio||1,t.style.backgroundColor=r.backgroundColor||"rgba(1,1,1,0)",t.hasAttribute("data-fragment"))this.fragmentString=t.getAttribute("data-fragment");else if(t.hasAttribute("data-fragment-url")){var i=t.getAttribute("data-fragment-url");ml.get(i,function(g,y,x){n.load(x,n.vertexString)})}if(t.hasAttribute("data-vertex"))this.vertexString=t.getAttribute("data-vertex");else if(t.hasAttribute("data-vertex-url")){var a=t.getAttribute("data-vertex-url");ml.get(a,function(g,y,x){n.load(n.fragmentString,x)})}if(this.load(),!this.program)return;var c=s.getAttribLocation(this.program,"a_texcoord");this.vbo.texCoords=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.texCoords),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(c),this.gl.vertexAttribPointer(c,2,s.FLOAT,!1,0,0);var l=s.getAttribLocation(this.program,"a_position");if(this.vbo.vertices=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.vertices),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(l),this.gl.vertexAttribPointer(l,2,s.FLOAT,!1,0,0),t.hasAttribute("data-textures")){var u=t.getAttribute("data-textures").split(",");for(var p in u)this.setUniform("u_tex"+p,u[p])}var f={x:0,y:0};document.addEventListener("mousemove",function(g){f.x=g.clientX||g.pageX,f.y=g.clientY||g.pageY},!1);var m=this;function h(){m.nMouse>1&&m.setMouse(f),m.resize()&&(m.forceRender=!0),m.render(),m.animationFrameRequest=window.requestAnimationFrame(h)}return this.setMouse({x:0,y:0}),h(),this}return kR(e,[{key:"destroy",value:function(){cancelAnimationFrame(this.animationFrameRequest),this.animated=!1,this.isValid=!1;for(var t in this.textures)t.destroy&&t.destroy();this.textures={};for(var r in this.attribs)this.gl.deleteBuffer(this.attribs[r]);this.gl.useProgram(null),this.gl.deleteProgram(this.program);for(var o in this.buffers){var n=this.buffers[o];this.gl.deleteProgram(n.program)}this.program=null,this.gl=null}},{key:"load",value:function(t,r){var o=this;r&&(this.vertexString=r),t&&(this.fragmentString=t);var n=this.fragmentString.split(/\r?\n/);this.fragmentString=#define PLATFORM_WEBGL
#line 0
,n.forEach(function(g,y){var x=g.trim();if(x.startsWith('#include "lygia')){var w=x.substring(15).replace(/\'|\"|\;|\s/g,"");if(w.endsWith("glsl")){if(o.deps[w]===void 0){var R="https://lygia.xyz"+w;o.deps[w]=CM(R)}o.fragmentString+=o.deps[w]+
#line +(y+1)+
}}else o.fragmentString+=g+
}),this.animated=!1,this.nDelta=(this.fragmentString.match(/u_delta/g)||[]).length,this.nTime=(this.fragmentString.match(/u_time/g)||[]).length,this.nDate=(this.fragmentString.match(/u_date/g)||[]).length,this.nMouse=(this.fragmentString.match(/u_mouse/g)||[]).length,this.animated=this.nDate>1||this.nTime>1||this.nMouse>1;var s=this.fragmentString.search(/sampler2D/g);if(s)for(var i=this.fragmentString.split(
),a=0;a<i.length;a++){var c=i[a].match(/uniform\s*sampler2D\s*([\w]*);\s*\/\/\s*([\w|\:\/\/|\.|\-|\_]*)/i);if(c){var l=c[2].split(".").pop().toLowerCase();c[1]&&c[2]&&(l==="jpg"||l==="jpeg"||l==="png"||l==="ogv"||l==="webm"||l==="mp4")&&this.setUniform(c[1],c[2])}var u=i[a].match(/\s*void\s*main\s*/g);if(u)break}var p=ps(this,this.vertexString,this.gl.VERTEX_SHADER),f=ps(this,this.fragmentString,this.gl.FRAGMENT_SHADER);f?this.isValid=!0:(f=ps(this,void main(){
gl_FragColor = vec4(1.0);
},this.gl.FRAGMENT_SHADER),this.isValid=!1);var m=wR(this,[p,f]);this.gl.useProgram(m),this.gl.deleteShader(p),this.gl.deleteShader(f),this.program=m,this.change=!0,this.BUFFER_COUNT=0;var h=this.getBuffers(this.fragmentString);Object.keys(h).length&&this.loadPrograms(h),this.buffers=h,this.texureIndex=this.BUFFER_COUNT,this.trigger("load",{}),this.forceRender=!0,this.render()}},{key:"test",value:function(t,r,o){var n=this.vertexString,s=this.fragmentString,i=this.paused,a=this.gl.getExtension("EXT_disjoint_timer_query"),c=a.createQueryEXT(),l=this.isValid;(r||o)&&(this.load(r,o),l=this.isValid,this.forceRender=!0,this.render()),this.paused=!0,a.beginQueryEXT(a.TIME_ELAPSED_EXT,c),this.forceRender=!0,this.render(),a.endQueryEXT(a.TIME_ELAPSED_EXT);var u=this;function p(){u.paused=i,(r||o)&&u.load(s,n)}function f(){u.forceRender=!0,u.render();var m=a.getQueryObjectEXT(c,a.QUERY_RESULT_AVAILABLE_EXT),h=u.gl.getParameter(a.GPU_DISJOINT_EXT);if(m&&!h){var g={wasValid:l,frag:r||u.fragmentString,vert:o||u.vertexString,timeElapsedMs:a.getQueryObjectEXT(c,a.QUERY_RESULT_EXT)/1e6};p(),t(g)}else window.requestAnimationFrame(f)}f()}},{key:"loadTexture",value:function(t,r,o){var n=this;o||(o={}),typeof r=="string"?o.url=r:(typeof r>"u"?"undefined":fl(r))==="object"&&r.data&&r.width&&r.height?(o.data=r.data,o.width=r.width,o.height=r.height):(typeof r>"u"?"undefined":fl(r))==="object"&&(o.element=r),this.textures[t]?this.textures[t]&&(this.textures[t].load(o),this.textures[t].on("loaded",function(s){n.forceRender=!0})):(this.textures[t]=new Of(this.gl,t,o),this.textures[t].on("loaded",function(s){n.forceRender=!0}))}},{key:"refreshUniforms",value:function(){this.uniforms={}}},{key:"setUniform",value:function(t){for(var r={},o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];r[t]=n,this.setUniforms(r)}},{key:"setUniforms",value:function(t){var r=Pf(t);for(var o in r)r[o].type==="sampler2D"?this.loadTexture(r[o].name,r[o].value[0]):this.uniform(r[o].method,r[o].type,r[o].name,r[o].value);this.forceRender=!0}},{key:"setMouse",value:function(t){var r=this.canvas.getBoundingClientRect();if(t&&t.x&&t.x>=r.left&&t.x<=r.right&&t.y&&t.y>=r.top&&t.y<=r.bottom){var o=(t.x-r.left)*this.realToCSSPixels,n=this.canvas.height-(t.y-r.top)*this.realToCSSPixels;this.uniform("2f","vec2","u_mouse",o,n)}}},{key:"uniform",value:function(t,r,o){this.uniforms[o]=this.uniforms[o]||{};for(var n=this.uniforms[o],s=arguments.length,i=Array(s>3?s-3:0),a=3;a<s;a++)i[a-3]=arguments[a];var c=MM(n.value,i);if(c||this.change||!n.location||!n.value){n.name=o,n.type=r,n.value=i,n.method="uniform"+t,this.gl.useProgram(this.program),n.location=this.gl.getUniformLocation(this.program,o),this.gl[n.method].apply(this.gl,[n.location].concat(n.value));for(var l in this.buffers){var u=this.buffers[l];this.gl.useProgram(u.program);var p=this.gl.getUniformLocation(u.program,o);this.gl[n.method].apply(this.gl,[p].concat(n.value))}}}},{key:"uniformTexture",value:function(t,r,o){if(this.textures[t]===void 0)this.loadTexture(t,r,o);else{this.uniform("1i","sampler2D",t,this.texureIndex);for(var n in this.buffers){var s=this.buffers[n];this.gl.useProgram(s.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture)}this.gl.useProgram(this.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture),this.uniform("2f","vec2",t+"Resolution",this.textures[t].width,this.textures[t].height)}}},{key:"resize",value:function(){if(this.width!==this.canvas.clientWidth||this.height!==this.canvas.clientHeight){this.realToCSSPixels=window.devicePixelRatio||1;var t=Math.floor(this.gl.canvas.clientWidth*this.realToCSSPixels),r=Math.floor(this.gl.canvas.clientHeight*this.realToCSSPixels);return(this.gl.canvas.width!==t||this.gl.canvas.height!==r)&&(this.gl.canvas.width=t,this.gl.canvas.height=r,this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)),this.width=this.canvas.clientWidth,this.height=this.canvas.clientHeight,this.resizeSwappableBuffers(),!0}else return!1}},{key:"render",value:function(){if(this.visible=LM(this.canvas),this.forceRender||this.change||this.animated&&this.visible&&!this.paused){var t=new Date,r=performance.now();this.timeDelta=(r-this.timePrev)/1e3,this.timePrev=r,this.nDelta>1&&this.uniform("1f","float","u_delta",this.timeDelta),this.nTime>1&&this.uniform("1f","float","u_time",(r-this.timeLoad)/1e3),this.nDate&&this.uniform("4f","float","u_date",t.getFullYear(),t.getMonth(),t.getDate(),t.getHours()*3600+t.getMinutes()*60+t.getSeconds()+t.getMilliseconds()*.001),this.uniform("2f","vec2","u_resolution",this.canvas.width,this.canvas.height);for(var o in this.buffers){var n=this.buffers[o];this.uniform("1i","sampler2D",n.name,n.bundle.input.index)}this.texureIndex=this.BUFFER_COUNT;for(var s in this.textures)this.uniformTexture(s),this.texureIndex++;this.renderPrograms(),this.trigger("render",{}),this.change=!1,this.forceRender=!1}}},{key:"pause",value:function(){this.paused=!0}},{key:"play",value:function(){this.paused=!1}},{key:"renderPrograms",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.render(r,o,s.program,s.name),t.bindFramebuffer(t.FRAMEBUFFER,null)}t.useProgram(this.program),t.drawArrays(t.TRIANGLES,0,6)}},{key:"getBuffers",value:function(t){var r={};return t&&t.replace(/(?:^\s*)((?:#if|#elif)(?:\s*)(defined\s*\(\s*BUFFER_)(\d+)(?:\s*\))|(?:#ifdef)(?:\s*BUFFER_)(\d+)(?:\s*))/gm,function(){var o=arguments[3]||arguments[4];r["u_buffer"+o]={fragment:"#define BUFFER_"+o+
+t}}),r}},{key:"loadPrograms",value:function(t){var r=this,o=this.gl,n=ps(r,r.vertexString,o.VERTEX_SHADER);for(var s in t){var i=t[s],a=ps(r,i.fragment,o.FRAGMENT_SHADER,1);a?r.isValid=!0:(a=ps(r,void main(){
gl_FragColor = vec4(1.0);
},o.FRAGMENT_SHADER),r.isValid=!1);var c=wR(r,[n,a]);i.name=s,i.program=c,i.bundle=r.createSwappableBuffer(r.canvas.width,r.canvas.height,c),o.deleteShader(a)}o.deleteShader(n)}},{key:"createSwappableBuffer",value:function(t,r,o){var n=this.createBuffer(t,r,o),s=this.createBuffer(t,r,o),i=this.gl;return{input:n,output:s,swap:function(){var a=n;n=s,s=a,this.input=n,this.output=s},render:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),i.bindFramebuffer(i.FRAMEBUFFER,this.input.buffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.output.texture,0),i.drawArrays(i.TRIANGLES,0,6),this.swap()},resize:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),this.input.resize(a,c),this.output.resize(a,c)}}}},{key:"createBuffer",value:function(t,r,o){var n=this.gl,s=this.BUFFER_COUNT;this.BUFFER_COUNT+=2,n.getExtension("OES_texture_float");var i=n.createTexture();n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t,r,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);var a=n.createFramebuffer();return{index:s,texture:i,buffer:a,W:t,H:r,resize:function(c,l){n.bindFramebuffer(n.FRAMEBUFFER,a);var u=Math.min(c,this.W),p=Math.min(l,this.H),f=new Float32Array(u*p*4);n.readPixels(0,0,u,p,n.RGBA,n.FLOAT,f),n.bindFramebuffer(n.FRAMEBUFFER,null);var m=s+1,h=n.createTexture();n.activeTexture(n.TEXTURE0+m),n.bindTexture(n.TEXTURE_2D,h),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,c,l,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,u,p,n.RGBA,n.FLOAT,f);var g=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,h),s=this.index=s,i=this.texture=h,a=this.buffer=g,this.W=c,this.H=l}}}},{key:"resizeSwappableBuffers",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.resize(r,o,s.program,s.name)}t.useProgram(this.program)}},{key:"version",value:function(){return"0.1.7"}}]),e}();function IM(){var e=document.getElementsByClassName("glslCanvas");if(e.length>0){window.glslCanvases=[];for(var t=0;t<e.length;t++){var r=new _R(e[t]);r.isValid&&window.glslCanvases.push(r)}}}window.addEventListener("load",function(){IM()});var dl=_R;var PR=e=>{if(!("after"in e))return Promise.resolve(void 0);let t=document.createElement("canvas");return new dl(t).load(ir(e.after)),e.render(t),Promise.resolve(void 0)};var OR=e=>{let t="";for(let r=0;r<e.length;r+=3)r+2===e.length?t+=Sf(e[r],e[r+1],0):r+1===e.length?t+=Sf(e[r],0,0):t+=Sf(e[r],e[r+1],e[r+2]);return t},hl=e=>e<10?String.fromCharCode(48+e):(e-=10,e<26?String.fromCharCode(65+e):(e-=26,e<26?String.fromCharCode(97+e):(e-=26,e===0?"-":e===1?"_":"?"))),Sf=(e,t,r)=>{let o=e>>2,n=(e&3)<<4|t>>4,s=(t&15)<<2|r>>6,i=r&63;return hl(o&63)+hl(n&63)+hl(s&63)+hl(i&63)};var SR=async(e,t="svg")=>{let r=new Blob([new TextEncoder().encode(e)]).stream().pipeThrough(new CompressionStream("deflate")),o=new Uint8Array(await new Response(r).arrayBuffer());returnhttps://www.plantuml.com/plantuml/${t}/~1${OR(o)}};var LR=async e=>{if(!("after"in e))return;let t=document.createElement("img"),r=await SR(ir(e.after));t.src=r,e.render(t)};var Lf=Promise.resolve({log:new Uint8Array(0)}),gl,NR=(e,t,r,o)=>(Lf=(async()=>{await Lf,gl??=await AM(t,r);let n=new Promise(i=>{let a=c=>{if(c.data.type==="stdout"){o(c.data.message);return}c.data.type==="compile"&&(i(c.data),gl.removeEventListener("message",a))};gl.addEventListener("message",a)}),s={type:"compile",input:e};return gl.postMessage(s),n})(),Lf),AM=async(e,t)=>{let r=new Worker(e,{type:"module"}),o=new Promise(s=>{let i=a=>{a.data.type==="asset-url"&&(s(),r.removeEventListener("message",i))};r.addEventListener("message",i)}),n={type:"asset-url",url:${t}};return r.postMessage(n),await o,r};var MR=(e,t)=>async r=>{if(!("after"in r))return;let o=FM(),n="Compile is not started yet. Please wait...",s=l=>{n=[...n.split(
),l].join(
),o.log(n)},i=document.createElement("img"),a=setTimeout(()=>{r.render(o.div),o.log(n)},2e3),{svg:c}=await NR(ir(r.after),e,t,s);if(clearTimeout(a),!c){r.render(o.div),o.log(n);return}i.src=await Pi(new Blob([c],{type:"image/svg+xml"})),r.render(i)},FM=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=document.createElement("style");r.textContent='*{box-sizing:border-box;}pre{display:block;padding:9.5px;margin:0 0 10px;border:1px solid #ccc;border-radius:4px;height:20em;overflow:auto;font-size:13px;line-height:1.428571429;}pre code{padding:0;font-family:Menlo,Monaco,Consolas,"Courier New",monospace;font-size:inherit;word-break:break-all;word-wrap:break-word;white-space:pre-wrap;color:var(--code-color,#342d9c);background-color: rgba(0,0,0,0);border-radius:0;}',t.append(r);let o=document.createElement("pre"),n=document.createElement("code");return o.append(n),t.append(o),{div:e,log:s=>{n.textContent=s,o.scroll(0,o.scrollHeight)}}};function Qt(e,t){return Ne(e,{...t,weekStartsOn:1})}function Rn(e,t){let r=v(e,t?.in),o=r.getFullYear(),n=U(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=Qt(n),i=U(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=Qt(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function Si(e,t){let r=Rn(e,t),o=U(t?.in||e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Qt(o)}function Nf(e,t){let r,o=t?.in;return e.forEach(n=>{!o&&typeof n=="object"&&(o=U.bind(null,n));let s=v(n,o);(!r||r<s||isNaN(+s))&&(r=s)}),U(o,r||NaN)}function Li(e,t,r){let o=tc(e,t)/1e3;return Ar(r?.roundingMethod)(o)}function yl(e){return(t={})=>{let r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}function us(e){return(t,r)=>{let o=r?.context?String(r.context):"standalone",n;if(o==="formatting"&&e.formattingValues){let i=e.defaultFormattingWidth||e.defaultWidth,a=r?.width?String(r.width):i;n=e.formattingValues[a]||e.formattingValues[i]}else{let i=e.defaultWidth,a=r?.width?String(r.width):e.defaultWidth;n=e.values[a]||e.values[i]}let s=e.argumentCallback?e.argumentCallback(t):t;return n[s]}}var GM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},zM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},VM={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},KM={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},YM={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},XM={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},JM=(e,t)=>{let r=Number(e),o=r%100;if(o>20||o<10)switch(o%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},QM={ordinalNumber:JM,era:us({values:GM,defaultWidth:"wide"}),quarter:us({values:zM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:us({values:VM,defaultWidth:"wide"}),day:us({values:KM,defaultWidth:"wide"}),dayPeriod:us({values:YM,defaultWidth:"wide",formattingValues:XM,defaultFormattingWidth:"wide"})};function ms(e){return(t,r={})=>{let o=r.width,n=o&&e.matchPatterns[o]||e.matchPatterns[e.defaultMatchWidth],s=t.match(n);if(!s)return null;let i=s[0],a=o&&e.parsePatterns[o]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(a)?eC(a,p=>p.test(i)):ZM(a,p=>p.test(i)),l;l=e.valueCallback?e.valueCallback(c):c,l=r.valueCallback?r.valueCallback(l):l;let u=t.slice(i.length);return{value:l,rest:u}}}function ZM(e,t){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function eC(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function FR(e){return(t,r={})=>{let o=t.match(e.matchPattern);if(!o)return null;let n=o[0],s=t.match(e.parsePattern);if(!s)return null;let i=e.valueCallback?e.valueCallback(s[0]):s[0];i=r.valueCallback?r.valueCallback(i):i;let a=t.slice(n.length);return{value:i,rest:a}}}var tC=/^(\d+)(th|st|nd|rd)?/i,rC=/\d+/i,oC={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},nC={any:[/^b/i,/^(a|c)/i]},sC={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},iC={any:[/1/i,/2/i,/3/i,/4/i]},aC={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},cC={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},lC={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},pC={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},uC={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},mC={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},fC={ordinalNumber:FR({matchPattern:tC,parsePattern:rC,valueCallback:e=>parseInt(e,10)}),era:ms({matchPatterns:oC,defaultMatchWidth:"wide",parsePatterns:nC,defaultParseWidth:"any"}),quarter:ms({matchPatterns:sC,defaultMatchWidth:"wide",parsePatterns:iC,defaultParseWidth:"any",valueCallback:e=>e+1}),month:ms({matchPatterns:aC,defaultMatchWidth:"wide",parsePatterns:cC,defaultParseWidth:"any"}),day:ms({matchPatterns:lC,defaultMatchWidth:"wide",parsePatterns:pC,defaultParseWidth:"any"}),dayPeriod:ms({matchPatterns:uC,defaultMatchWidth:"any",parsePatterns:mC,defaultParseWidth:"any"})};var dC={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},hC={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},gC={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},BNe={date:yl({formats:dC,defaultWidth:"full"}),time:yl({formats:hC,defaultWidth:"full"}),dateTime:yl({formats:gC,defaultWidth:"full"})};function Mf(e,t){let r=v(e,t?.in),o=+Qt(r)-+Si(r);return Math.round(o/Yo)+1}function DR(e,t){let r=v(e,t?.in).getDay();return r===0?7:r}function Cf(e){return Math.trunc(+v(e)/1e3)}function jR(e,t,r){let o=v(e,r?.in),n=Mf(o,r)-t;return o.setDate(o.getDate()-n*7),o}function ds(e,t,r){let o=yt(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=v(e,r?.in),i=s.getDay(),a=(t%7+7)%7,c=7-n,l=t<0||t>6?t-(i+c)%7:(a+c)%7-(i+c)%7;return ve(s,l,r)}function BR(e,t,r){let o=v(e,r?.in),n=DR(o,r),s=t-n;return ve(o,s,r)}var _C=class{subPriority=0;validate(e,t){return!0}},PC=class extends _C{constructor(e,t,r,o,n){super(),this.value=e,this.validateValue=t,this.setValue=r,this.priority=o,n&&(this.subPriority=n)}validate(e,t){return this.validateValue(e,this.value,t)}set(e,t,r){return this.setValue(e,t,this.value,r)}};var de=class{run(e,t,r,o){let n=this.parse(e,t,r,o);return n?{setter:new PC(n.value,this.validate,this.set,this.priority,this.subPriority),rest:n.rest}:null}validate(e,t,r){return!0}},OC=class extends de{priority=140;parse(e,t,r){switch(t){case"G":case"GG":case"GGG":return r.era(e,{width:"abbreviated"})||r.era(e,{width:"narrow"});case"GGGGG":return r.era(e,{width:"narrow"});default:return r.era(e,{width:"wide"})||r.era(e,{width:"abbreviated"})||r.era(e,{width:"narrow"})}}set(e,t,r){return t.era=r,e.setFullYear(r,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["R","u","t","T"]},Qe={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},Hr={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Ze(e,t){return e&&{value:t(e.value),rest:e.rest}}function $e(e,t){let r=t.match(e);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function Wr(e,t){let r=t.match(e);if(!r)return null;if(r[0]==="Z")return{value:0,rest:t.slice(1)};let o=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,s=r[3]?parseInt(r[3],10):0,i=r[5]?parseInt(r[5],10):0;return{value:o*(n*Oo+s*Cr+i*Za),rest:t.slice(r[0].length)}}function HR(e){return $e(Qe.anyDigitsSigned,e)}function We(e,t){switch(e){case 1:return $e(Qe.singleDigit,t);case 2:return $e(Qe.twoDigits,t);case 3:return $e(Qe.threeDigits,t);case 4:return $e(Qe.fourDigits,t);default:return $e(new RegExp("^\\d{1,"+e+"}"),t)}}function xl(e,t){switch(e){case 1:return $e(Qe.singleDigitSigned,t);case 2:return $e(Qe.twoDigitsSigned,t);case 3:return $e(Qe.threeDigitsSigned,t);case 4:return $e(Qe.fourDigitsSigned,t);default:return $e(new RegExp("^-?\\d{1,"+e+"}"),t)}}function If(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function WR(e,t){let r=t>0,o=r?t:1-t,n;if(o<=50)n=e||100;else{let s=o+50,i=Math.trunc(s/100)*100,a=e>=s%100;n=e+i-(a?100:0)}return r?n:1-n}function qR(e){return e%400===0||e%4===0&&e%100!==0}var SC=class extends de{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(e,t,r){let o=n=>({year:n,isTwoDigitYear:t==="yy"});switch(t){case"y":return Ze(We(4,e),o);case"yo":return Ze(r.ordinalNumber(e,{unit:"year"}),o);default:return Ze(We(t.length,e),o)}}validate(e,t){return t.isTwoDigitYear||t.year>0}set(e,t,r){let o=e.getFullYear();if(r.isTwoDigitYear){let s=WR(r.year,o);return e.setFullYear(s,0,1),e.setHours(0,0,0,0),e}let n=!("era"in t)||t.era===1?r.year:1-r.year;return e.setFullYear(n,0,1),e.setHours(0,0,0,0),e}},LC=class extends de{priority=130;parse(e,t,r){let o=n=>({year:n,isTwoDigitYear:t==="YY"});switch(t){case"Y":return Ze(We(4,e),o);case"Yo":return Ze(r.ordinalNumber(e,{unit:"year"}),o);default:return Ze(We(t.length,e),o)}}validate(e,t){return t.isTwoDigitYear||t.year>0}set(e,t,r,o){let n=Xo(e,o);if(r.isTwoDigitYear){let i=WR(r.year,n);return e.setFullYear(i,0,o.firstWeekContainsDate),e.setHours(0,0,0,0),Ne(e,o)}let s=!("era"in t)||t.era===1?r.year:1-r.year;return e.setFullYear(s,0,o.firstWeekContainsDate),e.setHours(0,0,0,0),Ne(e,o)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]},NC=class extends de{priority=130;parse(e,t){return xl(t==="R"?4:t.length,e)}set(e,t,r){let o=U(e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Qt(o)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]},MC=class extends de{priority=130;parse(e,t){return xl(t==="u"?4:t.length,e)}set(e,t,r){return e.setFullYear(r,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]},CC=class extends de{priority=120;parse(e,t,r){switch(t){case"Q":case"QQ":return We(t.length,e);case"Qo":return r.ordinalNumber(e,{unit:"quarter"});case"QQQ":return r.quarter(e,{width:"abbreviated",context:"formatting"})||r.quarter(e,{width:"narrow",context:"formatting"});case"QQQQQ":return r.quarter(e,{width:"narrow",context:"formatting"});default:return r.quarter(e,{width:"wide",context:"formatting"})||r.quarter(e,{width:"abbreviated",context:"formatting"})||r.quarter(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=1&&t<=4}set(e,t,r){return e.setMonth((r-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]},IC=class extends de{priority=120;parse(e,t,r){switch(t){case"q":case"qq":return We(t.length,e);case"qo":return r.ordinalNumber(e,{unit:"quarter"});case"qqq":return r.quarter(e,{width:"abbreviated",context:"standalone"})||r.quarter(e,{width:"narrow",context:"standalone"});case"qqqqq":return r.quarter(e,{width:"narrow",context:"standalone"});default:return r.quarter(e,{width:"wide",context:"standalone"})||r.quarter(e,{width:"abbreviated",context:"standalone"})||r.quarter(e,{width:"narrow",context:"standalone"})}}validate(e,t){return t>=1&&t<=4}set(e,t,r){return e.setMonth((r-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]},AC=class extends de{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(e,t,r){let o=n=>n-1;switch(t){case"M":return Ze($e(Qe.month,e),o);case"MM":return Ze(We(2,e),o);case"Mo":return Ze(r.ordinalNumber(e,{unit:"month"}),o);case"MMM":return r.month(e,{width:"abbreviated",context:"formatting"})||r.month(e,{width:"narrow",context:"formatting"});case"MMMMM":return r.month(e,{width:"narrow",context:"formatting"});default:return r.month(e,{width:"wide",context:"formatting"})||r.month(e,{width:"abbreviated",context:"formatting"})||r.month(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=0&&t<=11}set(e,t,r){return e.setMonth(r,1),e.setHours(0,0,0,0),e}},FC=class extends de{priority=110;parse(e,t,r){let o=n=>n-1;switch(t){case"L":return Ze($e(Qe.month,e),o);case"LL":return Ze(We(2,e),o);case"Lo":return Ze(r.ordinalNumber(e,{unit:"month"}),o);case"LLL":return r.month(e,{width:"abbreviated",context:"standalone"})||r.month(e,{width:"narrow",context:"standalone"});case"LLLLL":return r.month(e,{width:"narrow",context:"standalone"});default:return r.month(e,{width:"wide",context:"standalone"})||r.month(e,{width:"abbreviated",context:"standalone"})||r.month(e,{width:"narrow",context:"standalone"})}}validate(e,t){return t>=0&&t<=11}set(e,t,r){return e.setMonth(r,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]},DC=class extends de{priority=100;parse(e,t,r){switch(t){case"w":return $e(Qe.week,e);case"wo":return r.ordinalNumber(e,{unit:"week"});default:return We(t.length,e)}}validate(e,t){return t>=1&&t<=53}set(e,t,r,o){return Ne(oc(e,r,o),o)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]},UC=class extends de{priority=100;parse(e,t,r){switch(t){case"I":return $e(Qe.week,e);case"Io":return r.ordinalNumber(e,{unit:"week"});default:return We(t.length,e)}}validate(e,t){return t>=1&&t<=53}set(e,t,r){return Qt(jR(e,r))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]},$C=[31,28,31,30,31,30,31,31,30,31,30,31],jC=[31,29,31,30,31,30,31,31,30,31,30,31],BC=class extends de{priority=90;subPriority=1;parse(e,t,r){switch(t){case"d":return $e(Qe.date,e);case"do":return r.ordinalNumber(e,{unit:"date"});default:return We(t.length,e)}}validate(e,t){let r=e.getFullYear(),o=qR(r),n=e.getMonth();return o?t>=1&&t<=jC[n]:t>=1&&t<=$C[n]}set(e,t,r){return e.setDate(r),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]},HC=class extends de{priority=90;subpriority=1;parse(e,t,r){switch(t){case"D":case"DD":return $e(Qe.dayOfYear,e);case"Do":return r.ordinalNumber(e,{unit:"date"});default:return We(t.length,e)}}validate(e,t){let r=e.getFullYear();return qR(r)?t>=1&&t<=366:t>=1&&t<=365}set(e,t,r){return e.setMonth(0,r),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]},WC=class extends de{priority=90;parse(e,t,r){switch(t){case"E":case"EE":case"EEE":return r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});case"EEEEE":return r.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});default:return r.day(e,{width:"wide",context:"formatting"})||r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=0&&t<=6}set(e,t,r,o){return e=ds(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]},qC=class extends de{priority=90;parse(e,t,r,o){let n=s=>{let i=Math.floor((s-1)/7)*7;return(s+o.weekStartsOn+6)%7+i};switch(t){case"e":case"ee":return Ze(We(t.length,e),n);case"eo":return Ze(r.ordinalNumber(e,{unit:"day"}),n);case"eee":return r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});case"eeeee":return r.day(e,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});default:return r.day(e,{width:"wide",context:"formatting"})||r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=0&&t<=6}set(e,t,r,o){return e=ds(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]},GC=class extends de{priority=90;parse(e,t,r,o){let n=s=>{let i=Math.floor((s-1)/7)*7;return(s+o.weekStartsOn+6)%7+i};switch(t){case"c":case"cc":return Ze(We(t.length,e),n);case"co":return Ze(r.ordinalNumber(e,{unit:"day"}),n);case"ccc":return r.day(e,{width:"abbreviated",context:"standalone"})||r.day(e,{width:"short",context:"standalone"})||r.day(e,{width:"narrow",context:"standalone"});case"ccccc":return r.day(e,{width:"narrow",context:"standalone"});case"cccccc":return r.day(e,{width:"short",context:"standalone"})||r.day(e,{width:"narrow",context:"standalone"});default:return r.day(e,{width:"wide",context:"standalone"})||r.day(e,{width:"abbreviated",context:"standalone"})||r.day(e,{width:"short",context:"standalone"})||r.day(e,{width:"narrow",context:"standalone"})}}validate(e,t){return t>=0&&t<=6}set(e,t,r,o){return e=ds(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]},zC=class extends de{priority=90;parse(e,t,r){let o=n=>n===0?7:n;switch(t){case"i":case"ii":return We(t.length,e);case"io":return r.ordinalNumber(e,{unit:"day"});case"iii":return Ze(r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o);case"iiiii":return Ze(r.day(e,{width:"narrow",context:"formatting"}),o);case"iiiiii":return Ze(r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o);default:return Ze(r.day(e,{width:"wide",context:"formatting"})||r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o)}}validate(e,t){return t>=1&&t<=7}set(e,t,r){return e=BR(e,r),e.setHours(0,0,0,0),e}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]},VC=class extends de{priority=80;parse(e,t,r){switch(t){case"a":case"aa":case"aaa":return r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"});case"aaaaa":return r.dayPeriod(e,{width:"narrow",context:"formatting"});default:return r.dayPeriod(e,{width:"wide",context:"formatting"})||r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,t,r){return e.setHours(If(r),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]},KC=class extends de{priority=80;parse(e,t,r){switch(t){case"b":case"bb":case"bbb":return r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"});case"bbbbb":return r.dayPeriod(e,{width:"narrow",context:"formatting"});default:return r.dayPeriod(e,{width:"wide",context:"formatting"})||r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,t,r){return e.setHours(If(r),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]},YC=class extends de{priority=80;parse(e,t,r){switch(t){case"B":case"BB":case"BBB":return r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"});case"BBBBB":return r.dayPeriod(e,{width:"narrow",context:"formatting"});default:return r.dayPeriod(e,{width:"wide",context:"formatting"})||r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,t,r){return e.setHours(If(r),0,0,0),e}incompatibleTokens=["a","b","t","T"]},XC=class extends de{priority=70;parse(e,t,r){switch(t){case"h":return $e(Qe.hour12h,e);case"ho":return r.ordinalNumber(e,{unit:"hour"});default:return We(t.length,e)}}validate(e,t){return t>=1&&t<=12}set(e,t,r){let o=e.getHours()>=12;return o&&r<12?e.setHours(r+12,0,0,0):!o&&r===12?e.setHours(0,0,0,0):e.setHours(r,0,0,0),e}incompatibleTokens=["H","K","k","t","T"]},JC=class extends de{priority=70;parse(e,t,r){switch(t){case"H":return $e(Qe.hour23h,e);case"Ho":return r.ordinalNumber(e,{unit:"hour"});default:return We(t.length,e)}}validate(e,t){return t>=0&&t<=23}set(e,t,r){return e.setHours(r,0,0,0),e}incompatibleTokens=["a","b","h","K","k","t","T"]},QC=class extends de{priority=70;parse(e,t,r){switch(t){case"K":return $e(Qe.hour11h,e);case"Ko":return r.ordinalNumber(e,{unit:"hour"});default:return We(t.length,e)}}validate(e,t){return t>=0&&t<=11}set(e,t,r){return e.getHours()>=12&&r<12?e.setHours(r+12,0,0,0):e.setHours(r,0,0,0),e}incompatibleTokens=["h","H","k","t","T"]},ZC=class extends de{priority=70;parse(e,t,r){switch(t){case"k":return $e(Qe.hour24h,e);case"ko":return r.ordinalNumber(e,{unit:"hour"});default:return We(t.length,e)}}validate(e,t){return t>=1&&t<=24}set(e,t,r){let o=r<=24?r%24:r;return e.setHours(o,0,0,0),e}incompatibleTokens=["a","b","h","H","K","t","T"]},eI=class extends de{priority=60;parse(e,t,r){switch(t){case"m":return $e(Qe.minute,e);case"mo":return r.ordinalNumber(e,{unit:"minute"});default:return We(t.length,e)}}validate(e,t){return t>=0&&t<=59}set(e,t,r){return e.setMinutes(r,0,0),e}incompatibleTokens=["t","T"]},tI=class extends de{priority=50;parse(e,t,r){switch(t){case"s":return $e(Qe.second,e);case"so":return r.ordinalNumber(e,{unit:"second"});default:return We(t.length,e)}}validate(e,t){return t>=0&&t<=59}set(e,t,r){return e.setSeconds(r,0),e}incompatibleTokens=["t","T"]},rI=class extends de{priority=30;parse(e,t){let r=o=>Math.trunc(o*Math.pow(10,-t.length+3));return Ze(We(t.length,e),r)}set(e,t,r){return e.setMilliseconds(r),e}incompatibleTokens=["t","T"]},oI=class extends de{priority=10;parse(e,t){switch(t){case"X":return Wr(Hr.basicOptionalMinutes,e);case"XX":return Wr(Hr.basic,e);case"XXXX":return Wr(Hr.basicOptionalSeconds,e);case"XXXXX":return Wr(Hr.extendedOptionalSeconds,e);default:return Wr(Hr.extended,e)}}set(e,t,r){return t.timestampIsSet?e:U(e,e.getTime()-fr(e)-r)}incompatibleTokens=["t","T","x"]},nI=class extends de{priority=10;parse(e,t){switch(t){case"x":return Wr(Hr.basicOptionalMinutes,e);case"xx":return Wr(Hr.basic,e);case"xxxx":return Wr(Hr.basicOptionalSeconds,e);case"xxxxx":return Wr(Hr.extendedOptionalSeconds,e);default:return Wr(Hr.extended,e)}}set(e,t,r){return t.timestampIsSet?e:U(e,e.getTime()-fr(e)-r)}incompatibleTokens=["t","T","X"]},sI=class extends de{priority=40;parse(e){return HR(e)}set(e,t,r){return[U(e,r*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"},iI=class extends de{priority=20;parse(e){return HR(e)}set(e,t,r){return[U(e,r),{timestampIsSet:!0}]}incompatibleTokens="*"},WIe={G:new OC,y:new SC,Y:new LC,R:new NC,u:new MC,Q:new CC,q:new IC,M:new AC,L:new FC,w:new DC,I:new UC,d:new BC,D:new HC,E:new WC,e:new qC,c:new GC,i:new zC,a:new VC,b:new KC,B:new YC,h:new XC,H:new JC,K:new QC,k:new ZC,m:new eI,s:new tI,S:new rI,X:new oI,x:new nI,t:new sI,T:new iI};var GR=(e,t,r=0,o=[])=>{let[n,s]=Q("uninitialized"),[i,a]=Q({ok:!0,value:t}),c=D(e,o);return te(()=>{(async()=>{let l=setTimeout(()=>s("pending"),r);try{let u=await c();if(u===void 0)return;a({ok:!0,value:u})}catch(u){a({ok:!1,value:u})}finally{clearTimeout(l),s("resolved")}})()},[c,r,...o]),i.ok?{result:i.value,state:n}:{result:i.value,state:"rejected"}};var zR=e=>{let t=e.flatMap(({changes:n,created:s,userId:i})=>n.flatMap(a=>{let c=mI(a,i,s);return c?[c]:[]})),r=[...new Set(t.map(({created:n})=>n))].sort();return{history:t.reduce((n,s)=>{if(s.type==="insert"){let a=new Map;a.set(s.created,{text:s.text,type:s.type,userId:s.userId});let c={id:s.id,snapshots:a};if(s.parentId==="_end")return[...n,c];let l=n.findIndex(({id:u})=>u===s.parentId);return l<0?(console.warn("[scrapbox-snapshot@0.1.0] The parent line the snapshot would insert before is not found. change: ",s),[...n,c]):[...n.slice(0,l),c,...n.slice(l)]}let i=n.findIndex(({id:a})=>a===s.id);return i<0?(console.warn("[scrapbox-snapshot@0.1.0] The line data to be append the change is not found. change: ",s),n):(n[i].snapshots.set(s.created,{text:s.type==="update"?s.text:void 0,type:s.type,userId:s.userId}),n)},[]),range:r}},mI=(e,t,r)=>{if("_insert"in e)return{type:"insert",id:e.lines.id,parentId:e._insert,text:e.lines.text,userId:t,created:r};if("_update"in e)return{type:"update",id:e._update,text:e.lines.text,userId:t,created:r};if("_delete"in e)return{type:"delete",id:e._delete,userId:t,created:r}};var Zt=e=>{let{fetch:t=(n,s)=>globalThis.fetch(n,s),baseURL:r="https://scrapbox.io/",...o}=e;return{fetch:t,baseURL:r,...o}};var er=e=>connect.sid=${e};var fI=(e,t,r)=>{let{sid:o,baseURL:n,head:s}=Zt(r??{});return new Request(${n}api/commits/${e}/${t}?head=${s??""},o?{headers:{Cookie:er(o)}}:void 0)},VR=(e,t,r)=>Zt(r??{}).fetch(fI(e,t,r));var YR=async(e,t)=>{let r=await VR(e,t);if(!r.ok)throw new Error(Failed to fetch commits for ${e}/${t}: ${r.statusText},{cause:r});return zR((await r.json()).commits)};var XR=()=>{let e=document.createElement("div");e.dataset.userscriptName="takker99/scrapbox-history-slider";let t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>vt(d(gI,{getController:o=>r(o)}),t))},gI=({getController:e})=>{let[t,r]=Q(!0),o=D(()=>r(!1),[]),n=D(()=>r(!0),[]),s=D(()=>r(h=>!h),[]);te(()=>e({open:o,close:n,toggle:s}),[e]);let i=D(h=>{h.target instanceof HTMLElement&&h.target.id==="background"&&n()},[]),{state:a,result:c}=GR(async()=>{if(t||scrapbox.Layout!=="page")return;let h=await YR(scrapbox.Project.name,scrapbox.Page.id);return{range:h.range,getSnapshot:g=>h.history.flatMap(({snapshots:y})=>{let x=y.get(g);if(x)return x.text===void 0?[]:[x.text];let w=Math.max(...[...y.keys()].filter(b=>b<g));if(w===g)return[];let R=y.get(w)?.text;return R===void 0?[]:[R]})}},{range:[],getSnapshot:()=>[]},1e3,[t]),[l,u]=Q(0),[p,f]=Q(0);te(()=>{if(a!=="resolved")return;let h=Math.max(0,c.range.length-1);u(h),f(h)},[c]);let m=D(h=>f(parseInt(h.currentTarget.value)),[]);return d(ee,{children:[d("style",{children:'.modal{position:fixed;inset:0;z-index:1050;background-color:#000c;display:flex;flex-direction:column;align-items:center;row-gap:10px;padding:10px}.closed{display:none}.modal>*{color:var(--page-text-color, #4a4a4a);background-color:var(--page-bg, #fefefe);border:2px solid var(--body-bg, #dcdde0);border-radius:4px;padding:5px;width:calc(var(--item-width, 100%) - 10px)}@media (min-width: 768px){.modal{padding:30px}}.controller{display:flex;flex-direction:row-reverse;gap:.2em}input{width:100%}time{white-space:nowrap}.viewer{overflow-y:scroll}pre{width:100%;font-family:var(--history-slider-pre-font, Menlo,Monaco,Consolas,"Courier New",monospace);word-break:break-all;word-wrap:break-word;white-space:pre-wrap}'}),d("div",{id:"background",className:modal${t?" closed":""},onClick:i,children:[d("div",{className:"controller",children:[d("button",{type:"button",className:"close-button",onClick:n,children:"x"}),a==="resolved"&&c.range.length===0&&d("span",{className:"not-found",children:"no history found."}),a!=="rejected"&&c.range.length>0&&d(ee,{children:[d("input",{type:"range",max:l,min:"0",step:"1",value:p,title:ct(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),onInput:m}),d("time",{dateTime:ct(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),children:ct(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss")})]})]}),a!=="rejected"?d("div",{className:"viewer",children:d("pre",{children:c.getSnapshot(c.range[p]).join(
)})}):d("div",{className:"error viewer",children:Error: ${JSON.stringify(c)}})]})]})};var vn=()=>/mobile/i.test(navigator.userAgent);function JR(e){return Ke(e)?L(e):(K(e),e)}var yI=Object.defineProperty,xI=(e,t)=>{for(var r in t)yI(e,r,{get:t[r],enumerable:!0})},bI={};xI(bI,{andThen:()=>Hp,andThenAsync:()=>Wp,inspect:()=>qp,map:()=>Gp,mapAsync:()=>zp,mapOr:()=>Vp,mapOrAsync:()=>Kp,mapOrElse:()=>Yp,mapOrElseAsync:()=>Xp,okOr:()=>Jp,okOrElse:()=>Hs,okOrElseAsync:()=>Qp,orElse:()=>Zp,orElseAsync:()=>eu,toNullable:()=>tu,toResultErr:()=>ru,toResultOk:()=>wa,toUndefinable:()=>ou,transposeToResult:()=>JR,unwrapOr:()=>Ws,unwrapOrElse:()=>nu,unwrapOrElseAsync:()=>su});function QR(e,t){return tt(e)?e:t(e)}async function ZR(e,t){return tt(e)?null:await t(e)}function ev(e,t){return je(e)&&t(e),e}function tv(e,t){if(tt(e))return e;let r=t(e);return rt(r,cr)}async function rv(e,t){if(tt(e))return null;let r=await t(e);return rt(r,cr)}function ov(e,t,r){let o,n;return e!==null?(o=r(e),n=cr):(o=t,n=Fn),rt(o,n)}async function nv(e,t,r){if(tt(e))return rt(t,Fn);let o=await r(e);return rt(o,cr)}function sv(e,t,r){let o,n;return je(e)?(o=r(e),n=cr):(o=t(),n=yo),rt(o,n)}async function iv(e,t,r){let o,n;return je(e)?(o=await r(e),n=cr):(o=await t(),n=yo),rt(o,n)}function av(e,t){return je(e)?L(e):M(t)}function cv(e,t){if(je(e))return L(e);let r=t();return M(r)}async function lv(e,t){if(je(e))return L(e);let r=await t();return M(r)}function pv(e,t){return e!==null?e:t()}async function uv(e,t){return je(e)?e:await t()}function mv(e){return tt(e)?M(void 0):L(e)}function fv(e){return tt(e)?L(void 0):M(e)}function dv(e){if(!tt(e))return e}function hv(e){return tt(e)?L(null):(K(e),e)}function gv(e,t){return je(e)?e:rt(t,Fn)}function yv(e,t){if(je(e))return e;let r=t();return rt(r,yo)}async function xv(e,t){if(je(e))return e;let r=await t();return rt(r,yo)}var EI=Object.defineProperty,wI=(e,t)=>{for(var r in t)EI(e,r,{get:t[r],enumerable:!0})},RI={};wI(RI,{andThen:()=>QR,andThenAsync:()=>ZR,inspect:()=>ev,map:()=>tv,mapAsync:()=>rv,mapOr:()=>ov,mapOrAsync:()=>nv,mapOrElse:()=>sv,mapOrElseAsync:()=>iv,okOr:()=>av,okOrElse:()=>cv,okOrElseAsync:()=>lv,orElse:()=>pv,orElseAsync:()=>uv,toResultErr:()=>fv,toResultOk:()=>mv,toUndefinable:()=>dv,transposeToResult:()=>hv,unwrapOr:()=>gv,unwrapOrElse:()=>yv,unwrapOrElseAsync:()=>xv});function bv(e,t){return nt(e)?e:t(e)}async function Ev(e,t){return nt(e)?void 0:await t(e)}function wv(e,t){return ot(e)&&t(e),e}function Rv(e,t){if(nt(e))return e;let r=t(e);return st(r,lr)}async function vv(e,t){if(nt(e))return;let r=await t(e);return st(r,lr)}function kv(e,t,r){let o,n;return e!==void 0?(o=r(e),n=lr):(o=t,n=Dn),st(o,n)}async function Tv(e,t,r){if(nt(e))return st(t,Dn);let o=await r(e);return st(o,lr)}function _v(e,t,r){let o,n;return e!==void 0?(o=r(e),n=lr):(o=t(),n=xo),st(o,n)}async function Pv(e,t,r){let o,n;return ot(e)?(o=await r(e),n=lr):(o=await t(),n=xo),st(o,n)}function Ov(e,t){return ot(e)?L(e):M(t)}function Sv(e,t){if(ot(e))return L(e);let r=t();return M(r)}async function Lv(e,t){if(ot(e))return L(e);let r=await t();return M(r)}function Nv(e,t){return e!==void 0?e:t()}async function Mv(e,t){return ot(e)?e:await t()}function Cv(e){return nt(e)?null:e}function Iv(e){return nt(e)?M(void 0):L(e)}function Av(e){return nt(e)?L(void 0):M(e)}function Fv(e){return nt(e)?L(void 0):(K(e),e)}function Dv(e,t){return ot(e)?e:st(t,Dn)}function Uv(e,t){if(ot(e))return e;let r=t();return st(r,xo)}async function $v(e,t){if(ot(e))return e;let r=await t();return st(r,xo)}var vI=Object.defineProperty,kI=(e,t)=>{for(var r in t)vI(e,r,{get:t[r],enumerable:!0})},TI={};kI(TI,{andThen:()=>bv,andThenAsync:()=>Ev,inspect:()=>wv,map:()=>Rv,mapAsync:()=>vv,mapOr:()=>kv,mapOrAsync:()=>Tv,mapOrElse:()=>_v,mapOrElseAsync:()=>Pv,okOr:()=>Ov,okOrElse:()=>Sv,okOrElseAsync:()=>Lv,orElse:()=>Nv,orElseAsync:()=>Mv,toNullable:()=>Cv,toResultErr:()=>Av,toResultOk:()=>Iv,transposeToResult:()=>Fv,unwrapOr:()=>Dv,unwrapOrElse:()=>Uv,unwrapOrElseAsync:()=>$v});var bl=class{#o=[];#r;#t;constructor(t){if(t<=0||!Number.isSafeInteger(t))throw new RangeError(size must be a positive safe integer, got ${t});this.#r=t,this.#t=t}get locked(){return this.#r===0}get waiterCount(){return this.#o.length}acquire(){if(this.#r>0)return this.#r-=1,Promise.resolve();{let{promise:t,resolve:r}=Promise.withResolvers();return this.#o.push(r),t}}release(){let t=this.#o.shift();t?t():this.#r<this.#t&&(this.#r+=1)}};var El=class{#o;constructor(t){this.#o=new bl(t)}get locked(){return this.#o.locked}get waiterCount(){return this.#o.waiterCount}async lock(t){await this.#o.acquire();try{return await t()}finally{this.#o.release()}}};async function*jv(e,t){if(e.length===0||e.every(({before:n,after:s})=>n===s))return;let r=S(await It()),o=new El(5);try{yield*new ReadableStream({async start(n){let s=[];for(let i of e){if(i.before===i.after){n.enqueue({link:i,projectCount:0,replaced:0,done:!0});continue}let a=0,c=0,l=[];for(let u of new Set(t))l.push(o.lock(async()=>{let p=await _I(i,u,r);if(O(p)){n.error(PI(Z(p)));return}a++,c+=S(p),n.enqueue({link:i,projectCount:a,replaced:c,done:!1})}));s.push(Promise.all(l).then(()=>n.enqueue({link:i,projectCount:a,replaced:c,done:!0})))}await Promise.all(s),n.close()}})}finally{await At(r)}}var _I=async(e,t,r)=>{let[o]=await Promise.all([ka(t,e.before,e.after),Le(t,e.before,(n,{persistent:s})=>{if(s)return[e.after,...n.map(i=>i.text).slice(1)]},{socket:r})]);return o},uo=e=>e.split(
).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),PI=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var Bv=e=>it(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return OI(r);case"table":return SI(r);case"line":return LI(r)}}).map(r=>r).join(
),OI=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},SI=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[${o}table:${e},...t.map(n=>${o} ${n.map(s=>s.map(i=>Ni(i)).join("")).join(" ")})]},LI=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${Ni(r)}).join("")}],Ni=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Ni(t)).join("")};case"strong":return${e.nodes.map(t=>Ni(t)).join("")};case"decoration":{let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return[${t?${t} :""}${e.nodes.map(r=>Ni(r)).join("")}]}case"hashTag":return e.href;case"link":return e.pathType==="absolute"?e.raw:e.href;default:return e.raw}};scrapbox.PopupMenu.addButton({title:e=>uo(e).length>0?"":"",onClick:e=>{let t=Bv(e);if(e!=t)return t}});var Hv=e=>!e.includes(
)&&/\[[^\]]+\]/.test(e);scrapbox.PopupMenu.addButton({title:e=>Hv(e)?"[][]":"",onClick:e=>{if(!Hv(e))return;let t=e.replaceAll("[","").replaceAll("]","");return(async()=>{let{render:r,dispose:o}=Fe();try{let n=scrapbox.Project.name;r({type:"spinner"},{type:"text",text:create /${n}/${t}}),await Le(n,t,([{text:s}],{persistent:i})=>{if(!i)return[s,e]}),r({type:"check-circle"},{type:"text",text:create /${n}/${t}})}catch(n){if(console.error(n),!(n instanceof Error))throw n;r({type:"exclamation-triangle"},{type:"text",text:${n.name} ${n.message}})}finally{await Se(2e3),o()}})(),${t}}});var qv=(e,t)=>{switch(e.type){case"title":return"";case"codeBlock":return[e.fileName,
\\`\`${DI(e.fileName)},e.content,"\n"].join(
);case"table":return NI(e);case"line":return CI(e,t)}},NI=e=>{let t=[e.fileName],r=Math.max(...e.cells.map(o=>o.length));return e.cells.forEach((o,n)=>{t.push(| ${o.map(s=>s.map(i=>ys(i)).join("")).join(" | ")} |),n===0&&t.push(|${" -- |".repeat(r)})}),t.join(
)},MI=" ",CI=(e,t)=>{let r=e.nodes.map(n=>ys(n,{section:e.indent===t})).join("").trim();if(r==="")return"";if(e.indent===t)return r;let o=MI.repeat(e.indent-t-1);return/^\d+\. /.test(r)||(o+="- "),o+r},ys=(e,t)=>{let{section:r=!1}=t??{};switch(e.type){case"quote":return> ${e.nodes.map(o=>ys(o)).join("")};case"helpfeel":return\? ${e.text}\`;case"image":case"strongImage":return![image](${e.src});case"icon":case"strongIcon":return"/icons/hr","/scrapboxlab/hr".includes(e.path)?"---":"";case"strong":return**${e.nodes.map(o=>ys(o)).join("")}**;case"formula":return$${e.formula}$;case"decoration":{let o=e.nodes.map(n=>ys(n)).join("");return e.decos.includes("/")&&(o=*${o}*),r?(e.decos.includes("*-3")&&(o=`# ${o}
),e.decos.includes("*-2")&&(o=## ${o}
),e.decos.includes("*-1")&&(o=### ${o}
)):e.decos.some(n=>/\*-/.test(n[0]))&&(o=**${o}**),e.decos.includes("~")&&(o=~~${o}~~),o}case"code":return\${e.text}\`;case"commandLine":return\`${e.symbol} ${e.text}\`;case"link":switch(e.pathType){case"root":{let,o,...n=e.href.split("/");return[${e.href}](https://scrapbox.io/${o}/${Wv(n.join("/"))})}case"relative":return[${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${Wv(e.href)});default:return e.content===""? ${e.href} :[${e.content}](${e.href})}case"googleMap":return[${e.place}](${e.url});case"hashTag":return[#${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${e.href});case"numberList":return${e.number}. ${e.nodes.map(o=>ys(o)).join("")};case"blank":case"plain":return e.text}},Wv=e=>...e.map((t,r)=>t===" "?"_":!II.includes(t)||r===e.length-1&&AI.includes(t)?encodeURIComponent(t):t).join(""),II='@$&+=:;",',AI=':;",',FI=[{extensions:"javascript","js",fileType:"javascript"},{extensions:"typescript","ts",fileType:"typescript"},{extensions:"cpp","hpp",fileType:"cpp"},{extensions:"c","cc","h",fileType:"c"},{extensions:"cs","csharp",fileType:"cs"},{extensions:"markdown","md",fileType:"markdown"},{extensions:"htm","html",fileType:"html"},{extensions:"json",fileType:"json"},{extensions:"xml",fileType:"xml"},{extensions:"yaml","yml",fileType:"yaml"},{extensions:"toml",fileType:"toml"},{extensions:"ini",fileType:"ini"},{extensions:"tex","sty",fileType:"tex"},{extensions:"svg",fileType:"svg"}],DI=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return FI.find(r=>r.extensions.includes(t))?.fileType??""};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{(async()=>{try{let t=Pc.parse(e,{hasTitle:!1}),r=Math.min(...t.map(o=>o.indent));await navigator.clipboard.writeText(t.map(o=>qv(o,r)).join(`
))}catch(t){alert(Failed to copy:
${JSON.stringify(t)})}})()}});var Gv=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var zv=()=>UI(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),UI=(e,t)=>{if(e)return Gv(e,t),e};var Vv=()=>{let e=zv();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let o=Kv(...r);o&&t.append(o)},dispose:()=>t.remove(),[Symbol.dispose]:()=>t.remove()}},Kv=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[WI()];case"check-circle":return[qI()];case"exclamation-triangle":return[GI()];case"text":return[Rl(o.text)];case"group":{let n=Kv(...o.items);return n?[n]:[]}}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},Rl=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},WI=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Rl(e)},qI=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Rl(e)},GI=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Rl(e)};var Ff=(e,...t)=>{let r=t.reduce((o,n)=>Re(o)?o:o instanceof Promise?o.then(s=>Re(s)?s:n(s)):n(o),e);return r instanceof Promise?r.then(o=>${o}):${r}};var xs=e=>e.ok?L(e):M({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var Yv=e=>window.GM_fetch?.(https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x)?.then?.(t=>ae(xs(t),r=>r.json()));function Nt(e){return e.val}function jt(e){return e.err}var Xv=" must not return ",VI="transformer",KI="recoverer",YI="defaultValue",bs=VI+Xv,mo="called with ",Es=YI+" must not be ",ws=KI+Xv;var XI="Ok",Jv="Err",Qv=mo+Jv,JI=mo+XI,QI="Carrying E in "+Jv+" instead of throwing it directly. See .cause",Df="an instance of Error of the current realm.",HJe="The thrown value is not "+Df,WJe="The contained E should be "+Df,ZI="This .cause is not "+Df;function wt(e){return e.ok}function Ce(e){return{ok:!0,val:e,err:null}}function ie(e){return!e.ok}function Mt(e){return{ok:!1,val:null,err:e}}function ke(e){return Zv(e,Qv)}function Zv(e,t){if(ie(e))throw new TypeError(t);return e.val}function Mi(e,t){if(ie(e))return e;let r=Nt(e),o=t(r);return Ce(o)}async function qe(e,t){if(ie(e))return e;let r=Nt(e),o=await t(r);return Ce(o)}async function et(e,t){if(wt(e))return e;let r=jt(e),o=await t(r);return Mt(o)}async function vl(e,t){if(wt(e))return e;let r=jt(e);return await t(r)}var kl="null",tZe=bs+kl,rA=mo+kl,rZe=Es+kl,oZe=ws+kl;var Tl="undefined",cZe=bs+Tl,oA=mo+Tl,lZe=Es+Tl,pZe=ws+Tl;var Ge=e=>e.ok?Ce(e):Mt({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var tk=async(e,t)=>{let r=new Request(e,t);try{return Ce(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return Mt({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return Mt({name:"NetworkError",message:o.message,request:r});throw o}};var Ie=e=>{let{fetch:t=tk,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var rk=e=>{let{sid:t,hostName:r}=Ie(e??{});return new Request(https://${r}/api/users/me,t?{headers:{Cookie:ze(t)}}:void 0)},ok=e=>qe(Ge(e),async t=>await t.json()),nk=(()=>{let e=async t=>{let{fetch:r,...o}=Ie(t??{}),n=await r(rk(o));return ie(n)?n:ok(ke(n))};return e.toRequest=rk,e.fromResponse=ok,e})();var ze=e=>connect.sid=${e},fo=async e=>{let t=e?.csrf??globalThis._csrf;return t?Ce(t):Mi(await nk(e),r=>r.csrfToken)};var Bt=async(e,t)=>{let r=e.response.clone(),o=Wo(t);try{let n=await r.json();if(!bo(n))return;if(r.status===422){if(!Re(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!Re(n.message)?void 0:n.name==="NotLoggedInError"?!bo(n.detals)||!Re(n.detals.project)||!Bs(iA)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},iA=Wo(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var _l="null or undefined",Rs=bs+_l,aA=mo+_l,Uf=Es+_l,Pl=ws+_l;function qr(e){return e==null}function Ol(e){return qr(e)?Mt(void 0):Ce(e)}var sk=(e,t)=>{let{sid:r,hostName:o}=Ie(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:ze(r)}}:void 0)},ik=async e=>qe(await et(Ge(e),async t=>await Bt(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),ak=(()=>{let e=async(t,r)=>{let{fetch:o}=Ie(r??{}),n=sk(t,r),s=await o(n);return ie(s)?s:ik(ke(s))};return e.toRequest=sk,e.fromResponse=ik,e})();var ck=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=Ie(t??{}),s=await fo(t);if(ie(s))return s;let i=new Request(https://${o}/api/embed-text/url?url=${encodeURIComponent(${e})},{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":ke(s),...r?{Cookie:ze(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return ie(a)?a:qe(await et(Ge(ke(a)),async c=>await Bt(c,["SessionError","BadRequestError","InvalidURLError"])??c),async c=>{let{title:l}=await c.json();return l})};var lk=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=Ie(t??{}),s=await fo(t);if(ie(s))return s;let i=new Request(https://${o}/api/embed-text/twitter?url=${encodeURIComponent(${e})},{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":ke(s),...r?{Cookie:ze(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return ie(a)?a:et(await qe(Ge(ke(a)),c=>c.json()),async c=>c.response.status===422?{name:"InvalidURLError",message:(await c.response.json()).message}:await Bt(c,["SessionError","BadRequestError"])??c)};var pk=async e=>{let{fetch:t,sid:r,hostName:o,gyazoTeamsName:n}=Ie(e??{}),s=new Request(https://${o}/api/login/gyazo/oauth-upload/token${n??gyazoTeamsName=${n}:""},r?{headers:{Cookie:ze(r)}}:void 0),i=await t(s);return ie(i)?i:qe(await et(Ge(ke(i)),async a=>await Bt(a,["NotLoggedInError"])??a),a=>a.json().then(c=>c.token))};var uk=async(e,t,r)=>{let o=${hu(du(await e.arrayBuffer()))},n=await lA(e,t,o,r);if(ie(n))return n;let s=ke(n);if("embedUrl"in s)return Ce(s);let i=await pA(s.signedUrl,e,r);return ie(i)?i:uA(t,s.fileId,o,r)},lA=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=Ie(o??{}),c={md5:r,size:e.size,contentType:e.type,name:e.name},l=await vl(Ol(a),()=>fo(o));if(ie(l))return l;let u=new Request(https://${s}/api/gcs/${t}/upload-request,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":ke(l),...n?{Cookie:ze(n)}:{}}}),p=await i(u);return ie(p)?p:qe(await et(Ge(ke(p)),async f=>f.response.status===402?{name:"FileCapacityError",message:(await f.response.json()).message}:f),f=>f.json())},pA=async(e,t,r)=>{let{sid:o,fetch:n}=Ie(r??{}),s=await n(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...o?{Cookie:ze(o)}:{}}});return ie(s)?s:Mi(await et(Ge(ke(s)),async i=>i.response.headers.get("Content-Type")?.includes?.("/xml")?{name:"GCSError",message:await i.response.text()}:i),()=>{})},uA=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=Ie(o??{}),c=await vl(Ol(a),()=>fo(o));if(ie(c))return c;let l=new Request(https://${s}/api/gcs/${e}/verify,{method:"POST",body:JSON.stringify({md5:r,fileId:t}),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":ke(c),...n?{Cookie:ze(n)}:{}}}),u=await i(l);return ie(u)?u:qe(await et(Ge(ke(u)),async p=>p.response.status===404?{name:"NotFoundError",message:(await p.response.json()).message}:p),p=>p.json())};var mk=(e,t)=>{let r=new FormData;return r.append("data",e),r.append("metadata",JSON.stringify({app:"Gyazo",title:e.name})),GM_fetch(https://gif.gyazo.com/${t?.teams?"teams":"gif"}/upload,{method:"POST",body:r,credentials:"include",headers:{Origin:"https://gyazo.com","sec-fetch-site":"same-site"},referrer:"https://gyazo.com/"})};var Sl="",fk=!1,Ll=new Map,dk=async(e,t,r,o)=>{let n=Ll.get(e.href);if(n)return n;if(e.hostname==="video.twimg.com"||${e}.endsWith(".svg")){let l=await GM_fetch(e);if(!l.ok)return;let u=l.headers.get("content-type")?.split?.(";")?.[0]??${e}.endsWith(".mp4")?"video/mp4":"video/webm",p=new File([await l.blob()],o||${t},{type:u});if(u==="video/mp4"){let h=await mk(p);if(h.ok){let g=new URL(await h.text());return Ll.set(e.href,g),g}}let f=await uk(p,r);if(O(f))throw Error(Z(f).name);let m=new URL(S(f).embedUrl);return Ll.set(e.href,m),m}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(fk){if(!Sl)return}else{let l=await pk();if(fk=!0,O(l)){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(Sl=S(l)||"",!Sl){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let i=await kg(await s.blob(),{accessToken:Sl,refererURL:t,description:o});if(!i.ok)throw new Error(Gyazo upload failed: ${i.status} ${i.statusText});let a=await i.json(),c=new URL(a.permalink_url);return Ll.set(e.href,c),c};var yk=[["&","&amp;"],["<","&lt;"],[">","&gt;"],['"',"&quot;"],["'","&#39;"]],mA=Object.fromEntries([...yk.map(([e,t])=>[t,e]),["&apos;","'"],["&nbsp;"," "]]),fA=new Map(yk),pit=new RegExp([${...fA.keys().join("")}],"g");var dA={entityList:mA},hA=1114111,gA=/&#([0-9]+);/g,yA=/&#x(\p{AHex}+);/gu,hk=new WeakMap;function $f(e,t={}){let{entityList:r}={...dA,...t},o=hk.get(r);return o||(o=new RegExp((${Object.keys(r).sort((n,s)=>s.length-n.length).join("|")}),"g"),hk.set(r,o)),e.replaceAll(o,n=>r[n]).replaceAll(gA,(n,s)=>gk(s,10)).replaceAll(yA,(n,s)=>gk(s,16))}function gk(e,t){let r=parseInt(e,t);return r>hA?"�":String.fromCodePoint(r)}var Nl=e=>{let t={name:e.user.name,screenName:e.user.screen_name},r=new Date(e.created_at),o=[...e.entities.hashtags?.map?.(i=>({type:"hashtag",...i}))??[],...e.entities.symbols?.map?.(i=>({type:"symbol",...i}))??[],...e.entities.user_mentions?.map?.(i=>({type:"mention",name:i.name,screenName:i.screen_name,indices:i.indices}))??[],...e.entities.urls?.map?.(i=>{let a={type:"url",indices:i.indices,url:new URL(i.expanded_url)};if(e.card&&e.card?.url===i.url){let{description:c,title:l}=e.card.binding_values,u="STRING";c?.type===u&&(a.description=c.string_value),l?.type===u&&(a.title=l.string_value)}return a})??[],...e.entities.media?.map?.(i=>({type:"media",indices:i.indices,media:e.mediaDetails?.flatMap?.(a=>a.url===i.url?[{type:a.type,url:new URL(a.video_info?.variants?.sort?.((c,l)=>(l.bitrate??0)-(c.bitrate??0))?.[0].url??a.media_url_https)}]:[])??[]}))??[]].sort((i,a)=>i.indices[0]-a.indices[0]),n=[];{let i=0,a=e.text;for(let{indices:c,...l}of o){let u=[...a].slice(0,c[0]-i).join("");n.push({type:"plain",text:$f(u)}),n.push(l),a=[...a].slice(c[1]-i).join(""),i=c[1]}a&&n.push({type:"plain",text:$f(a)})}let s={id:e.id_str,content:n,author:t,posted:r,replyCount:"reply_count"in e?e.reply_count:e.conversation_count};return e.self_thread&&(s.rootId=e.self_thread.id_str),e.in_reply_to_status_id_str&&(s.replyId=e.in_reply_to_status_id_str),e.parent&&(s.replyTo=Nl(e.parent)),e.quoted_tweet&&(s.quote=Nl(e.quoted_tweet)),s};var xA=["landing","product","enterprise","pricing","try-enterprise","contact","terms","privacy","jp-commercial-act","support","case","features","business","auth","login","logout","oauth2","_","api","app.html","assets","file","files","billing","billings","config","feed","index","io","new","opensearch","project","projects","search","setting","settings","setup-profile","slide","socket.io","stream","user","users"],Ml=(e=scrapbox.Project.name,t=location.host)=>r=>{if(r.host!==t)return r;let[,o,n]=r.pathname.match(/^\/([\w\d][\w\d-]{0,22}[\w\d])(?:\/?|\/(.+))$/)??[];return!o||xA.includes(o)?r:n?o===e?${decodeURIComponent(n)}:/${o}/${decodeURIComponent(n)}:/${o}};var xk=(e=bA)=>t=>{let[,r]=t.href.match(/^https:\/\/(?:www\.|mobile\.|m\.|)(?:twitter|x)\.com\/[A-Za-z0-9_]*\/(?:status|statuses)\/(\d+)/)??[];return r?(async()=>{let o=await(Yv(r)??lk(t.href));if(O(o))throw Z(o);let n=S(o);return e("images"in n?{...n,id:r}:n,t)})():t},bA=async e=>{if("images"in e)return Ci(e);let{quote:t,replyTo:r,...o}=Nl(e);return[...r?[...(await Ci(r)).split(
).map(n=> > ${n}),...r.quote?(await Ci(r.quote)).split(
).map(n=> > ${n}):[]]:[],...(await Ci(o)).split(
).map(n=>> ${n}),...t?(await Ci(t)).split(
).map(n=>> > ${n}):[]].join(
)},Ci=async e=>{let t=new URL(https://twitter.com/${"author"in e?e.author.screenName:e.screenName}/status/${e.id});if("images"in e)return[> @${Ii(e.screenName)} ${t.origin}${t.pathname},...e.description?.split?.(
)?.map?.(n=>> ${Ii(n)})??["> [/ no description provided]"],...e.images.length>0?[> ${e.images.map(n=>[${n}])}]:[]].join(
);let r=e.content,o=e.author.screenName;return[@${Ii(o)} ${t},...(await Promise.all(r.map(async n=>{switch(n.type){case"plain":return n.text;case"hashtag":return #${n.text} ;case"symbol":return #$${n.text} ;case"mention":return@${n.screenName};case"media":{let s=[],i=1;for(;i<n.media.length;i+=2)s.push([${await jf(n.mediai-1,t)}] [${await jf(n.mediai,t)}]);return i===n.media.length&&s.push([${await jf(n.mediai-1,t)}]),
${s.join(`
`)}
}case"url":return${Ml()(n.url)} }}))).join("").split(
)].join(
)},Cl="",EA=async()=>{if(Cl)return Cl;let e=await ak(scrapbox.Project.name);if(O(e))throw new Error(Z(e).name);return Cl=S(e).id,Cl},jf=async(e,t)=>await dk(e.url,t,await EA(),"")??e.url,Ii=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]]\s*/g," ").trim();var bk=e=>window.GM_fetch?.(https://t.co/${e})?.then?.(t=>ae(xs(t),async r=>{let o=new DOMParser().parseFromString(await r.text(),"text/html");try{return new URL(o.title)}catch(n){if(n instanceof TypeError)return;throw n}}));var Ek=e=>{let t=window.GM_fetch;if("bit.ly","amzn.to","amzn.asia","goo.gl","s.nikkei.com","apple.co","nico.ms","w.wiki".includes(e.hostname)&&t)return t(e).then(o=>o.ok?new URL(o.url):e);if(e.hostname!=="t.co")return e;let r=bk(e.pathname.slice(1));return r?r.then(o=>js(o,()=>e,n=>n??e)):e};var wk=e=>{if(!e.pathname.startsWith("/wiki/"))return e;if(!/^\w+\.wikipedia\.org$/.test(e.hostname)){let,n=e.hostname.match(/^(\w+)\.m\.wikipedia\.org$/)??[];if(!n)return e;e.hostname=${n}.wikipedia.org}let t=decodeURIComponent(e.pathname.slice(6)),r=e.hash?decodeURIComponent(e.hash.slice(1)):"",o=${e.origin}/wiki/${t};return r?[${r} | ${t} - Wikipedia ${o}#${r}]:[${t} - Wikipedia ${o}]};var Rk=e=>{if(e.hostname!=="www.wikiwand.com")return e;let,t,r=e.pathname.match(/^\/(^\/+)\/(^\/+)/)??[];return!t||!r||(e.hostname=${t}.wikipedia.org,e.pathname=/wiki/${r},e.hash=e.hash.startsWith("#/")?#${e.hash.slice(2)}:e.hash),e};var Bf=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var vk=/charset=(^;+)/,kk=e=>window.GM_fetch?.(${e})?.then?.(t=>ae(xs(t),async r=>{let o=r.headers.get("content-type")?.match?.(vk)?.1??await wA(r.clone());return new TextDecoder(o).decode(await r.arrayBuffer())})),wA=async e=>{let t=new DOMParser().parseFromString(await e.text(),"text/html");return t.querySelector("metacharset")?.getAttribute?.("charset")??t.querySelector('metahttp-equiv="content-type"')?.getAttribute?.("content")?.match?.(vk)?.1??"utf-8"};var Il=(e=Hf)=>async t=>e(await RA(t),t),Hf=(e,t)=>{let r=(Re(e)?e:e.title).replace(/\s/g," ").replaceAll("","[").replaceAll("","]");return r?[${t.hash?${decodeURIComponent(t.hash.slice(1))} | :""}${r} ${t}]:${t}},RA=async e=>{let t=kk(e);if(!t){let o=await ck(e);if(O(o))throw Z(o);return S(o)}let r=await t;if(O(r))throw Z(r);return new DOMParser().parseFromString(S(r),"text/html")};var Tk=e=>{if(!/^(?:www\.)?amazon(?:\.co|com)?\.(?:au|br|ca|fr|de|in|it|jp|mx|nl|sg|es|tr|ae|uk|cn)$/.test(e.hostname))return e;let,t=e.pathname.match(/\/dp\/(\w\d+)/)??e.pathname.match(/\/gp\/product\/(\w\d+)/)??e.pathname.match(/\/exec\/obidos\/asin\/(\w\d+)/)??e.pathname.match(/\/o\/ASIN\/(\w\d+)/)??[];return t&&(e.hash="",e.search="",e.pathname=/dp/${t}),e};var _k=e=>{if(!/(?:0-9a-z-\.)?gyazo\.com/.test(e.hostname))return e;let,t=e.pathname.match(/^\/(0-9a-f{32})(?:\/raw)?$/)??[];return t?[https://gyazo.com/${t}]:e};var Pk=(e,...t)=>{if(e instanceof URL)return Ff(new URL(e),...t);let r=0,o=0,n=0,s=!1,i=e.split(/(https?:\/\/\S+)/g).map(u=>{if(!/^https?:\/\/\S+$/.test(u))return u;r++;try{let p=Ff(new URL(u),...t);return Re(p)?(o++,p):(s=!0,p,u)}catch(p){return console.error(p),n++,u}});if(!s)return i.join("");let{render:a,dispose:c}=Vv(),l=()=>a({type:"spinner"},{type:"text",text:URL: ${o}/${r} converted, ${n} failed});return l(),Promise.all(i.map(async u=>{if(Re(u))return u;try{let p=await u0;return o++,p}catch(p){return console.error(p),n++,u1}finally{l()}})).then(u=>(a({type:"check-circle"},{type:"text",text:URL: ${o}/${r} converted, ${n} failed}),u.join(""))).finally(()=>{setTimeout(c,1e3)})};var Ok=e=>{if(!/^(?:\w+\.nicovideo\.jp|nico\.ms)$/.test(e.hostname))return e;let t=e.pathname.match(/(?:sm|nm|so|ca|ax|yo|nl|ig|na|cw|za-e|om|sk|yk|lv)\d{1,14}$/)?.0;return t?[https://nicothumb2img.vercel.app/image/${t}#.png https://nico.ms/${t}]:e};var Sk=e=>e.hostname!=="catalog.he.u-tokyo.ac.jp"||!e.pathname.startsWith("/detail")||!e.searchParams.get("code")||!e.searchParams.has("year")?e:Il(vA)(e),vA=(e,t)=>{if(typeof e=="string")return Hf(e,t);let r=e.getElementsByClassName("code-cell")1.children1.textContent,o=[...e.getElementsByClassName("semester-cell")1.children].map(a=>a.textContent.trim()),n=Ii(e.getElementsByClassName("name-cell")1.textContent.trim()),s=e.getElementsByClassName("period-cell")1.textContent.trim().split("、").map(a=>a.replace(/(.)曜(\d)限/,"$1$2")),i=e.getElementsByClassName("catalog-page-detail-sub-table-row")0.lastElementChild?.textContent?.trim?.()??0;return${o.join("")} ${s.join("")} ${n} ${i}[. ${t}]};var Lk=e=>it(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return kA(r);case"table":return TA(r);case"line":return _A(r)}}).map(r=>r).join(`
),kA=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},TA=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[${o}table:${e},...t.map(n=>${o} ${n.map(s=>s.map(i=>i.raw).join("")).join(" ")})]},_A=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${Ai(r)}).join("")}],Ai=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Ai(t)).join("")};case"helpfeel":return-? ${e.text};case"commandLine":return-${e.symbol} ${e.text};case"icon":case"strongIcon":case"image":case"strongImage":case"formula":case"code":case"googleMap":return e.raw;case"strong":return${e.nodes.map(t=>Ai(t)).join("")};case"decoration":{e.decos.includes("-")||e.decos.push("-");let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return[${t?${t} :""}${e.nodes.map(r=>Ai(r)).join("")}]}case"link":switch(e.pathType){case"root":case"relative":return${e.href};case"absolute":return[- ${e.content?${e.content} :""}${e.href}]]}case"hashTag":return#${e.href};case"numberList":return${e.number}. ${e.nodes.map(t=>Ai(t)).join("")};case"blank":case"plain":return${e.text}}};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=Lk(e);if(e!==t)return t}});var Wf=e=>{let t=e.indexOf(
);if(t<0)return;let r=e.slice(0,t).split(
).map(s=>{let[i="",a=""]=s.split(" => ",2);return[i,a]});if(r.length===0)return;let o=e.slice(t+2).split(
);if(o.length===0)return;for(let[s,i]of r){let a=s.match(/^\/(.*?)\/([gimy]*)$/);if(a){let c=new RegExp(a[1],a[2]);o=o.map(l=>l.replace(c,i.replaceAll("\\n",
)))}else o=o.map(c=>c.replaceAll(s,i.replaceAll("\\n",
)))}let n=${e.slice(0,t+2)}${o.join(`
)};if(e!==n)return n};scrapbox.PopupMenu.addButton({title:e=>Wf(e)?"replace":"",onClick:e=>{let t=Wf(e);if(t!==void 0)return t}});var Nk=e=>{let t=document.createElement("div"),r=t.attachShadow({mode:"open"}),o=document.createElement("style");o.textContent="dialog::backdrop{background-color:#000c}dialog{flex-direction:column;align-items:center;row-gap:10px;padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset}dialogopen{display:flex}dialog>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}@media (min-width: 768px){dialog{padding:30px 0}}.container{display:flex;padding:5px;gap:0.2em;flex-direction:column;width:100%;}.button-container{flex-direction:unset;}.button-container>*{flex:1;}",r.append(o);let n=document.createElement("dialog");n.insertAdjacentHTML("beforeend",`
<div class="container">
Replace Links:
<textarea class="editor"></textarea>
<div class="container button-container">
<button class="cancel">cancel</button>
<button class="replace">replace</button>
</div>
</div>
),r.append(n);let s=n.querySelector(".editor");s.rows=e.length,s.value=e.join(
);let i=()=>{n.style.minWidth=${Math.max(...s.value.split(`
).map(u=>[...u].length))+6}em};i(),s.addEventListener("input",i);let a=n.querySelector(".cancel"),c=n.querySelector(".replace"),l=new Promise(u=>{let p=()=>{u({convert:!1}),t.remove()};n.addEventListener("close",p),n.addEventListener("click",p),a.addEventListener("click",p),c.addEventListener("click",()=>{let f=s.value.split(`
);u({convert:!0,links:e.flatMap((m,h)=>m===f[h]||m===""||!f[h]?[]:[{before:m,after:f[h]??m}])}),t.remove()}),n.querySelector(".container").addEventListener("click",f=>{f.stopPropagation()})});return document.body.append(t),n.showModal(),l};var Mk=async(e,t)=>{let r=uo(e),o=await Nk([...new Set(r)]);if(!o.convert||o.links.length===0)return;let n=new Map(o.links.map(s=>[s.before,Fe()]));for await(let{link:s,projectCount:i,replaced:a,done:c}of jv(o.links,t)){let l=n.get(s.before);if(l){if(c){l.render({type:"check-circle"},{type:"text",text:"${s.after}", ${a}l. ${i}p.}),setTimeout(()=>l.dispose(),1e3);continue}l.render({type:"spinner"},{type:"text",text:"${s.after}", ${a}l. ${i}p.})}}};var Ck=async(e,t)=>{let r=uo(e)[0];if(!r)return;let o=window.prompt(Replace "${r}" to this in ${t.map(a=>"/${a}").join(", ")},r)?.replace?.(/[\[\]\n]/g," ")??"";if(o==="")return;let{render:n,dispose:s}=Fe(),i=S(await It());try{n({type:"spinner"},{type:"text",text:Replacing links in ${t.length} projects...});let a=0,l=(await Promise.all(t.map(async u=>{let[p]=await Promise.all([ka(u,r,o),Le(u,r,(f,{persistent:m})=>{if(m)return[o,...f.map(h=>h.text).slice(1)]},{socket:i})]);if(O(p))throw n({type:"exclamation-triangle"},{type:"text",text:${Z(p).name} ${Z(p).message}}),PA(Z(p));return a++,n({type:"spinner"},{type:"text",text:Replacing links in ${t.length-a} projects...}),S(p)}))).reduce((u,p)=>u+p,0);n({type:"check-circle"},{type:"text",text:Successfully replaced ${l} links.})}finally{await At(i),setTimeout(s,1e3)}},PA=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var Ik=e=>{let t=[scrapbox.Project.name,...e];scrapbox.PopupMenu.addButton({title:r=>{let o=uo(r).length;return o>1?"update links":o===1?"update a link":""},onClick:r=>{let o=uo(r).length;o>1?Mk(r,t):o===1&&Ck(r,t)}})};scrapbox.PopupMenu.addButton({title:e=>/[\n..。]/.test(e)?"\\n":"",onClick:e=>e.replace(/(\w)\n(\w)/g,"$1 $2").replaceAll(
,"").replaceAll(".",.
).replaceAll(".",.
).replaceAll("。",。
)});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/[a-z0-9]+/.test(e)?globalThis.GM_fetch?"copy Gyazo OCR":"open Gyazo":"",onClick:async e=>{let t=e.match(/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/([a-z0-9]+)/)?.[1];if(!t)return;if(!globalThis.GM_fetch){window.open(https://gyazo.com/${t});return}let o=(await(await GM_fetch(https://gyazo.com/${t}.json)).json()).metadata?.ocr?.description;if(o)try{await navigator.clipboard.writeText(o)}catch(n){console.error(n),alert(${n.name} ${n.message})}}});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/gyazo\.com\/[a-z0-9]+/.test(e)?"":"",onClick:e=>{let t=e.match(/https:\/\/gyazo\.com\/([a-z0-9]+)/)?.[1];t&&window.open(https://gyazo.com/${t}/transform)}});var Ak=e=>{let t="",r=0;for(let o of e)if(o.type!=="title"){if(o.indent>r)for(let n=r;n<o.indent;n++)t+=Fi(${n!==r?"\\item":""}\\begin{itemize},n*2)+
;if(o.indent<r)for(let n=r;n>o.indent;n--)t+=Fi("\\end{itemize}",(n-1)*2)+
;r=o.indent,t+=Fi(${r>0?"\\item ":""}${OA(o)},r*2)+
}for(let o=r;o>0;o--)t+=Fi("\\end{itemize}",(o-1)*2)+
;return t},OA=e=>{switch(e.type){case"codeBlock":return SA(e);case"table":return LA(e);case"line":return NA(e)}},SA=e=>\\begin{lstlisting}language=${tr(CA(e.fileName))},caption=${tr(e.fileName)},label=lang:${e.fileName},numbers=left
${e.content}
\\end{lstlisting},LA=e=>{let t=\\caption{${tr(e.fileName)}}\\label{table:${tr(e.fileName)}},r=Math.max(...e.cells.map(n=>n.length)),o=e.cells.map(n=> ${n.map(s=>s.map(i=>vs(i)).join("")).join(" & ")}\\\\);return\\begin{table}htbp
${t}
\\centering
\\begin{tabular}{${"c".repeat(r)}}
${o.length===0?"":o.length===1?` \\toprule
${o.join(`
`)}
\\bottomrule: \\toprule
${o0}
\\midrule
${o.slice(1).join(`
`)}
\\bottomrule`}
\\end{tabular}
\\end{table}},NA=e=>e.nodes.map(t=>vs(t)).join(""),vs=e=>{switch(e.type){case"quote":return\\begin{quote}
${Fi(e.nodes.map(t=>vs(t)).join(""),2)}
\\end{quote};case"image":case"strongImage":return\\begin{figure}hbtp
iamge:\\url{${e.src}}
\\end{figure};case"icon":case"strongIcon":return\\textit{${tr(e.path)}};case"strong":return\\textbf{${e.nodes.map(t=>vs(t)).join("")}};case"formula":return$${e.formula}$;case"decoration":{let t=e.nodes.map(r=>vs(r)).join("");return e.decos.includes("/")&&(t=\\textit{${t}}),e.decos.some(r=>/\*-/.test(r[0]))&&(t=\\textbf{${t}}),e.decos.includes("_")&&(t=\\uline{${t}}),e.decos.includes("-")&&(t=\\sout{${t}}),t}case"numberList":return${e.number}. ${e.nodes.map(t=>vs(t)).join("")};case"helpfeel":return\\lstinline!? ${tr(e.text)}!;case"code":return\\lstinline!${tr(e.text)}!;case"commandLine":return\\lstinline!${tr(e.symbol)} ${tr(e.text)}!;case"link":return e.pathType==="absolute"?e.content===""?\\url{${e.href}}:\\href{${e.href}}{${tr(e.content)}}:tr(e.href);case"googleMap":return\\href{${e.url}}{${tr(e.place)}};case"hashTag":return tr(#${e.href});case"blank":case"plain":return tr(e.text)}},MA=[{extensions:["javascript","js"],fileType:"javascript"},{extensions:["typescript","ts"],fileType:"typescript"},{extensions:["cpp","hpp"],fileType:"C++"},{extensions:["c","cc","h"],fileType:"C"},{extensions:["cs","csharp"],fileType:"cs"},{extensions:["markdown","md"],fileType:"markdown"},{extensions:["htm","html"],fileType:"html"},{extensions:["json"],fileType:"json"},{extensions:["xml"],fileType:"xml"},{extensions:["yaml","yml"],fileType:"yaml"},{extensions:["toml"],fileType:"toml"},{extensions:["ini"],fileType:"ini"},{extensions:["tex","sty"],fileType:"tex"},{extensions:["svg"],fileType:"svg"}],CA=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return MA.find(r=>r.extensions.includes(t))?.fileType??""},tr=e=>e.replaceAll("\\","\\textbackslash ").replaceAll("#","\\#").replaceAll("%","\\%").replaceAll("$","\\$").replaceAll("&","\\&").replaceAll("~","\\textasciitilde ").replaceAll("^","\\textasciicircum ").replaceAll("_","\\_").replaceAll("{","\\{").replaceAll("}","\\}").replaceAll("|","\\textbar ").replaceAll("<","\\textless ").replaceAll(">","\\textgreater "),Fi=(e,t)=>e.split(
).map(r=>${" ".repeat(t)}${r}).join(
);scrapbox.PopupMenu.addButton({title:"TeX",onClick:e=>{navigator.clipboard.writeText(Ak(it(e))).catch(t=>{console.error(t),alert(${t.name} ${t.message}
${t.stack})})}});var Al="https://keicho.herokuapp.com/api/";var Fk=async(e,t)=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let r=await window.GM_fetch(${Al}web/,{mode:"cors",method:"POST",body:JSON.stringify({user:"nobody",talk:t,text:e}),headers:{"Content-Type":"application/json"}});if(!r.ok)return{ok:!1,value:{name:"ResponseError",res:r}};let o=await r.json();return{ok:!0,value:{text:o.text,buttons:o.buttons,canInput:o.can_input}}};var Dk=()=>{let{popupMenu:e,render:t}=IA();ry()?.append?.(e);let r=Po(),o=()=>{requestAnimationFrame(()=>{let n=document.getElementsByClassName("cursor")[0];e.style.top=${parseInt(n.style.top)+parseInt(n.style.height)+4}px})};return r.addChangeListener(o),{render:t,visible:()=>!e.hidden,open:()=>e.hidden=!1,close:()=>e.hidden=!0,toggle:()=>e.hidden=!e.hidden,dispose:()=>{e.remove(),r.removeChangeListener(o)}}},IA=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});t.innerHTML=
<style>
:host {
position: absolute;
left: 0px;
width:100%;
z-index:300;
user-select:none;
font-family:"Open Sans",Helvetica,Arial,"Hiragino Sans",sans-serif;
pointer-events:none
}
.button-container {
position: relative;
display:inline-block;
max-width:70vw;
min-width:80px;
text-align:center;
background-color:#111;
padding:0 1px;
border-radius:4px;
pointer-events:auto
}
htmldata-os*='android' .button-container {
max-width:90vw
}
htmldata-os*='ios' .button-container {
max-width:90vw
}
.button {
font-size:11px;
color:#eee;
cursor:pointer;
display:inline-block;
padding:0 5px
}
.button:not(:first-of-type) {
border:0;
border-left:1px solid #eee
}
.button.selected {
background-color:#222;
text-decoration:underline
}
htmldata-os*='android' .button {
font-size:13px;
padding:6px;
min-width:12vw
}
htmldata-os*='ios' .button{
font-size:13px;
padding:6px;
min-width:12vw
}
.button div.icon {
height:2em;
max-width:10em;
display:inline-block;
overflow:hidden;
margin-left:1px;
vertical-align:top
}
.button div.icon img {
max-height:100%;
vertical-align:unset
}
</style>
<div class="button-container"></div>
;let r=t.lastElementChild;return{popupMenu:e,render:(...o)=>{r.textContent="",r.append(...o.map(({text:n,onClick:s})=>{let i=document.createElement("div");return i.classList.add("button"),i.textContent=n,s&&i.addEventListener("click",()=>s()),i}))}}};var Uk=async(e="normal")=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let t=await window.GM_fetch(${Al}web/create/?mode=${e},{mode:"cors"});return t.ok?{ok:!0,value:await t.text()}:{ok:!1,value:{name:"ResponseError",res:t}}};var $k=e=>https://keicho.netlify.app/#talk=${e};var jk=e=>{let t=e.split(
),r=t[1]??t[0],o=e===t[0]?"":t[0];return o?[o.trim(),r].join(
):r};var Fl=async(e,t,r)=>{let o=Po(),n=o.lines.findIndex(i=>i.id===t.id);n<0&&(n=o.lines.findIndex(i=>i.text===t.text)),n<0&&(n=Math.min(r,Math.max(0,o.lines.length-1)));let s=o.lines[n].text;return Ya().clear(),o.setPosition({line:n,char:[...s].length}),await at(
${e}),o.getPosition().line};var Bk=e=>it(e,{hasTitle:!1}).map(t=>{if(t.type==="title")return t.text.trimEnd();let r=" ".repeat(t.indent);switch(t.type){case"codeBlock":return[${r}${t.fileName},...t.content.split(
).map(o=>${r} ${o})].join(
).trimEnd();case"table":return[${r}${t.fileName},...t.cells.map(o=>${r} ${o.flatMap(n=>n.map(s=>Dl(s))).join(" ")})].join(
).trimEnd();case"line":return${r}${t.nodes.map(o=>Dl(o)).join("")}.trimEnd()}}).join(
),Dl=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Dl(t)).join("")};case"helpfeel":case"commandLine":return e.raw;case"strongImage":case"image":case"strongIcon":case"icon":case"googleMap":return"";case"strong":case"decoration":case"numberList":return e.nodes.map(t=>Dl(t)).join("");case"formula":return\\(${e.formula}\\);case"code":return ${e.text} ;case"blank":case"plain":return e.raw;case"hashTag":return e.href;case"link":switch(e.pathType){case"absolute":return e.content? ${e.content} :"";case"root":return e.href.split("/").pop()??"";case"relative":return e.href}}};var ks=e=>/^[((]/.test(e);var Wk=async e=>{let t=scrapbox.Page.lines;if(!t)return;let{cursor:r,selection:o}=Wt(),n=e?.entire||o.hasSelectionAll(),s=n?t.map(_=>_.text).join(
):o.getSelectedText(),i=e?.botIcon??"[/nishio/nisbot.icon]",{render:a,visible:c,open:l,close:u,dispose:p}=Dk();u();let f=new Set,m=()=>{p();for(let _ of f)_()},h=_=>f.add(_),g={text:"Exit",onClick:m},y=e?.talkId||Hk(s)||(n?"":Hk(t.slice(0,1+r.getPosition().line).map(_=>_.text).join(
))),x=!y;if(!y){let _=Uk(e?.mode),C=setTimeout(()=>{a({text:"Start talking..."}),l();let j=0;C=setInterval(()=>{a({text:Start talking${".".repeat(j%3)}}),j++},1e3)},1e3),$=await _;if(clearTimeout(C),!$.ok){if($.value.name==="GMFetchNotAvailableError"){alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc.");return}if($.value.name==="ResponseError"){a({text:Error: ${$.value.res.status} ${$.value.res.statusText}},g),l(),console.error(Error: ${$.value.res.status} ${$.value.res.statusText},await $.value.res.text());return}return}y=$.value}let w=y,R=o.normalizeOrder(o.getRange()),b=n?t.length-1:R.end.line,E=t[b],T=n?"":" ".repeat(Math.min(...t.slice(R.start.line,R.end.line+1).map(_=>or(_.text)))),I=async _=>{let C=await Fk(_,w);if(!C.ok)switch(C.value.name){case"ResponseError":return a({text:Error: ${C.value.res.status} ${C.value.res.statusText}},g),l(),console.error(Error: ${C.value.res.status} ${C.value.res.statusText},await C.value.res.text()),C;case"GMFetchNotAvailableError":return alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc."),C}return C},F="",A=async _=>{let C=Bk(_).split(
).map(B=>B.trim()).join(
).trim();C.startsWith(F)&&(C=C.slice(F.length));let $=C.split(
);if($.length===0)return;if($.every(B=>ks(B))&&(F=C),$.filter(B=>!ks(B)).length<2){let B,Y;for(let G of $){if(Y=await I(G),!Y.ok)return Y;ks(G)||(B=Y)}return B??Y}let q=0;{let B;for(;q<$.length&&ks($[q]);q++)if(B=await I($[q]),!B.ok)return B}{let B=await I("まず聞いて");if(!B.ok)return B}for(;q<$.length&&!ks($[q]);q++){let B=await I($[q]);if(!B.ok)return B}return await I("おしまい")},N=async _=>{if(scrapbox.Layout!=="page"||_==="")return;let C=A(_),$=setTimeout(()=>{a({text:"Asking..."}),l();let G=0;$=setInterval(()=>{a({text:Asking${".".repeat(G%3)}}),G++},1e3)},1e3),j=await C;if(clearTimeout($),!j||!j.ok)return;let{text:q,buttons:B}=j.value,Y=jk(q);if(Y.trim()){let G=${T}${i}${Y.includes(`
)?
${Y.split(`
).map(X=> ${T}${X}).join(
)}:Y}
${T};b=await Fl(G,E,b),E=t[b]}a({text:"Send",onClick:P},{text:"🙂",onClick:()=>at("🙂")},{text:"🙁",onClick:()=>at("🙁")},...B.map(G=>({text:G,onClick:async()=>{b=await Fl(G,E,b),E=t[b],await N(G)}})),g),l()},P=async()=>{if(scrapbox.Layout!=="page")return;let _=scrapbox.Page.lines,C=r.getPosition().line,[$,j,q]=AA(_,C,i);$!==""&&(b=q,E=_[b],T=" ".repeat(Math.min(..._.slice(j,q+1).map(B=>or(B.text)))),await N($))};return x&&(b=await Fl($k(w),E,b),E=t[b]),await N(s),{ask:P,open:l,close:u,visible:c,exit:m,onExit:h}},Hk=e=>{for(let t of e.split(
).reverse()){let r=t.match(/https?:\/\/keicho\.netlify\.app\/#talk=(\w+)/)?.[1];if(r)return r}},AA=(e,t,r)=>{let o=Math.max(e.findLastIndex((s,i)=>i<t&&s.text.trim().startsWith(r)),1),n=o+Vo(o,e)+1;return[e.slice(n,t+1).map(s=>s.text.trim()).join(
).trim(),n,t]};scrapbox.PopupMenu.addButton({title:"",onClick:e=>${e}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>$ ${e}});var qk=[nn,sn,an];scrapbox.PopupMenu.addButton({title:e=>{let t=to({project:scrapbox.Project.name,mode:"noopen",hooks:qk});return!t||t.hookName.includes("default")?"":t.hookName.includes("task")?"":t.hookName.includes("split")?"":""},onClick:()=>{let e=window.prompt("Create a new page at",scrapbox.Project.name);e&&to({project:e,mode:"noopen",hooks:qk})?.()}});scrapbox.PopupMenu.addButton({title:e=>/(https?:\/\/[^\s]+)/g.test(e)?"":"",onClick:e=>{let t=e.replace(/(https?:\/\/[^\s]+)/g,"[$1#.jpg]");if(e!==t)return t}});scrapbox.PopupMenu.addButton({title:"S",onClick:e=>{window.open(https://scrapbox.io/${scrapbox.Project.name}/search/page?q=${e})}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(
);window.open(https://www.google.com/search?q=${encodeURIComponent(t)})}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=o=>[...o].some(n=>n.charCodeAt(0)>255),r=e.split(/\n/).map(o=>o.replace(/\[(.*)\]/g,"$1")).join(
).trim().replace(/\s+/g,"+");t(r)?window.open(https://www.ldoceonline.com/search/japanese-english/direct/?q=${encodeURIComponent(r)}):window.open(https://www.oxfordlearnersdictionaries.com/search/english/?q=${encodeURIComponent(r)})}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(
);window.open(https://www.google.com/search?q=${encodeURIComponent(t)}+site:scrapbox.io)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>${e}});scrapbox.PopupMenu.addButton({title:"🖍",onClick:e=>${e}});scrapbox.PopupMenu.addButton({title:e=>/\$([^$]+)\$/.test(e)?"L":"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\$([^$]+)\$/g,"[$ $1]")).join(
);if(e!=t)return t}});var FA=[Bf,Ek,Bf,Rk,Tk,Ml(),_k,xk(),Sk,wk,e=>{if(e.hostname!=="ekitan.com"||!/^\/transit\/(?:route|first|last)\//.test(e.pathname))return e;let t=e.searchParams.get("dt"),r=e.searchParams.get("tm"),o=e.searchParams.get("sr"),n=new URL(e);return n.search="",t&&n.searchParams.append("dt",t),n.pathname.startsWith("/transit/route/")&&(r&&n.searchParams.append("tm",r),o&&n.searchParams.append("sr",o)),n},e=>{if(e.host!==location.host||!e.pathname.startsWith("/api/code/"))return e;let t=encodeURIComponent(${e.origin}${e.pathname});return${e}.endsWith(".svg")?${e}:${e}.endsWith(".mlt")?${e}:e},e=>{if(e.hostname==="raw.githubusercontent.com")return${e};if(e.hostname!=="github.com")return e;let[t,r,o]=e.pathname.match(/^\/([^\\]+)\/([^\\]+)\/blob\/(.+)$/)?.slice?.(1)??[];if(!t||!r||!o)return e;let[,n,s]=e.hash.match(/L(\d+)-L(\d+)/)??e.hash.match(/L(\d+)/)??[];return[https://code2svg.vercel.app/svg/${n&&s?L${n}-${s}/:n?L${n}/:""}https://raw.githubusercontent.com/${t}/${r}/${o}#.svg ${e}]},e=>e.hostname==="github.com"?${e}:e,Ok,Il()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=Pk(e,...FA);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return at(r)})}});Ik(["takker","takker-memex","takker-private","takker-books"]);if(!/mobile/i.test(navigator.userAgent)){let e=(t,r)=>{t.trim()!==""&&Wk({mode:r}).then(o=>{if(!o)return;let{ask:n,visible:s,onExit:i}=o,a=c=>{!s()||c.key!=="Enter"||!c.ctrlKey||c.altKey||c.shiftKey||(c.preventDefault(),c.stopPropagation(),n())};dt().addEventListener("keydown",a),i(()=>dt().removeEventListener("keydown",a))})};scrapbox.PopupMenu.addButton({title:()=>"🤖",onClick:t=>e(t)})}var Di=(e,t)=>t.map(r=>r.replace(/@yyyy-MM-dd HH:mm:ss@/g,ct(e,"yyyy-MM-dd HH:mm:ss")).replace(/@yyyy-MM-dd@/g,ct(e,"yyyy-MM-dd")).replace(/@yyyy-MM-dd(?:([+-])(\d+)(w?))?(?:\((Sun|Mon|Tue|Wed|Thu|Fri|Sat)\))?@/g,(o,n,s,i,a)=>{let c=n?n==="+"?ve(e,parseInt(s)*(i==="w"?7:1)):Yt(e,parseInt(s)*(i==="w"?7:1)):e;return ct(a?ve(Ne(c),DA(a)):c,"yyyy-MM-dd")}).replace(/@yyyy-ww@/g,${oi(e)}-w${${Lo(e)}.padStart(2,"0")}).replace(/@yyyy-ww([+-])(\d+)(w?)@/g,(o,n,s,i)=>{let a=n==="+"?ve(e,parseInt(s)*(i==="w"?7:1)):Yt(e,parseInt(s)*(i==="w"?7:1));return${oi(a)}-w${${Lo(a)}.padStart(2,"0")}}).replace(/@yyyy@/g,${oi(e)}).replace(/@yyyy([+-])(\d+)y@/g,(o,n,s)=>{let i=parseInt(s);return${oi(e)+(n==="+"?i:-i)}})),DA=e=>{switch(e){case"Sun":return 0;case"Mon":return 1;case"Tue":return 2;case"Wed":return 3;case"Thu":return 4;case"Fri":return 5;default:return 6}};var zk=async(e,t,r,o=new Date(2023,1,3))=>{if(scrapbox.Project.name!==e)return()=>{};let n=scrapbox.Project.pages;await new Promise(l=>{let u=setInterval(()=>{if(n.length===0){n=scrapbox.Project.pages;return}clearInterval(u),l()},2e3)});let s=async()=>{let l=new Date,u={start:o,end:ve(l,1)},{render:p,dispose:f}=Fe(),m;try{let h=await Gk(t),g=await Gk(r),y=ri(u).filter(b=>{let E=Di(b,h)[0],T=n.find(I=>I.title===E);return!T||!T.exists}),x=nx(u).filter(b=>{let E=Di(b,g)[0],T=n.find(I=>I.title===E);return!T||!T.exists});if(y.length===0&&x.length===0)return;let w=y.length+x.length;p({type:"spinner"},{type:"text",text:create ${w} review pages...});let R=await It();if(O(R))throw Z(R);m=S(R);for(let b of[...y.map(E=>Di(E,h)),...x.map(E=>Di(E,g))])await Le(e,b[0],(E,T)=>T.persistent?void 0:b,m?{socket:m}:{}),w--,p({type:"spinner"},{type:"text",text:create ${w} review pages...});p({type:"check-circle"},{type:"text",text:created ${y.length+x.length} review pages.}),o=l}catch(h){p({type:"exclamation-triangle"},{type:"text",text:h instanceof Error?${h.name} ${h.message}:"Unknown error! (see developper console)"}),console.error(h)}finally{m&&await At(m),await Se(1e3),f()}},i=s(),a=new Date,c=setInterval(()=>{let l=new Date;gt(a,l)||(a=l,i.then(()=>i=s()))},1e4);return()=>(clearTimeout(c),i)},Gk=async e=>{let t=await Ta(e[0],e[1],e[2]);if(O(t)){let o=new Error;throw o.name=Z(t).name,o.message=${Z(t).message} at fetching /${e0}/${e1}/${e2},o}let r=S(t).split(
);if(r.length===0)throw new Error(template "/${e0}/${e1}/${e2}" is empty!);return r};var UA=class{__unenv__=!0;_currentStore;_enterStore;_enabled=!0;getStore(){return this._currentStore??this._enterStore}disable(){this._enabled=!1}enable(){this._enabled=!0}enterWith(e){this._enterStore=e}run(e,t,...r){this._currentStore=e;let o=t(...r);return this._currentStore=void 0,o}exit(e,...t){let r=this._currentStore;this._currentStore=void 0;let o=e(...t);return this._currentStore=r,o}static snapshot(){throw new Error("[unenv] AsyncLocalStorage.snapshot is not implemented!")}},Xct=globalThis.AsyncLocalStorage||UA,$A=Symbol("init"),jA=Symbol("before"),BA=Symbol("after"),HA=Symbol("destroy"),WA=Symbol("promiseResolve"),Jct=class{__unenv__=!0;_enabled=!1;_callbacks={};constructor(e={}){this._callbacks=e}enable(){return this._enabled=!0,this}disable(){return this._enabled=!1,this}get[$A](){return this._callbacks.init}get[jA](){return this._callbacks.before}get[BA](){return this._callbacks.after}get[HA](){return this._callbacks.destroy}get[WA](){return this._callbacks.promiseResolve}};var qA=function(){return 0};var Qct=Object.assign(Object.create(null),{NONE:0,DIRHANDLE:1,DNSCHANNEL:2,ELDHISTOGRAM:3,FILEHANDLE:4,FILEHANDLECLOSEREQ:5,BLOBREADER:6,FSEVENTWRAP:7,FSREQCALLBACK:8,FSREQPROMISE:9,GETADDRINFOREQWRAP:10,GETNAMEINFOREQWRAP:11,HEAPSNAPSHOT:12,HTTP2SESSION:13,HTTP2STREAM:14,HTTP2PING:15,HTTP2SETTINGS:16,HTTPINCOMINGMESSAGE:17,HTTPCLIENTREQUEST:18,JSSTREAM:19,JSUDPWRAP:20,MESSAGEPORT:21,PIPECONNECTWRAP:22,PIPESERVERWRAP:23,PIPEWRAP:24,PROCESSWRAP:25,PROMISE:26,QUERYWRAP:27,QUIC_ENDPOINT:28,QUIC_LOGSTREAM:29,QUIC_PACKET:30,QUIC_SESSION:31,QUIC_STREAM:32,QUIC_UDP:33,SHUTDOWNWRAP:34,SIGNALWRAP:35,STATWATCHER:36,STREAMPIPE:37,TCPCONNECTWRAP:38,TCPSERVERWRAP:39,TCPWRAP:40,TTYWRAP:41,UDPSENDWRAP:42,UDPWRAP:43,SIGINTWATCHDOG:44,WORKER:45,WORKERHEAPSNAPSHOT:46,WRITEWRAP:47,ZLIB:48,CHECKPRIMEREQUEST:49,PBKDF2REQUEST:50,KEYPAIRGENREQUEST:51,KEYGENREQUEST:52,KEYEXPORTREQUEST:53,CIPHERREQUEST:54,DERIVEBITSREQUEST:55,HASHREQUEST:56,RANDOMBYTESREQUEST:57,RANDOMPRIMEREQUEST:58,SCRYPTREQUEST:59,SIGNREQUEST:60,TLSWRAP:61,VERIFYREQUEST:62}),GA=100,zA=class{__unenv__=!0;type;_asyncId;_triggerAsyncId;constructor(e,t=qA()){this.type=e,this._asyncId=-1*GA++,this._triggerAsyncId=typeof t=="number"?t:t?.triggerAsyncId}static bind(e,t,r){return new qf(t??"anonymous").bind(e)}bind(e,t){let r=(...o)=>this.runInAsyncScope(e,t,...o);return r.asyncResource=this,r}runInAsyncScope(e,t,...r){return e.apply(t,r)}emitDestroy(){return this}asyncId(){return this._asyncId}triggerAsyncId(){return this._triggerAsyncId}},qf=globalThis.AsyncResource||zA;function VA(e){return new Error(unenv ${e} is not implemented yet!)}function Qf(e){return Object.assign(()=>{throw VA(e)},{__unenv__:!0})}var _s=10,KA=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),eT=(e,t)=>e,Ps=Error,YA=Error,Tn=Error,Ul=Error,XA=Error,Yf=Symbol.for("nodejs.rejection"),Gr=Symbol.for("kCapture"),Gf=Symbol.for("events.errorMonitor"),Ts=Symbol.for("shapeMode"),$l=Symbol.for("events.maxEventTargetListeners"),JA=Symbol.for("kEnhanceStackBeforeInspector"),QA=Symbol.for("nodejs.watermarkData"),zf=Symbol.for("kEventEmitter"),kn=Symbol.for("kAsyncResource"),ZA=Symbol.for("kFirstEventParam"),Xf=Symbol.for("kResistStopPropagation"),Vk=Symbol.for("events.maxEventTargetListenersWarned"),jl=class Ui{_events=void 0;_eventsCount=0;_maxListeners=_s;[Gr]=!1;[Ts]=!1;static captureRejectionSymbol=Yf;static errorMonitor=Gf;static kMaxEventTargetListeners=$l;static kMaxEventTargetListenersWarned=Vk;static usingDomains=!1;static get on(){return rF}static get once(){return oF}static get getEventListeners(){return nF}static get getMaxListeners(){return sF}static get addAbortListener(){return tT}static get EventEmitterAsyncResource(){return eF}static get EventEmitter(){return Ui}static setMaxListeners(t=_s,...r){if(r.length===0)_s=t;else for(let o of r)if(oT(o))o[$l]=t,o[Vk]=!1;else if(typeof o.setMaxListeners=="function")o.setMaxListeners(t);else throw new Tn("eventTargets",["EventEmitter","EventTarget"],o)}static listenerCount(t,r){if(typeof t.listenerCount=="function")return t.listenerCount(r);Ui.prototype.listenerCount.call(t,r)}static init(){throw new Error("EventEmitter.init() is not implemented.")}static get captureRejections(){return this[Gr]}static set captureRejections(t){this[Gr]=t}static get defaultMaxListeners(){return _s}static set defaultMaxListeners(t){_s=t}constructor(t){this._events===void 0||this._events===Object.getPrototypeOf(this)._events?(this._events={__proto__:null},this._eventsCount=0,this[Ts]=!1):this[Ts]=!0,this._maxListeners=this._maxListeners||void 0,t?.captureRejections?this[Gr]=!!t.captureRejections:this[Gr]=Ui.prototype[Gr]}setMaxListeners(t){return this._maxListeners=t,this}getMaxListeners(){return Zf(this)}emit(t,...r){let o=t==="error",n=this._events;if(n!==void 0)o&&n[Gf]!==void 0&&this.emit(Gf,...r),o=o&&n.error===void 0;else if(!o)return!1;if(o){let i;if(r.length>0&&(i=r[0]),i instanceof Error){try{let l={};Error.captureStackTrace?.(l,Ui.prototype.emit),Object.defineProperty(i,JA,{__proto__:null,value:Function.prototype.bind(aF,this,i,l),configurable:!0})}catch{}throw i}let a;try{a=eT(i)}catch{a=i}let c=new YA(a);throw c.context=i,c}let s=n[t];if(s===void 0)return!1;if(typeof s=="function"){let i=s.apply(this,r);i!=null&&Xk(this,i,t,r)}else{let i=s.length,a=ed(s);for(let c=0;c<i;++c){let l=a[c].apply(this,r);l!=null&&Xk(this,l,t,r)}}return!0}addListener(t,r){return Jk(this,t,r,!1),this}on(t,r){return this.addListener(t,r)}prependListener(t,r){return Jk(this,t,r,!0),this}once(t,r){return this.on(t,Qk(this,t,r)),this}prependOnceListener(t,r){return this.prependListener(t,Qk(this,t,r)),this}removeListener(t,r){let o=this._events;if(o===void 0)return this;let n=o[t];if(n===void 0)return this;if(n===r||n.listener===r)this._eventsCount-=1,this[Ts]?o[t]=void 0:this._eventsCount===0?this._events={__proto__:null}:(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){let s=-1;for(let i=n.length-1;i>=0;i--)if(n[i]===r||n[i].listener===r){s=i;break}if(s<0)return this;s===0?n.shift():uF(n,s),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,r)}return this}off(t,r){return this.removeListener(t,r)}removeAllListeners(t){let r=this._events;if(r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events={__proto__:null},this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events={__proto__:null}:delete r[t]),this[Ts]=!1,this;if(arguments.length===0){for(let n of Reflect.ownKeys(r))n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events={__proto__:null},this._eventsCount=0,this[Ts]=!1,this}let o=r[t];if(typeof o=="function")this.removeListener(t,o);else if(o!==void 0)for(let n=o.length-1;n>=0;n--)this.removeListener(t,o[n]);return this}listeners(t){return Zk(this,t,!0)}rawListeners(t){return Zk(this,t,!1)}eventNames(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}listenerCount(t,r){let o=this._events;if(o!==void 0){let n=o[t];if(typeof n=="function")return r!=null?r===n||r===n.listener?1:0:1;if(n!==void 0){if(r!=null){let s=0;for(let i=0,a=n.length;i<a;i++)(n[i]===r||n[i].listener===r)&&s++;return s}return n.length}}return 0}},eF=class extends jl{constructor(e){let t;typeof e=="string"?(t=e,e=void 0):t=e?.name||new.target.name,super(e),this[kn]=new tF(this,t,e)}emit(e,...t){if(this[kn]===void 0)throw new Ps("EventEmitterAsyncResource");let{asyncResource:r}=this;return Array.prototype.unshift(t,super.emit,this,e),Reflect.apply(r.runInAsyncScope,r,t)}emitDestroy(){if(this[kn]===void 0)throw new Ps("EventEmitterAsyncResource");this.asyncResource.emitDestroy()}get asyncId(){if(this[kn]===void 0)throw new Ps("EventEmitterAsyncResource");return this.asyncResource.asyncId()}get triggerAsyncId(){if(this[kn]===void 0)throw new Ps("EventEmitterAsyncResource");return this.asyncResource.triggerAsyncId()}get asyncResource(){if(this[kn]===void 0)throw new Ps("EventEmitterAsyncResource");return this[kn]}},tF=class extends qf{constructor(e,t,r){super(t,r),this[zf]=e}get eventEmitter(){if(this[zf]===void 0)throw new Ps("EventEmitterReferencingAsyncResource");return this[zf]}},rF=function(e,t,r={}){let o=r.signal;if(o?.aborted)throw new Ul(void 0,{cause:o?.reason});let n=r.highWaterMark??r.highWatermark??Number.MAX_SAFE_INTEGER,s=r.lowWaterMark??r.lowWatermark??1,i=new Yk,a=new Yk,c=!1,l=null,u=!1,p=0,f=Object.setPrototypeOf({next(){if(p){let E=i.shift();return p--,c&&p<s&&(e.resume?.(),c=!1),Promise.resolve(Kf(E,!1))}if(l){let E=Promise.reject(l);return l=null,E}return u?b():new Promise(function(E,T){a.push({resolve:E,reject:T})})},return(){return b()},throw(E){if(!E||!(E instanceof Error))throw new Tn("EventEmitter.AsyncIterator","Error",E);R(E)},[Symbol.asyncIterator](){return this},[QA]:{get size(){return p},get low(){return s},get high(){return n},get isPaused(){return c}}},KA),{addEventListener:m,removeAll:h}=pF();m(e,t,r[ZA]?w:function(...E){return w(E)}),t!=="error"&&typeof e.on=="function"&&m(e,"error",R);let g=r?.close;if(g?.length)for(let E of g)m(e,E,b);let y=o?tT(o,x):null;return f;function x(){R(new Ul(void 0,{cause:o?.reason}))}function w(E){a.isEmpty()?(p++,!c&&p>n&&(c=!0,e.pause?.()),i.push(E)):a.shift().resolve(Kf(E,!1))}function R(E){a.isEmpty()?l=E:a.shift().reject(E),b()}function b(){y?.[Symbol.dispose](),h(),u=!0;let E=Kf(void 0,!0);for(;!a.isEmpty();)a.shift().resolve(E);return Promise.resolve(E)}},oF=async function(e,t,r={}){let o=r?.signal;if(o?.aborted)throw new Ul(void 0,{cause:o?.reason});return new Promise((n,s)=>{let i=u=>{typeof e.removeListener=="function"&&e.removeListener(t,a),o!=null&&$i(o,"abort",l),s(u)},a=(...u)=>{typeof e.removeListener=="function"&&e.removeListener("error",i),o!=null&&$i(o,"abort",l),n(u)},c={__proto__:null,once:!0,[Xf]:!0};Jf(e,t,a,c),t!=="error"&&typeof e.once=="function"&&e.once("error",i);function l(){$i(e,t,a),$i(e,"error",i),s(new Ul(void 0,{cause:o?.reason}))}o!=null&&Jf(o,"abort",l,{__proto__:null,once:!0,[Xf]:!0})})},tT=function(e,t){if(e===void 0)throw new Tn("signal","AbortSignal",e);let r;return e.aborted?queueMicrotask(()=>t()):(e.addEventListener("abort",t,{__proto__:null,once:!0,[Xf]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[Symbol.dispose](){r?.()}}},nF=function(e,t){if(typeof e.listeners=="function")return e.listeners(t);if(oT(e)){let r=e[kEvents].get(t),o=[],n=r?.next;for(;n?.listener!==void 0;){let s=n.listener?.deref?n.listener.deref():n.listener;o.push(s),n=n.next}return o}throw new Tn("emitter",["EventEmitter","EventTarget"],e)},sF=function(e){if(typeof e?.getMaxListeners=="function")return Zf(e);if(e?.[$l])return e[$l];throw new Tn("emitter",["EventEmitter","EventTarget"],e)},rT=2048,Vf=rT-1,Kk=class{bottom;top;list;next;constructor(){this.bottom=0,this.top=0,this.list=new Array(rT),this.next=null}isEmpty(){return this.top===this.bottom}isFull(){return(this.top+1&Vf)===this.bottom}push(e){this.list[this.top]=e,this.top=this.top+1&Vf}shift(){let e=this.list[this.bottom];return e===void 0?null:(this.list[this.bottom]=void 0,this.bottom=this.bottom+1&Vf,e)}},Yk=class{head;tail;constructor(){this.head=this.tail=new Kk}isEmpty(){return this.head.isEmpty()}push(e){this.head.isFull()&&(this.head=this.head.next=new Kk),this.head.push(e)}shift(){let e=this.tail,t=e.shift();return e.isEmpty()&&e.next!==null&&(this.tail=e.next,e.next=null),t}};function oT(e){return typeof e?.addEventListener=="function"}function Xk(e,t,r,o){if(e[Gr])try{let n=t.then;typeof n=="function"&&n.call(t,void 0,function(s){setTimeout(iF,0,e,s,r,o)})}catch(n){e.emit("error",n)}}function iF(e,t,r,o){if(typeof e[Yf]=="function")e[Yf](t,r,...o);else{let n=e[Gr];try{e[Gr]=!1,e.emit("error",t)}finally{e[Gr]=n}}}function Zf(e){return e._maxListeners===void 0?_s:e._maxListeners}function aF(e,t){let r="";try{let{name:s}=this.constructor;s!=="EventEmitter"&&(r= on ${s} instance)}catch{}let o=
Emitted 'error' event${r} at:
,n=(t.stack||"").split(
).slice(1);return e.stack+o+n.join(
)}function Jk(e,t,r,o){let n,s,i;if(s=e._events,s===void 0?(s=e._events={__proto__:null},e._eventsCount=0):(s.newListener!==void 0&&(e.emit("newListener",t,r.listener??r),s=e._events),i=s[t]),i===void 0)s[t]=r,++e._eventsCount;else if(typeof i=="function"?i=s[t]=o?[r,i]:[i,r]:o?i.unshift(r):i.push(r),n=Zf(e),n>0&&i.length>n&&!i.warned){i.warned=!0;let a=new XA(Possible EventEmitter memory leak detected. ${i.length} ${String(t)} listeners added to ${eT(e,{depth:-1})}. MaxListeners is ${n}. Use emitter.setMaxListeners() to increase limit,{name:"MaxListenersExceededWarning",emitter:e,type:t,count:i.length});console.warn(a)}return e}function cF(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Qk(e,t,r){let o={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=cF.bind(o);return n.listener=r,o.wrapFn=n,n}function Zk(e,t,r){let o=e._events;if(o===void 0)return[];let n=o[t];return n===void 0?[]:typeof n=="function"?r?[n.listener||n]:[n]:r?lF(n):ed(n)}function ed(e){switch(e.length){case 2:return[e[0],e[1]];case 3:return[e[0],e[1],e[2]];case 4:return[e[0],e[1],e[2],e[3]];case 5:return[e[0],e[1],e[2],e[3],e[4]];case 6:return[e[0],e[1],e[2],e[3],e[4],e[5]]}return Array.prototype.slice.call(e)}function lF(e){let t=ed(e);for(let r=0;r<t.length;++r){let o=t[r].listener;typeof o=="function"&&(t[r]=o)}return t}function Kf(e,t){return{value:e,done:t}}function $i(e,t,r,o){if(typeof e.removeListener=="function")e.removeListener(t,r);else if(typeof e.removeEventListener=="function")e.removeEventListener(t,r,o);else throw new Tn("emitter","EventEmitter",e)}function Jf(e,t,r,o){if(typeof e.on=="function")o?.once?e.once(t,r):e.on(t,r);else if(typeof e.addEventListener=="function")e.addEventListener(t,r,o);else throw new Tn("emitter","EventEmitter",e)}function pF(){let e=[];return{addEventListener(t,r,o,n){Jf(t,r,o,n),Array.prototype.push(e,[t,r,o,n])},removeAll(){for(;e.length>0;)Reflect.apply($i,void 0,e.pop())}}}function uF(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}var nlt=Symbol.for("nodejs.rejection");var slt=Symbol.for("events.errorMonitor");var ilt=Qf("node:events.setMaxListeners"),alt=Qf("node:events.listenerCount"),clt=Qf("node:events.init");var nT=class{fd;isRaw=!1;isTTY=!1;constructor(e){this.fd=e}setRawMode(e){return this.isRaw=e,this}},td=class{fd;columns=80;rows=24;isTTY=!1;constructor(e){this.fd=e}clearLine(e,t){return t&&t(),!1}clearScreenDown(e){return e&&e(),!1}cursorTo(e,t,r){return r&&typeof r=="function"&&r(),!1}moveCursor(e,t,r){return r&&r(),!1}getColorDepth(e){return 1}hasColors(e,t){return!1}getWindowSize(){return[this.columns,this.rows]}write(e,t,r){e instanceof Uint8Array&&(e=new TextDecoder().decode(e));try{console.log(e)}catch{}return r&&typeof r=="function"&&r(),!1}};function Lt(e){return new Error(unenv ${e} is not implemented yet!)}function Os(e){return Object.assign(()=>{throw Lt(e)},{__unenv__:!0})}var sT="22.14.0",mF=class iT extends jl{env;hrtime;nextTick;constructor(t){super(),this.env=t.env,this.hrtime=t.hrtime,this.nextTick=t.nextTick;for(let r of[...Object.getOwnPropertyNames(iT.prototype),...Object.getOwnPropertyNames(jl.prototype)]){let o=this[r];typeof o=="function"&&(this[r]=o.bind(this))}}emitWarning(t,r,o){console.warn(${o?[${o}] :""}${r?${r}: :""}${t})}emit(...t){return super.emit(...t)}listeners(t){return super.listeners(t)}#o;#r;#t;get stdin(){return this.#o??=new nT(0)}get stdout(){return this.#r??=new td(1)}get stderr(){return this.#t??=new td(2)}#e="/";chdir(t){this.#e=t}cwd(){return this.#e}arch="";platform="";argv=[];argv0="";execArgv=[];execPath="";title="";pid=200;ppid=100;get version(){returnv${sT}}get versions(){return{node:sT}}get allowedNodeEnvironmentFlags(){return new Set}get sourceMapsEnabled(){return!1}get debugPort(){return 0}get throwDeprecation(){return!1}get traceDeprecation(){return!1}get features(){return{}}get release(){return{}}get connected(){return!1}get config(){return{}}get moduleLoadList(){return[]}constrainedMemory(){return 0}availableMemory(){return 0}uptime(){return 0}resourceUsage(){return{}}ref(){}unref(){}umask(){throw Lt("process.umask")}getBuiltinModule(){}getActiveResourcesInfo(){throw Lt("process.getActiveResourcesInfo")}exit(){throw Lt("process.exit")}reallyExit(){throw Lt("process.reallyExit")}kill(){throw Lt("process.kill")}abort(){throw Lt("process.abort")}dlopen(){throw Lt("process.dlopen")}setSourceMapsEnabled(){throw Lt("process.setSourceMapsEnabled")}loadEnvFile(){throw Lt("process.loadEnvFile")}disconnect(){throw Lt("process.disconnect")}cpuUsage(){throw Lt("process.cpuUsage")}setUncaughtExceptionCaptureCallback(){throw Lt("process.setUncaughtExceptionCaptureCallback")}hasUncaughtExceptionCaptureCallback(){throw Lt("process.hasUncaughtExceptionCaptureCallback")}initgroups(){throw Lt("process.initgroups")}openStdin(){throw Lt("process.openStdin")}assert(){throw Lt("process.assert")}binding(){throw Lt("process.binding")}permission={has:Os("process.permission.has")};report={directory:"",filename:"",signal:"SIGUSR2",compact:!1,reportOnFatalError:!1,reportOnSignal:!1,reportOnUncaughtException:!1,getReport:Os("process.report.getReport"),writeReport:Os("process.report.writeReport")};finalization={register:Os("process.finalization.register"),unregister:Os("process.finalization.unregister"),registerBeforeExit:Os("process.finalization.registerBeforeExit")};memoryUsage=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0});mainModule=void 0;domain=void 0;send=void 0;exitCode=void 0;channel=void 0;getegid=void 0;geteuid=void 0;getgid=void 0;getgroups=void 0;getuid=void 0;setegid=void 0;seteuid=void 0;setgid=void 0;setgroups=void 0;setuid=void 0;_events=void 0;_eventsCount=void 0;_exiting=void 0;_maxListeners=void 0;_debugEnd=void 0;_debugProcess=void 0;_fatalException=void 0;_getActiveHandles=void 0;_getActiveRequests=void 0;_kill=void 0;_preload_modules=void 0;_rawDebug=void 0;_startProfilerIdleNotifier=void 0;_stopProfilerIdleNotifier=void 0;_tickCallback=void 0;_disconnect=void 0;_handleQueue=void 0;_pendingMessage=void 0;_channel=void 0;_send=void 0;_linkedBinding=void 0},Bl=Object.create(null),fF=globalThis.process,Ss=e=>globalThis.__env__||fF?.env||(e?Bl:globalThis),dF=new Proxy(Bl,{get(e,t){return Ss()[t]??Bl[t]},has(e,t){let r=Ss();return t in r||t in Bl},set(e,t,r){let o=Ss(!0);return o[t]=r,!0},deleteProperty(e,t){let r=Ss(!0);return delete r[t],!0},ownKeys(){let e=Ss();return Object.keys(e)},getOwnPropertyDescriptor(e,t){let r=Ss();if(t in r)return{value:r[t],writable:!0,enumerable:!0,configurable:!0}}}),hF=Object.assign(function(e){let t=Date.now(),r=Math.trunc(t/1e3),o=t%1e3*1e6;if(e){let n=r-e[0],s=o-e[0];return s<0&&(n=n-1,s=1e9+s),[n,s]}return[r,o]},{bigint:function(){return BigInt(Date.now()*1e6)}}),gF=globalThis.queueMicrotask?(e,...t)=>{globalThis.queueMicrotask(e.bind(void 0,...t))}:yF();function yF(){let e=[],t=!1,r,o=-1;function n(){!t||!r||(t=!1,r.length>0?e=[...r,...e]:o=-1,e.length>0&&s())}function s(){if(t)return;let i=setTimeout(n);t=!0;let a=e.length;for(;a;){for(r=e,e=[];++o<a;)r&&r[o]();o=-1,a=e.length}r=void 0,t=!1,clearTimeout(i)}return(i,...a)=>{e.push(i.bind(void 0,...a)),e.length===1&&!t&&setTimeout(s)}}var aT=new mF({env:dF,hrtime:hF,nextTick:gF}),ji=aT,{abort:blt,addListener:Elt,allowedNodeEnvironmentFlags:wlt,hasUncaughtExceptionCaptureCallback:Rlt,setUncaughtExceptionCaptureCallback:vlt,loadEnvFile:klt,sourceMapsEnabled:Tlt,arch:_lt,argv:Plt,argv0:Olt,chdir:Slt,config:Llt,connected:Nlt,constrainedMemory:Mlt,availableMemory:Clt,cpuUsage:Ilt,cwd:Alt,debugPort:Flt,dlopen:Dlt,disconnect:Ult,emit:$lt,emitWarning:jlt,env:Blt,eventNames:Hlt,execArgv:Wlt,execPath:qlt,exit:Glt,finalization:zlt,features:Vlt,getBuiltinModule:Klt,getActiveResourcesInfo:Ylt,getMaxListeners:Xlt,hrtime:Jlt,kill:Qlt,listeners:Zlt,listenerCount:ept,memoryUsage:tpt,nextTick:rpt,on:opt,off:npt,once:spt,pid:ipt,platform:apt,ppid:cpt,prependListener:lpt,prependOnceListener:ppt,rawListeners:upt,release:mpt,removeAllListeners:fpt,removeListener:dpt,report:hpt,resourceUsage:gpt,setMaxListeners:ypt,setSourceMapsEnabled:xpt,stderr:bpt,stdin:Ept,stdout:wpt,title:Rpt,umask:vpt,uptime:kpt,version:Tpt,versions:_pt,domain:Ppt,initgroups:Opt,moduleLoadList:Spt,reallyExit:Lpt,openStdin:Npt,assert:Mpt,binding:Cpt,send:Ipt,exitCode:Apt,channel:Fpt,getegid:Dpt,geteuid:Upt,getgid:$pt,getgroups:jpt,getuid:Bpt,setegid:Hpt,seteuid:Wpt,setgid:qpt,setgroups:Gpt,setuid:zpt,permission:Vpt,mainModule:Kpt,ref:Ypt,unref:Xpt,_events:Jpt,_eventsCount:Qpt,_exiting:Zpt,_maxListeners:eut,_debugEnd:tut,_debugProcess:rut,_fatalException:out,_getActiveHandles:nut,_getActiveRequests:sut,_kill:iut,_preload_modules:aut,_rawDebug:cut,_startProfilerIdleNotifier:lut,_stopProfilerIdleNotifier:put,_tickCallback:uut,_disconnect:mut,_handleQueue:fut,_pendingMessage:dut,_channel:hut,_send:gut,_linkedBinding:yut}=aT;var xF=Object.create,fT=Object.defineProperty,bF=Object.getOwnPropertyDescriptor,EF=Object.getOwnPropertyNames,wF=Object.getPrototypeOf,RF=Object.prototype.hasOwnProperty,dT=(e=>typeof Bo<"u"?Bo:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Bo<"u"?Bo:t)[r]}):e)(function(e){if(typeof Bo<"u")return Bo.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),hT=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vF=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of EF(t))!RF.call(e,n)&&n!==r&&fT(e,n,{get:()=>t[n],enumerable:!(o=bF(t,n))||o.enumerable});return e},gT=(e,t,r)=>(r=e!=null?xF(wF(e)):{},vF(t||!e||!e.__esModule?fT(r,"default",{value:e,enumerable:!0}):r,e)),kF=hT((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ji&&"node"in ji.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[dT][0](${"node","util".join(":")})}catch{r=null}t.exports=r}),TF=hT((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ji&&"node"in ji.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[dT][0](${"node","fs".join(":")})}catch{r=null}t.exports=r}),_F={},Hl=PF(globalThis,_F);function PF(e,t){return new Proxy(e,{get(r,o,n){return o in t?t[o]:e[o]},set(r,o,n){return o in t&&delete t[o],e[o]=n,!0},deleteProperty(r,o){let n=!1;return o in t&&(delete t[o],n=!0),o in e&&(delete e[o],n=!0),n},ownKeys(r){let o=Reflect.ownKeys(e),n=Reflect.ownKeys(t),s=new Set(n);return[...o.filter(i=>!s.has(i)),...n]},defineProperty(r,o,n){return o in t&&delete t[o],Reflect.defineProperty(e,o,n),!0},getOwnPropertyDescriptor(r,o){return o in t?Reflect.getOwnPropertyDescriptor(t,o):Reflect.getOwnPropertyDescriptor(e,o)},has(r,o){return o in t||o in e}})}var cT=["debug","info","warning","error","fatal"];function lT(e,t){let r=cT.indexOf(e);if(r<0)throw new TypeError(Invalid log level: ${JSON.stringify(e)}.);let o=cT.indexOf(t);if(o<0)throw new TypeError(Invalid log level: ${JSON.stringify(t)}.);return r-o}function Bi(e=[]){return yT.getLogger(e)}var rd=Symbol.for("logtape.rootLogger"),yT=class jo{static getLogger(t=[]){let r=rd in Hl?Hl[rd]??null:null;return r==null&&(r=new jo(null,[]),Hl[rd]=r),typeof t=="string"?r.getChild(t):t.length===0?r:r.getChild(t)}constructor(t,r){Object.defineProperty(this,"parent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"children",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sinks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parentSinks",{enumerable:!0,configurable:!0,writable:!0,value:"inherit"}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowestLevel",{enumerable:!0,configurable:!0,writable:!0,value:"debug"}),Object.defineProperty(this,"contextLocalStorage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.parent=t,this.children={},this.category=r,this.sinks=[],this.filters=[]}getChild(t){let r=typeof t=="string"?t:t[0],o=this.children[r],n=o instanceof jo?o:o?.deref();return n==null&&(n=new jo(this,[...this.category,r]),this.children[r]="WeakRef"in Hl?new WeakRef(n):n),typeof t=="string"||t.length===1?n:n.getChild(t.slice(1))}reset(){for(;this.sinks.length>0;)this.sinks.shift();for(this.parentSinks="inherit";this.filters.length>0;)this.filters.shift();this.lowestLevel="debug"}resetDescendants(){for(let t of Object.values(this.children))(t instanceof jo?t:t.deref())?.resetDescendants();this.reset()}with(t){return new OF(this,{...t})}filter(t){for(let r of this.filters)if(!r(t))return!1;return this.filters.length<1?this.parent?.filter(t)??!0:!0}*getSinks(t){if(!(this.lowestLevel===null||lT(t,this.lowestLevel)<0)){if(this.parent!=null&&this.parentSinks==="inherit")for(let r of this.parent.getSinks(t))yield r;for(let r of this.sinks)yield r}}emit(t,r){if(!(this.lowestLevel===null||lT(t.level,this.lowestLevel)<0||!this.filter(t))){for(let o of this.getSinks(t.level))if(!r?.has(o))try{o(t)}catch(n){let s=new Set(r);s.add(o),SF.log("fatal","Failed to emit a log record to sink {sink}: {error}",{sink:o,error:n,record:t},s)}}}log(t,r,o,n){let s=jo.getLogger().contextLocalStorage?.getStore()??{},i,a=typeof o=="function"?{category:this.category,level:t,timestamp:Date.now(),get message(){return pT(r,this.properties)},rawMessage:r,get properties(){return i==null&&(i={...s,...o()}),i}}:{category:this.category,level:t,timestamp:Date.now(),message:pT(r,{...s,...o}),rawMessage:r,properties:{...s,...o}};this.emit(a,n)}logLazily(t,r,o={}){let n=jo.getLogger().contextLocalStorage?.getStore()??{},s,i;function a(){if((i==null||s==null)&&(i=r((c,...l)=>(s=c,uT(c,l))),s==null))throw new TypeError("No log record was made.");return[i,s]}this.emit({category:this.category,level:t,get message(){return a()[0]},get rawMessage(){return a()[1]},timestamp:Date.now(),properties:{...n,...o}})}logTemplate(t,r,o,n={}){let s=jo.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:t,message:uT(r,o),rawMessage:r,timestamp:Date.now(),properties:{...s,...n}})}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},OF=class xT{constructor(t,r){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=t,this.properties=r}get category(){return this.logger.category}get parent(){return this.logger.parent}getChild(t){return this.logger.getChild(t).with(this.properties)}with(t){return new xT(this.logger,{...this.properties,...t})}log(t,r,o,n){this.logger.log(t,r,typeof o=="function"?()=>({...this.properties,...o()}):{...this.properties,...o},n)}logLazily(t,r){this.logger.logLazily(t,r,this.properties)}logTemplate(t,r,o){this.logger.logTemplate(t,r,o,this.properties)}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},SF=yT.getLogger(["logtape","meta"]);function pT(e,t){let r=[],o="";for(let n=0;n<e.length;n++){let s=e.charAt(n),i=e.charAt(n+1);if(s==="{"&&i==="{")o=o+s,n++;else if(s==="}"&&i==="}")o=o+s,n++;else if(s==="{")r.push(o),o="";else if(s==="}"){let a;o.match(/^\s|\s$/)?a=o in t?t[o]:t[o.trim()]:a=t[o],r.push(a),o=""}else o=o+s}return r.push(o),r}function uT(e,t){let r=[];for(let o=0;o<e.length;o++)r.push(e[o]),o<t.length&&r.push(t[o]);return r}var LF=gT(kF()),Wl=LF.default,mT={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},bT="Deno"in globalThis&&"inspect"in globalThis.Deno&&typeof globalThis.Deno.inspect=="function"?(e,t)=>globalThis.Deno.inspect(e,{strAbbreviateSize:1/0,iterableLimit:1/0,...t}):Wl!=null&&"inspect"in Wl&&typeof Wl.inspect=="function"?(e,t)=>Wl.inspect(e,{maxArrayLength:1/0,maxStringLength:1/0,...t}):e=>JSON.stringify(e);function ET(e={}){let t=e.timestamp==null||e.timestamp==="date-time-timezone"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00:00"):e.timestamp==="date-time-tz"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00"):e.timestamp==="date-time"?i=>new Date(i).toISOString().replace("T"," ").replace("Z",""):e.timestamp==="time-timezone"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00:00"):e.timestamp==="time-tz"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00"):e.timestamp==="time"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z",""):e.timestamp==="date"?i=>new Date(i).toISOString().replace(/T.*/,""):e.timestamp==="rfc3339"?i=>new Date(i).toISOString():e.timestamp,r=e.category??"·",o=e.value??bT,n=e.level==null||e.level==="ABBR"?i=>mT[i]:e.level==="abbr"?i=>mT[i].toLowerCase():e.level==="FULL"?i=>i.toUpperCase():e.level==="full"?i=>i:e.level==="L"?i=>i.charAt(0).toUpperCase():e.level==="l"?i=>i.charAt(0):e.level,s=e.format??(({timestamp:i,level:a,category:c,message:l})=>${i} ${a} ${c}: ${l});return i=>{let a="";for(let p=0;p<i.message.length;p++)p%2===0?a+=i.message[p]:a+=o(i.message[p]);let c=t(i.timestamp),l=n(i.level),u=typeof r=="function"?r(i.category):i.category.join(r);return${s({timestamp:c,level:l,category:u,message:a,record:i})}
}}var Eut=ET(),od="\x1B[0m",nd={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},sd={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},NF={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function MF(e={}){let t=e.format,r=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=${r==null?"":sdr}${o==null?"":ndo},s=r==null&&o==null?"":od,i=typeof e.levelStyle>"u"?"bold":e.levelStyle,a=e.levelColors??NF,c=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,l=e.categoryColor??null,u=${c==null?"":sdc}${l==null?"":ndl},p=c==null&&l==null?"":od;return ET({timestamp:"date-time-tz",value(f){return bT(f,{colors:!0})},...e,format({timestamp:f,level:m,category:h,message:g,record:y}){let x=a[y.level];return f=${n}${f}${s},m=${i==null?"":sdi}${x==null?"":ndx}${m}${i==null&&x==null?"":od},t==null?${f} ${m} ${u}${h}:${p} ${g}:t({timestamp:f,level:m,category:${u}${h}${p},message:g,record:y})}})}var wut=MF();var CF=gT(TF()),IF=CF.default;function Ls(){throw new Error("File sink is not available in the browser.")}var AF={openSync:Ls,writeSync:Ls,flushSync:Ls,closeSync:Ls,statSync:Ls,renameSync:Ls},_n=IF,Rut=_n==null?AF:{openSync(e){return _n.openSync(e,"a")},writeSync:_n.writeSync,flushSync:_n.fsyncSync,closeSync:_n.closeSync,statSync:_n.statSync,renameSync:_n.renameSync};async function*wT(e){let t=[],r=[],o=new Map,n=[];for(let s of e)s.isValid&&(s.id?s.isMember||t.push(s.id):r.push(s.name),n.push(s.name),o.set(s.name,s.checked));for(let s=0;s<t.length;s+=50){let i=t.slice(s,s+50);if(i.length===0)break;i.length===1&&i.push(i[0]);let a=await Ra(i);if(O(a)){r=n;break}for(let c of S(a).projects)o.has(c.name)&&(yield L({...c,checked:o.get(c.name)??0}))}for(let s of r){let i=await qo(s);yield K(i)?L({...S(i),checked:o.get(s)??0}):M({...Z(i),project:s})}}var cd=(e,t)=>t.some(r=>e instanceof r),RT,vT;function FF(){return RT||(RT=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function DF(){return vT||(vT=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var ld=new WeakMap,id=new WeakMap,ql=new WeakMap;function UF(e){let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(Pn(e.result)),n()},i=()=>{o(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)});return ql.set(t,e),t}function $F(e){if(ld.has(e))return;let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),n()},i=()=>{o(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});ld.set(e,t)}var pd={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return ld.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Pn(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function PT(e){pd=e(pd)}function jF(e){return DF().includes(e)?function(...t){return e.apply(ud(this),t),Pn(this.request)}:function(...t){return Pn(e.apply(ud(this),t))}}function BF(e){return typeof e=="function"?jF(e):(e instanceof IDBTransaction&&$F(e),cd(e,FF())?new Proxy(e,pd):e)}function Pn(e){if(e instanceof IDBRequest)return UF(e);if(id.has(e))return id.get(e);let t=BF(e);return t!==e&&(id.set(e,t),ql.set(t,e)),t}var ud=e=>ql.get(e);function OT(e,t,{blocked:r,upgrade:o,blocking:n,terminated:s}={}){let i=indexedDB.open(e,t),a=Pn(i);return o&&i.addEventListener("upgradeneeded",c=>{o(Pn(i.result),c.oldVersion,c.newVersion,Pn(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),n&&c.addEventListener("versionchange",l=>n(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}var HF=["get","getKey","getAll","getAllKeys","count"],WF=["put","add","delete","clear"],ad=new Map;function kT(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(ad.get(t))return ad.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,n=WF.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(n||HF.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,n?"readwrite":"readonly"),l=c.store;return o&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),n&&c.done]))[0]};return ad.set(t,s),s}PT(e=>({...e,get:(t,r,o)=>kT(t,r)||e.get(t,r,o),has:(t,r)=>!!kT(t,r)||e.has(t,r)}));var qF=["continue","continuePrimaryKey","advance"],TT={},md=new WeakMap,ST=new WeakMap,GF={get(e,t){if(!qF.includes(t))return e[t];let r=TT[t];return r||(r=TT[t]=function(...o){md.set(this,ST.get(this)[t](...o))}),r}};async function*zF(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,GF);for(ST.set(r,t),ql.set(r,ud(t));t;)yield r,t=await(md.get(r)||t.continue()),md.delete(r)}function _T(e,t){return t===Symbol.asyncIterator&&cd(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&cd(e,[IDBIndex,IDBObjectStore])}PT(e=>({...e,get(t,r,o){return _T(t,r)?zF:e.get(t,r,o)},has(t,r){return _T(t,r)||e.has(t,r)}}));var LT,fd=async()=>{let e=Bi(["@takker/cosense-storage","open"]);return LT??=await OT("scrapbox-storage",4,{upgrade(t,r,o){e.infostart updating DB: ${r} -> ${o};let n=Date.now();for(let a of t.objectStoreNames)t.deleteObjectStore(a);t.createObjectStore("titles",{keyPath:"id"}).createIndex("project","project");let i=t.createObjectStore("projects",{keyPath:"id"});i.createIndex("checked","checked"),i.createIndex("name","name"),e.infofinish updating DB: ${Date.now()-n}ms},blocked(t,r){let o=The database "@takker/cosense-storage"(v${r}) is blocked because the older one (v${t}) is opened in other tabs.
Please close the other tabs and reload this page.;e.error(o),alert(o)},blocking(t,r){let o=The database "@takker/cosense-storage"(v${t}) is blocking the newer one (v${r}) opened.
Please close this page.;e.error(o),alert(o)}}),LT};var NT=(e,t)=>(dd||(dd=new BroadcastChannel(CT),dd.addEventListener("message",r=>MT(r.data))),Gl.set(t,new Set(e).union(Gl.get(t)??new Set)),()=>Gl.delete(t)),hd=(e,t)=>{if((t.added?.size??0)+(t.updated?.size??0)+(t.deleted?.size??0)===0)return;let r={type:"links:changed",project:e,diff:t};MT(r);let o=new BroadcastChannel(CT);o.postMessage(r),o.close()},MT=e=>{for(let[t,r]of Gl)r.has(e.project)&&t(e)},CT="scrapbox-storage-notify",dd,Gl=new Map;var IT=async(e,t)=>{let r=await fd(),o=Bi(["@takker/cosense-storage","check"]),n=new Map;try{{o.debugcheck updates of links...;let i=new Set,a=r.transaction("projects","readwrite"),c=Cf(new Date),l=c-600;for await(let f of a.store.index("checked").iterate(IDBKeyRange.lowerBound(l,!0))){let m=f.value;if(m.isValid===!1){i.add(m.id);continue}i.add(m.name);let h=m.checked;if(h+t>c||m?.updating&&h>l)continue;let g=structuredClone(m);g.updating=!0,n.set(m.id,g),f.update(g)}let u=[],p=a.store.index("name");for(let f of e)i.has(f)||u.push(p.get(f).then(m=>{m?.updating&&(m?.checked??0)>l||n.set(f,m??VF(f))}));if(await Promise.all(u),await a.done,n.size===0){o.debugchecked. No project needs upgrade.;return}o.debugchecked. ${n.size} projects maybe need upgrade.}let s=Cf(new Date);for await(let i of wT(n.values())){if(O(i)){let{project:h,name:g}=Z(i);switch(g){default:continue;case"NotFoundError":o.warn("${h}" is not found.);break;case"NotMemberError":o.warn(You are not a member of "${h}".);break;case"NotLoggedInError":o.warn(You are not a member of "${h}" or You are not logged in yet.);break}n.set(h,{id:h,name:h,checked:s,updating:!1,isValid:!1,reason:g});continue}let{checked:a,...c}=S(i);if(c.updated<a){o.debugno updates in "${c.name}",n.set(c.name,{...c,isValid:!0,checked:s,updating:!1});continue}o.debugstart downloading and storing links of "${c.name}";let l=new Set(await r.getAllKeysFromIndex("titles","project",c.name)),u=0,p=0;for await(let h of pg(c.name)){if(O(h)){let{name:w,message:R}=Z(h);o.errorFailed to get links of "${c.name}" with ${w}: ${R};break}let g=S(h),y={},x=r.transaction("titles","readwrite");await Promise.all(g.map(async w=>{let R={...w,project:c.name},b=await x.store.get(w.id);if(!b)return y.added?.set?.(w.id,R)??(y.added=new Map([[w.id,R]])),x.store.add(R);if(l.delete(w.id),!!KF(R,b))return y.updated?.set?.(w.id,[b,R])??(y.updated=new Map([[w.id,[b,R]]])),x.store.put(R)})),await x.done,u+=y.added?.size??0,p+=y.updated?.size??0,o.debugUpdating "/${c.name}": +${u} pages, ~${p} pages,hd(c.name,y)}let f=r.transaction("titles","readwrite"),m=new Map((await Promise.all([...l].map(async h=>{let g=await f.store.get(h);if(!g)return[];let y=[[h,g]];return await f.store.delete(h),y}))).flat());await f.done,o.debugFinish downloading and storing links of "${c.name}",o.debugUpdate "/${c.name}": +${u} pages, ~${p} pages, -${m.size} pages,n.set(c.name,{...c,isValid:!0,checked:s,updating:!1}),hd(c.name,{deleted:m})}}finally{let s=r.transaction("projects","readwrite");await Promise.all([...n].map(([,i])=>(i.updating=!1,s.store.put({...i})))),await s.done}},zl=async e=>{let t=[...new Set(e)];if(t.length===0)return[];let r=Date.now(),n=(await fd()).transaction("titles","readonly"),s=n.store.index("project"),i=(await Promise.all(t.map(c=>s.getAll(c)))).flat();return await n.done,Bi(["@takker/cosense-storage","load"]).debugRead ${i.length} links from ${t.length} projects in ${Date.now()-r}ms,i},VF=e=>({name:e,displayName:e,id:"",isValid:!0,publicVisible:!0,isMember:!0,loginStrategies:[],theme:"default",gyazoTeamsName:null,translation:!0,infobox:!0,checked:0,updated:0,created:0,updating:!0}),KF=(e,t)=>e.updated>t.updated||e.links.sort().join()!==t.links.sort().join();var Vt=e=>${e.getFullYear()}-${Pr(e.getMonth()+1)}-${Pr(e.getDate())},Hi=e=>{let[t,r,o]=e.split("-").map(n=>parseInt(n,10));return{year:t,month:r,date:o}},Wi=e=>${Xo(e)}-w${Pr(Lo(e))},Vl=e=>{let[t,r]=e.split("-w").map(o=>parseInt(o,10));return Ne(oc(new Date(t,0,1),r))};var AT="takker-memex",FT=async(e=new Date(2023,0,24))=>{if(scrapbox.Project.name!==AT)return()=>{};let t=scrapbox.Project.pages;await new Promise(i=>{let a=setInterval(()=>{if(t.length===0){t=scrapbox.Project.pages;return}clearInterval(a),i()},2e3)});let r=async()=>{let i=new Date,c=ri({start:e,end:i}).filter(f=>{let m=_r(f),h=t.find(g=>g.title===m);return!h||!h.exists});if(c.length===0)return;let{render:l,dispose:u}=Fe(),p;try{l({type:"spinner"},{type:"text",text:load tasks for ${c.length} diary pages});let f=new Map,m=new Set,h=c.map(x=>Vt(x));for(let{title:x,links:w,project:R}of await zl(["takker","takker-memex"]))for(let b of[x,...w]){let E=Dr(b);if(!E)continue;if(O(E)){let{name:F,message:A}=Z(E);console.error(/${R}/${b}: ${F} ${A});continue}let T=ce(b);if(m.has(T))continue;m.add(T);let I=S(E);if(I.freshness?.status!=="done")for(let F of c){let A=li(I,F);if(!A)continue;let N=Vt(A.base);h.includes(N)&&(f.set(N,[...f.get(N)??[],A]),Mo(I))}}let g=await It();if(O(g))throw Z(g);p=S(g);let y=0;l({type:"spinner"},{type:"text",text:create 0/${c.length} diary pages...});for(let x of c){let w=_r(x),R=f.get(Vt(x))?.map?.(T=>_e(T))??[],b=#${ct(x,"yyyy-MM-dd")},E=#${ct(x,"yyyy-MM-dd HH:mm:ss")};await Le(AT,w,(T,{persistent:I})=>{if(I)return;let F=[...T.map(A=>A.text),...R];return F.some(A=>A.includes(b))?rn(F):rn([...F,E])},{socket:p}),y++,l({type:"spinner"},{type:"text",text:create ${y}/${c.length} diary pages...})}l({type:"check-circle"},{type:"text",text:created ${c.length} diary pages.}),e=i}catch(f){l({type:"exclamation-triangle"},{type:"text",text:f instanceof Error?${f.name} ${f.message}:"Unknown error! (see developper console)"}),console.error(f)}finally{p&&await At(p),await Se(1e3),u()}},o=r(),n=new Date,s=setInterval(()=>{let i=new Date;gt(n,i)||(n=i,o.then(()=>o=r()))},1e4);return()=>(clearTimeout(s),o)};FT(new Date(2024,11,24));var yd=(...e)=>{let t=e.flatMap(o=>{if(typeof o=="string")return[Kl(o)];if(Array.isArray(o.type))return[DT(o.type)];switch(o.type){case"text":return[Kl(o.text)];case"group":{let n=yd(...o.items);return n?[n]:[]}default:return[DT(o.type)]}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},Kl=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},DT=e=>{if(Array.isArray(e)){let t=document.createElement("span");t.classList.add("fa-stack");let r=gd(e[0]);r.classList.add("fa-stack-1x");let o=gd(e[1]);return o.classList.add("fa-stack-1x"),t.append(r,o),Kl(t)}return Kl(gd(e))},gd=e=>{let t=document.createElement("i");switch(e){case"spinner":t.classList.add("fa","fa-spinner");break;case"check-circle":case"gyazo":case"ocr":case"calendar":case"trim":t.classList.add("kamon",kamon-${e});break;case"markdown":case"google":t.classList.add("fab",fa-${e});break;case"copy":case"clipboard":t.classList.add("far",fa-${e});break;default:t.classList.add("fas",fa-${e});break}return t};var{cursor:xd,selection:bd}=Wt(),$T=e=>{let{className:t,display:r,onClick:o,context:n="page"}=e,s=document.createElement("div");t&&s.classList.add(t),UT(n)||(s.style.display="none");let i=(...l)=>{if(l.length===1&&l[0]===""){s.style.display="none";return}s.textContent="";let u=yd(...l);u&&s.append(u)},a=typeof r=="function"?r({cursor:xd,selection:bd}):r;return i(...Array.isArray(a)?a:[a]),s.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),o({cursor:xd,selection:bd,setDisplay:i})}),{status:s,context:n,update:()=>{if(UT(n)?s.removeAttribute("style"):s.style.display="none",typeof r=="function"){let l=r({cursor:xd,selection:bd});i(...Array.isArray(l)?l:[l])}}}},UT=e=>e!=="stream"?scrapbox.Layout===e:scrapbox.Layout==="list"&&location.pathname.startsWith("/stream");var jT=()=>{let e=document.createElement("style");e.textContent=.status-bar.left {
position: absolute;
top: 0;
left: 0;
max-width: 80vw;
overflow-x: auto;
overflow-y: hidden;
}
.status-bar.left:empty {
display: none;
}
.status-bar.left > div {
border-left: unset;
}
.status-bar.left > div {
border-right: 1px solid var(--tool-light-color, #a9aaaf);
}
.status-bar.left > div:first-of-type {
border-top-left-radius: unset;
}
.status-bar.left > div:last-of-type {
border-top-right-radius: 3px;
},document.head.append(e);let t=document.createElement("div");return t.classList.add("status-bar","left"),document.getElementsByClassName("footer")[0].append(t),t};var Ed=new Set,{cursor:YF,selection:XF}=Wt(),JF=jT();var Er=e=>{let t=$T(e);return Ed.add(t),JF.append(t.status),()=>{t.status.remove(),Ed.delete(t)}},wd=()=>{for(let{update:e}of Ed)e()};YF.addChangeListener(()=>wd());XF.addChangeListener(()=>wd());scrapbox.addListener("layout:changed",wd);var BT=async(e,t)=>{try{let r=t.getSelectedText()||kt(e.getPosition().line);if(!r)return;await navigator.clipboard.writeText(r)}catch(r){console.error(r),alert(Faild to copy:
${JSON.stringify(r)})}},HT=async(e,t)=>{try{let r=t.hasSelection(),o=r?t.getRange().start.line:e.getPosition().line,n=r?t.getSelectedText():kt(o);if(!n)return;await navigator.clipboard.writeText(n),r||t.setRange({start:{line:o,char:0},end:{line:o,char:n.length}}),e.focus(),Tt("Delete")}catch(r){console.error(r),alert(Faild to cut:
${JSON.stringify(r)})}},WT=async e=>{try{let t=await navigator.clipboard.readText();if(!t)return;e.focus(),await at(t)}catch(t){console.error(t),alert(Faild to paste:
${JSON.stringify(t)})}},qT=e=>{e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?e.hide():(e.focus(),e.showEditPopupMenu())};globalThis.addEventListener("keydown",e=>{if(e.key!=="i"||e.shiftKey||e.altKey||e.metaKey||!e.ctrlKey||e.isComposing)return;let t=Po();t.hasFocus||(e.preventDefault(),t.focus())});var Rd=class{get editor(){return document.getElementById("editor")}get lines(){return document.getElementsByClassName("lines")?.[0]}get computeLine(){return document.getElementById("compute-line")}get grid(){return document.getElementsByClassName("related-page-list clearfix")?.[0]?.getElementsByClassName("grid")?.[0]}get cursorLine(){return document.getElementsByClassName("cursor-line")?.[0]}get textInput(){return document.getElementById("text-input")}get cursor(){return document.getElementsByClassName("cursor")?.[0]}get selections(){return document.getElementsByClassName("selections")?.[0]}get popupMenu(){return document.getElementsByClassName("popup-menu")?.[0]}get pageMenus(){return document.getElementsByClassName("page-menu")?.[0]}get pageInfoMenu(){return document.getElementById("page-info-menu")}get pageEditMenu(){return document.getElementById("page-edit-menu")}get pageEditButtons(){return this.pageEditMenu.nextElementSibling.getElementsByTagName("a")}get randomJumpButton(){return document.getElementsByClassName("random-jump-button")?.[0]}get pageCustomButtons(){return document.getElementsByClassName("page-menu-extension")}},GT=new Rd;var zT=e=>new Promise(t=>setTimeout(t,e));async function Sr(e,{wait:t=1}={}){let r=GT.textInput;r.focus(),r.value=e;let o=document.createEvent("UIEvent");o.initEvent("input",!0,!1),r.dispatchEvent(o),await zT(t)}if(vn()){let e="Timestamp";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/add-time.png"}),scrapbox.PageMenu(e).addItem({title:"#YYYY-MM-DD HH:mm:ss ",onClick:()=>Sr(qt(new Date,"#yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD HH:mm:ss ",onClick:()=>Sr(qt(new Date,"yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD",onClick:()=>Sr(qt(new Date,"yyyy-MM-dd"))}),scrapbox.PageMenu(e).addItem({title:"HH:mm:ss ",onClick:()=>Sr(qt(new Date,"HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"⬜",onClick:()=>Sr("⬜")}),scrapbox.PageMenu(e).addItem({title:"🚧",onClick:()=>Sr("🚧")}),scrapbox.PageMenu(e).addItem({title:"⌛",onClick:()=>Sr("⌛")}),scrapbox.PageMenu(e).addItem({title:"📝",onClick:()=>Sr("📝")}),scrapbox.PageMenu(e).addItem({title:"✅",onClick:()=>Sr("✅")}),scrapbox.PageMenu(e).addItem({title:"❌",onClick:()=>Sr("❌")})}scrapbox.PageMenu.addItem({title:"Open kakeru",image:"https://i.kakeru.app/15c3b1a40b6b3c2ebd68f33f4c86b3f6-opaque.png",onClick:()=>window.open("https://kakeru.app")});var qi=e=>{let{fetch:t=(n,s)=>globalThis.fetch(n,s),baseURL:r="https://scrapbox.io/",...o}=e;return{fetch:t,baseURL:r,...o}};var QF=(e,t,r)=>{let{sid:o,baseURL:n,followRename:s,projects:i}=qi(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(${n}api/pages/${e}/${se(t)}?${a},o?{headers:{Cookie:we(o)}}:void 0)},vd=(e,t,r)=>qi(r??{}).fetch(QF(e,t,r));var kd=e=>{let t=Math.round(e/5),r=Math.floor(t/6),o=Math.floor((t-r*6)/3),n=t-r*6-o*3;return${r>20?🍅x${(e/30).toFixed(1)}:"🍅".repeat(r)}${"🍊".repeat(o)}${"🍓".repeat(n)}};var ZF=()=>{let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.right="0",e.style.textAlign="right",e},Ns=new Map,Yl,Td=()=>{for(let r of Ns.values())r.remove();Ns.clear();let e=ll(()=>eD(Dt()),{interval:1e3,maxQueued:0}),t=()=>{e.clear(),e()};if(scrapbox.Layout!=="page"){if(scrapbox.removeListener("lines:changed",t),!Yl)return;clearInterval(Yl),Yl=void 0;return}t(),scrapbox.addListener("lines:changed",t),Yl=setInterval(t,60*1e3)},eD=e=>{for(let t of e){let r=_t(t.text);if(!r?.record?.start){Ns.get(t.id)?.remove?.(),Ns.delete(t.id);continue}let o=Ns.get(t.id)??ZF();eo(t.id)?.append?.(o),Ns.set(t.id,o),o.textContent=kd(So(r.record.end??new Date,r.record.start))}};scrapbox.Project.name==="takker-memex"&&(Td(),scrapbox.addListener("page:changed",Td),scrapbox.addListener("lines:changed",Td));var tD=e=>{let[t,r]=e.reduce((o,{text:n})=>{let s=_t(n);return s?.record?.start?s.record.end?(o[1].push(s.record.end),o):(s.record.start&&o[0].push(s.record.start),o):o},[[],[]]);if(t.length===0&&t.push(...r),t.length!==0)return Nf(t)},rD=async(e,t)=>{let[r,o]=await Promise.all([vd(e,_r(t),{fetch:VT}),vd(e,_r(Yt(t,1)),{fetch:VT})]),n=r.ok?(await r.json()).lines:[];return o.ok&&n.push(...(await o.json()).lines),n},VT=async(e,t)=>{let r=await _o(new Request(e,t));return!r||Li(new Date,new Date(${r.headers.get("Date")}))>=60?globalThis.fetch(e,t):r},{render:oD}=Fe(),KT=async()=>{let e=tD(await rD("takker-memex",new Date))??kr(new Date);oD({type:"text",text:kd(So(new Date,e))})};KT();setInterval(KT,60*1e3);async function YT(e,{from:t,to:r,merge:o}){if(t===r)return{success:!0,dup:!1};let n=await ur(t,e);if(O(n))return{success:!1,at:"from",name:Z(n).name,message:Z(n).message};let s=S(n);if(!s.persistent)return{success:!1,at:"from",name:"EmptyPageError",message:"The request page is empty."};let i=await ur(r,e);if(O(i))return{success:!1,at:"to",name:Z(i).name,message:Z(i).message};let a=S(n);return a.persistent&&!o?{success:!1,at:"to",name:"NoEmptyPageError",message:The same page already exists in "/${r}"}:(await Le(r,e,c=>[...c,...s.lines.slice(1)].map(l=>l.text)),await ag(t,e),{success:!0,dup:a.persistent})}var _d=async()=>{let e=scrapbox.Page.title,t=scrapbox.Project.name,r=globalThis.prompt(Take "/${t}/${e}" from "${t}" to:,"takker");if(!r)return;let{render:o,dispose:n}=Fe();o({type:"spinner"},{type:"text",text:/${t}/${e} → /${r}/${e}});try{let s=await YT(e,{from:t,to:r,merge:!0});if(!s.success){o({type:"exclamation-triangle"},{type:"text",text:${s.name} ${s.message}});return}return o({type:"check-circle"},{type:"text",text:Moved ${s.dup?"and merged ":""}to "/${r}/${e}".}),https://scrapbox.io/${r}/${se(e)}}catch(s){o({type:"exclamation-triangle"},{type:"text",text:s instanceof Error?${s.name} ${s.message}:"Unknown error! (see developper console)"}),console.error(s)}finally{setTimeout(()=>n(),1e3)}};scrapbox.PageMenu.addItem({title:"Transport",onClick:async()=>{await _d()}});scrapbox.PageMenu.addItem({title:"Transport and Open",onClick:async()=>{let e=await _d();e&&window.open(e)}});var nD="button.";document.getElementById("editor").addEventListener("click",async e=>{let t=e.target;if(t.tagName==="IMG"&&t.classList.contains("icon")&&t.title.endsWith("-button")){e.preventDefault(),e.stopImmediatePropagation();try{let r=../${encodeURIComponent(t.title)}/${nD},{execute:o}=await import(r);o()}catch(r){console.log(r)}}});scrapbox.PageMenu.addItem({title:"Copy link for Markdown",onClick:()=>{let e=scrapbox.Page.title.replaceAll(" ","_").replace(/[/?#\{}^|<>]/g,t=>encodeURIComponent(t));navigator.clipboard.writeText(${scrapbox.Page.title}(https://${location.hostname}/${scrapbox.Project.name}/${e}${location.hash})).catch(t=>alert(${t.name}: ${t.message}))}});Xr.PageMenu.addMenu({image:"https://img.icons8.com/ios/180/FFFFFF/inbox.png",title:"~task",onClick:()=>{let{cursor:e,selection:t}=Wt(),r=e.getPosition().line,o=t.getSelectedText(),n=o||e.lines[r].text,s=n.split(
).map(i=>i.replace(/^\s*(.+)$/g,$1~@${ct(new Date,"yyyy-MM-dd")})).join(
);o||t.setRange({start:{line:r,char:0},end:{line:r,char:n.length}}),at(s)}});var Gi=e=>tl(...H(()=>{let t={tasks:[],errors:[],load:async()=>{},loading:!1},r=Promise.resolve();return[o=>{t.load=()=>(r=(async()=>{await r,t={...t,loading:!0},o(),await IT(e,60),t={...t,loading:!1},o()})(),r);let n=()=>{r=(async()=>{await r,t={...t,loading:!0},o();let[s,i]=sD(await zl(e));t={...t,tasks:s,errors:i,loading:!1},o()})()};return n(),NT(e,n)},()=>t]},e)),sD=e=>{let t=new Set,r=[],o=[];for(let{title:n,links:s,project:i}of e)for(let a of[n,...s]){let c=ce(a);if(t.has(c))continue;t.add(c);let l=Dr(a);if(l){if(O(l)){o.push({project:i,title:a,...Z(l)});continue}r.push({project:i,title:a,...S(l)})}}return[r,o]};var Xl=()=>{let[e,t]=ko(iD,{isOpen:!1,prevOverflowY:""}),r=ft(null),o=D(()=>{t(i=>{r?.current?.showModal?.();let a=r?.current?.open??!1,c=i.isOpen?i.prevOverflowY:document.documentElement.style.overflowY;return document.documentElement.style.overflowY="hidden",{isOpen:a,prevOverflowY:c}})},[]),n=D(()=>{t(i=>{r?.current?.close?.();let a=r?.current?.open??!1;return a?{isOpen:a,prevOverflowY:i.prevOverflowY}:(i.prevOverflowY?document.documentElement.style.overflowY=i.prevOverflowY:document.documentElement.style.removeProperty("overflow-y"),{isOpen:a})})},[]),s=H(()=>{let i;return a=>{if(!a){i?.(),r.current=null;return}let c=new AbortController;a.addEventListener("cancel",n,{signal:c.signal}),a.addEventListener("click",l=>{if(l.target!==l.currentTarget){l.stopPropagation();return}n()},{signal:c.signal}),i=()=>{c.abort()},r.current=a}},[n]);return{isOpen:e.isOpen,open:o,close:n,ref:s}},iD=(e,t)=>{let r=t(e);return e.isOpen===r.isOpen&&e.prevOverflowY===r.prevOverflowY?e:r.isOpen?r:{isOpen:!1}};var zi=String.raw.fa,.far{font-weight:900;font-family:"Font Awesome 5 Free";-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.far{font-weight:400}.fa-spinner{animation:spin 2s infinite linear}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(359deg)}}.fa-spinner:before{content:"\f110"}.fa-sync:before{content:"\f021"}.fa-bookmark:before{content:"\f02e"}.fa-fw{text-align:center;width:1.25em}.kamon:before{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.kamon-check-circle:before{content:"\e018"}.timeline-wrap{display:flex;flex-direction:column;height:100%;overflow-y:hidden;--timeline-bg: var(--dropdown-menu-bg, #fff);--timeline-text-color: var(--page-text-color, #4a4a4a);--timeline-link-color: var(--page-link-color, #5e8af7);--row-header-width: 40px;--timeline-border-color: #888;--timeline-border: solid 1px var(--timeline-border-color);--timeline-hour-height: 40px;background-color:var(--timeline-bg);color:var(--timeline-text-color);.column-header{flex:none;display:flex;flex-direction:row;.cell{flex:1 1 1px;h2{font-weight:400;margin:0;text-align:center;width:100%}}}.week-container{position:relative;height:100%;overflow-y:auto;scrollbar-width:none;.week{flex:auto;display:flex;width:100%;.borders{.border{height:var(--timeline-hour-height)}.border:after{content:attr(data-time);font-size:10px;text-align:right;border-top:var(--timeline-border);position:absolute;width:100%;margin-top:-1px;pointer-events:none}}.timeline{flex:auto;border-left:var(--timeline-border);position:relative;.indicator{position:absolute;top:calc(var(--start) * 40px - .5px);width:100%;height:1px;background-color:red}.copy{position:absolute;top:1.5em}.event{position:absolute;top:calc(var(--start) * 40px - 1px);height:calc(40px * var(--duration) / 60);outline:none;--event-bg2: var(--timeline-text-color);--event-bg: var(--timeline-bg);--event-bg-ratio: 50%;--event-color-ratio: 0%;--event-border-color-ratio: 0%;background-color:color-mix(in srgb,var(--event-bg) var(--event-bg-ratio),var(--event-bg2));color:color-mix(in srgb,var(--event-bg) var(--event-color-ratio),var(--timeline-text-color));border:var(--timeline-border);border-color:color-mix(in srgb,var(--event-bg) var(--event-border-color-ratio),var(--timeline-border-color));border-radius:4px;overflow:hidden;text-wrap:nowrap;max-width:100%;text-overflow:ellipsis}.eventdata-status=done{--event-bg-ratio: 90%;--event-color-ratio: 50%;--event-border-color-ratio: 50%}.eventdata-status=expired{font-weight:700}a.event{--event-bg2: var(--timeline-link-color);text-decoration:none}}.timeline:first-child{border-right:var(--timeline-border)}}}}.wedget{position:fixed;top:60px;left:10px;max-height:calc(90vh - 60px);max-width:100px;width:calc(100vw / 767 * 100 - 10px);min-width:60px;border:solid 1px #888;border-radius:4px;display:flex;flex-direction:column;background-color:var(--dropdown-menu-bg, #fff);color:var(--page-text-color, #4a4a4a);&:not(.open){display:none}}dialog{flex-direction:column;align-items:center;row-gap:10px;&::backdrop{background-color:#000c}padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset;overflow-y:hidden;&open{display:flex}>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}}@media (min-width: 768px){dialog{padding:30px 0;--item-width: 600px}}.result{padding:15px;width:calc(var(--item-width, 100%) - 30px);overflow-y:scroll}.controller{padding:5px;width:calc(var(--item-width, 100%) - 10px);display:flex;flex-wrap:wrap;flex:none;gap:.2em}.progress{flex-grow:1;>*{padding:0 2px}}a{text-decoration:none;color:var(--page-link-color, #5e8af7);&:hover{color:var(--page-link-hover-color, #2d67f5)}}button{cursor:pointer;background:unset;color:unset;border:unset}.copy,.close,.today{font-family:"Font Awesome 5 Free"}.navi{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.close,.today{font-weight:900}ul{list-style-type:none;word-break:break-all}.task-list li:not(data-freshness^="-"):not(data-freshness="0"){font-weight:700}.scheduler details li{&data-status=done{opacity:.4}&data-status=expired{font-weight:700}}.task-list li{&data-type=deadline .label.type{color:var(--takker-scheduler-label-deadline-color, rgb(255, 75, 0))}&data-type=todo .label.type{color:var(--takker-scheduler-label-todo-color, rgb(246, 170, 0))}&data-type=note .label.type{color:var(--takker-scheduler-label-note-color, rgb(200, 200, 203))}&data-type=up-down .label.type{color:var(--takker-scheduler-label-up-down-color, rgb(77, 196, 255))}}:is(data-page-no=expired,data-page-no=errors) li{opacity:1!important}.scheduler{--takker-scheduler-summary-meter-width: 10em;overflow-y:hidden}.label{display:inline-block;font-size:90%;padding:0 3px}.type{text-align:center;width:2.5em;border:1px solid;border-radius:3px}.freshness{text-align:right;width:2.5em}.start,.duration{text-align:right;width:3em}
;var Ms=({text:e,title:t})=>{let[r,o]=Q(""),n=D(async s=>{s.preventDefault(),s.stopPropagation();try{await navigator.clipboard.writeText(e),o("Copied"),await Se(1e3),o("")}catch(i){alert(Failed to copy the code block
Error:${i instanceof Error?i.message:i}),console.error(i)}},[e]);return d("button",{type:"button",className:"copy",title:t??"Copy",onClick:n,children:r})};var aD=60*60*24*1e3,XT=(e,t)=>{let r=he(e.refDate),o=(t.getTime()-r.getTime())/aD;switch(r.setHours(0),r.setMinutes(0),e.status){case"done":return-1/0;case"deadline":return o/(e.speed??1);case"todo":return Math.min(o/(e.speed??1),0);case"note":return t.getTime()<r.getTime()?-1/0:-o/(e.speed??1);case"up-down":{let n=e.speed??30;return n*(-1+Math.cos(Math.PI*2*o/n))}}};var QT=(e,t)=>{if(t.score!==e.score)return t.score-e.score;let r=JT(e.freshness),o=JT(t.freshness);return r!==o?o-r:dr($r(e),$r(t))?-1:1},JT=e=>{switch(e.status){case"todo":return 3;case"note":return 2;case"deadline":return 5;case"up-down":return 1;case"done":return 0}};var Vi=({loading:e,onClick:t})=>e?d("div",{children:d("i",{className:"fa fa-spinner"})}):d("button",{type:"button",className:"navi reload",onClick:t,children:""});var Cs=()=>{let[e,t]=Q(new Date);return te(()=>{let r=setInterval(()=>t(new Date),6e4);return()=>{clearInterval(r)}},[]),e};var ZT=e=>{switch(e){case"todo":return"ToDo";case"note":return"覚書";case"deadline":return"締切";case"up-down":return"浮遊";case"done":return"完了"}};var e0=(e,t)=>new URL(/${e.project}/${se(e.title)},t??location.href);var Jl=({children:e,project:t,title:r,className:o,...n})=>d("a",{...n,className:[o??"","page-link"].join(" "),type:"link",href:e0({project:t,title:r}).pathname,...t===scrapbox.Project.name?{rel:"route"}:{rel:"noopener noreferrer",target:"_blank"},children:e});var t0=({action:e,pActions:t})=>{let r=H(()=>ZT(e.freshness.status),[e.freshness.status]),o=H(()=>Fr($r(e)).slice(11)||" ",[$r(e)]),n=H(()=>ci(e),[e]),s=Math.floor(Math.round(e.score)/7),i=Cs(),a=H(()=>e.executed!==void 0&&Zo(Ir(he(e.executed.start),e.executed.duration),i),[e.executed?.start,e.executed?.duration,i]),c=H(()=>[...t,e].map(l=>${l.raw}).join(
),[t,e]);return d("li",{"data-type":e.freshness.status,"data-freshness":e.score.toFixed(0),"data-level":s,...s<0?{style:{opacity:cD(e).toFixed(2)}}:{},children:[d(Ms,{text:c,title:"ここまでコピー"}),d("span",{className:"label type",children:r}),d("i",{className:label far fa-fw${a?" fa-bookmark":""}}),d("span",{className:"label freshness",children:e.score.toFixed(0)}),d("time",{className:"label start",children:o}),d("span",{className:"label duration",children:[n,"m"]}),d(Jl,{project:e.project,title:e.raw,children:e.name})]})},cD=e=>Math.max(.8*Math.exp(Math.log(8/7)/7*e.score),.05);var r0=(e=Vt(new Date))=>{let[t,r]=Q(e),o=D(()=>{r(s=>{switch(s){case"errors":return"expired";case"expired":return Vt(new Date);default:{let i=he(Hi(s));return i.setDate(i.getDate()+1),Vt(i)}}})},[]),n=D(()=>{r(s=>{let i=Vt(new Date);switch(s){case"errors":return"errors";case"expired":return"errors";case i:return"expired";default:{let a=he(Hi(s));return a.setDate(a.getDate()-1),Vt(a)}}})},[]);return{pageNo:t,next:o,prev:n}};var Ql=(e,t)=>te(()=>(scrapbox.on(e,t),()=>scrapbox.off(e,t)),[]);var Ki=(e,t)=>{let r=ft({...t});te(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),te(()=>{e(r.current)},[e])};var o0=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-workflow@0.0.1/next-action-viewer";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>vt(d(lD,{getController:o,projects:e}),r))},lD=({getController:e,projects:t})=>{let{tasks:r,errors:o,load:n,loading:s}=Gi(t),{pageNo:i,next:a,prev:c}=r0(),l=H(()=>{if(i==="errors")return o.map(g=>({name:${g.title}
name:${g.name}
message:${g.message},raw:g.title,freshness:{refDate:{year:9999,month:1,date:1},status:"todo"},project:g.project,generated:!0,score:0}));if(i==="expired"){let g=new Date;return r.flatMap(y=>!Ur(y)&&dr(yx(y),Gt(g))&&y.freshness===void 0&&y.recurrence===void 0?[{...y,score:0,freshness:{refDate:y.executed.start,status:"todo"}}]:[]).sort((y,x)=>dr($r(y),$r(x))?-1:0)}let h=he(Hi(i));return r.flatMap(g=>{if(!g.freshness)return[];if(Mo(g))return[];let y=XT(g.freshness,h);return y>-999?[{...g,score:y}]:[]}).sort(QT)},[r,o,i]),{ref:u,open:p,close:f}=Xl();Ki(e,{open:p,close:f});let m=H(()=>[i,...l.map(h=> ${h.raw})].join(
),[l,i]);return Ql("page:changed",f),d(ee,{children:[d("style",{children:zi}),d("dialog",{ref:u,children:[d("div",{className:"controller",children:[d(Ms,{text:m,title:"Copy All Tasks"}),d("span",{children:i}),d("button",{type:"button",className:"navi left",onClick:c,children:""}),d("button",{type:"button",className:"navi right",onClick:a,children:""}),d(Vi,{loading:s,onClick:n}),d("button",{type:"button",className:"close",onClick:f,children:""})]}),d("ul",{className:"result task-list","data-page-no":i,children:l.map((h,g)=>d(t0,{action:h,pActions:l.slice(0,g)},h.raw))})]})]})};var ep=(e,t)=>/${e}/${ce(t)},Yi=new Map,Pd=new Map,n0=(e,t)=>{Yi.set(e,t);for(let r of Pd.get(e)??[])r(t)},Zl=()=>{On!==void 0&&(clearInterval(On),On=void 0);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=ep(e,t);if(!Yi.has(r))return;let o=Dt().map(n=>n.text);On=setInterval(()=>{ce(t)===ce(o[0])&&(n0(r,o),On!==void 0&&(clearInterval(On),On=void 0))},1e3)},On;scrapbox.on("page:changed",()=>{scrapbox.off("lines:changed",Zl);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=ep(e,t);Yi.has(r)&&scrapbox.on("lines:changed",Zl)});var pD=(e,t)=>{let r=ep(e,t),o=Yi.get(r);return o||(Yi.set(r,[]),ur(e,t).then(n=>{if(O(n))return[];let s=S(n).lines.map(i=>i.text);n0(r,s),t===scrapbox.Page.title&&!scrapbox.listeners("lines:changed").includes(Zl)&&scrapbox.on("lines:changed",Zl)})),o??[]},s0=(e,t)=>{let[r,o]=Q(pD(e,t));return te(()=>{let n=ep(e,t),s=Pd.get(n)??new Set;return s.add(o),Pd.set(n,s),()=>{s.delete(o)}},[e,t]),r};var Od=e=>e.duration===void 0?void 0:Gt(Ir(he(e.start),e.duration)),Sd=(e,t)=>{let r=he(e.start),o=t.getTime(),n=Math.round((o-r.getTime())/(60*1e3));if(n<=0)return[void 0,e];if(e.duration<=n)return[e,void 0];let s={start:e.start,duration:n};return[s,{start:Od(s),duration:e.duration-n}]};var Sn=e=>"title"in e,uD=e=>e.record?.duration!==void 0,i0=(e,t)=>Sn(e)&&e.status==="done"?e.status:uD(e)?Sn(e)&&e.executed?dr(Gt(t),e.executed.start)?"moved":"expired":"done":dr(Od(e.plan),Gt(t))?Sn(e)?"expired":"done":"undone";var a0=(e,t)=>{let r=Dr(e.title.slice(1,-1));if(!e.plan.start)return;let o={name:r&&K(r)?S(r).name:e.title,plan:{start:Gt(e.plan.start),duration:(e.plan.duration??0)/60}};if(e.record.start&&(o.record={start:Gt(e.record.start)},e.record.end&&(o.record.duration=So(e.record.end,e.record.start))),!r||O(r))return o;let n=S(r),s={...o,title:n.raw,project:t};return n.freshness&&(s.status=n.freshness.status),Ur(n)||(s.executed=n.executed),s},Ld=(e,t)=>{let r=cc(e);return r!==void 0?{name:e.name,project:t,title:r,executed:e.executed,plan:e.executed,status:e.freshness?.status}:{name:e.name,plan:e.executed}};var c0=(e,t,r)=>{let o=[Nd(e,Yt(t,1),r),Nd(e,t,r),Nd(e,ve(t,1),r)],n=H(()=>o.flat(),o);return H(()=>{let s=kr(t),i=rc(t);return n.flatMap(a=>{let[,c]=Sd(a.plan,s);if(!c)return[];let[l]=Sd(c,i);if(!l)return[];let{plan:u,...p}=a;return[{plan:l,...p}]}).sort((a,c)=>dr(a.plan.start,c.plan.start)?-1:0)},[n,t])},Nd=(e,t,r)=>{let o=s0(e,_r(t)),n=H(()=>fD(o,e),[o,e]);return H(()=>n.length!==0?n:mD(t,r),[n,t,r])},mD=(e,t)=>t.flatMap(r=>{if(r.freshness?.status==="done")return[];if(Ur(r))return[];if(Mo(r)){let n=ac(r,e);return n?[Ld(n,r.project)]:[]}let o=he(r.executed.start);return gt(o,e)?[Ld(r,r.project)]:[]}),fD=(e,t)=>{let r=[];for(let o of en(e)){if(No(o))continue;let n=a0(o,t);n&&r.push(n)}return r};var l0=({event:e})=>{let t=H(()=>e.plan.start.hours+e.plan.start.minutes/60,[e.plan.start]),r=H(()=>--start: ${t}; --duration: ${e.plan.duration};,[t,e.plan.duration]),o=Cs(),n=H(()=>i0(e,o),[e,o]);return Sn(e)?d(Jl,{className:"event","data-status":n,style:r,title:e.title,project:e.project,children:e.name}):d("div",{className:"event","data-status":n,title:e.name,style:r,children:e.name})};var p0=({project:e,date:t,tasks:r})=>{let o=c0(e,t,r),n=H(()=>o.flatMap(a=>Sn(a)?[${a.title}]:[]).join(
),[o]),s=Cs(),i=H(()=>gt(s,t)&&d("div",{className:"indicator",style:--start: ${rx(s)+tx(s)/60}}),[s,t]);return d("div",{className:"timeline",role:"gridcell",children:[o.map(a=>d(l0,{event:a},a.name)),i,d(Ms,{text:n})]})};var Md=({dateList:e,tasks:t,project:r,hasColumn:o})=>d("div",{className:"timeline-wrap",role:"grid",children:[(o??!0)&&d("div",{className:"column-header",role:"row",children:e.map(n=>d("div",{className:"cell",role:"columnheader",children:d("h2",{children:Yu(n)})},Vt(n)))}),d("div",{className:"week-container",role:"presentation",children:d("div",{className:"week",role:"presentation",children:[d("div",{className:"borders",children:[...Array(24).keys()].map(n=>d("div",{className:"border","data-time":${Pr(n)}:00},n))}),e.map(n=>d(p0,{project:r,date:n,tasks:t},Vt(n)))]})})]});var Cd=(e,t,r)=>{let[o,n]=Q(e),s=D(()=>n(t),[t]),i=D(()=>n(r),[t]),a=D(c=>n(c),[]);return{pageNo:o,next:s,prev:i,jump:a}};var u0=e=>{let t=ft(new Set),[r,o]=Q(e),n=D(()=>{for(let l of t.current)l()},[]),s=D(()=>{o(!0),n()},[]),i=D(()=>o(!1),[]),a=D(()=>o(l=>(l||n(),!l)),[]),c=D(l=>(t.current.add(l),()=>t.current.delete(l)),[]);return{isOpen:r,open:s,close:i,toggle:a,onOpen:c}};var d0=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-scheduler/weekly-scheduler";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>vt(d(dD,{getController:o,projects:e,mainProject:e[0]}),r))},h0=(e,t)=>{let r=document.createElement("div");r.dataset.userscriptName="takker-scheduler/timeline-wedget";let o=r.attachShadow({mode:"open"});return document.body.append(r),new Promise(n=>vt(d(hD,{getController:n,projects:e,mainProject:e[0],open:t}),o))},m0=!1,dD=({getController:e,projects:t,mainProject:r})=>{let{tasks:o,load:n,loading:s}=Gi(t),{pageNo:i,next:a,prev:c,jump:l}=Cd(Wi(new Date),gD,yD),u=H(()=>{let y=Vl(i);return[0,1,2,3,4,5,6].map(x=>ve(y,x))},[i]),{ref:p,open:f,close:m,isOpen:h}=Xl();m0||=h,Ki(e,{open:f,close:m,isOpen:h}),Ql("page:changed",m);let g=D(()=>l(Wi(new Date)),[l]);return d(ee,{children:[d("style",{children:zi}),d("dialog",{ref:p,children:[d("div",{className:"controller",children:[d("span",{children:i}),d("button",{type:"button",className:"navi left",onClick:c,children:""}),d("button",{type:"button",className:"navi right",onClick:a,children:""}),d("button",{type:"button",className:"today",onClick:g,children:""}),d(Vi,{loading:s,onClick:n}),d("button",{type:"button",className:"close",onClick:m,children:""})]}),m0&&d("div",{ref:g0,className:"result scheduler","data-page-no":i,children:d(Md,{dateList:u,tasks:o,project:r})})]})]})},f0=!1,hD=({projects:e,mainProject:t,getController:r,open:o})=>{let{tasks:n,load:s,loading:i}=Gi(e),{pageNo:a,next:c,prev:l,jump:u}=Cd(new Date,xD,bD),p=H(()=>[a],[a]),f=D(()=>u(new Date),[u]),{isOpen:m,open:h,close:g}=u0(o);return f0||=m,Ki(r,{open:h,close:g,isOpen:m}),d(ee,{children:[d("style",{children:zi}),f0&&d("div",{className:wedget${m?" open":""},ref:g0,children:[d("div",{className:"controller",children:[d("span",{children:Vt(a)}),d("button",{type:"button",className:"navi left",onClick:l,children:""}),d("button",{type:"button",className:"navi right",onClick:c,children:""}),d("button",{type:"button",className:"today",onClick:f,children:""}),d(Vi,{loading:i,onClick:s})]}),d(Md,{dateList:p,tasks:n,project:t,hasColumn:!1})]})]})},gD=e=>Wi(Jo(Vl(e),1)),yD=e=>Wi(ox(Vl(e),1)),xD=e=>ve(e,1),bD=e=>Yt(e,1),g0=e=>{let t=e?.getElementsByClassName?.("indicator")?.[0];if(!t)return;let r=globalThis.scrollY;t.scrollIntoView({block:"center"}),globalThis.scroll(0,r)};Rg({project:"takker-dist"});_a(!0);Tg({maxCount:10,accessToken:ED,onClick:async(e,t)=>{try{if(t.ctrlKey){await navigator.clipboard.writeText(e.permalink_url);return}let r=document.getElementById("text-input");if(!r)throw Error("#text-input is not ditected.");r.focus(),r.value=e.permalink_url;let o=new InputEvent("input",{bubbles:!0});r.dispatchEvent(o),await scrapbox.Page.waitForSave()}catch(r){alert(${r}),console.error(r)}}});Sy().then(e=>{scrapbox.PageMenu.addItem({title:"Fulltext Search",onClick:()=>{e.toggle()}})});var wD="https://scrapbox.io/files/67344295032adf96d1e4c276.wasm",RD="/api/code/takker-dist/for-any-project-min/esbuild-worker.js";(async()=>{let e=new Request(wD),t=await _o(e);t||(t=await fetch(e),await Ka(e,t)),await xw(await WebAssembly.compileStreaming(t),RD)})();(async()=>{let e=[scrapbox.Project.name,"takker","takker-memex","takker-books","takker-private","villagepump","hub","arpla","work4ai","unnamedcamp","unnamed-project","nishio","enchi","rashitamemo","motoso","shokai","masui","rakusai","yuiseki","akiroom","c4j","miyamonz","mrsekut-p","masuilab","kidaaam-92022284","nwtgck","juneboku","marshmallow-rm","sushitecture","sno2wman","inteltank","issac-37765679","blu3mo","yosider","Mijinko","Mijinko-other","scrapbox-drinkup","nota-techconf","customize","scrapboxlab","scrasobox","programming-notes","tus-alpine","tus-alpine-private","guiland","evergreens","fab-wiki"],t=await aR({projects:e,mark:{...Object.fromEntries([["takker","takker"],["takker-memex","takker"],["takker-books","takker-books"],["takker-private","takker-private"],["nishio","nishio"],["rashitamemo","rashita"],["enchi","雑談_2022-04-12~"],["rakusai","rakusai"],["masui","概要"],["shokai","shokai"],["yuiseki","yuiseki"],["akiroom","はじめに"],["inteltank","sawachin"],["motoso","もとそのもと"],["villagepump","井戸端"],["hub","scrapbox.io%2Fhub_について"],["masuilab","増井研に入ったらまずやること"],["marshmallow-rm","読書猿マシュマロ全質問回答"],["miyamonz","miyamonz"],["mrsekut-p","mrsekut"],["kidaaam-92022284","kidooom"],["c4j","Code_for_Japan"],["suto3","suto3"],["blu3mo","blu3mo"],["nwtgck","nwtgck"],["juneboku","juneboku"],["jigsaw","jgs"],["sno2wman","SnO2WMaN"],["sushitecture","hashrock"],["unnamedcamp","知を営む"],["unnamed-project","unnamed-project"],["issac-37765679","cFQ2f7LRuLYP"],["blu3mo","blu3mo"],["yosider","yosider"],["Mijinko","Mijinko_SD"],["Mijinko-other","Mijinko_SD"],["customize","みんなのカスタマイズ"],["scrapboxlab","入会手続き"],["scrasobox","Scrapboxとあそぶ"],["programming-notes","参加する"],["guiland","概要と参加方法"],["work4ai","work4ai"],["evergreens","HOME"],["fab-wiki","fab-wikiに参加する"]].map(([n,s])=>[n,https://scrapbox.io/api/pages/${n}/${s}/icon])),"NDLSH-SB":"📚","scrapbox-drinkup":"https://scrapbox.io/assets/img/page-icon/scrapbox_beaver.png","nota-techconf":"https://i.gyazo.com/727f42bbd9e2534d99d70e6ea90705b3.jpg","plurality-japanese":"⿻"},workerUrl:"/api/code/takker-dist/for-any-project-min/select-suggestion-worker.js",enableSelfProjectOnStart:!0}),r=n=>{n.preventDefault(),n.stopPropagation()},o=()=>document.querySelector(".line .popup-menu")!==null;pm.bind({"<Tab>":n=>{o()||t.selectNext?.({cyclic:!0})&&r(n)},"<S-Tab>":n=>{o()||t.selectPrev?.({cyclic:!0})&&r(n)},"<Enter>":n=>{o()||t.confirm?.()&&r(n)},"<Esc>":n=>{o()||t.cancel?.()&&r(n)}})})();uR({previewers:[{when:/(?:^|\.)svg$/,preview:mR},{when:/(?:^|\.)glsl$/,preview:PR},{when:/(?:^|\.)(?:plantuml|puml|pu)$/,preview:LR},{when:/(?:^|\.)tikz\(tex\)$/,preview:MR("/api/code/takker-dist/for-any-project-min/tex-worker.js","https://scrapbox.io/files/65d1645c19cd8e002433c3df")}]});(async()=>{let{toggle:e}=await XR();scrapbox.PageMenu.addItem({title:"履歴スライダー",image:"https://1.bp.blogspot.com/-UZtkSEX0wh4/U5l5_dNcEsI/AAAAAAAAhWs/UzJGVzyiX8Y/s800/kaichu_dokei.png",onClick:e})})();zk("takker",["takker","振り返り(takker-workflow@0.0.1)のtemplate","txt"],["takker","1週間の振り返り(takker-workflow@0.0.1)のtemplate","txt"],new Date(2024,11,24));vn()&&(Er({display:{type:"caret-left"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?qa():ja()}}),Er({display:{type:"caret-right"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Wa():$a()}}),Er({display:{type:"caret-up"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ga():Ba()}}),Er({display:{type:"caret-down"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?za():Ha()}}),Er({display:{type:"copy"},onClick:async({cursor:e,selection:t})=>await BT(e,t)}),Er({display:{type:"cut"},onClick:async({cursor:e,selection:t})=>await HT(e,t)}),Er({display:{type:"clipboard"},onClick:async({cursor:e})=>await WT(e)}),Er({display:{type:"undo"},onClick:()=>gy()}),Er({display:{type:"redo"},onClick:()=>yy()}),Er({display:({cursor:e})=>e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?{type:["i-cursor","slash"]}:{type:"i-cursor"},onClick:({cursor:e})=>qT(e)}));if(vn()&&scrapbox.Project.name!=="takker-memex"){let e="task";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/todo-list--v2.png"}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:ni}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>ii({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})})}if(vn()){let e="New Page",t=[nn,sn,an];scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/cut-paper.png"}),scrapbox.PageMenu(e).addItem({title:"New Page",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&to({project:r,mode:"noopen",hooks:t})?.()}}),scrapbox.PageMenu(e).addItem({title:"New Page and Open",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&to({project:r,mode:"self",hooks:t})?.()}})}(async()=>{let e="next-action",t=head styledata-userscript-name="${e}";document.querySelector(t)?.remove?.();let r=document.createElement("style");r.dataset.userscriptName=e,r.textContent=
button:is(#${e}, #scheduler).tool-btn::before {
position: absolute;
font: 900 20px/46px "Font Awesome 5 Free";
}
button#${e}.tool-btn::before {
content: "\\f0ae";
}
button#scheduler.tool-btn::before {
content: "\\f073";
font-weight: 400;
}
button:is(#${e}, #scheduler).tool-btn img {
opacity: 0;
}`,document.head.append(r);let o="takker-memex","takker",{open:n}=await o0(o);scrapbox.PageMenu.addMenu({title:e,image:"/assets/img/favicon/apple-touch-icon.png",onClick:n});let s=await d0(o);scrapbox.PageMenu.addMenu({title:"scheduler",image:"/assets/img/favicon/apple-touch-icon.png",onClick:s.open});{let i="takker-scheduler/wedget",a=JSON.parse(localStorage.getItem(i)??"{}"),c=scrapbox.Project.name;ac??=!1;let l=await h0(o,ac),u=()=>{ac=!l.isOpen,l.isOpen?l.close():l.open?.(),localStorage.setItem(i,JSON.stringify(a))};vn()?Er({display:{type:"calendar"},onClick:u}):scrapbox.PageMenu.addItem({title:"toggle wedget",onClick:u})}})();export{Er as addButton,at as insertText,pm as scrapBindings};
/** @license
* esbuild-wasm@v0.24.0
*
* MIT License
*
* Copyright (c) 2020 Evan Wallace
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*! Bundled license information:
comlink/dist/esm/comlink.mjs:
(**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*)
*/
code:takker-memex.js
var _0=Object.defineProperty;var Wo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)r}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var oa=(e,t)=>{for(var r in t)_0(e,r,{get:tr,enumerable:!0})};function _e(e){if(e)return P0(e)}function P0(e){for(var t in _e.prototype)et=_e.prototypet;return e}_e.prototype.on=_e.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks"$"+e=this._callbacks"$"+e||[]).push(t),this};_e.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};_e.prototype.off=_e.prototype.removeListener=_e.prototype.removeAllListeners=_e.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var r=this._callbacks"$"+e;if(!r)return this;if(arguments.length==1)return delete this._callbacks"$"+e,this;for(var o,n=0;n<r.length;n++)if(o=rn,o===t||o.fn===t){r.splice(n,1);break}return r.length===0&&delete this._callbacks"$"+e,this};_e.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks"$"+e,o=1;o<arguments.length;o++)to-1=argumentso;if(r){r=r.slice(0);for(var o=0,n=r.length;o<n;++o)ro.apply(this,t)}return this};_e.prototype.emitReserved=_e.prototype.emit;_e.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks"$"+e||[]};_e.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Mr=Object.create(null);Mr.open="0";Mr.close="1";Mr.ping="2";Mr.pong="3";Mr.message="4";Mr.upgrade="5";Mr.noop="6";var ia=Object.create(null);Object.keys(Mr).forEach(e=>{ia[Mre]=e});var up={type:"error",data:"parser error"},Hd=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="object BlobConstructor",Wd=typeof ArrayBuffer=="function",qd=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,aa=({type:e,data:t},r,o)=>Hd&&t instanceof Blob?r?o(t):$d(t,o):Wd&&(t instanceof ArrayBuffer||qd(t))?r?o(t):$d(new Blob(t),o):o(Mre+(t||"")),$d=(e,t)=>{let r=new FileReader;return r.onload=function(){let o=r.result.split(",")1;t("b"+(o||""))},r.readAsDataURL(e)};function jd(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var lp;function O0(e,t){if(Hd&&e.data instanceof Blob)return e.data.arrayBuffer().then(jd).then(t);if(Wd&&(e.data instanceof ArrayBuffer||qd(e.data)))return t(jd(e.data));aa(e,!1,r=>{lp||(lp=new TextEncoder),t(lp.encode(r))})}var Bd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$s=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Bd.length;e++)$sBd.charCodeAt(e)=e;var S0=e=>{let t=e.length*.75,r=e.length,o,n=0,s,i,a,c;ee.length-1==="="&&(t--,ee.length-2==="="&&t--);let l=new ArrayBuffer(t),u=new Uint8Array(l);for(o=0;o<r;o+=4)s=$se.charCodeAt(o),i=$se.charCodeAt(o+1),a=$se.charCodeAt(o+2),c=$se.charCodeAt(o+3),un++=s<<2|i>>4,un++=(i&15)<<4|a>>2,un++=(a&3)<<6|c&63;return l},L0=typeof ArrayBuffer=="function",ca=(e,t)=>{if(typeof e!="string")return{type:"message",data:Gd(e,t)};let r=e.charAt(0);return r==="b"?{type:"message",data:N0(e.substring(1),t)}:iar?e.length>1?{type:iar,data:e.substring(1)}:{type:iar}:up},N0=(e,t)=>{if(L0){let r=S0(e);return Gd(r,t)}else return{base64:!0,data:e}},Gd=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob(e);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},zd="",Vd=(e,t)=>{let r=e.length,o=new Array(r),n=0;e.forEach((s,i)=>{aa(s,!1,a=>{oi=a,++n===r&&t(o.join(zd))})})},Kd=(e,t)=>{let r=e.split(zd),o=[];for(let n=0;n<r.length;n++){let s=ca(rn,t);if(o.push(s),s.type==="error")break}return o};function Yd(){return new TransformStream({transform(e,t){O0(e,r=>{let o=r.length,n;if(o<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,o);else if(o<65536){n=new Uint8Array(3);let s=new DataView(n.buffer);s.setUint8(0,126),s.setUint16(1,o)}else{n=new Uint8Array(9);let s=new DataView(n.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(o))}e.data&&typeof e.data!="string"&&(n0|=128),t.enqueue(n),t.enqueue(r)})}})}var pp;function na(e){return e.reduce((t,r)=>t+r.length,0)}function sa(e,t){if(e0.length===t)return e.shift();let r=new Uint8Array(t),o=0;for(let n=0;n<t;n++)rn=e0o++,o===e0.length&&(e.shift(),o=0);return e.length&&o<e0.length&&(e0=e0.slice(o)),r}function Xd(e,t){pp||(pp=new TextDecoder);let r=[],o=0,n=-1,s=!1;return new TransformStream({transform(i,a){for(r.push(i);;){if(o===0){if(na(r)<1)break;let c=sa(r,1);s=(c0&128)===128,n=c0&127,n<126?o=3:n===126?o=1:o=2}else if(o===1){if(na(r)<2)break;let c=sa(r,2);n=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),o=3}else if(o===2){if(na(r)<8)break;let c=sa(r,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(up);break}n=u*Math.pow(2,32)+l.getUint32(4),o=3}else{if(na(r)<n)break;let c=sa(r,n);a.enqueue(ca(s?c:pp.decode(c),t)),o=0}if(n===0||n>e){a.enqueue(up);break}}}})}var mp=4;var js=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),ar=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),M0="arraybuffer";function Qd(e,...t){return t.reduce((r,o)=>(e.hasOwnProperty(o)&&(ro=eo),r),{})}var C0=ar.setTimeout,I0=ar.clearTimeout;function Bs(e,t){t.useNativeTimers?(e.setTimeoutFn=C0.bind(ar),e.clearTimeoutFn=I0.bind(ar)):(e.setTimeoutFn=ar.setTimeout.bind(ar),e.clearTimeoutFn=ar.clearTimeout.bind(ar))}var A0=1.33;function F0(e){return typeof e=="string"?D0(e):Math.ceil((e.byteLength||e.size)*A0)}function D0(e){let t=0,r=0;for(let o=0,n=e.length;o<n;o++)t=e.charCodeAt(o),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(o++,r+=4);return r}function Zd(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function U0(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(er));return t}function $0(e){let t={},r=e.split("&");for(let o=0,n=r.length;o<n;o++){let s=ro.split("=");t[decodeURIComponent(s0)]=decodeURIComponent(s1)}return t}var j0=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},hp=class extends _e{constructor(e){super(),this.writable=!1,Bs(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new j0(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=ca(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:""+e+""}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=U0(e);return t.length?"?"+t:""}},B0=class extends hp{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(r++,this.once("pollComplete",function(){--r||t()})),this.writable||(r++,this.once("drain",function(){--r||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};Kd(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){let e=()=>{this.write({type:"close"})};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,Vd(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(tthis.opts.timestampParam=Zd()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},eh=!1;try{eh=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var H0=eh;function W0(){}var q0=class extends B0{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(o,n)=>{this.onError("xhr post error",o,n)})}doPoll(){let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},An=class la extends _e{constructor(t,r,o){super(),this.createRequest=t,Bs(this,o),this._opts=o,this._method=o.method||"GET",this._uri=r,this._data=o.data!==void 0?o.data:null,this._create()}_create(){var t;let r=Qd(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;let o=this._xhr=this.createRequest(r);try{o.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){o.setDisableHeaderCheck&&o.setDisableHeaderCheck(!0);for(let n in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(n)&&o.setRequestHeader(n,this._opts.extraHeadersn)}}catch{}if(this._method==="POST")try{o.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{o.setRequestHeader("Accept","*/*")}catch{}(t=this._opts.cookieJar)===null||t===void 0||t.addCookies(o),"withCredentials"in o&&(o.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(o.timeout=this._opts.requestTimeout),o.onreadystatechange=()=>{var n;o.readyState===3&&((n=this._opts.cookieJar)===null||n===void 0||n.parseCookies(o.getResponseHeader("set-cookie"))),o.readyState===4&&(o.status===200||o.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof o.status=="number"?o.status:0)},0))},o.send(this._data)}catch(n){this.setTimeoutFn(()=>{this._onError(n)},0);return}typeof document<"u"&&(this._index=la.requestsCount++,la.requeststhis._index=this)}_onError(t){this.emitReserved("error",t,this._xhr),this._cleanup(!0)}_cleanup(t){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=W0,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete la.requeststhis._index,this._xhr=null}}_onLoad(){let t=this._xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};An.requestsCount=0;An.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Jd);else if(typeof addEventListener=="function"){let e="onpagehide"in ar?"pagehide":"unload";addEventListener(e,Jd,!1)}}function Jd(){for(let e in An.requests)An.requests.hasOwnProperty(e)&&An.requestse.abort()}var G0=function(){let e=th({xdomain:!1});return e&&e.responseType!==null}(),gp=class extends q0{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=G0&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new An(th,this.uri(),e)}};function th(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||H0))return new XMLHttpRequest}catch{}if(!t)try{return new ar["Active".concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var rh=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",z0=class extends hp{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=rh?{}:Qd(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=et,o=t===e.length-1;aa(r,this.supportsBinary,n=>{try{this.doWrite(r,n)}catch{}o&&js(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(tthis.opts.timestampParam=Zd()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},fp=ar.WebSocket||ar.MozWebSocket,yp=class extends z0{createSocket(e,t,r){return rh?new fp(e,t,r):t?new fp(e,t):new fp(e)}doWrite(e,t){this.ws.send(t)}},oh=class extends hp{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptionsthis.name)}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Xd(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),o=Yd();o.readable.pipeTo(e.writable),this._writer=o.writable.getWriter();let n=()=>{r.read().then(({done:i,value:a})=>{i||(this.onPacket(a),n())}).catch(i=>{})};n();let s={type:"open"};this.query.sid&&(s.data={"sid":"${this.query.sid}"}),this._writer.write(s).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=et,o=t===e.length-1;this._writer.write(r).then(()=>{o&&js(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}},V0={websocket:yp,webtransport:oh,polling:gp},K0=/^(?:(?!^:@\/?#+:^:@\/*@)(http|https|ws|wss):\/\/)?((?:((^:@\/?#*)(?::(^:@\/?#*))?)?@)?((?:a-f0-9{0,4}:){2,7}a-f0-9{0,4}|^:\/?#*)(?::(\d*))?)(((\/(?:^?#(?!^?#\/*\.^?#\/.+(?:?#|$)))*\/?)?(^?#\/*))(?:\?(^#*))?(?:#(.*))?)/,Y0="source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor";function fa(e){if(e.length>8e3)throw"URI too long";let t=e,r=e.indexOf(""),o=e.indexOf("");r!=-1&&o!=-1&&(e=e.substring(0,r)+e.substring(r,o).replace(/:/g,";")+e.substring(o,e.length));let n=K0.exec(e||""),s={},i=14;for(;i--;)s[Y0i]=ni||"";return r!=-1&&o!=-1&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("","").replace("","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=X0(s,s.path),s.queryKey=J0(s,s.query),s}function X0(e,t){let r=/\/{2,9}/g,o=t.replace(r,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&o.splice(0,1),t.slice(-1)=="/"&&o.splice(o.length-1,1),o}function J0(e,t){let r={};return t.replace(/(?:^|&)(^&=*)=?(^&*)/g,function(o,n,s){n&&(rn=s)}),r}var dp=typeof addEventListener=="function"&&typeof removeEventListener=="function",pa=[];dp&&addEventListener("offline",()=>{pa.forEach(e=>e())},!1);var ua=class ma extends _e{constructor(t,r){if(super(),this.binaryType=M0,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,t&&typeof t=="object"&&(r=t,t=null),t){let o=fa(t);r.hostname=o.host,r.secure=o.protocol==="https"||o.protocol==="wss",r.port=o.port,o.query&&(r.query=o.query)}else r.host&&(r.hostname=fa(r.host).host);Bs(this,r),this.secure=r.secure!=null?r.secure:typeof location<"u"&&location.protocol==="https:",r.hostname&&!r.port&&(r.port=this.secure?"443":"80"),this.hostname=r.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=r.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},r.transports.forEach(o=>{let n=o.prototype.name;this.transports.push(n),this._transportsByNamen=o}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},r),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=$0(this.opts.query)),dp&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},pa.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){let r=Object.assign({},this.opts.query);r.EIO=mp,r.transport=t,this.id&&(r.sid=this.id);let o=Object.assign({},this.opts,{query:r,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptionst);return new this._transportsByNamet(o)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let t=this.opts.rememberUpgrade&&ma.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports0;this.readyState="opening";let r=this.createTransport(t);r.open(),this.setTransport(r)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",r=>this._onClose("transport close",r))}onOpen(){this.readyState="open",ma.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let r=new Error("server error");r.code=t.data,this._onError(r);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data);break}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this._pingInterval=t.pingInterval,this._pingTimeout=t.pingTimeout,this._maxPayload=t.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let t=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+t,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},t),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let t=this._getWritablePackets();this.transport.send(t),this._prevBufferLen=t.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let o=this.writeBufferr.data;if(o&&(t+=F0(o)),r>0&&t>this._maxPayload)return this.writeBuffer.slice(0,r);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let t=Date.now()>this._pingTimeoutTime;return t&&(this._pingTimeoutTime=0,js(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),t}write(t,r,o){return this._sendPacket("message",t,r,o),this}send(t,r,o){return this._sendPacket("message",t,r,o),this}_sendPacket(t,r,o,n){if(typeof r=="function"&&(n=r,r=void 0),typeof o=="function"&&(n=o,o=null),this.readyState==="closing"||this.readyState==="closed")return;o=o||{},o.compress=o.compress!==!1;let s={type:t,data:r,options:o};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){let t=()=>{this._onClose("forced close"),this.transport.close()},r=()=>{this.off("upgrade",r),this.off("upgradeError",r),t()},o=()=>{this.once("upgrade",r),this.once("upgradeError",r)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?o():t()}):this.upgrading?o():t()),this}_onError(t){if(ma.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",t),this._onClose("transport error",t)}_onClose(t,r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),dp&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let o=pa.indexOf(this._offlineEventListener);o!==-1&&pa.splice(o,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};ua.protocol=mp;var Q0=class extends ua{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgradese)}_probe(e){let t=this.createTransport(e),r=!1;ua.priorWebsocketSuccess=!1;let o=()=>{r||(t.send({type:"ping",data:"probe"}),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ua.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(l(),this.setTransport(t),t.send({type:"upgrade"}),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{let p=new Error("probe error");p.transport=t.name,this.emitReserved("upgradeError",p)}}))};function n(){r||(r=!0,l(),t.close(),t=null)}let s=u=>{let p=new Error("probe error: "+u);p.transport=t.name,n(),this.emitReserved("upgradeError",p)};function i(){s("transport closed")}function a(){s("socket closed")}function c(u){t&&u.name!==t.name&&n()}let l=()=>{t.removeListener("open",o),t.removeListener("error",s),t.removeListener("close",i),this.off("close",a),this.off("upgrading",c)};t.once("open",o),t.once("error",s),t.once("close",i),this.once("close",a),this.once("upgrading",c),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(er)&&t.push(er);return t}},xp=class extends Q0{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports0=="string")&&(r.transports=(r.transports||"polling","websocket","webtransport").map(o=>V0o).filter(o=>!!o)),super(e,r)}};var zD=xp.protocol;var Rp={};oa(Rp,{Decoder:()=>i_,Encoder:()=>s_,PacketType:()=>ne,isPacketValid:()=>m_,protocol:()=>ih});var Z0=typeof ArrayBuffer=="function",e_=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,nh=Object.prototype.toString,t_=typeof Blob=="function"||typeof Blob<"u"&&nh.call(Blob)==="object BlobConstructor",r_=typeof File=="function"||typeof File<"u"&&nh.call(File)==="object FileConstructor";function wp(e){return Z0&&(e instanceof ArrayBuffer||e_(e))||t_&&e instanceof Blob||r_&&e instanceof File}function da(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,o=e.length;r<o;r++)if(da(er))return!0;return!1}if(wp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return da(e.toJSON(),!0);for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&da(er))return!0;return!1}function o_(e){let t=[],r=e.data,o=e;return o.data=bp(r,t),o.attachments=t.length,{packet:o,buffers:t}}function bp(e,t){if(!e)return e;if(wp(e)){let r={_placeholder:!0,num:t.length};return t.push(e),r}else if(Array.isArray(e)){let r=new Array(e.length);for(let o=0;o<e.length;o++)ro=bp(eo,t);return r}else if(typeof e=="object"&&!(e instanceof Date)){let r={};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&(ro=bp(eo,t));return r}return e}function n_(e,t){return e.data=Ep(e.data,t),delete e.attachments,e}function Ep(e,t){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<t.length)return te.num;throw new Error("illegal attachments")}else if(Array.isArray(e))for(let r=0;r<e.length;r++)er=Ep(er,t);else if(typeof e=="object")for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(er=Ep(er,t));return e}var sh="connect","connect_error","disconnect","disconnecting","newListener","removeListener",ih=5,ne;(function(e){ee.CONNECT=0="CONNECT",ee.DISCONNECT=1="DISCONNECT",ee.EVENT=2="EVENT",ee.ACK=3="ACK",ee.CONNECT_ERROR=4="CONNECT_ERROR",ee.BINARY_EVENT=5="BINARY_EVENT",ee.BINARY_ACK=6="BINARY_ACK"})(ne||(ne={}));var s_=class{constructor(e){this.replacer=e}encode(e){return(e.type===ne.EVENT||e.type===ne.ACK)&&da(e)?this.encodeAsBinary({type:e.type===ne.EVENT?ne.BINARY_EVENT:ne.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):this.encodeAsString(e)}encodeAsString(e){let t=""+e.type;return(e.type===ne.BINARY_EVENT||e.type===ne.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){let t=o_(e),r=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(r),o}},i_=class ah extends _e{constructor(t){super(),this.reviver=t}add(t){let r;if(typeof t=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");r=this.decodeString(t);let o=r.type===ne.BINARY_EVENT;o||r.type===ne.BINARY_ACK?(r.type=o?ne.EVENT:ne.ACK,this.reconstructor=new a_(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(wp(t)||t.base64)if(this.reconstructor)r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,super.emitReserved("decoded",r));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+t)}decodeString(t){let r=0,o={type:Number(t.charAt(0))};if(neo.type===void 0)throw new Error("unknown packet type "+o.type);if(o.type===ne.BINARY_EVENT||o.type===ne.BINARY_ACK){let s=r+1;for(;t.charAt(++r)!=="-"&&r!=t.length;);let i=t.substring(s,r);if(i!=Number(i)||t.charAt(r)!=="-")throw new Error("Illegal attachments");o.attachments=Number(i)}if(t.charAt(r+1)==="/"){let s=r+1;for(;++r&&!(t.charAt(r)===","||r===t.length););o.nsp=t.substring(s,r)}else o.nsp="/";let n=t.charAt(r+1);if(n!==""&&Number(n)==n){let s=r+1;for(;++r;){let i=t.charAt(r);if(i==null||Number(i)!=i){--r;break}if(r===t.length)break}o.id=Number(t.substring(s,r+1))}if(t.charAt(++r)){let s=this.tryParse(t.substr(r));if(ah.isPayloadValid(o.type,s))o.data=s;else throw new Error("invalid payload")}return o}tryParse(t){try{return JSON.parse(t,this.reviver)}catch{return!1}}static isPayloadValid(t,r){switch(t){case ne.CONNECT:return ha(r);case ne.DISCONNECT:return r===void 0;case ne.CONNECT_ERROR:return typeof r=="string"||ha(r);case ne.EVENT:case ne.BINARY_EVENT:return Array.isArray(r)&&(typeof r0=="number"||typeof r0=="string"&&sh.indexOf(r0)===-1);case ne.ACK:case ne.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},a_=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=n_(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function c_(e){return typeof e=="string"}var l_=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e};function p_(e){return e===void 0||l_(e)}function ha(e){return Object.prototype.toString.call(e)==="object Object"}function u_(e,t){switch(e){case ne.CONNECT:return t===void 0||ha(t);case ne.DISCONNECT:return t===void 0;case ne.EVENT:return Array.isArray(t)&&(typeof t0=="number"||typeof t0=="string"&&sh.indexOf(t0)===-1);case ne.ACK:return Array.isArray(t);case ne.CONNECT_ERROR:return typeof t=="string"||ha(t);default:return!1}}function m_(e){return c_(e.nsp)&&p_(e.id)&&u_(e.type,e.data)}function f_(e,t="",r){let o=e;r=r||typeof location<"u"&&location,e==null&&(e=r.protocol+"//"+r.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=r.protocol+e:e=r.host+e),/^(https?|wss?):\/\//.test(e)||(typeof r<"u"?e=r.protocol+"//"+e:e="https://"+e),o=fa(e)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";let n=o.host.indexOf(":")!==-1?""+o.host+"":o.host;return o.id=o.protocol+"://"+n+":"+o.port+t,o.href=o.protocol+"://"+n+(r&&r.port===o.port?"":":"+o.port),o}function Rr(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var d_=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),ch=class extends _e{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=Rr(e,"open",this.onopen.bind(this)),Rr(e,"packet",this.onpacket.bind(this)),Rr(e,"error",this.onerror.bind(this)),Rr(e,"close",this.onclose.bind(this))}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,o,n;if(d_.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let s={type:ne.EVENT,data:t};if(s.options={},s.options.compress=this.flags.compress!==!1,typeof tt.length-1=="function"){let c=this.ids++,l=t.pop();this._registerAckCallback(c,l),s.id=c}let i=(o=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||o===void 0?void 0:o.writable,a=this.connected&&!(!((n=this.io.engine)===null||n===void 0)&&n._hasPingExpired());return this.flags.volatile&&!i||(a?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(e,t){var r;let o=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(o===void 0){this.ackse=t;return}let n=this.io.setTimeoutFn(()=>{delete this.ackse;for(let i=0;i<this.sendBuffer.length;i++)this.sendBufferi.id===e&&this.sendBuffer.splice(i,1);t.call(this,new Error("operation has timed out"))},o),s=(...i)=>{this.io.clearTimeoutFn(n),t.apply(this,i)};s.withError=!0,this.ackse=s}emitWithAck(e,...t){return new Promise((r,o)=>{let n=(s,i)=>s?o(s):r(i);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;typeof ee.length-1=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((o,...n)=>(this._queue0,o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(o)):(this._queue.shift(),t&&t(null,...n)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;let t=this._queue0;t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:ne.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){let t=this.ackse;delete this.ackse,t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case ne.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ne.EVENT:case ne.BINARY_EVENT:this.onevent(e);break;case ne.ACK:case ne.BINARY_ACK:this.onack(e);break;case ne.DISCONNECT:this.ondisconnect();break;case ne.CONNECT_ERROR:this.destroy();let t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t);break}}onevent(e){let t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof ee.length-1=="string"&&(this._lastOffset=ee.length-1)}ack(e){let t=this,r=!1;return function(...o){r||(r=!0,t.packet({type:ne.ACK,id:e,data:o}))}}onack(e){let t=this.ackse.id;typeof t=="function"&&(delete this.ackse.id,t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ne.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===tr)return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===tr)return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}};function Dn(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Dn.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+r:e-r}return Math.min(e,this.max)|0};Dn.prototype.reset=function(){this.attempts=0};Dn.prototype.setMin=function(e){this.ms=e};Dn.prototype.setMax=function(e){this.max=e};Dn.prototype.setJitter=function(e){this.jitter=e};var vp=class extends _e{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Bs(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Dn({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let o=t.parser||Rp;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new xp(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let o=Rr(t,"open",function(){r.onopen(),e&&e()}),n=i=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",i),e?e(i):this.maybeReconnectOnOpen()},s=Rr(t,"error",n);if(this._timeout!==!1){let i=this._timeout,a=this.setTimeoutFn(()=>{o(),n(new Error("timeout")),t.close()},i);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}return this.subs.push(o),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Rr(e,"ping",this.onping.bind(this)),Rr(e,"data",this.ondata.bind(this)),Rr(e,"error",this.onerror.bind(this)),Rr(e,"close",this.onclose.bind(this)),Rr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){js(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nspse;return r?this._autoConnect&&!r.active&&r.connect():(r=new ch(this,e,t),this.nspse=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nspsr.active)return;this._close()}_packet(e){let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(tr,e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(o=>{o?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",o)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}},Hs={};function Fn(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};let r=f_(e,t.path||"/socket.io"),o=r.source,n=r.id,s=r.path,i=Hsn&&s in Hsn.nsps,a=t.forceNew||t"force new connection"||t.multiplex===!1||i,c;return a?c=new vp(o,t):(Hsn||(Hsn=new vp(o,t)),c=Hsn),r.query&&!t.query&&(t.query=r.queryKey),c.socket(r.path,t)}Object.assign(Fn,{Manager:vp,Socket:ch,io:Fn,connect:Fn});var lh=" must not return ",h_="transformer",g_="recoverer",y_="defaultValue",Un=h_+lh,Yr="called with ",$n=y_+" must not be ",jn=g_+lh;var x_="Ok",ph="Err",uh=Yr+ph,mh=Yr+x_,fh="Carrying E in "+ph+" instead of throwing it directly. See .cause",kp="an instance of Error of the current realm.",CU="The thrown value is not "+kp,IU="The contained E should be "+kp,dh="This .cause is not "+kp;function K(e){return e.ok}function L(e){return{ok:!0,val:e,err:null}}function O(e){return!e.ok}function M(e){return{ok:!1,val:null,err:e}}function S(e){return Tp(e,uh)}function Z(e){return _p(e,mh)}function Tp(e,t){if(O(e))throw new TypeError(t);return e.val}function _p(e,t){if(K(e))throw new TypeError(t);return e.err}function ue(e){return e.val}function ye(e){return e.err}function Ws(e,t){if(O(e))return e;let r=ue(e);return t(r)}async function qs(e,t){if(O(e))return e;let r=ue(e);return await t(r)}function b_(e){return e}function Pp(e){return Ws(e,b_)}function Op(e){let t=e.status;switch(t){case"fulfilled":{let r=e.value;return L(r)}case"rejected":{let r=e.reason;return M(r)}default:{let r=\`PromiseSettledResult.status=${String(t)}\` is not supported;throw new TypeError(r)}}}function Sp(e,t){if(K(e)){let r=ue(e);t(r)}return e}function Lp(e,t){if(O(e)){let r=ye(e);t(r)}return e}function Np(e,t,r){if(K(e)){let o=ue(e);t(o)}else{let o=ye(e);r(o)}return e}function ga(e,t){if(K(e))return!1;let r=ye(e);return t(r)}function Mp(e,t){return ga(e,t)}function ya(e,t){if(O(e))return!1;let r=ue(e);return t(r)}function Cp(e,t){return ya(e,t)}function Xr(e,t){if(O(e))return e;let r=ue(e),o=t(r);return L(o)}async function ae(e,t){if(O(e))return e;let r=ue(e),o=await t(r);return L(o)}function Ip(e,t){if(K(e))return e;let r=ye(e),o=t(r);return M(o)}async function Ae(e,t){if(K(e))return e;let r=ye(e),o=await t(r);return M(o)}function Ap(e,t,r){if(K(e)){let o=ue(e);return r(o)}return t}async function Fp(e,t,r){if(O(e))return t;let o=ue(e);return await r(o)}function Gs(e,t,r){if(K(e)){let n=ue(e);return r(n)}let o=ye(e);return t(o)}async function Dp(e,t,r){if(K(e)){let n=ue(e);return await r(n)}let o=ye(e);return await t(o)}function Up(e,t){if(K(e))return e;let r=ye(e);return t(r)}async function xa(e,t){if(K(e))return e;let r=ye(e);return await t(r)}function ba(e,t){return K(e)?t:ye(e)}function qo(e,t){return K(e)?ue(e):t}function $p(e){return qo(e,null)}function jp(e){return ba(e,null)}function Bp(e){return qo(e,void 0)}function Hp(e){return ba(e,void 0)}var Ea="null",cr=Un+Ea,E_=Yr+Ea,Bn=$n+Ea,Eo=jn+Ea;function je(e){return e!==null}function rt(e){return e===null}function ot(e,t){if(je(e))return e;throw new TypeError(t)}var wa="undefined",lr=Un+wa,w_=Yr+wa,Hn=$n+wa,wo=jn+wa;function nt(e){return e!==void 0}function st(e){return e===void 0}function it(e,t){if(nt(e))return e;throw new TypeError(t)}function Wp(e){if(O(e))return e;let t=ue(e);return rt(t)?null:L(t)}function qp(e){if(O(e))return e;let t=ue(e);if(!st(t))return L(t)}function hh(e){return e instanceof Error}var R_="UnknownCausalError",v_=class extends Error{constructor(e){super(dh,{cause:e}),this.name=R_}};function Ra(e){return hh(e)?e:new v_(e)}function va(e){try{let t=e();return L(t)}catch(t){return M(t)}}function Gp(e){let t=va(e);if(K(t))return t;let r=ye(t),o=Ra(r);return M(o)}async function ka(e){let t;try{t=await e()}catch(r){return M(r)}return L(t)}async function zp(e){let t=await ka(e);if(K(t))return t;let r=ye(t),o=Ra(r);return M(o)}function Vp(e,t){if(K(e))return ue(e);let r=ye(e);return t(r)}async function Kp(e,t){if(K(e))return ue(e);let r=ye(e);return await t(r)}var k_="CausalCarrierError",T_=class extends Error{constructor(e){super(fh,{cause:e}),this.name=k_}};function Yp(e){if(K(e))return ue(e);let t=ye(e);throw new T_(t)}var Be=e=>e.ok?L(e):M({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var gh=async(e,t)=>{let r=new Request(e,t);try{return L(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return M({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return M({name:"NetworkError",message:o.message,request:r});throw o}};var we=e=>{let{fetch:t=gh,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var yh=e=>{let{sid:t,hostName:r}=we(e??{});return new Request(https://${r}/api/users/me,t?{headers:{Cookie:Re(t)}}:void 0)},xh=e=>ae(Be(e),async t=>await t.json()),Ta=(()=>{let e=async t=>{let{fetch:r,...o}=we(t??{}),n=await r(yh(o));return O(n)?n:xh(S(n))};return e.toRequest=yh,e.fromResponse=xh,e})();var Re=e=>connect.sid=${e},Wn=async e=>{let t=e?.csrf??globalThis._csrf;return t?L(t):Xr(await Ta(e),r=>r.csrfToken)};var It=(e,t)=>{if(e?.connected)return Promise.resolve(L(e));e??=Fn("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"],...t?{rejectUnauthorized:!1,extraHeaders:{Cookie:Re(t),Host:"scrapbox.io",Referer:"https://scrapbox.io/"}}:{}});let r=new Promise(o=>{let n=s=>o(M(s));e.once("connect",()=>{e.off("disconnect",n),o(L(e))}),e.once("disconnect",n)});return e.connect(),r},At=e=>{if(e.disconnected)return Promise.resolve(L(void 0));let t=new Promise(r=>{let o=n=>{if(n!=="io client disconnect"){r(M(n));return}r(L(void 0)),e.off("disconnect",o)};e.on("disconnect",o)});return e.disconnect(),t};var bh=e=>__.includes(e.name),__="SocketIOError","DuplicateTitleError","NotFastForwardError";var Eh=(e,t,r,o)=>{if(t==="cursor")return e.emit(t,r),Promise.resolve(L(void 0));let{resolve:n,promise:s,reject:i}=Promise.withResolvers(),a=()=>{e.off("disconnect",c),clearTimeout(u)},c=f=>{if(f==="io client disconnect"){a(),i(new Error("io client disconnect"));return}if(f==="io server disconnect"){a(),n(M({name:"SocketIOError"}));return}};e.on("disconnect",c);let l=o?.timeout??9e4,u=setTimeout(()=>{a(),n(M({name:"TimeoutError",message:exceeded ${l} (ms)}))},l),p=t==="commit"?{method:"commit",data:r}:{method:"room:join",data:r};return e.emit("socket.io-request",p,f=>{if(a(),"error"in f){n(M(bh(f.error)?f.error:{name:"UnexpectedRequestError",...f}));return}n(L(f.data))}),s};function _a(e,t={}){if(e===null)return"null";if(Array.isArray(e))return P_(e,t);switch(typeof e){case"string":return JSON.stringify(e);case"bigint":return${e}n;case"object":return e.constructor?.name!=="Object"?e.constructor?.name:O_(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function P_(e,t){let{threshold:r=20}=t,o=e.map(i=>_a(i,t)),n=o.join(", ");if(n.length<=r)return[${n}];let s=o.join(`,
);return[
${wh(2,s)}
]}function O_(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(i=>${i.toString()}: ${_a(ei,t)}),n=o.join(", ");if(n.length<=r)return{${n}};let s=o.join(,
);return{
${wh(2,s)}
}}function wh(e,t){let r=" ".repeat(e);return t.split(
).map(o=>${r}${o}).join(
)}function mt(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=${t}(${r.map(n=>_a(n)).join(", ")}),o)}})}function vr(e){return Array.isArray(e)}function zs(e){return mt(t=>vr(t)&&t.every(r=>e(r)),"isArrayOf",e)}function Go(e){let t=new Set(e);return mt(r=>t.has(r),"isLiteralOneOf",e)}function Ro(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function ve(e){return typeof e=="string"}var ft=async(e,t)=>{let r=e.response.clone(),o=Go(t);try{let n=await r.json();if(!Ro(n))return;if(r.status===422){if(!ve(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!ve(n.message)?void 0:n.name==="NotLoggedInError"?!Ro(n.detals)||!ve(n.detals.project)||!zs(S_)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},S_=Go(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var ce=e=>e.replaceAll(" ","_").toLowerCase();var se=e=>[...e].map((t,r)=>t===" "?"_":!L_.includes(t)||r===e.length-1&&N_.includes(t)?encodeURIComponent(t):t).join(""),L_='@$&+=:;",',N_=':;",';var Pa="null or undefined",pr=Un+Pa,M_=Yr+Pa,qn=$n+Pa,vo=jn+Pa;function Ke(e){return e!=null}function Ye(e){return e==null}function Xe(e,t){if(Ke(e))return e;throw new TypeError(t)}function Xp(e,t){return Ye(e)?e:t(e)}async function Jp(e,t){return Ye(e)?e:await t(e)}function Qp(e,t){return Ke(e)&&t(e),e}function Zp(e,t){if(Ye(e))return e;let r=t(e);return Xe(r,pr)}async function eu(e,t){if(Ye(e))return e;let r=await t(e);return Xe(r,pr)}function tu(e,t,r){let o,n;return e!=null?(o=r(e),n=pr):(o=t,n=qn),Xe(o,n)}async function ru(e,t,r){if(Ye(e))return Xe(t,qn);let o=await r(e);return Xe(o,pr)}function ou(e,t,r){let o,n;return e!=null?(o=r(e),n=pr):(o=t(),n=vo),Xe(o,n)}async function nu(e,t,r){let o,n;return Ke(e)?(o=await r(e),n=pr):(o=await t(),n=vo),Xe(o,n)}function su(e,t){return Ke(e)?L(e):M(t)}function Vs(e,t){if(Ke(e))return L(e);let r=t();return M(r)}async function iu(e,t){if(Ke(e))return L(e);let r=await t();return M(r)}function au(e,t){return e??t()}async function cu(e,t){return Ke(e)?e:await t()}function lu(e){return Ye(e)?null:e}function Oa(e){return Ye(e)?M(void 0):L(e)}function pu(e){return Ye(e)?L(void 0):M(e)}function uu(e){if(!Ye(e))return e}function Ks(e,t){return Ke(e)?e:Xe(t,qn)}function mu(e,t){if(Ke(e))return e;let r=t();return Xe(r,vo)}async function fu(e,t){if(Ke(e))return e;let r=await t();return Xe(r,vo)}var Rh=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=we(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(https://${n}/api/pages/${e}/${se(t)}?${a},o?{headers:{Cookie:Re(o)}}:void 0)},vh=async e=>Ae(await ae(Be(e),t=>t.json()),async t=>t.response.status===414?{name:"TooLongURIError",message:"project ids may be too much."}:Ks(await ft(t,["NotFoundError","NotLoggedInError","NotMemberError"]),t)),ur=(()=>{let e=async(t,r,o)=>qs(await we(o??{}).fetch(Rh(t,r,o)),n=>vh(n));return e.toRequest=Rh,e.fromResponse=vh,e})();var kh=(e,t)=>{let{sid:r,hostName:o}=we(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:Re(r)}}:void 0)},Th=async e=>ae(await Ae(Be(e),async t=>await ft(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),zo=(()=>{let e=async(t,r)=>{let{fetch:o}=we(r??{}),n=kh(t,r),s=await o(n);return O(s)?s:Th(S(s))};return e.toRequest=kh,e.fromResponse=Th,e})(),_h=(e,t)=>{let{sid:r,hostName:o}=we(t??{}),n=new URLSearchParams(e.map(s=>["ids",s]));return new Request(https://${o}/api/projects?${n},r?{headers:{Cookie:Re(r)}}:void 0)},Ph=async e=>ae(await Ae(Be(e),async t=>await ft(t,["NotLoggedInError"])??t),t=>t.json()),Sa=(()=>{let e=async(t,r)=>{let{fetch:o}=we(r??{}),n=await o(_h(t,r));return O(n)?n:Ph(S(n))};return e.toRequest=_h,e.fromResponse=Ph,e})();var hu=async(e,t,r)=>{let[o,n,s]=await Promise.all([ur(e,t,r),I_(r),A_(e,r)]);return O(o)?o:O(n)?n:O(s)?s:L({...S(o),projectId:S(s),userId:S(n)})},du,I_=async e=>{if(du)return L(du);let t=await Ta(e);if(O(t))return t;let r=S(t);return"id"in r?(du=r.id,L(r.id)):M({name:"NotLoggedInError",message:"This script cannot be used without login"})},Oh=new Map,A_=async(e,t)=>{let r=Oh.get(e);return r?L(r):Xr(await zo(e,t),({id:o})=>(Oh.set(e,o),o))};function Se(e,t={}){let{signal:r,persistent:o=!0}=t;return r?.aborted?Promise.reject(r.reason):new Promise((n,s)=>{let i=()=>{clearTimeout(+c),s(r?.reason)},c=F_(()=>{r?.removeEventListener("abort",i),n()},e);if(r?.addEventListener("abort",i,{once:!0}),o===!1)try{Deno.unrefTimer(+c)}catch(l){if(!(l instanceof ReferenceError))throw clearTimeout(+c),l;console.error("persistent option is only available in Deno")}})}var gu=2**31-1;function F_(e,t){if(t=Math.trunc(Math.max(t,0)||0),t<=gu){let s=Number(setTimeout(e,t));return{valueOf:()=>s}}let r=Date.now(),o,n=()=>{let s=t-(Date.now()-r);o=s>gu?Number(setTimeout(n,gu)):Number(setTimeout(e,s))};return n(),{valueOf:()=>o}}var Vo=async(e,t,r,o)=>{let n=await It(o?.socket,o?.sid);if(O(n))return M({name:"UnexpectedRequestError",error:Z(n)});let s=S(n),i=await hu(e,t,o);if(O(i))return i;let a=S(i);try{let c=0,l=[],u;for(;o?.maxAttempts===void 0||c<o.maxAttempts;){let p=r(a,c,l,u);if(l=p instanceof Promise?await p:p,c++,l.length===0)return L(a.commitId);let f={kind:"page",projectId:a.projectId,pageId:a.id,parentId:a.commitId,userId:a.userId,changes:l,cursor:null,freeze:!0};for(;;){let m=await Eh(s,"commit",f);if(K(m))return a.commitId=S(m).commitId,L(a.commitId);let h=Z(m),g=h.name;if(g==="SocketIOServerDisconnectError"||g==="UnexpectedRequestError")return M(h);if(g==="TimeoutError"||g==="SocketIOError"){await Se(3e3);continue}if(g==="NotFastForwardError"){await Se(1e3);let y=await hu(e,t,o);if(O(y))return y;a=S(y)}u=g;break}}return M({name:"RetryError",attempts:c,message:Retrying exceeded the maxAttempts (${c}).})}finally{o?.socket||await At(s)}};var yu=(e,t)=>{let r=e.length>t.length,o=r?t:e,n=r?e:t,s=o.length+1,i=o.length+n.length+3,a=new Array(i);a.fill(-1);let c=[];function l(g,y,x){let w=Math.max(y,x),R=w-g;for(;R<o.length&&w<n.length&&o[R]===n[w];)++R,++w;return a[g+s]=c.length,c.push([{x:R,y:w},a[g+(y>x?-1:1)+s]]),w}let u=new Array(i);u.fill(-1);let p=-1,f=n.length-o.length;do{++p;for(let g=-p;g<=f-1;++g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);for(let g=f+p;g>=f+1;--g)u[g+s]=l(g,u[g-1+s]+1,u[g+1+s]);u[f+s]=l(f,u[f-1+s]+1,u[f+1+s])}while(u[f+s]!==n.length);let m=[],h=a[f+s];for(;h!==-1;)m.push(c[h][0]),h=c[h][1];return{from:e,to:t,editDistance:f+p*2,buildSES:function*(){let g=0,y=0;for(let{x,y:w}of D_(m))for(;g<x||y<w;)w-x>y-g?(yield{value:n[y],type:r?"deleted":"added"},++y):w-x<y-g?(yield{value:o[g],type:r?"added":"deleted"},++g):(yield{value:o[g],type:"common"},++g,++y)}}};function*xu(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield Sh(t[n],r[n]);for(let n=r.length;n<t.length;n++)yield t[n]}else{for(let n=0;n<t.length;n++)yield Sh(t[n],r[n]);for(let n=t.length;n<r.length;n++)yield r[n]}t=[],r=[]}for(let n of e)switch(n.type){case"added":t.push(n);break;case"deleted":r.push(n);break;case"common":yield*o(),yield n;break}yield*o()}var Sh=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*D_(e){for(let t=e.length-1;t>=0;t--)yield e[t]}var Lh=e=>e.padStart(8,"0"),bu=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${Lh(t).slice(-8)}${e.slice(-6)}0000${Lh(r)}};function*Eu(e,t,{userId:r}){let{buildSES:o}=yu(e.map(({text:i})=>i),t),n=0,s=e[0].id;for(let i of xu(o())){switch(i.type){case"added":yield{_insert:s,lines:{id:bu(r),text:i.value}};continue;case"deleted":yield{_delete:s,lines:-1};break;case"replaced":yield{_update:s,lines:{text:i.value}};break}n++,s=e[n]?.id??"_end"}}var Nh=e=>{let{rows:[{indent:t,text:r},...o]}=e,n=r.replace(/^\s*code:/,"");return{indent:t,type:"codeBlock",fileName:n,content:o.map(s=>s.text.substring(t+1)).join(
)}};var pe=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested||!r&&s.quoted)return i();for(let a of o){let c=a.exec(n);if(c===null)continue;let l=n.substring(0,c.index),u=n.substring(c.index+c[0].length),p=e(c,s);return[...Ht(l,s),...p,...Ht(u,s)]}return i()};var me=e=>[{type:"plain",raw:e,text:e}],Mh=me;var U_=/\[\s+\]/,$_=([e],t)=>t.context==="table"?me(e):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Ch=pe($_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[U_]});var j_=/.*?/,B_=([e],t)=>t.context==="table"?me(e):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Ih=pe(B_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[j_]});var H_=/^[$%] .+$/,W_=([e],t)=>{if(t.context==="table")return me(e);let r=e.charAt(0),o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},Ah=pe(W_,{parseOnNested:!1,parseOnQuoted:!1,patterns:[H_]});var q_=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,G_=([e],t)=>{if(t.context==="table")return me(e);let r=e.indexOf(" "),o=e.substring(1,r),n=e.substring(r+1,e.length-1),s=new Set(o);if(s.has("*")){let i=o.split("*").length-1;s.delete("*"),s.add(*-${Math.min(i,10)})}return[{type:"decoration",raw:e,rawDecos:o,decos:Array.from(s),nodes:Ht(n,{...t,nested:!0})}]},Fh=pe(G_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[q_]});var z_=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,V_=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,K_=/\[https?:\/\/[^\s\]]+\]/,Y_=/https?:\/\/[^\s]+/,X_=([e],t)=>{if(t.context==="table")return me(e);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,o=/^https?:\/\/[^\s\]]/.test(r),n=(o?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(n===null)return[];let s=o?r.substring(n[0].length):r.substring(0,n.index-1);return[{type:"link",raw:e,pathType:"absolute",href:n[0],content:s.trim()}]},Dh=pe(X_,{parseOnNested:!0,parseOnQuoted:!0,patterns:[z_,V_,K_,Y_]});var J_=/\[\$ .+? \]/,Q_=/\[\$ [^\]]+\]/,Z_=([e],t)=>t.context==="table"?me(e):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],Uh=pe(Z_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[J_,Q_]});var eP=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,tP=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,rP=e=>{let[t="",r="",o=""]=e.split(","),n=Number.parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=Number.parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),i=/^Z\d+$/.test(o)?Number.parseInt(o.replace(/^Z/,""),10):14;return{latitude:n,longitude:s,zoom:i}},oP=(e,t)=>{let r=e[0];if(t.context==="table")return me(r);let o=r.startsWith("[N")||r.startsWith("[S"),[,n="",s=""]=o?e:[e[0],e[2],e[1]],{latitude:i,longitude:a,zoom:c}=rP(n),l=s!==""?https://www.google.com/maps/place/${encodeURIComponent(s)}/@${i},${a},${c}z:https://www.google.com/maps/@${i},${a},${c}z;return[{type:"googleMap",raw:r,latitude:i,longitude:a,zoom:c,place:s,url:l}]},$h=pe(oP,{parseOnNested:!1,parseOnQuoted:!0,patterns:[eP,tP]});var nP=/(?:^|\s)#\S+/,sP=([e],t)=>{if(t.context==="table")return me(e);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...me(r),{type:"hashTag",raw:o,href:o.substring(1)}]},jh=pe(sP,{parseOnNested:!0,parseOnQuoted:!0,patterns:[nP]});var iP=/^\? .+$/,aP=([e],t)=>t.context==="table"?me(e):[{type:"helpfeel",raw:e,text:e.substring(2)}],Bh=pe(aP,{parseOnNested:!1,parseOnQuoted:!1,patterns:[iP]});var cP=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,lP=([e])=>{let t=e.substring(1,e.length-1),r=t.lastIndexOf(".icon"),o=t.substring(0,r),n=o.startsWith("/")?"root":"relative",s=t.substring(r+5,t.length),i=s.startsWith("*")?Number.parseInt(s.substring(1),10):1;return new Array(i).fill({}).map(()=>({path:o,pathType:n,type:"icon",raw:e}))},Hh=pe(lP,{parseOnNested:!0,parseOnQuoted:!0,patterns:[cP]});var pP=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,uP=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,mP=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,fP=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,dP=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||hP(e),hP=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),gP=([e],t)=>{if(t.context==="table")return me(e);let r=e.search(/\s/),o=r!==-1?e.substring(1,r):e.substring(1,e.length-1),n=r!==-1?e.substring(r,e.length-1).replace(/^\s+/,""):"",[s,i]=dP(n)?[n,o]:[o,n];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?${s}/thumb/1000:s,link:i}]},Wh=pe(gP,{parseOnNested:!0,parseOnQuoted:!0,patterns:[pP,uP,mP,fP]});var yP=/\[\/?[^[\]]+\]/,xP=([e])=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},qh=pe(xP,{parseOnNested:!0,parseOnQuoted:!0,patterns:[yP]});var bP=/^[0-9]+\. .*$/,EP=([e],t)=>{if(t.context==="table")return me(e);let r=e.indexOf(" "),o=e.substring(0,r-1),n=Number.parseInt(o,10),s=e.substring(r+1,e.length);return[{type:"numberList",raw:e,rawNumber:o,number:n,nodes:Ht(s,{...t,nested:!1})}]},Gh=pe(EP,{parseOnNested:!1,parseOnQuoted:!1,patterns:[bP]});var wP=/^>.*$/,RP=([e],t)=>t.context==="table"?me(e):[{type:"quote",raw:e,nodes:Ht(e.substring(1),{...t,quoted:!0})}],zh=pe(RP,{parseOnNested:!1,parseOnQuoted:!1,patterns:[wP]});var vP=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,kP=([e],t)=>{if(t.context==="table")return me(e);let r=e.substring(2,e.length-2),o=r.lastIndexOf(".icon"),n=r.substring(0,o),s=n.startsWith("/")?"root":"relative",i=r.substring(o+5,r.length),a=i.startsWith("*")?Number.parseInt(i.substring(1),10):1;return new Array(a).fill({}).map(()=>({path:n,pathType:s,type:"strongIcon",raw:e}))},Vh=pe(kP,{parseOnNested:!1,parseOnQuoted:!0,patterns:[vP]});var TP=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,_P=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,PP=([e],t)=>{if(t.context==="table")return me(e);let r=e.substring(2,e.length-2),o=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:o?${r}/thumb/1000:r}]},Kh=pe(PP,{parseOnNested:!1,parseOnQuoted:!0,patterns:[TP,_P]});var OP=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,SP=([e],t)=>t.context==="table"?me(e):[{type:"strong",raw:e,nodes:Ht(e.substring(2,e.length-2),{...t,nested:!0})}],Yh=pe(SP,{parseOnNested:!1,parseOnQuoted:!0,patterns:[OP]});var LP=(e,t,r)=>e!==""?r():[],NP=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>Mh(t,r))(),Ht=NP(LP,zh,Bh,Gh,Ih,Ah,Ch,Fh,Uh,Kh,Vh,Yh,Wh,Dh,Hh,$h,qh,jh);var Xh=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:Ht(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var Jh=e=>{let{rows:[{indent:t,text:r},...o]}=e,n=r.replace(/^\s*table:/,"");return{indent:t,type:"table",fileName:n,cells:o.map(s=>s.text.substring(t+1)).map(s=>s.split(" ").map(i=>Ht(i,{nested:!1,quoted:!1,context:"table"})))}};var Qh=e=>({type:"title",text:e.rows[0].text});var Zh=e=>{switch(e.type){case"title":return Qh(e);case"codeBlock":return Nh(e);case"table":return Jh(e);case"line":return Xh(e)}};var MP=({type:e,rows:[t]},r)=>(e==="codeBlock"||e==="table")&&r.indent>t.indent,eg=(e,t)=>{let r=e[e.length-1];return r!==void 0&&MP(r,t)?r.rows.push(t):e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e},tg=(e,{hasTitle:t=!0})=>{if(t){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(eg,[])]}return e.reduce(eg,[])};var rg=e=>e.split(
).map(t=>({indent:/^\s+/.exec(t)?.[0].length??0,text:t}));var at=(e,{hasTitle:t=!0}={})=>{let r=rg(e);return tg(r,{hasTitle:t}).map(Zh)},og=e=>/^\s*\S.*$/m.exec(e)?.[0].trim()??"Untitled";var CP=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,IP=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,AP=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,FP=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,La=e=>{if(CP.test(e)){let t=new URL(e).searchParams,r=t.get("v");if(r)return{pathType:"com",videoId:r,params:t}}{let t=e.match(IP);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(AP);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match(FP);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};var ig=e=>{let t=at(e,{hasTitle:!0}),r="",o=new Map,n=[],s=new Set,i=[],a=new Set,c=[],l=null,u=[],p=new Set,f=new Set,m=new RegExp(${globalThis.location?.origin??"https://scrapbox.io"}/files/([a-z0-9]{24})(?:|\\.[a-zA-Z0-9]+)(?:|\\?[^\\s]*)$),h=x=>{switch(x.type){case"hashTag":if(o.has(ce(x.href)))return;o.set(ce(x.href),!1),n.push(x.href);return;case"link":switch(x.pathType){case"relative":{let w=sg(x.href);if(o.get(ce(w)))return;o.set(ce(w),!0),n.push(w);return}case"root":{let w=sg(x.href);if(/^\/[\w\d-]+\/?$/.test(w)||s.has(ce(w)))return;s.add(ce(w)),i.push(w);return}case"absolute":{if(x.content)return;let w=La(x.href);if(w&&w.pathType!=="list"){l??=https://i.ytimg.com/vi/${w.videoId}/mqdefault.jpg;return}let R=x.href.match(m)?.[1];R&&p.add(R);return}default:return}case"icon":case"strongIcon":{if(x.pathType==="root"||a.has(ce(x.path)))return;a.add(ce(x.path)),c.push(x.path);return}case"image":case"strongImage":{l??=x.src.endsWith("/thumb/1000")?x.src.replace(/\/thumb\/1000$/,"/raw"):x.src;{let w=x.src.match(m)?.[1];w&&p.add(w)}if(x.type==="image"){let w=x.link.match(m)?.[1];w&&p.add(w)}return}case"helpfeel":f.add(x.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let w of x.nodes)h(w);return}default:return}},g=[];for(let x of t)switch(x.type){case"title":{r=x.text;continue}case"line":u.length<5&&x.nodes.length>0&&u.push(x.nodes[0].type==="helpfeel"||x.nodes[0].type==="commandLine"?ng(x.nodes[0].raw):x.nodes.map(w=>w.raw).join("").trim().slice(0,200));for(let w of x.nodes)h(w);continue;case"codeBlock":u.length<5&&u.push(ng(x.content));continue;case"table":{for(let w of x.cells)for(let R of w)for(let b of R)h(b);if(!["infobox","cosense"].includes(x.fileName))continue;g.push(...x.cells.map(w=>w.map(R=>R.map(b=>b.raw).join("")).join(" ").trim()));continue}}let y=e.split(
);return[r,n,i,c,l,u,[...p],[...f],g,y.length,y.reduce((x,w)=>x+[...w].length,0)]},ng=e=>\${e.trim().replaceAll("","\\").slice(0,198)}\`,sg=e=>e.replace(/#a-f\d{24,32}$/,"");var ko=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));var ag=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?t.trimStart().slice(2):[]);function*cg(e,t,r){let o=t.flatMap(g=>(ve(g)?g:g.text).split(`
));for(let g of Eu(e.lines,o,{userId:r}))yield g;let[n,s,i,a,c,l,u,p,f,m,h]=ig(o.join(
));(e.title!==n||!e.persistent)&&(yield{title:n}),ko(e.links,s)||(yield{links:s}),ko(e.projectLinks,i)||(yield{projectLinks:i}),ko(e.icons,a)||(yield{icons:a}),e.image!==c&&(yield{image:c}),ko(e.descriptions,l)||(yield{descriptions:l}),ko(e.files,u)||(yield{files:u}),ko(ag(e.lines),p)||(yield{helpfeels:p}),ko(e.infoboxDefinition,f)||(yield{infoboxDefinition:f}),yield{linesCount:m},yield{charsCount:h}}var lg=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,o=t?.[2]?parseInt(t[2])+1:2;return${r}_${o}};var pg=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);var Le=(e,t,r,o)=>Vo(e,t,async(n,s,i,a)=>{if(a==="DuplicateTitleError"){let m=lg(t);return i.map(h=>("title"in h&&(h.title=m),h))}let c=r(n.lines,{...n,attempts:s}),l=c instanceof Promise?await c:c;if(l===void 0)return[];let[u,p]=Array.isArray(l)?[l,void 0]:[l.lines,l.pin];if(u.length===0)return[{deleted:!0}];let f=n.lines===u?[]:[...cg(n,u,n.userId)];return p!==void 0&&(p&&n.pin===0||!p&&n.pin>0)&&f.push({pin:p?pg():0}),f},o);var ug=(e,t,r)=>Vo(e,t,o=>o.persistent?[{deleted:!0}]:[],r);var Na=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i}=we(o??{}),a=await Wn(o);if(O(a))return a;let c=new Request(https://${s}/api/pages/${e}/replace/links,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":S(a),...n?{Cookie:Re(n)}:{}},body:JSON.stringify({from:t,to:r})}),l=await i(c);return O(l)?l:ae(await Ae(Be(S(l)),async u=>await ft(u,["NotFoundError","NotLoggedInError","NotMemberError"])??u),async u=>{let{message:p}=await u.json();return parseInt(p.match(/\d+/)?.[0]??"0")})};var mg=(e,t)=>{let{sid:r,hostName:o,followingId:n}=we(t??{});return new Request(https://${o}/api/pages/${e}/search/titles${n??followingId=${n}:""},r?{headers:{Cookie:Re(r)}}:void 0)},fg=async e=>ae(await Ae(Be(e),async t=>t.response.status===422?{name:"InvalidFollowingIdError",message:await t.response.text()}:await ft(t,["NotFoundError","NotLoggedInError"])??t),t=>t.json().then(r=>({pages:r,followingId:t.headers.get("X-following-id")??""}))),$P=(()=>{let e=async(t,r)=>{let o=await we(r??{}).fetch(mg(t,r));return O(o)?o:fg(S(o))};return e.toRequest=mg,e.fromResponse=fg,e})();async function*dg(e,t){let r;do{let o=await $P(e,{followingId:r,...t});if(O(o)){yield o;return}let n=S(o);yield L(n.pages),r=n.followingId}while(r)}var hg=async(e,t,r)=>{let{sid:o,hostName:n,fetch:s}=we(r??{}),i=new Request(https://${n}/api/pages/${t}/search/query?q=${encodeURIComponent(e)},o?{headers:{Cookie:Re(o)}}:void 0),a=await s(i);return O(a)?a:ae(await Ae(Be(S(a)),async c=>await ft(c,["NotFoundError","NotLoggedInError","NotMemberError","NoQueryError"])??c),c=>c.json())};var gg=(e,t,r,o)=>{let{sid:n,hostName:s}=we(o??{});return new Request(https://${s}/api/code/${e}/${se(t)}/${se(r)},n?{headers:{Cookie:Re(n)}}:void 0)},yg=async e=>ae(await Ae(Be(e),async t=>t.response.status===404&&t.response.headers.get("Content-Type")?.includes?.("text/plain")?{name:"NotFoundError",message:"Code block is not found"}:await ft(t,["NotLoggedInError","NotMemberError"])??t),t=>t.text()),Ma=(()=>{let e=async(t,r,o,n)=>{let s=gg(t,r,o,n),i=await we(n??{}).fetch(s);return O(i)?i:yg(S(i))};return e.toRequest=gg,e.fromResponse=yg,e})();var Ru=e=>{let t=typeof e=="string"?new TextEncoder().encode(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),r=[1732584193,4023233417,2562383102,271733878],o=new Uint8Array(wu),n=0,s=0,i=0;[r,o,n,s,i]=bg(r,o,n,s,i,t);let a=wu-n;a<9&&(a+=wu);let c=new Uint8Array(a);c[0]=128,[s,i]=[s<<3,i<<3|s>>>29],c[c.length-8]=s&255,c[c.length-7]=s>>>8&255,c[c.length-6]=s>>>16&255,c[c.length-5]=s>>>24&255,c[c.length-4]=i&255,c[c.length-3]=i>>>8&255,c[c.length-2]=i>>>16&255,c[c.length-1]=i>>>24&255,[r,o,n,s,i]=bg(r,o,n,s,i,new Uint8Array(c.buffer));let l=new ArrayBuffer(16),u=new DataView(l);return u.setUint32(0,r[0],!0),u.setUint32(4,r[1],!0),u.setUint32(8,r[2],!0),u.setUint32(12,r[3],!0),l},wu=64,z=(e,t)=>e<<t|e>>>32-t,Ft=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,xg=(e,t)=>{let[r,o,n,s]=e,i=Ft(t,0),a=Ft(t,4),c=Ft(t,8),l=Ft(t,12),u=Ft(t,16),p=Ft(t,20),f=Ft(t,24),m=Ft(t,28),h=Ft(t,32),g=Ft(t,36),y=Ft(t,40),x=Ft(t,44),w=Ft(t,48),R=Ft(t,52),b=Ft(t,56),E=Ft(t,60);return r=o+z(((n^s)&o^s)+r+i+3614090360,7),s=r+z(((o^n)&r^n)+s+a+3905402710,12),n=s+z(((r^o)&s^o)+n+c+606105819,17),o=n+z(((s^r)&n^r)+o+l+3250441966,22),r=o+z(((n^s)&o^s)+r+u+4118548399,7),s=r+z(((o^n)&r^n)+s+p+1200080426,12),n=s+z(((r^o)&s^o)+n+f+2821735955,17),o=n+z(((s^r)&n^r)+o+m+4249261313,22),r=o+z(((n^s)&o^s)+r+h+1770035416,7),s=r+z(((o^n)&r^n)+s+g+2336552879,12),n=s+z(((r^o)&s^o)+n+y+4294925233,17),o=n+z(((s^r)&n^r)+o+x+2304563134,22),r=o+z(((n^s)&o^s)+r+w+1804603682,7),s=r+z(((o^n)&r^n)+s+R+4254626195,12),n=s+z(((r^o)&s^o)+n+b+2792965006,17),o=n+z(((s^r)&n^r)+o+E+1236535329,22),r=o+z(((o^n)&s^n)+r+a+4129170786,5),s=r+z(((r^o)&n^o)+s+f+3225465664,9),n=s+z(((s^r)&o^r)+n+x+643717713,14),o=n+z(((n^s)&r^s)+o+i+3921069994,20),r=o+z(((o^n)&s^n)+r+p+3593408605,5),s=r+z(((r^o)&n^o)+s+y+38016083,9),n=s+z(((s^r)&o^r)+n+E+3634488961,14),o=n+z(((n^s)&r^s)+o+u+3889429448,20),r=o+z(((o^n)&s^n)+r+g+568446438,5),s=r+z(((r^o)&n^o)+s+b+3275163606,9),n=s+z(((s^r)&o^r)+n+l+4107603335,14),o=n+z(((n^s)&r^s)+o+h+1163531501,20),r=o+z(((o^n)&s^n)+r+R+2850285829,5),s=r+z(((r^o)&n^o)+s+c+4243563512,9),n=s+z(((s^r)&o^r)+n+m+1735328473,14),o=n+z(((n^s)&r^s)+o+w+2368359562,20),r=o+z((o^n^s)+r+p+4294588738,4),s=r+z((r^o^n)+s+h+2272392833,11),n=s+z((s^r^o)+n+x+1839030562,16),o=n+z((n^s^r)+o+b+4259657740,23),r=o+z((o^n^s)+r+a+2763975236,4),s=r+z((r^o^n)+s+u+1272893353,11),n=s+z((s^r^o)+n+m+4139469664,16),o=n+z((n^s^r)+o+y+3200236656,23),r=o+z((o^n^s)+r+R+681279174,4),s=r+z((r^o^n)+s+i+3936430074,11),n=s+z((s^r^o)+n+l+3572445317,16),o=n+z((n^s^r)+o+f+76029189,23),r=o+z((o^n^s)+r+g+3654602809,4),s=r+z((r^o^n)+s+w+3873151461,11),n=s+z((s^r^o)+n+E+530742520,16),o=n+z((n^s^r)+o+c+3299628645,23),r=o+z((n^(o|~s))+r+i+4096336452,6),s=r+z((o^(r|~n))+s+m+1126891415,10),n=s+z((r^(s|~o))+n+b+2878612391,15),o=n+z((s^(n|~r))+o+p+4237533241,21),r=o+z((n^(o|~s))+r+w+1700485571,6),s=r+z((o^(r|~n))+s+l+2399980690,10),n=s+z((r^(s|~o))+n+y+4293915773,15),o=n+z((s^(n|~r))+o+a+2240044497,21),r=o+z((n^(o|~s))+r+h+1873313359,6),s=r+z((o^(r|~n))+s+E+4264355552,10),n=s+z((r^(s|~o))+n+f+2734768916,15),o=n+z((s^(n|~r))+o+R+1309151649,21),r=o+z((n^(o|~s))+r+u+4149444226,6),s=r+z((o^(r|~n))+s+x+3174756917,10),n=s+z((r^(s|~o))+n+c+718787259,15),o=n+z((s^(n|~r))+o+g+3951481745,21),[e[0]+r>>>0,e[1]+o>>>0,e[2]+n>>>0,e[3]+s>>>0]},bg=(e,t,r,o,n,s)=>{let i=64-r;if(s.length<i)t.set(s,r),r+=s.length;else{t.set(s.slice(0,i),r),e=xg(e,t);let a=i;for(;a+64<=s.length;)e=xg(e,s.slice(a,a+64)),a+=64;t.fill(0).set(s.slice(a),0),r=s.length-a}return[o,n]=jP(o,n,s.length),[e,t,r,o,n]},jP=(e,t,r)=>(e+=r,e>4294967295&&(t+=1),[e>>>0,t]);var BP=new TextEncoder().encode("0123456789abcdef"),Eg=new Uint8Array(128).fill(16);BP.forEach((e,t)=>Eg[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>Eg[e]=t+10);function wg(e){return e*2}function Rg(e,t,r,o){for(;t<e.length;++t){let n=e[t];e[r++]=o[n>>4],e[r++]=o[n&15]}return r}function vg(e,t){let r=e.length;if(e.byteOffset){let o=new Uint8Array(e.buffer);o.set(e),e=o.subarray(0,r)}return e=new Uint8Array(e.buffer.transfer(t)),e.set(e.subarray(0,r),t-r),[e,t-r]}var kg=new TextEncoder().encode("0123456789abcdef"),Tg=new Uint8Array(128).fill(16);kg.forEach((e,t)=>Tg[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>Tg[e]=t+10);function vu(e){typeof e=="string"?e=new TextEncoder().encode(e):e instanceof ArrayBuffer?e=new Uint8Array(e).slice():e=e.slice();let[t,r]=vg(e,wg(e.length));return Rg(t,r,0,kg),new TextDecoder().decode(t)}var _g=async e=>{let t=e.title??".watchlistrc",r="projectsLastAccessed.json",o=await Ma(e.project,t,r),n=O(o)?{}:JSON.parse(S(o)||"{}"),s=JSON.parse(localStorage.getItem("projectsLastAccessed")??"{}"),i=new Set([...Object.keys(n),...Object.keys(s)]),a=Object.fromEntries([...i].map(l=>[l,Math.max(n[l]??0,s[l]??0)]).sort((l,u)=>u[1]-l[1])),c=JSON.stringify(a);localStorage.setItem("projectsLastAccessed",c),await Le(e.project,t,()=>[t,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","",code:${r}, ${c},""])};var rr=!1,Ca=e=>{rr=typeof e=="boolean"?e:new Set(e)},Gn=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(%c${e},ku,...o)];case"log":case"info":case"debug":return[t,(...o)=>{rr!==!0&&(!rr||!rr.has(e))||r(%c${e},ku,...o)}];case"assert":return[t,(o,...n)=>{rr!==!0&&(!rr||!rr.has(e))||r(o,%c${e},ku,...n)}];case"time":case"timeEnd":return[t,o=>{rr!==!0&&(!rr||!rr.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(rr!==!0&&(!rr||!rr.has(e))))return r(...o)}]}})),ku="color: gray";var Jr=globalThis.scrapbox;var Ys=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}};var Pg=e=>{let{accessToken:t,fetch:r,page:o,per:n}=Ys(e??{}),i=https://api.gyazo.com/api/images?${new URLSearchParams({access_token:t,...n!==void 0?{per_page:${Math.max(1,Math.min(100,Math.round(n)))}}:{},...o!==void 0?{page:${o}}:{}})};return r(i)};var Og=(e,t)=>{let{title:r,description:o,metadataIsPublic:n,collectionId:s,refererURL:i,accessToken:a,created:c,app:l,fetch:u}=Ys(t),p=new FormData;return p.append("imagedata",e),p.append("access_token",a),i&&p.append("referer_url",i.toString()),l!==void 0&&p.append("app",l),r!==void 0&&p.append("title",r),o!=null&&p.append("desc",o),s&&p.append("collection_id",s),n&&p.append("metadata_is_public","true"),c!==void 0&&p.append("created_at",${c}),u("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:p})};var zn="Gyazo Viewer",Sg=e=>{let t=Promise.resolve(),r=globalThis.GM_fetch;Jr.PageMenu.addMenu({title:r?zn:"Open Gyazo",icon:"kamon kamon-gyazo",onClick:r?()=>{t=t.then(()=>HP({per:e.maxCount??10,accessToken:e.accessToken,fetch:r,onClick:e.onClick}))}:()=>globalThis.open("https://gyazo.com/captures")})},HP=async e=>{let t;try{let r=Pg({page:0,...e});t=setTimeout(()=>{Jr.PageMenu(zn).addItem({title:"Loading...",icon:"fas fa-spinner",onClick:()=>{}})},100);let o=await r;if(!o.ok)throw new Error(${o.status} ${o.statusText});let n=await o.json();clearTimeout(t),Jr.PageMenu(zn).removeAllItems();for(let s of n)s.image_id&&Jr.PageMenu(zn).addItem({title:s.metadata?.title||"Untitled",image:s.url,onClick:i=>e.onClick?.(s,i)??navigator?.clipboard?.writeText?.(s.permalink_url)?.catch?.(a=>{alert(${a}),console.error(a)})})}catch(r){clearTimeout(t),Jr.PageMenu(zn).removeAllItems(),Jr.PageMenu(zn).addItem({title:"Failed to load the image list.",icon:"fas fa-exclamation-triangle",onClick:()=>{}}),console.error("Failed to load the image list",r)}};import{GYAZO_ACCESS_TOKEN as _D}from"https://scrapbox.io/api/code/takker-memex/GYAZO_ACCESS_TOKEN/auth.js";var ja,re,Cg,WP,To,Lg,Ig,Ag,Tu,Aa,Xs,Fg,Lu,_u,Pu,Dg,Da={},Ua=[],qP=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Js=Array.isArray;function Qr(e,t){for(var r in t)e[r]=t[r];return e}function Nu(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Zr(e,t,r){var o,n,s,i={};for(s in t)s=="key"?o=t[s]:s=="ref"?n=t[s]:i[s]=t[s];if(arguments.length>2&&(i.children=arguments.length>3?ja.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(s in e.defaultProps)i[s]===void 0&&(i[s]=e.defaultProps[s]);return Fa(e,i,o,n,null)}function Fa(e,t,r,o,n){var s={type:e,props:t,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:n??++Cg,__i:-1,__u:0};return n==null&&re.vnode!=null&&re.vnode(s),s}function ee(e){return e.children}function kr(e,t){this.props=e,this.context=t}function Vn(e,t){if(t==null)return e.__?Vn(e.__,e.__i+1):null;for(var r;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null)return r.__e;return typeof e.type=="function"?Vn(e):null}function GP(e){if(e.__P&&e.__d){var t=e.__v,r=t.__e,o=[],n=[],s=Qr({},t);s.__v=t.__v+1,re.vnode&&re.vnode(s),Mu(e.__P,s,t,e.__n,e.__P.namespaceURI,32&t.__u?[r]:null,o,r??Vn(t),!!(32&t.__u),n),s.__v=t.__v,s.__.__k[s.__i]=s,Bg(o,s,n),t.__e=t.__=null,s.__e!=r&&Ug(s)}}function Ug(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Ug(e)}function Ou(e){(!e.__d&&(e.__d=!0)&&To.push(e)&&!$a.__r++||Lg!=re.debounceRendering)&&((Lg=re.debounceRendering)||Ig)($a)}function $a(){try{for(var e,t=1;To.length;)To.length>t&&To.sort(Ag),e=To.shift(),t=To.length,GP(e)}finally{To.length=$a.__r=0}}function $g(e,t,r,o,n,s,i,a,c,l,u){var p,f,m,h,g,y,x,w=o&&o.__k||Ua,R=t.length;for(c=zP(r,t,w,c,R),p=0;p<R;p++)(m=r.__k[p])!=null&&(f=m.__i!=-1&&w[m.__i]||Da,m.__i=p,y=Mu(e,m,f,n,s,i,a,c,l,u),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Cu(f.ref,null,m),u.push(m.ref,m.__c||h,m)),g==null&&h!=null&&(g=h),(x=!!(4&m.__u))||f.__k===m.__k?(c=jg(m,c,e,x),x&&f.__e&&(f.__e=null)):typeof m.type=="function"&&y!==void 0?c=y:h&&(c=h.nextSibling),m.__u&=-7);return r.__e=g,c}function zP(e,t,r,o,n){var s,i,a,c,l,u=r.length,p=u,f=0;for(e.__k=new Array(n),s=0;s<n;s++)(i=t[s])!=null&&typeof i!="boolean"&&typeof i!="function"?(typeof i=="string"||typeof i=="number"||typeof i=="bigint"||i.constructor==String?i=e.__k[s]=Fa(null,i,null,null,null):Js(i)?i=e.__k[s]=Fa(ee,{children:i},null,null,null):i.constructor===void 0&&i.__b>0?i=e.__k[s]=Fa(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):e.__k[s]=i,c=s+f,i.__=e,i.__b=e.__b+1,a=null,(l=i.__i=VP(i,r,c,p))!=-1&&(p--,(a=r[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(n>u?f--:n<u&&f++),typeof i.type!="function"&&(i.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,i.__u|=4))):e.__k[s]=null;if(p)for(s=0;s<u;s++)(a=r[s])!=null&&!(2&a.__u)&&(a.__e==o&&(o=Vn(a)),Wg(a,a));return o}function jg(e,t,r,o){var n,s;if(typeof e.type=="function"){for(n=e.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=e,t=jg(n[s],t,r,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=Vn(e)),r.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function _o(e,t){return t=t||[],e==null||typeof e=="boolean"||(Js(e)?e.some(function(r){_o(r,t)}):t.push(e)),t}function VP(e,t,r,o){var n,s,i,a=e.key,c=e.type,l=t[r],u=l!=null&&(2&l.__u)==0;if(l===null&&a==null||u&&a==l.key&&c==l.type)return r;if(o>(u?1:0)){for(n=r-1,s=r+1;n>=0||s<t.length;)if((l=t[i=n>=0?n--:s++])!=null&&!(2&l.__u)&&a==l.key&&c==l.type)return i}return-1}function Ng(e,t,r){t[0]=="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||qP.test(t)?r:r+"px"}function Ia(e,t,r,o,n){var s,i;e:if(t=="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof o=="string"&&(e.style.cssText=o=""),o)for(t in o)r&&t in r||Ng(e.style,t,"");if(r)for(t in r)o&&r[t]==o[t]||Ng(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(Fg,"$1")),i=t.toLowerCase(),t=i in e||t=="onFocusOut"||t=="onFocusIn"?i.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=r,r?o?r[Xs]=o[Xs]:(r[Xs]=Lu,e.addEventListener(t,s?Pu:_u,s)):e.removeEventListener(t,s?Pu:_u,s);else{if(n=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=r??"";break e}catch{}typeof r=="function"||(r==null||r===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&r==1?"":r))}}function Mg(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t[Aa]==null)t[Aa]=Lu++;else if(t[Aa]<r[Xs])return;return r(re.event?re.event(t):t)}}}function Mu(e,t,r,o,n,s,i,a,c,l){var u,p,f,m,h,g,y,x,w,R,b,E,T,I,F,A=t.type;if(t.constructor!==void 0)return null;128&r.__u&&(c=!!(32&r.__u),s=[a=t.__e=r.__e]),(u=re.__b)&&u(t);e:if(typeof A=="function")try{if(x=t.props,w=A.prototype&&A.prototype.render,R=(u=A.contextType)&&o[u.__c],b=u?R?R.props.value:u.__:o,r.__c?y=(p=t.__c=r.__c).__=p.__E:(w?t.__c=p=new A(x,b):(t.__c=p=new kr(x,b),p.constructor=A,p.render=YP),R&&R.sub(p),p.state||(p.state={}),p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),w&&p.__s==null&&(p.__s=p.state),w&&A.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Qr({},p.__s)),Qr(p.__s,A.getDerivedStateFromProps(x,p.__s))),m=p.props,h=p.state,p.__v=t,f)w&&A.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),w&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(w&&A.getDerivedStateFromProps==null&&x!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,b),t.__v==r.__v||!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,b)===!1){t.__v!=r.__v&&(p.props=x,p.state=p.__s,p.__d=!1),t.__e=r.__e,t.__k=r.__k,t.__k.some(function(N){N&&(N.__=t)}),Ua.push.apply(p.__h,p._sb),p._sb=[],p.__h.length&&i.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,b),w&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(m,h,g)})}if(p.context=b,p.props=x,p.__P=e,p.__e=!1,E=re.__r,T=0,w)p.state=p.__s,p.__d=!1,E&&E(t),u=p.render(p.props,p.state,p.context),Ua.push.apply(p.__h,p._sb),p._sb=[];else do p.__d=!1,E&&E(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++T<25);p.state=p.__s,p.getChildContext!=null&&(o=Qr(Qr({},o),p.getChildContext())),w&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),I=u!=null&&u.type===ee&&u.key==null?Hg(u.props.children):u,a=$g(e,Js(I)?I:[I],t,r,o,n,s,i,a,c,l),p.base=t.__e,t.__u&=-161,p.__h.length&&i.push(p),y&&(p.__E=p.__=null)}catch(N){if(t.__v=null,c||s!=null)if(N.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;s[s.indexOf(a)]=null,t.__e=a}else{for(F=s.length;F--;)Nu(s[F]);Su(t)}else t.__e=r.__e,t.__k=r.__k,N.then||Su(t);re.__e(N,t,r)}else s==null&&t.__v==r.__v?(t.__k=r.__k,t.__e=r.__e):a=t.__e=KP(r.__e,t,r,o,n,s,i,c,l);return(u=re.diffed)&&u(t),128&t.__u?void 0:a}function Su(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Su))}function Bg(e,t,r){for(var o=0;o<r.length;o++)Cu(r[o],r[++o],r[++o]);re.__c&&re.__c(t,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(s){s.call(n)})}catch(s){re.__e(s,n.__v)}})}function Hg(e){return typeof e!="object"||e==null||e.__b>0?e:Js(e)?e.map(Hg):e.constructor!==void 0?null:Qr({},e)}function KP(e,t,r,o,n,s,i,a,c){var l,u,p,f,m,h,g,y=r.props||Da,x=t.props,w=t.type;if(w=="svg"?n="http://www.w3.org/2000/svg":w=="math"?n="http://www.w3.org/1998/Math/MathML":n||(n="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((m=s[l])&&"setAttribute"in m==!!w&&(w?m.localName==w:m.nodeType==3)){e=m,s[l]=null;break}}if(e==null){if(w==null)return document.createTextNode(x);e=document.createElementNS(n,w,x.is&&x),a&&(re.__m&&re.__m(t,s),a=!1),s=null}if(w==null)y===x||a&&e.data==x||(e.data=x);else{if(s=w=="textarea"&&x.defaultValue!=null?null:s&&ja.call(e.childNodes),!a&&s!=null)for(y={},l=0;l<e.attributes.length;l++)y[(m=e.attributes[l]).name]=m.value;for(l in y)m=y[l],l=="dangerouslySetInnerHTML"?p=m:l=="children"||l in x||l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x||Ia(e,l,null,m,n);for(l in x)m=x[l],l=="children"?f=m:l=="dangerouslySetInnerHTML"?u=m:l=="value"?h=m:l=="checked"?g=m:a&&typeof m!="function"||y[l]===m||Ia(e,l,m,y[l],n);if(u)a||p&&(u.__html==p.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),$g(t.type=="template"?e.content:e,Js(f)?f:[f],t,r,o,w=="foreignObject"?"http://www.w3.org/1999/xhtml":n,s,i,s?s[0]:r.__k&&Vn(r,0),a,c),s!=null)for(l=s.length;l--;)Nu(s[l]);a&&w!="textarea"||(l="value",w=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[l]||w=="progress"&&!h||w=="option"&&h!=y[l])&&Ia(e,l,h,y[l],n),l="checked",g!=null&&g!=e[l]&&Ia(e,l,g,y[l],n))}return e}function Cu(e,t,r){try{if(typeof e=="function"){var o=typeof e.__u=="function";o&&e.__u(),o&&t==null||(e.__u=e(t))}else e.current=t}catch(n){re.__e(n,r)}}function Wg(e,t,r){var o,n;if(re.unmount&&re.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||Cu(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){re.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(n=0;n<o.length;n++)o[n]&&Wg(o[n],t,r||typeof e.type!="function");r||Nu(e.__e),e.__c=e.__=e.__e=void 0}function YP(e,t,r){return this.constructor(e,r)}function Tt(e,t,r){var o,n,s,i;t==document&&(t=document.documentElement),re.__&&re.__(e,t),n=(o=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],Mu(t,e=(!o&&r||t).__k=Zr(ee,null,[e]),n||Da,Da,t.namespaceURI,!o&&r?[r]:n?null:t.firstChild?ja.call(t.childNodes):null,s,!o&&r?r:n?n.__e:t.firstChild,o,i),Bg(s,e,i)}function Qs(e){function t(r){var o,n;return this.getChildContext||(o=new Set,(n={})[t.__c]=this,this.getChildContext=function(){return n},this.componentWillUnmount=function(){o=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&o.forEach(function(i){i.__e=!0,Ou(i)})},this.sub=function(s){o.add(s);var i=s.componentWillUnmount;s.componentWillUnmount=function(){o&&o.delete(s),i&&i.call(s)}}),r.children}return t.__c="__cC"+Dg++,t.__=e,t.Provider=t.__l=(t.Consumer=function(r,o){return r.children(o)}).contextType=t,t}ja=Ua.slice,re={__e:function(e,t,r,o){for(var n,s,i;t=t.__;)if((n=t.__c)&&!n.__)try{if((s=n.constructor)&&s.getDerivedStateFromError!=null&&(n.setState(s.getDerivedStateFromError(e)),i=n.__d),n.componentDidCatch!=null&&(n.componentDidCatch(e,o||{}),i=n.__d),i)return n.__E=n}catch(a){e=a}throw e}},Cg=0,WP=function(e){return e!=null&&e.constructor===void 0},kr.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Qr({},this.state),typeof e=="function"&&(e=e(Qr({},r),this.props)),e&&Qr(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),Ou(this))},kr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ou(this))},kr.prototype.render=ee,To=[],Ig=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ag=function(e,t){return e.__v.__b-t.__v.__b},$a.__r=0,Tu=Math.random().toString(8),Aa="__d"+Tu,Xs="__a"+Tu,Fg=/(PointerCapture)$|Capture$/i,Lu=0,_u=Mg(!1),Pu=Mg(!0),Dg=0;var Ko,Me,Iu,qg,Zs=0,Qg=[],Je=re,Gg=Je.__b,zg=Je.__r,Vg=Je.diffed,Kg=Je.__c,Yg=Je.unmount,Xg=Je.__;function ei(e,t){Je.__h&&Je.__h(Me,e,Zs||t),Zs=0;var r=Me.__H||(Me.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function Q(e){return Zs=1,Po(Zg,e)}function Po(e,t,r){var o=ei(Ko++,2);if(o.t=e,!o.__c&&(o.__=[r?r(t):Zg(void 0,t),function(a){var c=o.__N?o.__N[0]:o.__[0],l=o.t(c,a);c!==l&&(o.__N=[l,o.__[1]],o.__c.setState({}))}],o.__c=Me,!Me.__f)){var n=function(a,c,l){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(f){return f.__c});if(u.every(function(f){return!f.__N}))return!s||s.call(this,a,c,l);var p=o.__c.props!==a;return u.some(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(p=!0)}}),s&&s.call(this,a,c,l)||p};Me.__f=!0;var s=Me.shouldComponentUpdate,i=Me.componentWillUpdate;Me.componentWillUpdate=function(a,c,l){if(this.__e){var u=s;s=void 0,n(a,c,l),s=u}i&&i.call(this,a,c,l)},Me.shouldComponentUpdate=n}return o.__N||o.__}function te(e,t){var r=ei(Ko++,3);!Je.__s&&Fu(r.__H,t)&&(r.__=e,r.u=t,Me.__H.__h.push(r))}function Ha(e,t){var r=ei(Ko++,4);!Je.__s&&Fu(r.__H,t)&&(r.__=e,r.u=t,Me.__h.push(r))}function dt(e){return Zs=5,H(function(){return{current:e}},[])}function H(e,t){var r=ei(Ko++,7);return Fu(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function D(e,t){return Zs=8,H(function(){return e},t)}function eo(e){var t=Me.context[e.__c],r=ei(Ko++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(Me)),t.props.value):e.__}function XP(){for(var e;e=Qg.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Ba),t.__h.some(Au),t.__h=[]}catch(r){t.__h=[],Je.__e(r,e.__v)}}}Je.__b=function(e){Me=null,Gg&&Gg(e)},Je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Xg&&Xg(e,t)},Je.__r=function(e){zg&&zg(e),Ko=0;var t=(Me=e.__c).__H;t&&(Iu===Me?(t.__h=[],Me.__h=[],t.__.some(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})):(t.__h.some(Ba),t.__h.some(Au),t.__h=[],Ko=0)),Iu=Me},Je.diffed=function(e){Vg&&Vg(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Qg.push(t)!==1&&qg===Je.requestAnimationFrame||((qg=Je.requestAnimationFrame)||JP)(XP)),t.__H.__.some(function(r){r.u&&(r.__H=r.u),r.u=void 0})),Iu=Me=null},Je.__c=function(e,t){t.some(function(r){try{r.__h.some(Ba),r.__h=r.__h.filter(function(o){return!o.__||Au(o)})}catch(o){t.some(function(n){n.__h&&(n.__h=[])}),t=[],Je.__e(o,r.__v)}}),Kg&&Kg(e,t)},Je.unmount=function(e){Yg&&Yg(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.some(function(o){try{Ba(o)}catch(n){t=n}}),r.__H=void 0,t&&Je.__e(t,r.__v))};var Jg=typeof requestAnimationFrame=="function";function JP(e){var t,r=function(){clearTimeout(o),Jg&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(r,35);Jg&&(t=requestAnimationFrame(r))}function Ba(e){var t=Me,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),Me=t}function Au(e){var t=Me;e.__c=e.__(),Me=t}function Fu(e,t){return!e||e.length!==t.length||t.some(function(r,o){return r!==e[o]})}function Zg(e,t){return typeof t=="function"?t(e):t}function Qe(e){return typeof e=="number"}var QP=(e,t,r)=>{let o=t.name||"anonymous predicate",n=typeof e,s=JSON.stringify(e,null,2);returnExpected ${r??"a value"} that satisfies the predicate ${o}, got ${n}: ${s}},ZP=QP,Du=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name=this.constructor.name}};function ey(e,t,r={}){if(!t(e))throw new Du(r.message??ZP(e,t,r.name))}function Uu(e,t,r={}){return ey(e,t,r),e}function Kt(e){return typeof e>"u"}var Wa=!1,ty=null,ry=()=>{scrapbox.addListener("lines:changed",()=>Wa=!1),scrapbox.addListener("layout:changed",()=>Wa=!1),ry=void 0},oy=()=>(ry?.(),Wa||(ty=scrapbox.Page.lines,Wa=!0),ty);var ny=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var sy=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var iy=()=>qa(document.getElementById("editor"),"div#editor"),ti=()=>qa(document.getElementsByClassName("lines").item(0),"div.lines");var ht=()=>{let e=document.getElementById("text-input");if(e)return sy(e,"textarea#text-input"),e};var ay=()=>qa(document.getElementsByClassName("popup-menu")?.[0],"div.popup-menu");var cy=()=>qa(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),qa=(e,t)=>{if(e)return ny(e,t),e};var Dt=()=>{let e=ti();if(!e)throw Error("div.lines is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.lines must has the property whose name starts with "__reactFiber"');return e[t].return.stateNode.props.lines};var or=e=>e.match(/^(\s*)/)?.[1]?.length??0,Yo=(e,t)=>{let r=or(ly(e,t)),o=0;for(;e+o+1<t.length&&or(ly(e+o+1,t))>r;)o++;return o},ly=(e,t)=>{let r=t[e];return ve(r)?r:r.text};var $u=e=>{if(Kt(e))return;if(Qe(e))return Ga(e)?.id;if(ve(e))return e.startsWith("L")?e.slice(1):e;if(e.classList.contains("line"))return e.id.slice(1);let t=e.closest(".line");if(t)return t.id.slice(1)},py=e=>{if(Kt(e))return;if(Qe(e))return e;let t=$u(e);return t?Dt().findIndex(r=>r.id===t):-1};var Ga=e=>{if(Kt(e))return;if(Qe(e))return Dt()[e];let t=$u(e);return t?Dt().find(r=>r.id===t):void 0},to=e=>{if(uy(e))return e;let t=$u(e);if(Kt(t))return t;let r=document.getElementById(L${t});if(!Kt(r))return r},uy=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var Cr=()=>Uu(oy(),vr),gt=e=>{if(Kt(e))return;if(Qe(e)||ve(e))return Ga(e)?.text;if(!(e instanceof HTMLElement))return;if(uy(e))return Ga(e)?.text;if(e.classList.contains("char-index"))return e.textContent??void 0;if(e.classList.contains("line")||e.getElementsByClassName("lines")?.[0])return Dt().map(({text:o})=>o).join(
);let t=[],r=Ga(e);if(!Kt(r)){for(let o of tO(e))t.push(rO(o));return r.text.slice(Math.min(...t),Math.max(...t)+1)}};var my=()=>{let e=ti()?.firstElementChild;if(!Kt(e))return e},fy=()=>{let e=ti()?.lastElementChild;if(!Kt(e))return e};var ju=e=>{let t=py(e);if(!Kt(t))return Yo(t,Cr())};function*tO(e){let t=e.getElementsByClassName("char-index");for(let r=0;r<t.length;r++)yield t[0]}var Bu=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index"),rO=e=>{if(!Bu(e))throw Error("A char DOM is required.");let t=e.className.match(/c-(\d+)/)?.[1];if(Kt(t))throw Error('.char-index must have ".c-{\\d}"');return parseInt(t)},dy=e=>{let t=e?.getElementsByClassName?.("c-0")?.[0];return Bu(t)?t:void 0};var ri=(e,t)=>{let r=to(e)?.getElementsByClassName?.(c-${t})?.[0];return Bu(r)?r:void 0};var _t=(e,t)=>{let{noModifiedKeys:r=!1,...o}=t??{},n={bubbles:!0,cancelable:!0,keyCode:oO[e],...r?{}:{...o}},s=ht();if(!s)throw Error("#text-input must exist.");s.dispatchEvent(new KeyboardEvent("keydown",n)),s.dispatchEvent(new KeyboardEvent("keyup",n))},oO={Backspace:8,Tab:9,Enter:13,Delete:46,Escape:27," ":32,PageUp:33,PageDown:34,End:35,Home:36,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,a:65,A:65,b:66,B:66,c:67,C:67,d:68,D:68,e:69,E:69,f:70,F:70,g:71,G:71,h:72,H:72,i:73,I:73,j:74,J:74,k:75,K:75,l:76,L:76,m:77,M:77,n:78,N:78,o:79,O:79,p:80,P:80,q:81,Q:81,r:82,R:82,s:83,S:83,t:84,T:84,u:85,U:85,v:86,V:86,w:87,W:87,x:88,X:88,y:89,Y:89,z:90,Z:90,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,F1:113,F2:114,F3:115,F4:116,F5:117,F6:118,F7:119,F8:120,F9:121,F10:122,F11:123,F12:124,":":186,"*":186,";":187,"+":187,"-":189,"=":189,".":190,">":190,"/":191,"?":191,"@":192,"":192,"":219,"{":219,"\\":220,"|":220,"":221,"}":221,"^":222,"~":222,_:226};var Hu=async(e,t)=>{let r={button:t.button??0,clientX:t.X,clientY:t.Y,bubbles:!0,cancelable:!0,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,view:window};e.dispatchEvent(new MouseEvent("mousedown",r)),e.dispatchEvent(new MouseEvent("mouseup",r)),e.dispatchEvent(new MouseEvent("click",r)),await Se(10)};var He=()=>{let e=ht();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(r=>r.startsWith("__reactFiber"));if(!t)throw Error('div.cursor must has the property whose name starts with "__reactFiber"');return et.return.return.stateNode.props};var Wu=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=globalThis.innerHeight};function Ut(e,t,r){if(r??=e>t?-1:1,!Number.isFinite(e))throw new RangeError(start must be finite, but got ${e}.);if(!Number.isFinite(r))throw new RangeError(step must be finite, but got ${r}.);if(r===0)throw new RangeError("step must not be 0.");if(!Number.isFinite(t))throw new RangeError(stop must be finite, but got ${t}.);if(r>0&&e>t)throw new RangeError("start must be less than stop for positive step.");if(r<0&&e<t)throw new RangeError("start must be greater than stop for negative step.");return function*(){if(r>=0)for(let o=e;o<=t;o+=r)yield o;else for(let o=e;o>=t;o+=r)yield o}()}var hy=()=>{_t("Home"),_t("Home")};var gy=async()=>{let e=my();if(!e)throw Error(".line:first-of-type can't be found.");Wu(e)||e.scrollIntoView({block:"center"});let t=dy(e);if(!t)throw Error(".line:first-of-type .c-0 can't be found.");let{left:r,top:o}=t.getBoundingClientRect();await Hu(e,{X:r,Y:o})},yy=async()=>{await by(fy())},xy=async e=>{await by(to(e))},by=async e=>{if(!e)throw Error("The target line DOM is failed to find.");Wu(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:o}=e.getElementsByClassName("text")0.getBoundingClientRect();await Hu(e,{X:t+1,Y:r+o/2})};var Ey=(e=1)=>{for(let t of Ut(1,e))_t("z",{ctrlKey:!0})},wy=(e=1)=>{for(let t of Ut(1,e))_t("z",{shiftKey:!0,ctrlKey:!0})};var za=async(e,t,r)=>{await xy(e),hy();for(let o of Ut(e,t))_t("ArrowDown",{shiftKey:!0});_t("End",{shiftKey:!0}),await ct(r)};var Va=(e=1)=>{for(let t of Ut(1,e))_t("ArrowRight",{ctrlKey:!0})},Ka=(e=1)=>{for(let t of Ut(1,e))_t("ArrowLeft",{ctrlKey:!0})};var Ya=(e=1)=>{for(let t of Ut(1,e))_t("ArrowUp",{ctrlKey:!0})},Xa=(e=1)=>{for(let t of Ut(1,e))_t("ArrowDown",{ctrlKey:!0})},Ja=(e=1)=>{for(let t of Ut(1,e))_t("ArrowRight",{altKey:!0})},Qa=(e=1)=>{for(let t of Ut(1,e))_t("ArrowLeft",{altKey:!0})};var Za=(e=1)=>{for(let t of Ut(1,e))_t("ArrowUp",{altKey:!0})},ec=(e=1)=>{for(let t of Ut(1,e))_t("ArrowDown",{altKey:!0})},ct=e=>{let t=ht();if(!t)throw Error("#text-input is not ditected.");t.focus(),t.value=e;let r=new InputEvent("input",{bubbles:!0});return t.dispatchEvent(r),scrapbox.Page.waitForSave()};var Fe=()=>{let e=cy();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let o=Ry(...r);o&&t.append(o)},dispose:()=>t.remove(),Symbol.dispose:()=>t.remove()}},Ry=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":returnsO();case"check-circle":returniO();case"exclamation-triangle":returnaO();case"text":returntc(o.text);case"group":{let n=Ry(...o.items);return n?n:[]}}});if(t.length===0)return;if(t.length===1)return t0;let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},tc=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},sO=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),tc(e)},iO=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),tc(e)},aO=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),tc(e)};var Kn=e=>{let t=JSON.parse(localStorage.getItem("pageTransitionContext")??""),r=e.type==="page"?e.from.project===e.to.project?e.from.title===e.to.title?{titleHint:e.to.title}:{linkFrom:e.from.title}:{linkFrom:/${e.from.project}/${e.from.title}}:{searchQuery:e.query};t[page_${ce(e.to.title)}]=r,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var cO=(e,t,r)=>{let o=new URL(/${e}/${se(t)},location.href);if(r?.body&&(o.search=?body=${encodeURIComponent(r.body)}),r?.id&&(o.hash=#${r.id}),r?.context&&Kn({...r?.context,to:{project:e,title:t}}),r?.newTab!==!1&&(r?.newTab===!0||e!==scrapbox.Project.name)){globalThis.open(o);return}if(r?.reload!==!1&&(r?.reload===!0||e!==scrapbox.Project.name)){globalThis.open(o,"_self");return}let n=document.createElement("a");n.href=o.toString(),document.body.append(n),n.click(),n.remove()},qu=(e,t,r)=>cO(e,t,{newTab:!1,reload:!1,body:r});var Oo=async(e,t)=>{let r=await globalThis.caches.keys();for(let o of r.sort().reverse()){let s=await(await caches.open(o)).match(e,t);if(s)return s}},rc=async(e,t)=>{let r=t.clone();return await(await caches.open(lO(new Date))).put(e,r)},lO=e=>api-${e.getFullYear()}-${${e.getMonth()+1}.padStart(2,"0")}-${${e.getDate()}.padStart(2,"0")};var Wt=()=>{let e=ht();if(!e)throw Error("#text-input is not found.");let t=Object.keys(e).find(s=>s.startsWith("__reactFiber"));if(!t)throw Error('#text-input must has the property whose name starts with "__reactFiber"');let r=et.return.return.stateNode._stores,o=r.find(s=>s.constructor.name==="Cursor");if(!o)throw Error('#text-input must has a "Cursor" store.');let n=r.find(s=>s.constructor.name==="Selection");if(!n)throw Error('#text-input must has a "Selection" store.');return{cursor:o,selection:n}};var So=()=>Wt().cursor;var oc=()=>Wt().selection;var oi=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),vy=e=>{if(e===0)return;let t={};return e&1&&(t.capture=!0),e&2&&(t.once=!0),e&4&&(t.passive=!0),t};var nc=new Map,Gu=new Map,zu=()=>{scrapbox.on("layout:changed",()=>{let e=ht();if(e)for(lett,rof nc)for(leto,nof r)for(let s of n)e.addEventListener(t,o,vy(s))}),zu=void 0},ky=(e,t,r)=>{zu?.();let o=nc.get(e)??new Map,n=o.get(t)??new Set;if(n.has(oi(r)))return;if(n.add(oi(r)),o.set(t,n),nc.set(e,o),typeof r=="object"&&r?.once){let i=Gu.get(t)??new Map,a=oi(r),c=function(u){return Vu(e,t,r),i.delete(a),t.call(this,u)};i.set(a,c),Gu.set(t,i);let l=ht();if(!l)return;l.addEventListener(e,c,r)}let s=ht();s&&s.addEventListener(e,t,r)},Vu=(e,t,r)=>{zu?.();let o=nc.get(e);if(!o)return;let n=o.get(t);if(!n)return;let s=oi(r);if(n.delete(s),typeof r=="object"&&r?.once){let a=Gu.get(t);if(!a)return;let c=a.get(s);if(!c)return;let l=ht();if(!l)return;l.removeEventListener(e,c,r),a.delete(s);return}let i=ht();i&&i.removeEventListener(e,t,r)};var Ty={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\[","]":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},pO=new RegExp(${Object.values(Ty).join("")},"gu");function _y(e){return e.replaceAll(pO,t=>Ty[t]).replace(/^[0-9a-zA-Z]/,t=>\\x${t.codePointAt(0).toString(16)})}var uO=0,T8=Array.isArray;function d(e,t,r,o,n,s){t||(t={});var i,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?i=t[a]:c[a]=t[a];var l={type:e,props:c,key:r,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--uO,__i:-1,__u:0,__source:n,__self:s};if(typeof e=="function"&&(i=e.defaultProps))for(a in i)c[a]===void 0&&(c[a]=i[a]);return re.vnode&&re.vnode(l),l}var Py=({project:e,title:t,words:r,lines:o,query:n,close:s})=>{let i=D(c=>{Kn({type:"search",query:n,to:{project:e,title:t}}),!(c.metaKey||c.ctrlKey||c.altKey||c.shiftKey)&&s()},[e,t,n,s]),a=H(()=>{let c=new RegExp((${r.map(l=>_y(l)).join("|")}),"i");return o.flatMap(l=>{let u=l.split(c);return d("span",{children:u.map((p,f)=>f%2===0?p:d("strong",{children:p}))})})},[o,r]);return d("a",{href:/${e}/${se(t)},target:${e===scrapbox.Project.name?"":"_blank"},rel:${e===scrapbox.Project.name?"route":"noopener noreferrer"},onClick:i,children:[t,d("div",{className:"description",children:a})]})};var Oy=e=>{let[t,r]=Q(e),o=D(()=>r(!0),[]),n=D(()=>r(!1),[]),s=D(()=>r(i=>!i),[]);return[t,{open:o,close:n,toggle:s}]};var Sy=(e,t)=>{let[r,o]=Q(),[n,s]=Q(!1),i=dt(Promise.resolve());return te(()=>{if(t===""){o(void 0);return}let a=!1;return i.current=(async()=>{if(await i.current,!a){s(!0);try{let c=await hg(t,e);if(a)return;o(K(c)?S(c):void 0)}finally{s(!1)}}})(),()=>a=!0},[t,e]),{loading:n,result:r}};var Ly=()=>d("style",{children:.modal {
position:fixed;
inset:0;
z-index:1050;
background-color:#000c;
display: flex;
flex-direction: column;
align-items: center;
row-gap: 10px;
padding: 10px;
}
.closed {
display: none;
}
.modal > * {
color: var(--page-text-color, #4a4a4a);
background-color: var(--page-bg, #fefefe);
border: 2px solid var(--body-bg, #dcdde0);
border-radius: 4px;
padding: 5px;
width: calc(var(--item-width, 100%) - 10px);
}
@media (min-width: 768px) {
.modal {
padding: 30px;
}
}
.controller {
display: flex;
gap: 0.2em;
flex-direction: column;
}
input {
border-radius: 5px;
padding: 0 10px;
height: 32px;
border: transparent;
box-shadow: none;
color: var(--search-form-text-color, rgba(255, 255, 255, 0.35));
background-color: var(--search-form-bg, rgba(255, 255, 255, 0.15))
}
.result {
flex-direction: column;
width: 100%;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
font-weight: normal;
line-height: 28px;
text-align: left;
border: 1px solid rgba(0,0,0,0.15);
border-radius: 4px;
background-clip: padding-box;
white-space: nowrap;
overflow-x: hidden;
overflow-y: auto;
}
a {
display: block;
padding: 3px 20px;
clear: both;
align-items: center;
user-select: none;
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
color: inherit;
}
.description {
margin-top: 0.5em;
color: var(--incremental-fulltext-search-description-text-color, #c4c4c4);
font-size: 12px;
line-height: 14px;
max-height: 28px;
overflow: hidden;
text-overflow: ellipsis;
}
.description strong {
background-color: #ff0;
color: #666;
}
.spinner::before {
display: inline-block;
font-style: normal;
font-variant: normal;
text-rendering: auto;
line-height: 1;
content: "\f110";
font-family: "Font Awesome 5 Free";
font-weight: 900;
margin: 0;
padding: 0;
box-sizing: border-box;
animation: fa-spin 2s linear infinite;
}});var mO=()=>d("i",{className:"spinner"}),Ny=({exportOps:e})=>{let[t,r]=Q(""),o=scrapbox.Project.name,{loading:n,result:s}=Sy(o,t),i=D(m=>{r(m.currentTarget.value)},[]),[a,{open:c,close:l,toggle:u}]=Oy(!1),p=dt({open:c,close:l,toggle:u});te(()=>{Object.assign(p.current,{open:c,close:l,toggle:u})},[]),te(()=>e(p.current),[e]);let f=D(m=>{m.target instanceof HTMLElement&&m.target.id==="background"&&l()},[]);return d(ee,{children:[d(Ly,{}),d("div",{id:"background",className:modal${a?"":" closed"},onClick:f,children:[d("div",{className:"controller",children:[d("input",{type:"text",value:t,onInput:i}),d("div",{className:"info",children:[n&&d(mO,{}),${s?.pages?.length??0} pages]})]}),s?.pages&&s.pages.length>0&&d("ul",{className:"result",children:s.pages.map(m=>d("li",{children:d(Py,{...m,project:o,query:t,close:l})},m.title))})]})]})};var My=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>{Tt(d(Ny,{exportOps:r}),t)})};var sc=(e,t)=>Object.hasOwn(e,t),Cy={left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown",bs:"Backspace",menu:"ContextMenu",apps:"ContextMenu",del:"Delete",return:"Enter",cr:"Enter",esc:"Escape",pgup:"PageUp",pgdn:"PageDown",lt:"<",less:"<",lesser:"<",gt:">",greater:">"},Dy=e=>{let t=e.toLowerCase();return sc(Cy,t)?Cy[t]:e},Iy={Backquote:["","~"],Digit1:"1","!",Digit2:"2","@",Digit3:"3","#",Digit4:"4","$",Digit5:"5","%",Digit6:"6","^",Digit7:"7","&",Digit8:"8","*",Digit9:"9","(",Digit0:"0",")",Minus:"-","_",Equal:"=","+",Backslash:"\\","|",BracketLeft:["","{",BracketRight:"","}"],Semicolon:";",":",Quote:"'",'"',Comma:",","<",Period:".",">",Slash:"/","?"},fO=(e,t)=>{if(e.startsWith("Key")){let r=e.slice(3);return t||(r=r.toLowerCase()),r}return sc(Iy,e)?Iyet?1:0:e},Ay={"<":"lt",">":"gt"},dO=/^($|Unidentified$|Process$|Dead$|Alt|Control|Hyper|Meta|Shift|Super|OS)/,Ku=e=>{let t=e.shiftKey,r=e.key||"Unidentified";if(r==="Unidentified"?r=fO(e.code||"",t):(r=Dy(r),r===" "&&(r="Space")),dO.test(r))return"";r.length===1?t=!1:r=r.toLowerCase();let o="";return e.altKey&&(o+="a-"),e.ctrlKey&&(o+="c-"),e.metaKey&&(o+="m-"),t&&(o+="s-"),sc(Ay,r)&&(r=Ayr),o||r.length>1?<${o}${r}>:r},Fy={a:"altKey",c:"ctrlKey",m:"metaKey",s:"shiftKey"},hO=e=>{if(e.length===1)return/\s/.test(e)?{ok:!1,value:{name:"InvalidKeyError",key:e,message:Invalid key: ${e}}}:{ok:!0,value:{key:e}};let t=e.match(/^<((?:a-z-)*)(a-z\d+|^<>\s)>$/i);if(!t)return{ok:!1,value:{name:"InvalidKeyError",key:e,message:Invalid key: ${e}}};let,r,o=t,n={key:Dy(o)};for(let s of r.split("-").slice(0,-1)){let i=s.toLowerCase();if(!sc(Fy,i))return{ok:!1,value:{name:"UnknownModifierError",modifier:s,context:e,message:${e}: Unknown modifier: ${s}}};let a=Fyi;if(na!==void 0)return{ok:!1,value:{name:"DuplicateModifierError",modifier:s,context:e,message:${e}: Duplicate modifier: ${s}}};if(na=!0,n.key.length===1&&n.shiftKey)return{ok:!1,value:{name:"DisallowedModifierError",modifier:s,context:e,message:${e}: Unusable modifier with single-character keys: ${s}}}}return{ok:!0,value:n}},Uy=e=>{let t=hO(e);return t.ok?{ok:!0,value:Ku(t.value)}:t},$y=e=>e.match(/<^<>\s+>|\s\S|^$/g);var mr=!1;var jy=e=>Object.fromEntries(...Object.entries(console).map((t,r)=>{if(typeof r!="function")returnt,r;switch(t){case"warn":case"error":return[t,(...o)=>r(%c${e},"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{mr!==!0&&(!mr||!mr.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{mr!==!0&&(!mr||!mr.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{mr!==!0&&(!mr||!mr.has(e))||r(${e} ${o})}];default:returnt,(...o)=>{if(!(mr!==!0&&(!mr||!mr.has(e))))return r(...o)}}}));var Xo=jy("ScrapBindings:mod.ts"),ic=class{constructor(t,r){this.target=t;this.onSequenceUpdate=r?.onSequenceUpdate,this.flushInterval=r?.flushInterval??1e3}bind(t,r){let o=new Map,n=[];for(lets,iof t instanceof Map?t.entries():typeof t=="string"?t,r:Object.entries(t)){let a=By(s);if(!a.ok){for(let l of a.value)Xo.error(${s}: ${l.message});o.set(s,a.value);continue}let c=a.value;this.bindings.set(c,i),c.startsWith(this.currentSequence)&&this.filtered.add(c),n.push(c)}return Xo.debug("Binded the following commands:",n),this.emitChange(),o}unbind(...t){for(let r of t){let o=By(r);if(!o.ok)continue;let n=o.value;this.bindings.delete(n),this.filtered.delete(n)}this.emitChange()}reset(){this.bindings.clear(),this.emitChange()}bindings=new Map;onSequenceUpdate;flushInterval;_sequence="";set currentSequence(t){let r=this._sequence!==t;this._sequence=t,r&&this.onSequenceUpdate?.(t)}get currentSequence(){return this._sequence}prevBestMatchCommand;filtered=new Set;timer;backToInitial=()=>{clearTimeout(this.timer),this.currentSequence="",this.prevBestMatchCommand=void 0,this.filtered=new Set(this.bindings.keys()),Xo.debug("reset the sequence")};handleKeydown=t=>{if(!t.isTrusted)return;let r=Ku(t);if(!r)return;if(clearTimeout(this.timer),t.isComposing){this.backToInitial();return}this.currentSequence+=r,Xo.debug("sequence",this.currentSequence);let o;for(let s of this.filtered){if(s.startsWith(this.currentSequence)||this.filtered.delete(s),this.currentSequence!==s)continue;let i=this.bindings.get(s);if(!i){this.filtered.delete(s);continue}o=()=>{Xo.debug(run ${s});try{i(t)}catch(a){Xo.error(a)}finally{this.backToInitial()}}}let n=this.filtered.size;if(Xo.debug(${n} candidates: ${[...this.filtered.keys()].join(", ")}),n>0&&(this.prevBestMatchCommand=o),this.prevBestMatchCommand&&n<2){if(this.prevBestMatchCommand(),n===0){this.handleKeydown(t);return}return}if(n===0){this.backToInitial();return}t.preventDefault(),t.stopPropagation(),this.timer=setTimeout(this.prevBestMatchCommand??this.backToInitial,this.flushInterval)};emitChange=()=>{if(this.bindings.size===0){this.backToInitial(),this.target.removeEventListener("keydown",this.handleKeydown);return}this.target.addEventListener("keydown",this.handleKeydown)}},gO={name:"InvalidSequenceError",message:"cannot parse the sequence"},By=e=>{let t=$y(e);if(!t)return{ok:!1,value:gO};let r="",o=[];for(let n of t){let s=Uy(n);if(!s.ok){o.push(s.value);continue}r+=s.value}return o.length>0?{ok:!1,value:o}:{ok:!0,value:r}};var Hy=()=>{if(scrapbox.Layout!=="page")return{selectionRange:{start:{line:0,char:0},end:{line:0,char:0}},selectedText:""};let{selectionRange:e,selectedText:t,position:r}=He();if(!t){let u=ju(r.line)??0,p={start:{line:r.line,char:0},end:{line:r.line+u,char:gt(r.line+u)?.length??0}};return{selectionRange:p,selectedText:scrapbox.Page.lines.slice(p.start.line,p.end.line+1).map(f=>f.text).join(`
)}}let{start:o,end:n}=e,s=o.line>n.line,i=s?n.line:o.line,a=s?n.char:o.char,c=s?o.line:n.line,l=s?o.char:n.char;return{selectedText:t,selectionRange:{start:{line:i,char:a},end:{line:c,char:l}}}};var Yu=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=n.replaceAll("[","").replaceAll("]","").trim(),a=Math.min(...[n,...s].map(l=>or(l))),c=[from ${t},n.slice(a),...s.map(l=>l.slice(a))];return{text:${i},pages:[{project:r,title:i,lines:c,mode:o}]}};Yu.hookName="default-hook";var ro=e=>{let{project:t=scrapbox.Project.name,mode:r="newtab"}=e??{},o=[...e?.hooks??[],Yu],{selectionRange:{start:n,end:s},selectedText:i}=Hy();if(!i||scrapbox.Layout!=="page")return;let a=(()=>{for(let p of o){let f=p(i,{title:scrapbox.Page.title,projectFrom:scrapbox.Project.name,projectTo:t,lines:Dt().slice(n.line,s.line+1),mode:r});if(f)return[p.hookName,f]}})();if(!a)return;let[c,l]=a,u=async()=>{let p=l instanceof Promise?await l:l;if(p.pages.length===0&&p.text===i)return;let f,{render:m,dispose:h}=Fe();try{if(p.pages.length>0){let y=p.pages.length;m({type:"spinner"},{type:"text",text:Create new ${y} pages...});let x=await It(e?.socket);if(O(x))throw Z(x);f=S(x);let w=0;await Promise.all(p.pages.map(async R=>{let b=Array.isArray(R.lines)?E=>[...E.map(T=>T.text),...R.lines]:R.lines;await Le(R.project,R.title,b,{socket:f}),m({type:"spinner"},{type:"text",text:Create ${y-++w} pages...})}))}m({type:"spinner"},{type:"text",text:${p.pages.length>0?"Created. ":""}Removing cut text...});let g=p.text;if(i===g)return;await Le(scrapbox.Project.name,scrapbox.Page.title,y=>{let x=y.map(w=>w.text);return[...x.slice(0,n.line),...${xn.line.slice(0,n.char)}${g}${x.slice(s.line).join(`
).slice(s.char)}.split(`
)]}),m({type:"check-circle"},{type:"text",text:"Removed."});for(let y of p.pages)switch(y.mode){case"self":y.project===scrapbox.Project.name?qu(y.project,y.title):globalThis.open(https://scrapbox.io/${y.project}/${se(y.title)},"_self");break;case"newtab":globalThis.open(https://scrapbox.io/${y.project}/${se(y.title)});break}}catch(g){m({type:"exclamation-triangle"},{type:"text",text:"Failed to create new pages (see console)."}),console.error(g)}finally{let g=Se(1e3);f&&await At(f),await g,h()}};return u.hookName=c,u};var yO=Math.pow(10,8)*24*60*60*1e3,rY=-yO;var xO=3600;var Wy=xO*24,oY=Wy*7,bO=Wy*365.2425,EO=bO/12,nY=EO*3,Xu=Symbol.for("constructDateFrom");function Ir(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Xu in e?e[Xu](t):e instanceof Date?new e.constructor(t):new Date(t)}function De(e,t){return Ir(t||e,e)}function oo(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var Gy={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return oo(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):oo(r+1,2)},d(e,t){return oo(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(e,t){return oo(e.getHours()%12||12,t.length)},H(e,t){return oo(e.getHours(),t.length)},m(e,t){return oo(e.getMinutes(),t.length)},s(e,t){return oo(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return oo(n,t.length)}};function zy(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Vy(e){return!(!zy(e)&&typeof e!="number"||isNaN(+De(e)))}var RO=/(\w)\1*|''|'(''|[^'])+('|$)|./g,vO=/^'([^]*?)'?$/,kO=/''/g,TO=/[a-zA-Z]/;function qt(e,t){let r=De(e);if(!Vy(r))throw new RangeError("Invalid time value");let o=t.match(RO);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return _O(n);let i=Gy[s];if(i)return i(r,n);if(s.match(TO))throw new RangeError("Format string contains an unescaped latin alphabet character "+s+"");return n}).join(""):""}function _O(e){let t=e.match(vO);return t?t[1].replace(kO,"'"):e}function Yy(e,t){return De(e,t?.in).getDate()}function Jy(e,t){return De(e,t?.in).getMonth()}function Qy(e,t){return De(e,t?.in).getFullYear()}var Zy=e=>{let t=new Map;for(let r of e){let o=${Qy(r)}-${Jy(r)}-${Yy(r)},n=t.get(o);n&&n.getTime()>r.getTime()||t.set(o,r)}return[...t.values()]};var PO=Math.pow(10,8)*24*60*60*1e3,L7=-PO,Jo=6048e5,Ju=864e5,Ar=6e4,Lo=36e5,ac=1e3;var cc=3600;var Qu=cc*24,OO=Qu*7,ex=Qu*365.2425,tx=ex/12,SO=tx*3,Zu=Symbol.for("constructDateFrom");function U(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Zu in e?e[Zu](t):e instanceof Date?new e.constructor(t):new Date(t)}function v(e,t){return U(t||e,e)}function ke(e,t,r){let o=v(e,r?.in);return isNaN(t)?U(r?.in||e,NaN):(t&&o.setDate(o.getDate()+t),o)}function ni(e,t,r){let o=v(e,r?.in);if(isNaN(t))return U(r?.in||e,NaN);if(!t)return o;let n=o.getDate(),s=U(r?.in||e,o.getTime());s.setMonth(o.getMonth()+t+1,0);let i=s.getDate();return n>=i?s:(o.setFullYear(s.getFullYear(),s.getMonth(),n),o)}function em(e,t,r){let{years:o=0,months:n=0,weeks:s=0,days:i=0,hours:a=0,minutes:c=0,seconds:l=0}=t,u=v(e,r?.in),p=n||o?ni(u,n+o*12):u,f=i||s?ke(p,i+s*7):p,m=c+a*60,h=(l+m*60)*1e3;return U(r?.in||e,+f+h)}function rx(e,t){let r=v(e,t?.in),o=r.getFullYear(),n=r.getMonth(),s=U(r,0);return s.setFullYear(o,n+1,0),s.setHours(0,0,0,0),s.getDate()}function tm(e,t,r){let o=v(e,r?.in),n=o.getFullYear(),s=o.getDate(),i=U(r?.in||e,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);let a=rx(i);return o.setMonth(t,Math.min(s,a)),o}function ox(e,t,r){let o=v(e,r?.in);return isNaN(+o)?U(r?.in||e,NaN):(t.year!=null&&o.setFullYear(t.year),t.month!=null&&(o=tm(o,t.month)),t.date!=null&&o.setDate(t.date),t.hours!=null&&o.setHours(t.hours),t.minutes!=null&&o.setMinutes(t.minutes),t.seconds!=null&&o.setSeconds(t.seconds),t.milliseconds!=null&&o.setMilliseconds(t.milliseconds),o)}function si(e,t,r){return U(r?.in||e,+v(e)+t)}function ii(e,t,r){return si(e,t*1e3,r)}function nx(e,t){return v(e,t?.in).getMinutes()}function Fr(e,t,r){let o=v(e,r?.in);return o.setTime(o.getTime()+t*Ar),o}function Dr(e){return t=>{let r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function lc(e,t){return+v(e)-+v(t)}function No(e,t,r){let o=lc(e,t)/Ar;return Dr(r?.roundingMethod)(o)}function sx(e,t){return v(e,t?.in).getHours()}function rm(e,t,r){return si(e,t*Lo,r)}function om(e,t){return v(e,t?.in).getDate()}function Yt(e,t,r){return ke(e,-t,r)}function Tr(e,t){let r=v(e,t?.in);return r.setHours(0,0,0,0),r}function pc(e,t){let r=v(e,t?.in);return r.setHours(23,59,59,999),r}function fe(e,...t){let r=U.bind(null,e||t.find(o=>typeof o=="object"));return t.map(r)}function yt(e,t,r){let[o,n]=fe(r?.in,e,t);return+Tr(o)==+Tr(n)}function _r(e,t){let[r,o]=fe(e,t.start,t.end);return{start:r,end:o}}function ai(e,t){let{start:r,end:o}=_r(t?.in,e),n=+r>+o,s=n?+r:+o,i=n?o:r;i.setHours(0,0,0,0);let a=t?.step??1;if(!a)return[];a<0&&(a=-a,n=!n);let c=[];for(;+i<=s;)c.push(U(r,i)),i.setDate(i.getDate()+a),i.setHours(0,0,0,0);return n?c.reverse():c}function fr(e){let t=v(e),r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return r.setUTCFullYear(t.getFullYear()),+e-+r}function no(e,t,r){let[o,n]=fe(r?.in,e,t),s=Tr(o),i=Tr(n),a=+s-fr(s),c=+i-fr(i);return Math.round((a-c)/Ju)}var LO={};function xt(){return LO}function Ne(e,t){let r=xt(),o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=v(e,t?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function Qo(e,t){let r=v(e,t?.in),o=r.getFullYear(),n=xt(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=U(t?.in||e,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=Ne(i,t),c=U(t?.in||e,0);c.setFullYear(o,0,s),c.setHours(0,0,0,0);let l=Ne(c,t);return+r>=+a?o+1:+r>=+l?o:o-1}function nm(e,t){let r=xt(),o=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=Qo(e,t),s=U(t?.in||e,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),Ne(s,t)}function Mo(e,t){let r=v(e,t?.in),o=+Ne(r,t)-+nm(r,t);return Math.round(o/Jo)+1}function Zo(e,t,r){return ke(e,t*7,r)}function ix(e,t,r){return Zo(e,-t,r)}function uc(e,t,r){let o=v(e,r?.in),n=Mo(o,r)-t;return o.setDate(o.getDate()-n*7),v(o,r?.in)}function ax(e,t){let{start:r,end:o}=_r(t?.in,e),n=+r>+o,s=n?Ne(o,t):Ne(r,t),i=n?Ne(r,t):Ne(o,t);s.setHours(15),i.setHours(15);let a=+i.getTime(),c=s,l=t?.step??1;if(!l)return[];l<0&&(l=-l,n=!n);let u=[];for(;+c<=a;)c.setHours(0),u.push(U(r,c)),c=Zo(c,l),c.setHours(15);return n?u.reverse():u}function mc(e,t,r){let[o,n]=fe(r?.in,e,t),s=o.getFullYear()-n.getFullYear(),i=o.getMonth()-n.getMonth();return s*12+i}function ci(e,t){return v(e,t?.in).getFullYear()}function en(e,t){let r=+v(e)-+v(t);return r<0?-1:r>0?1:r}function tn(e,t){return+v(e)>+v(t)}function cx(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Xt(e){return!(!cx(e)&&typeof e!="number"||isNaN(+v(e)))}function Jt(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var sm={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return Jt(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):Jt(r+1,2)},d(e,t){return Jt(e.getDate(),t.length)},a(e,t){let r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h(e,t){return Jt(e.getHours()%12||12,t.length)},H(e,t){return Jt(e.getHours(),t.length)},m(e,t){return Jt(e.getMinutes(),t.length)},s(e,t){return Jt(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return Jt(n,t.length)}};var NO=/(\w)\1*|''|'(''|[^'])+('|$)|./g,MO=/^'([^]*?)'?$/,CO=/''/g,IO=/[a-zA-Z]/;function lt(e,t){let r=v(e);if(!Xt(r))throw new RangeError("Invalid time value");let o=t.match(NO);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return AO(n);let i=sm[s];if(i)return i(r,n);if(s.match(IO))throw new RangeError("Format string contains an unescaped latin alphabet character "+s+"");return n}).join(""):""}function AO(e){let t=e.match(MO);return t?t[1].replace(CO,"'"):e}var lx=e=>e==null,Co=e=>typeof e=="string";async function*px(e){let t=[],r,o=i=>{if(!r){t.push(i);return}r(i),r=void 0},n=()=>t.length>0?Promise.resolve(t.pop()):new Promise(i=>r=i),s=0;for(let i of e)i.then(a=>o({state:"fulfilled",value:a})).catch(a=>o({state:"rejected",reason:a})),s++;for(let i=0;i<s;i++)yield await n()}var bt=e=>{let t=e.match(/^(\d{4})-(\d{2})-(\d{2}) (?: {5}|(\d{2}):(\d{2})) (?: {4}|(\d{4})) (?: {8}|(\d{2}):(\d{2}):(\d{2})) (?: {8}|(\d{2}):(\d{2}):(\d{2}))([^\n]*)$/);if(!t)return;let[,r,o,n,s,i,a,c,l,u,p,f,m,h]=t,g={title:h,base:new Date(parseInt(r),parseInt(o)-1,parseInt(n)),plan:{},record:{}};if(s){let y=new Date(g.base);y.setHours(parseInt(s)),y.setMinutes(parseInt(i)),g.plan.start=y}if(a&&(g.plan.duration=parseInt(a)*60),c){let y=new Date(g.base);y.setHours(parseInt(c)),y.setMinutes(parseInt(l)),y.setSeconds(parseInt(u)),g.record.start=y}if(p){let y=new Date(g.base);y.setHours(parseInt(p)),y.setMinutes(parseInt(f)),y.setSeconds(parseInt(m)),g.record.start&&tn(g.record.start,y)&&y.setDate(y.getDate()+1),g.record.end=y}return g};var Yn=e=>e.record?.start??e.plan?.start??e.base,ux=e=>e.record?.end??(lx(e.plan?.duration)?e.base:ii(Yn(e),e.plan.duration));var xe=({title:e,base:t,plan:r,record:o})=>["",lt(t,"yyyy-MM-dd")," ",r?.start?lt(r.start,"HH:mm"):" ".repeat(5)," ",r?.duration?${r.duration/60}.padStart(4,"0"):" ".repeat(4)," ",o?.start?lt(o?.start,"HH:mm:ss"):" ".repeat(8)," ",o?.end?lt(o?.end,"HH:mm:ss"):" ".repeat(8),"",e].join("");function*mx(e){for(let t of rn(e))Co(t)||(yield t)}function*rn(e){for(let t=0;t<e.length;t++){let r=e[t],o=Co(r)?r:r.text,n=Yo(t,e),s=bt(o);if(!s){yield o;continue}yield{...s,lines:e.slice(t+1,t+1+n).map(i=>Co(i)?i:i.text)},t+=n}}var FO=5*60,li=async()=>{let e=He().position.line,t=bt(gt(e)??""),r=t?.base??new Date,o={start:t?.plan?.start?ii(t.plan.start,FO+(t.plan.duration??0)):void 0,duration:t?.plan?.duration};scrapbox.Page.insertLine(xe({title:"",base:r,plan:o,record:{}}),e+1),await scrapbox.Page.waitForSave()};var on=async()=>{let e=He().position.line,t=bt(gt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;o||(scrapbox.Page.updateLine(xe({record:{start:r?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var so=async()=>{let e=He().position.line,t=bt(gt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;r&&(scrapbox.Page.updateLine(xe({record:{start:r,end:o?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var im=async()=>{let e=He().position.line,t=bt(gt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(!r){await on();return}if(!o){await so();return}scrapbox.Page.updateLine(xe({record:{},...n}),e),await scrapbox.Page.waitForSave()};var pi=async()=>{let e=He().position.line,t=bt(gt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(r){if(o)return;await so();return}if(o)return;let s;for(let{text:a}of Cr().slice(0,(e??0)+1).reverse()){let{record:c}=bt(a)??{};if(c?.end){s=c.end;break}}let i=new Date;scrapbox.Page.updateLine(xe({record:{start:s??i,end:i},...n}),e),await scrapbox.Page.waitForSave()};var nn=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=He();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var am=(e,t=7)=>new Date((e+2592e3*((t+1)**1.5-1)/5221.154823442138)*1e3);var cm=(e,t)=>{let r,o,n,s,i=null;if(i=e.match(/^(.*?)(s|e):([^\s]+)\s+d:(\d+)/))[,o,s,n,r]=i;else if(i=e.match(/^(.*?)d:(\d+)\s+(s|e):([^\s]+)/))[,o,r,s,n]=i;else if(i=e.match(/^(.*?)(s|e):([^\s]+)/))[,o,s,n]=i;else return(i=e.match(/^(.*?)d:(\d+)/))?([,o,r]=i,{name:o.trimEnd(),duration:parseInt(r)*60}):void 0;for(let{test:a,parse:c}of DO){let l=n.match(a);if(!l)continue;let u=c(l),p=u.isDuration?em(t,u):ox(t,u);return s==="s"?{name:o.trimEnd(),start:p,...r!==void 0?{duration:parseInt(r)*60}:{}}:{name:o.trimEnd(),start:am(t.getTime()/1e3,(p.getTime()-t.getTime())/(24*60*60*1e3)),...r!==void 0?{duration:parseInt(r)*60}:{}}}},DO=[{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/(\d{4})-(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3]),hours:parseInt(e[4])})},{test:/(\d{4})-(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,year:parseInt(e[1]),month:parseInt(e[2])-1,date:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/(\d{2})-(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2]),hours:parseInt(e[3])})},{test:/(\d{2})-(\d{2})T?$/i,parse:e=>({isDuration:!1,month:parseInt(e[1])-1,date:parseInt(e[2])})},{test:/(\d{2})T(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/(\d{2})T(\d{2})$/i,parse:e=>({isDuration:!1,date:parseInt(e[1]),hours:parseInt(e[2])})},{test:/T?(\d{2}):(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/T?(\d{2})$/i,parse:e=>({isDuration:!1,hours:parseInt(e[1])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4]),minutes:parseInt(e[5])})},{test:/P(\d+)Y(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3]),hours:parseInt(e[4])})},{test:/P(\d+)Y(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,year:parseInt(e[1]),month:parseInt(e[2])-1,days:parseInt(e[3])})},{test:/P(\d+)M(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3]),minutes:parseInt(e[4])})},{test:/P(\d+)M(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2]),hours:parseInt(e[3])})},{test:/P(\d+)M(\d+)D$/i,parse:e=>({isDuration:!0,month:parseInt(e[1])-1,days:parseInt(e[2])})},{test:/P(\d+)DT(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2]),minutes:parseInt(e[3])})},{test:/P(\d+)DT(\d+)H$/i,parse:e=>({isDuration:!0,days:parseInt(e[1]),hours:parseInt(e[2])})},{test:/P(\d+)D$/i,parse:e=>({isDuration:!0,days:parseInt(e[1])})},{test:/PT?(\d+)H(\d+)M$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1]),minutes:parseInt(e[2])})},{test:/PT?(\d+)H$/i,parse:e=>({isDuration:!0,hours:parseInt(e[1])})},{test:/PT?(\d+)M$/i,parse:e=>({isDuration:!0,minutes:parseInt(e[1])})},{test:/P(\d+)W$/i,parse:e=>({isDuration:!0,weeks:parseInt(e[1])})}];var sn=async()=>{let e=new Date,[t,r]=nn(),o=Cr().slice(t,r+1).map(s=>s.text),n=o.flatMap(s=>{let i=s.trimEnd();if(i==="")return s;let{name:a,start:c,duration:l}=cm(i,e)??{};return!a||!c&&!l?s:[xe({title:a.trim(),base:c??e,plan:{start:c,duration:l},record:{}})]});if(o.join(
)!==n.join(
)){for(let s=t;s<=r;s++)scrapbox.Page.updateLine(n[s-t],s);await scrapbox.Page.waitForSave()}};var fc=async(e,t,r)=>{let o=[];for(let n=e;n<=t;n++){let s=gt(n)??"",i=bt(s);if(!i){o.push(s);continue}o.push(xe(r(i,n)))}for(let n=e;n<=t;n++)scrapbox.Page.updateLine(o[n-e],n);await scrapbox.Page.waitForSave()};var ui=async(e=1)=>{let[t,r]=nn();await fc(t,r,o=>(o.base=ke(o.base,e),o))};var mi=async()=>{let[e,t]=nn(),r=new Date;await fc(e,t,o=>(yt(o.base,r)||(o.base=r),o))};var UO="日刊記録sheet",$O=/日刊記録sheet (\d{4})-(\d{2})-(\d{2})/,fi=["[** 00:00 - 03:00] 未明","[** 03:00 - 06:00] 明け方","[** 06:00 - 09:00] 朝","[** 09:00 - 12:00] 昼前","[** 12:00 - 15:00] 昼過ぎ","[** 15:00 - 18:00] 夕方","[** 18:00 - 21:00] 夜のはじめ頃","[** 21:00 - 00:00] 夜遅く"];var lm=e=>{let t=e.match($O);if(!t)return;let[,r,o,n]=t,s=new Date(parseInt(r),parseInt(o)-1,parseInt(n));return Xt(s)?s:void 0},Pr=e=>lt(e,'${UO}' yyyy-MM-dd),an=e=>{let t=lm(e[0]);if(!t)return e;let r=jO(t),o=[],n=[];for(let a of rn(e.slice(1))){if(typeof a=="string"){if(fi.includes(a)||r!==""&&r===a)continue;n.push(a);continue}o.push(a)}let s=o.sort((a,c)=>en(Yn(a),Yn(c)));if(s.length===0)return[e[0],r,...fi,...n];let i=[0,0,0,0,0,0,0,0];for(let a=1;a<fi.length;a++){let c=rm(new Date(t.getFullYear(),t.getMonth(),t.getDate()),3*a),l=s.findIndex(m=>tn(Yn(m),c));if(l<0){i[a]=-1;continue}if(l===0)continue;let u=s[l-1],p=Yn(u),f=ux(u);i[a]=(f.getTime()-p.getTime())/2<c.getTime()-p.getTime()?l:l-1}return[e[0],r,...s.flatMap((a,c)=>[...i.flatMap((l,u)=>l===c?[fi[u]]:[]),xe(a),...a.lines]),...i.flatMap((a,c)=>a===-1?[fi[c]]:[]),...n]},jO=e=>yesterday: ${Pr(Yt(e,1))};var di=async(e,t)=>{let r=()=>{},o=setTimeout(()=>{let{render:n,dispose:s}=Fe();r=s,n({type:"spinner"},{type:"text",text:"formatting..."})},500);await Le(e,t,n=>an(n.map(s=>s.text))),clearTimeout(o),r()};async function*pm(e,t,r){let o=[...t],n=[];for(;o.length>0;){let s=o.shift();if(!s)break;let i=s.base,a=[s];for(let c=0;c<o.length;c++)yt(o[c].base,i)&&(a.push(...o.splice(c,1)),c--);n.push((async()=>(await Le(e,Pr(i),c=>an([...c.map(l=>l.text),...a.flatMap(l=>[xe(l),...l.lines??[]])]),r),{date:i,size:a.length}))())}yield*px(n)}var cn=async({from:{project:e,title:t},to:r})=>{let o=await ur(e,t);if(O(o))throw Z(o);let n=lm(t),{lines:s}=S(o),i=[];for(let p of mx(s))n&&yt(p.base,n)||i.push(p);let{render:a,dispose:c}=Fe();a({type:"spinner"},{type:"text",text:copying ${i.length} tasks...});let l=await It();if(O(l))throw Z(l);let u=S(l);try{let p=0,f=!1;for await(let m of pm(r,i,{socket:u})){if(m.state!=="fulfilled"){console.error(m.reason),f=!0;continue}p+=m.value.size,a({type:"spinner"},{type:"text",text:copying ${i.length-p} tasks...})}if(f){a({type:"exclamation-triangle"},{type:"text",text:"Some tasks failed to be written"});return}a({type:"spinner"},{type:"text",text:Copied. removing ${i.length} original tasks...}),await Le(e,t,m=>{let h=[];for(let g of rn(m)){if(Co(g)){h.push(g);continue}n&&yt(g.base,n)&&h.push(xe(g),...g.lines)}return h},{socket:u}),a({type:"check-circle"},{type:"text",text:"Moved"})}finally{await At(u),await Se(1e3),c()}};var Or=e=>${e}.padStart(2,"0");var ln=e=>"hours"in e,dr=(e,t)=>e.year!==t.year?e.year<t.year:e.month!==t.month?e.month<t.month:e.date!==t.date?e.date<t.date:"hours"in t?"hours"in e?e.hours*60+e.minutes<t.hours*60+t.minutes:0<t.hours*60+t.minutes:!1,Ur=e=>${${e.year}.padStart(4,"0")}-${Or(e.month)}-${Or(e.date)}${"hours"in e?T${Or(e.hours)}:${Or(e.minutes)}:""},he=e=>{let t=Ur(e);return new Date(t.includes("T")?t:${t}T00:00)},Gt=e=>({year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes()});var dx=e=>{switch(e.toLowerCase()){case"y":return"yearly";case"m":return"monthly";case"w":return"weekly";case"d":return"daily";default:return}};var hx=e=>{switch(e){case"+":return"todo";case"-":return"note";case"!":return"deadline";case".":return"done";case"~":return"up-down";default:return}},gx=e=>{switch(e){case"todo":return"+";case"note":return"-";case"deadline":return"!";case"done":return".";case"up-down":return"~"}};var hr=e=>{let t=e.match(/(?:([\+\-!~.])(\d+)?)?@(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?(?:R([YMWD])?(\d+))?(?:@(?:(\d{2}):(\d{2})|(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)?(?:\/(\d{2}):(\d{2})|\/(?:(?:(?:(\d{4})-)?(\d{2})-)?(\d{2})(?:T(\d{2}):(\d{2}))?)|D(\d+))?)?/i);if(!t)return;let[r,o,n,s,i,a,c,l,u,p,f,m,h,g,y,x,w,R,b,E,T,I,F,A,N,P,_,C,$,j,q,B,Y]=t,G=${e.slice(0,t.index).trim()}${e.slice((t.index??0)+r.length).trim()},X=yx(s,i,a,c,l);if(!Xt(he(X)))return M({name:"InvalidDateError",message:The reference point of the task "${Ur(X)}" is an invalid date.});let J=xx(X,f,m,h,u||g,p||y,x);if(J!==void 0){if(Qe(J)&&isNaN(J)||!Qe(J)&&!Xt(he(J)))return M({name:"InvalidDateError",message:The estimated end of the task${Qe(J)?"": "${Ur(J)}"} is an invalid date.});if(Qe(J)&&J<0||!Qe(J)&&dr(J,X))return M({name:"TaskRangeError",message:The reference point of an task cannot be after its estimated end.
reference point:${Ur(X)}
estimated end:${Ur(Qe(J)?Gt(Fr(he(X),J)):J)}})}let le=/^[\uFE00-\uFE0F]*[✅❌]/.test(e)?"done":hx(o),oe=le?{status:le,refDate:X}:void 0;oe&&n&&(oe.speed=parseInt(n));let kt=yx(T||s,I||i,F||a,b||A||c,E||N||l);if(!Xt(he(kt)))return M({name:"InvalidDateError",message:The start of the task/event "${Ur(kt)}" is an invalid date.});let Oe=xx(kt,C||f,$||m,j||h,P||q||u||g,_||B||p||y,Y||x),W=ln(kt)&&Qe(Oe)?{start:kt,duration:Oe}:void 0;if(W){let Ct={name:G,executed:W,generated:!1,raw:e};return oe&&(Ct.freshness=oe),(w||R)&&(Ct.recurrence={frequency:dx(w??"D")??"daily",count:R?parseInt(R):1}),L(Ct)}if(!oe)return M({name:"InvalidDateError",message:"Task requires freshness to be spec"});let Ee={name:G,freshness:oe,generated:!1,raw:e};return J&&(Ee.estimated=J),L(W?{...Ee,executed:W}:Ee)},$r=e=>!("executed"in e),Io=e=>"recurrence"in e,bx=e=>!("executed"in e||"freshness"in e&&ln(e.freshness.refDate)&&e.estimated&&(Qe(e.estimated)||ln(e.estimated))),gi=e=>"executed"in e?e.executed.duration:Qe(e.estimated)?e.estimated:void 0,jr=e=>$r(e)?e.freshness.refDate:e.executed.start,Ex=e=>{if(!$r(e)){let r=he(e.executed.start);return Gt(Fr(r,e.executed.duration))}if(Qe(e.estimated)&&ln(e.freshness.refDate)){let r=he(e.freshness.refDate);return Gt(Fr(r,e.estimated))}let t=he(Qe(e.estimated)?e.freshness.refDate:e.estimated??e.freshness.refDate);return t.setHours(0),t.setMinutes(0),Gt(ke(t,1))},zO=e=>{let t=e.freshness?${gx(e.freshness.status)}${e.freshness.speed??""}:"",r=${Ur(jr(e))},o=gi(e);return${t}@${r}${o===void 0?"":D${o}}${e.name}},dc=(e,t)=>{let r=Gt(t),{recurrence:o,executed:n}=e;switch(o.frequency){case"yearly":{if(Math.abs(r.year-n.start.year)%(o.count??1)!==0||n.start.month!==r.month||n.start.date!==r.date)return;break}case"monthly":{if(mc(he(r),he(n.start))%(o.count??1)!==0)return;break}case"weekly":case"daily":{let a=o.frequency==="weekly"?7:1;if(no(he(r),he(n.start))%((o.count??1)*a)!==0)return;break}}let s={...n.start};s.year=r.year,s.month=r.month,s.date=r.date;let i={name:e.name,executed:{start:s,duration:n.duration},generated:!0,raw:e.raw};return e.freshness&&(i.freshness=e.freshness),i},hc=e=>e.freshness?e.generated?zO(e):e.raw:e.generated?void 0:e.raw,yx=(e,t,r,o,n)=>{let s=parseInt(e),i=parseInt(t),a=parseInt(r),c=o?parseInt(o):void 0,l=n?parseInt(n):void 0;return c!==void 0&&l!==void 0?{year:s,month:i,date:a,hours:c,minutes:l}:{year:s,month:i,date:a}},xx=(e,t,r,o,n,s,i)=>{if(!t&&!r&&!o&&!n&&!s&&!i)return;if(i)return parseInt(i);let a=t?parseInt(t):e.year,c=r?parseInt(r):e.month,l=o?parseInt(o):e.date,u=n?parseInt(n):void 0,p=s?parseInt(s):void 0,f=u!==void 0&&p!==void 0?{year:a,month:c,date:l,hours:u,minutes:p}:{year:a,month:c,date:l};return!ln(e)||!ln(f)?f:Math.round((he(f).getTime()-he(e).getTime())/(60*1e3))};var pn=(e,t)=>{if(!e.generated&&Io(e)){let s=dc(e,t);return s?pn(s,t):void 0}let r=he($r(e)?e.freshness.refDate:e.executed.start),o=gi(e),n=hc(e);return{title:n!==void 0?${n}:e.name,base:r,plan:{start:bx(e)?void 0:r,duration:o!==void 0?o*60:void 0},record:{}}};var um={あさごはん:"#log-breakfast",ひるごはん:"#log-lunch",よるごはん:"#log-dinner"},un=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=bt(n);if(!i)return;if(s.length===0)return{text:e,pages:[]};let{title:a,base:c,record:l,...u}=i,p=VO(a,c,l),f=xe({title:${p},base:c,record:l,...u}),m=Math.min(...s.map(g=>or(g))),h=[.../[\[\]]/.test(a)&&a!==${p}?[a]:[],...t in um?[...s.map(g=>g.slice(m)),"",um[t],"#log-eatenfood"]:[...s.map(g=> ${g.slice(m)}),""]];return{text:f,pages:[{project:r,title:p,lines:wx(t,h,[l.start??c]),mode:o}]}};un.hookName="task-hook";var VO=(e,t,r)=>{let o=qt(r.start??t,"yyyy-MM-dd");if(e in um)return${o} ${e};if(hr(e.slice(1,-1)))return e.slice(1,-1);let n=e.replace(/[\[\]]/g,"").trim();return${n}${n.endsWith(o)?"": ${o}}},mn=(e,{title:t,projectTo:r,mode:o,lines:n})=>{let[s,...i]=e.split(
);if(i.length===0)return;let a=s.replace(/[\[\]]/g,"").trim(),c=Math.min(...i.map(p=>or(p))),l=r.startsWith("takker")?Zy([new Date,...n.map(({updated:p})=>new Date(p*1e3))]).sort((p,f)=>f.getTime()-p.getTime()):[],u=["",.../[\[\]]/.test(s)?[s.trimStart()]:[],...i.map(p=>p.slice(c))];return{text:${" ".repeat(or(s))}${a},pages:[{project:r,title:a,lines:wx(t,u,l),mode:o}]}};mn.hookName="new-page-hook";var fn=(e,{projectTo:t,mode:r})=>{if(e.includes(
)||!/\[[^\]]+\]/.test(e))return;let[o,n]=e.match(/^(\s*)(.*)$/)?.slice?.(1)??["",e],s=[...n.matchAll(/\[([^\]])\]/g)].map(a=>ce(a[1])),i=n.replaceAll("[","").replaceAll("]","");return{text:${o}${i},pages:[{project:t,title:i,lines:(a,{links:c})=>{let l=c.map(u=>ce(u));if(!s.every(u=>l.includes(u)))return[...a.map(u=>u.text),n]},mode:r}]}};fn.hookName="splitted-link-hook";var wx=(e,t,r)=>(o,{links:n})=>{let s=n.map(p=>ce(p)),i=s.includes(ce(e))?[]:[from ${e}],a=r.flatMap(p=>{let f=qt(p,"yyyy-MM-dd");if(s.includes(f))return[];let m=qt(p,"HH:mm:ss");return[#${f} ${m}]}),c=o.map(p=>p.text),l=c.findIndex(p=>/^#\d{4}-\d{2}-\d{2}/.test(p)),u=l<0?c.length:l;return[...c.slice(0,u),...i,...t,"",...a,...c.slice(u)]};var Rx=e=>e.preventDefault(),vx=e=>e.stopPropagation(),kx={"<A-a><A-t>":async e=>{Rx(e),vx(e);let[t,r]=KO(),o=Cr().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=hr(i);if(!a||O(a))return s;let c=S(a);if(c.freshness?.status==="done")return s;let l=pn(c,new Date);return l?(l.title=${i},xe(l)):s}).join(
);await za(t,r,o),await sn()},"<A-a><A-m>":e=>{scrapbox.Layout==="page"&&(Rx(e),vx(e),cn({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"}))}},KO=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=He();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var dn=e=>e.preventDefault(),hn=e=>e.stopPropagation(),mm={"<A-a><A-a>":e=>{dn(e),hn(e),li()},"<A-a><A-s>":e=>{dn(e),hn(e),on()},"<A-a><A-e>":e=>{dn(e),hn(e),so()},"<A-a><A-0>":e=>{dn(e),hn(e),pi()},"<A-a><A-1>":e=>{dn(e),hn(e),ui(1)},"<A-a><A-t>":e=>{dn(e),hn(e),mi()},"<A-a><A-f>":e=>{scrapbox.Layout==="page"&&(dn(e),hn(e),di(scrapbox.Project.name,scrapbox.Page.title))}};var Et=e=>e.preventDefault(),wt=e=>e.stopPropagation(),gn=(e,t)=>{let r=ay()?.getElementsByClassName?.("button");if(!r)return;let o=[...r].find(n=>t instanceof RegExp?t.test(n.textContent??""):n.textContent===t);o instanceof HTMLDivElement&&e.target===document.activeElement&&(Et(e),wt(e),o.click())},YO={"-":e=>gn(e,""),"]":e=>gn(e,""),c:e=>gn(e,"Copy plain"),$:e=>gn(e,""),"{":e=>gn(e,/{{c\d+}}/),"}":e=>gn(e,"reset cloze"),n:e=>gn(e,"make note")},XO={"<C-]>":e=>{let{position:{line:t,char:r}}=He(),o=ri(t,r)?.closest("a.page-link")??to(t)?.querySelector?.("a.page-link");o instanceof HTMLAnchorElement&&(Et(e),wt(e),o.click())},"<C-o>":e=>{Et(e),wt(e),history.back()}},JO={"<C-home>":e=>{Et(e),wt(e),gy()},"<C-end>":e=>{Et(e),wt(e),yy()}},Tx=[un,mn,fn],QO={"<C-X>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Et(e),wt(e),ro({project:t,mode:"self",hooks:Tx})?.())},"<C-D>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Et(e),wt(e),ro({project:t,mode:"noopen",hooks:Tx})?.())},"<C-h>":e=>{Et(e),wt(e),Ka()},"<C-j>":e=>{Et(e),wt(e),Xa()},"<C-k>":e=>{Et(e),wt(e),Ya()},"<C-l>":e=>{Et(e),wt(e),Va()},"<A-h>":e=>{Et(e),wt(e),Qa()},"<A-j>":e=>{Et(e),wt(e),ec()},"<A-k>":e=>{Et(e),wt(e),Za()},"<A-l>":e=>{Et(e),wt(e),Ja()}};scrapbox.TimeStamp.removeAllFormats();var ZO={"<A-t><A-t>":e=>{Et(e),wt(e),ct(qt(new Date,"#yyyy-MM-dd HH:mm:ss "))},"<A-t><A-j>":e=>{Et(e),wt(e),ct(qt(new Date,"yyyy-MM-dd HH:mm:ss "))},"<A-t><A-k>":e=>{Et(e),wt(e),ct(qt(new Date,"HH:mm:ss "))},"<A-t><A-l>":e=>{Et(e),wt(e),ct(qt(new Date,"yyyy-MM-dd"))}},_x={...YO,...XO,...JO,...QO,...ZO,...kx};var{render:eS}=Fe(),fm,tS=e=>{fm!==void 0&&cancelAnimationFrame(fm),fm=requestAnimationFrame(()=>eS({type:"text",text:e}))},dm=new ic({addEventListener:ky,removeEventListener:Vu},{onSequenceUpdate:tS}),Px=dm.bind({..._x,...scrapbox.Project.name==="takker-memex"?mm:{}});Px.size>0&&alert([...Px.entries()].map(([e,t])=>${e}:
${t.map(r=>- ${r}).join(`
)}).join(`
));var rS=/https?:\/\/vimeo\.com\/([0-9]+)/i,Ox=e=>{let t=e.match(rS);if(t)return t[1]};var oS=/https?:\/\/open\.spotify\.com\/(track|artist|playlist|album|episode|show)\/([a-zA-Z\d_-]+)(?:\?[^\s]{0,100}|)/,Sx=e=>{let t=e.match(oS);if(!t)return;let[,r,o]=t;return{videoId:o,pathType:r}};var nS=/https?:\/\/anchor\.fm\/[a-zA-Z\d_-]+\/episodes\/([a-zA-Z\d_-]+(?:\/[a-zA-Z\d_-]+)?)(?:\?[^\s]{0,100}|)/,Lx=e=>{let t=e.match(nS);if(!t)return;let[,r]=t;return r};var Nx=e=>{let{type:t,pathType:r,content:o,href:n,...s}=e;if(o===""){let i=La(n);if(i)return{type:"youtube",href:n,...i,...s};let a=Ox(n);if(a)return{type:"vimeo",videoId:a,href:n,...s};let c=Sx(n);if(c)return{type:"spotify",href:n,...c,...s};let l=Lx(n);if(l)return{type:"anchor-fm",videoId:l,href:n,...s};if(iS(n))return{type:"video",href:n,...s}}return sS(n)?{type:"audio",content:o,href:n,...s}:{type:"absoluteLink",content:o,href:n,...s}},sS=e=>/\.(?:mp3|ogg|wav|aac)$/.test(e),iS=e=>/\.(?:mp4|webm)$/.test(e);var aS=Object.defineProperty,cS=(e,t)=>{for(var r in t)aS(e,r,{get:t[r],enumerable:!0})},lS={};cS(lS,{andThen:()=>Ws,andThenAsync:()=>qs,flatten:()=>Pp,fromPromiseSettledResult:()=>Op,inspectBoth:()=>Np,inspectErr:()=>Lp,inspectOk:()=>Sp,isErrAnd:()=>ga,isErrAndWithEnsureType:()=>Mp,isOkAnd:()=>ya,isOkAndWithEnsureType:()=>Cp,map:()=>Xr,mapAsync:()=>ae,mapErr:()=>Ip,mapErrAsync:()=>Ae,mapOr:()=>Ap,mapOrAsync:()=>Fp,mapOrElse:()=>Gs,mapOrElseAsync:()=>Dp,orElse:()=>Up,orElseAsync:()=>xa,toNullableFromErr:()=>jp,toNullableFromOk:()=>$p,toUndefinableFromErr:()=>Hp,toUndefinableFromOk:()=>Bp,transposeToNullable:()=>Wp,transposeToUndefinable:()=>qp,tryCatchInto:()=>va,tryCatchIntoAsync:()=>ka,tryCatchIntoWithEnsureError:()=>Gp,tryCatchIntoWithEnsureErrorAsync:()=>zp,unwrapOr:()=>qo,unwrapOrElse:()=>Vp,unwrapOrElseAsync:()=>Kp,unwrapOrThrow:()=>Yp});var Mx=async()=>{let e=localStorage.getItem("projectsLastAccessed");if(!e)return[];try{let t=JSON.parse(e),r=Object.entries(t).sort(([,s],[,i])=>i-s).map(([s])=>s),o=await Sa([]);if(O(o))return r;let n=S(o).projects.map(s=>s.id);return r.filter(s=>!n.includes(s))}catch(t){if(!(t instanceof SyntaxError))throw t;return[]}};var pS;(e=>{})(pS||={});var gc="0.16.9",hm,gm,Cx=e=>{let t=https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${e}/katex.min.js;if(gm)throw gm;if(!document.querySelector(scriptsrc="${t}")){let r=document.createElement("script");r.src=t,hm=new Promise((o,n)=>{r.onload=()=>o(window.katex),r.onerror=s=>{gm=s,n(s)},document.head.append(r)})}return hm||new Promise(r=>{let o=setInterval(()=>{window.katex&&(clearInterval(o),r(window.katex))},500)})};var yc=(e,t)=>{let[r,o]=Q("");return{ref:D(s=>{s&&Cx(gc).then(i=>{try{i.render(e,s,t),o("")}catch(a){if(a instanceof Error&&a.name==="ParseError")o(a.message.slice(19));else throw a}})},[e,...Object.values(t??{})]),error:r}};var Ix=e=>{let t=[],r=new Set,o=n=>{r.delete(n);let s=t.pop();if(!s)return;let i=s[0]().finally(()=>o(i)).then(a=>s[1](a)).catch(a=>s[2](a));r.add(i)};return n=>{if(r.size<e){let s=n().finally(()=>o(s));return r.add(s),s}return new Promise((s,i)=>{t.push([n,s,i])})}};var uS="0.6.5",Dx=ScrapBubble-${uS},Ax=await globalThis.caches.open(Dx);(async()=>{for(let e of await globalThis.caches.keys())e.startsWith("ScrapBubble-")&&e!==Dx&&(await globalThis.caches.delete(e),console.log(ScrapBubble deleted old cache :"${e}"))})();var Fx=Ix(3);async function*xc(e,t){let r=((t?.saveFailedResponse?Ax.match(e):void 0)??Oo(e,t)).then(i=>["cache",i]);{let i=Se(1e3).then(()=>"timeout"),a=await Promise.race([r,i]);if(a!=="timeout"){a[1]&&(yield["cache",a[1]]);let c=await Fx(()=>fetch(e));!c.ok&&t?.saveFailedResponse&&await Ax.put(e,c.clone()),yield["network",c]}}let o=Fx(()=>fetch(e)).then(i=>["network",i]),[n,s]=await Promise.race([r,o]);if(n==="network"){yield[n,s];return}s&&(yield[n,s]),yield await o}var Ux=(e,t)=>new Date(e.headers.get("Date")??0).getTime()/1e3+t<new Date().getTime()/1e3;var bc=()=>{let e=new Map;return{dispatch:(t,r)=>{let o=e.get(t);if(o)for(let n of o)n(r)},on:(t,r)=>{let o=e.get(t)??new Set;o.add(r),e.set(t,o)},off:(t,r)=>{let o=e.get(t);o&&o.delete(r)}}};var nr=!1,$x=e=>{nr=typeof e=="boolean"?e:new Set(e)},Ao=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...o)=>r(%c${e},"color: gray",...o)];case"log":case"info":case"debug":return[t,(...o)=>{nr!==!0&&(!nr||!nr.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{nr!==!0&&(!nr||!nr.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{nr!==!0&&(!nr||!nr.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(nr!==!0&&(!nr||!nr.has(e))))return r(...o)}]}}));var ym=bc(),Ec=new Map,mS=Ao("ScrapBubble:useProject.ts"),jx=e=>{let[t,r]=Q();return te(()=>{ym.on(e,r);let o=Ec.get(e);return o?r(o.loading?void 0:o.value):(Ec.set(e,{loading:!0}),r(void 0),(async()=>{try{let n=zo.toRequest(e);for await(let[,s]of xc(n)){let i=await zo.fromResponse(s);Ec.set(e,{loading:!1,value:i}),ym.dispatch(e,i);break}}catch(n){mS.error(n),Ec.delete(e)}})()),()=>ym.off(e,r)},[e]),t};var fS=["default-light","default-dark","default-minimal"],dS=["paper-light","paper-dark-dark","paper-dark"],Bx=["blue","purple","green","orange","red"],hS=["hacker1","hacker2"],Hx=["winter","spring","summer","automn"],Wx=["tropical"],qx=["kyoto","newyork","paris"],Gx=["mred","lgreen"],lue=["default-light","default-minimal","paper-light",...Bx,...Hx,...Wx,...qx,...Gx];var gS=[...fS,...dS,...Bx,...hS,...Hx,...Wx,...qx,...Gx];function zx(e){return gS.includes(e)}var Vx="default-light",yn=e=>{let t=jx(e);return H(()=>{if(!t||O(t))return Vx;let r=S(t).theme;return zx(r)?r:Vx},[t])};var Xn=(e,t)=>new Promise(r=>{let o=!1,n=()=>{o=!0,r(!1)};e.addEventListener("click",n),e.addEventListener("pointerleave",n),setTimeout(()=>{o||r(!0),e.removeEventListener("click",n),e.removeEventListener("pointerleave",n),r(!1)},t)});var Jn=e=>{let{top:t,right:r,left:o,bottom:n}=e.getBoundingClientRect(),s=document.body.getBoundingClientRect(),i=(o-s.left)/s.width>.5;return{top:Math.round(n-s.top),bottom:Math.round(globalThis.innerHeight-globalThis.scrollY-t),...i?{right:Math.round(s.right-r)}:{left:Math.round(o-s.left)},maxWidth:i?r-10:document.documentElement.clientWidth-o-10}};var Kx=({project:e,title:t,descriptions:r,thumbnail:o,linkTo:n,bubble:s,delay:i,prefetch:a})=>{let c=H(()=>o?[]:at(r.join(
),{hasTitle:!1}),[o,r]),l=yn(e),u=D(async({currentTarget:f})=>{a(e,t),await Xn(f,i)&&s({project:e,title:t,linkTo:n,type:"link",position:Jn(f)})},[e,t,i,n?.project,n?.titleLc]),p=H(()=>n?()=>{Kn({type:"page",from:{project:n.project??e,title:n.titleLc},to:{project:e,title:t}})}:()=>{},[e,t,n?.project,n?.titleLc]);return d("a",{className:"related-page-card page-link",type:"link","data-theme":l,href:/${e}/${se(t)},rel:e===scrapbox.Project.name?"route":"noopner noreferrer",target:e!==scrapbox.Project.name?"_blank":"",onPointerEnter:u,onClick:p,children:[d("div",{class:"hover"}),d("div",{class:"content",children:[d("div",{class:"header",children:d("div",{class:"title",children:t})}),o?d("div",{class:"thumbnail",children:d("img",{src:o})}):d("div",{class:"description",children:c.flatMap((f,m)=>f.type==="line"?[d("p",{children:f.nodes.map(h=>d(Yx,{node:h,project:e}))},m)]:[])})]})]})},Yx=({node:e,project:t})=>{switch(e.type){case"code":return d("code",{children:e.text});case"formula":return d(yS,{node:e});case"commandLine":return d("code",{children:[e.symbol," $",e.text]});case"helpfeel":return d("code",{children:["? ",e.text]});case"quote":case"strong":case"decoration":return d(ee,{children:e.nodes.map(r=>d(Yx,{node:r,project:t}))});case"icon":case"strongIcon":return d(xS,{node:e,project:t});case"hashTag":return d(bS,{node:e});case"link":return d(ES,{node:e});case"plain":case"blank":return d(ee,{children:e.text});default:return}},yS=({node:{formula:e}})=>{let{ref:t,error:r}=yc(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},xS=({node:{pathType:e,path:t},project:r})=>{let[o,n]=e==="relative"?[r,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[r,t];return d("img",{class:"icon",src:/api/pages/${o}/${se(n)}/icon})},bS=({node:{href:e}})=>d("span",{class:"page-link",children:["#",e]}),ES=({node:{pathType:e,href:t,content:r}})=>e!=="absolute"?d("span",{class:"page-link",children:t}):d("span",{class:"link",children:r||t});var be=(e,t)=>/${e.toLowerCase()}/${ce(t)},wc=e=>{let t=e.match("/([^/]+)/(.+)");if(!t)throw SyntaxError("${e}" cannnot match "/(^/+)/(.+)");return{project:t[1],titleLc:t[2]}};var rb=Symbol.for("immer-nothing"),Xx=Symbol.for("immer-draftable"),ge=Symbol.for("immer-state");function gr(e,...t){throw new Error(Immer minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf)}var yi=Object.getPrototypeOf;function Qn(e){return!!e&&!!e[ge]}function ao(e){return e?ob(e)||Array.isArray(e)||!!e[Xx]||!!e.constructor?.[Xx]||Ri(e)||Pc(e):!1}var wS=Object.prototype.constructor.toString(),Jx=new WeakMap;function ob(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);if(t===null||t===Object.prototype)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if(typeof r!="function")return!1;let o=Jx.get(r);return o===void 0&&(o=Function.toString.call(r),Jx.set(r,o)),o===wS}function xi(e,t,r=!0){_c(e)===0?(r?Reflect.ownKeys(e):Object.keys(e)).forEach(o=>{t(o,e[o],e)}):e.forEach((o,n)=>t(n,o,e))}function _c(e){let t=e[ge];return t?t.type_:Array.isArray(e)?1:Ri(e)?2:Pc(e)?3:0}function Em(e,t){return _c(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function nb(e,t,r){let o=_c(e);o===2?e.set(t,r):o===3?e.add(r):e[t]=r}function RS(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ri(e){return e instanceof Map}function Pc(e){return e instanceof Set}function Pt(e){return e.copy_||e.base_}function wm(e,t){if(Ri(e))return new Map(e);if(Pc(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=ob(e);if(t===!0||t==="class_only"&&!r){let o=Object.getOwnPropertyDescriptors(e);delete o[ge];let n=Reflect.ownKeys(o);for(let s=0;s<n.length;s++){let i=n[s],a=o[i];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(o[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(yi(e),o)}else{let o=yi(e);if(o!==null&&r)return{...e};let n=Object.create(o);return Object.assign(n,e)}}function Tm(e,t=!1){return Oc(e)||Qn(e)||!ao(e)||(_c(e)>1&&Object.defineProperties(e,{set:Rc,add:Rc,clear:Rc,delete:Rc}),Object.freeze(e),t&&Object.values(e).forEach(r=>Tm(r,!0))),e}function vS(){gr(2)}var Rc={value:vS};function Oc(e){return e===null||typeof e!="object"?!0:Object.isFrozen(e)}var Rm={};function xn(e){let t=Rm[e];return t||gr(0,e),t}function kS(e,t){Rm[e]||(Rm[e]=t)}var bi;function vc(){return bi}function TS(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Qx(e,t){t&&(xn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function vm(e){km(e),e.drafts_.forEach(_S),e.drafts_=null}function km(e){e===bi&&(bi=e.parent_)}function Zx(e){return bi=TS(bi,e)}function _S(e){let t=e[ge];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function eb(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[ge].modified_&&(vm(t),gr(4)),ao(e)&&(e=kc(t,e),t.parent_||Tc(t,e)),t.patches_&&xn("Patches").generateReplacementPatches_(r[ge].base_,e,t.patches_,t.inversePatches_)):e=kc(t,r,[]),vm(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==rb?e:void 0}function kc(e,t,r){if(Oc(t))return t;let o=e.immer_.shouldUseStrictIteration(),n=t[ge];if(!n)return xi(t,(s,i)=>tb(e,n,t,s,i,r),o),t;if(n.scope_!==e)return t;if(!n.modified_)return Tc(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let s=n.copy_,i=s,a=!1;n.type_===3&&(i=new Set(s),s.clear(),a=!0),xi(i,(c,l)=>tb(e,n,s,c,l,r,a),o),Tc(e,s,!1),r&&e.patches_&&xn("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function tb(e,t,r,o,n,s,i){if(n==null||typeof n!="object"&&!i)return;let a=Oc(n);if(!(a&&!i)){if(Qn(n)){let c=s&&t&&t.type_!==3&&!Em(t.assigned_,o)?s.concat(o):void 0,l=kc(e,n,c);if(nb(r,o,l),Qn(l))e.canAutoFreeze_=!1;else return}else i&&r.add(n);if(ao(n)&&!a){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[o]===n&&a)return;kc(e,n),(!t||!t.scope_.parent_)&&typeof o!="symbol"&&(Ri(r)?r.has(o):Object.prototype.propertyIsEnumerable.call(r,o))&&Tc(e,n)}}}function Tc(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Tm(t,r)}function PS(e,t){let r=Array.isArray(e),o={type_:r?1:0,scope_:t?t.scope_:vc(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=o,s=_m;r&&(n=[o],s=Ei);let{revoke:i,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=i,a}var _m={get(e,t){if(t===ge)return e;let r=Pt(e);if(!Em(r,t))return OS(e,r,t);let o=r[t];return e.finalized_||!ao(o)?o:o===xm(e.base_,t)?(bm(e),e.copy_[t]=wi(o,e)):o},has(e,t){return t in Pt(e)},ownKeys(e){return Reflect.ownKeys(Pt(e))},set(e,t,r){let o=sb(Pt(e),t);if(o?.set)return o.set.call(e.draft_,r),!0;if(!e.modified_){let n=xm(Pt(e),t),s=n?.[ge];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(RS(r,n)&&(r!==void 0||Em(e.base_,t)))return!0;bm(e),io(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_[t]=!0),!0},deleteProperty(e,t){return xm(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,bm(e),io(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Pt(e),o=Reflect.getOwnPropertyDescriptor(r,t);return o&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:o.enumerable,value:r[t]}},defineProperty(){gr(11)},getPrototypeOf(e){return yi(e.base_)},setPrototypeOf(){gr(12)}},Ei={};xi(_m,(e,t)=>{Ei[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Ei.deleteProperty=function(e,t){return Ei.set.call(this,e,t,void 0)};Ei.set=function(e,t,r){return _m.set.call(this,e[0],t,r,e[0])};function xm(e,t){let r=e[ge];return(r?Pt(r):e)[t]}function OS(e,t,r){let o=sb(t,r);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}function sb(e,t){if(!(t in e))return;let r=yi(e);for(;r;){let o=Object.getOwnPropertyDescriptor(r,t);if(o)return o;r=yi(r)}}function io(e){e.modified_||(e.modified_=!0,e.parent_&&io(e.parent_))}function bm(e){e.copy_||(e.copy_=wm(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var SS=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(t,r,o)=>{if(typeof t=="function"&&typeof r!="function"){let s=r;r=t;let i=this;return function(a=s,...c){return i.produce(a,l=>r.call(this,l,...c))}}typeof r!="function"&&gr(6),o!==void 0&&typeof o!="function"&&gr(7);let n;if(ao(t)){let s=Zx(this),i=wi(t,void 0),a=!0;try{n=r(i),a=!1}finally{a?vm(s):km(s)}return Qx(s,o),eb(n,s)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===rb&&(n=void 0),this.autoFreeze_&&Tm(n,!0),o){let s=[],i=[];xn("Patches").generateReplacementPatches_(t,n,s,i),o(s,i)}return n}else gr(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...i)=>this.produceWithPatches(s,a=>t(a,...i));let o,n;return[this.produce(t,r,(s,i)=>{o=s,n=i}),o,n]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),typeof e?.useStrictIteration=="boolean"&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){ao(e)||gr(8),Qn(e)&&(e=LS(e));let t=Zx(this),r=wi(e,void 0);return r[ge].isManual_=!0,km(t),r}finishDraft(e,t){let r=e&&e[ge];(!r||!r.isManual_)&&gr(9);let{scope_:o}=r;return Qx(o,t),eb(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];if(n.path.length===0&&n.op==="replace"){e=n.value;break}}r>-1&&(t=t.slice(r+1));let o=xn("Patches").applyPatches_;return Qn(e)?o(e,t):this.produce(e,n=>o(n,t))}};function wi(e,t){let r=Ri(e)?xn("MapSet").proxyMap_(e,t):Pc(e)?xn("MapSet").proxySet_(e,t):PS(e,t);return(t?t.scope_:vc()).drafts_.push(r),r}function LS(e){return Qn(e)||gr(10,e),ib(e)}function ib(e){if(!ao(e)||Oc(e))return e;let t=e[ge],r,o=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=wm(e,t.scope_.immer_.useStrictShallowCopy_),o=t.scope_.immer_.shouldUseStrictIteration()}else r=wm(e,!0);return xi(r,(n,s)=>{nb(r,n,ib(s))},o),t&&(t.finalized_=!1),r}function ab(){class e extends Map{constructor(c,l){super(),this[ge]={type_:2,parent_:l,scope_:l?l.scope_:vc(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return Pt(this[ge]).size}has(c){return Pt(this[ge]).has(c)}set(c,l){let u=this[ge];return i(u),(!Pt(u).has(c)||Pt(u).get(c)!==l)&&(r(u),io(u),u.assigned_.set(c,!0),u.copy_.set(c,l),u.assigned_.set(c,!0)),this}delete(c){if(!this.has(c))return!1;let l=this[ge];return i(l),r(l),io(l),l.base_.has(c)?l.assigned_.set(c,!1):l.assigned_.delete(c),l.copy_.delete(c),!0}clear(){let c=this[ge];i(c),Pt(c).size&&(r(c),io(c),c.assigned_=new Map,xi(c.base_,l=>{c.assigned_.set(l,!1)}),c.copy_.clear())}forEach(c,l){let u=this[ge];Pt(u).forEach((p,f,m)=>{c.call(l,this.get(f),f,this)})}get(c){let l=this[ge];i(l);let u=Pt(l).get(c);if(l.finalized_||!ao(u)||u!==l.base_.get(c))return u;let p=wi(u,l);return r(l),l.copy_.set(c,p),p}keys(){return Pt(this[ge]).keys()}values(){let c=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{let l=c.next();return l.done?l:{done:!1,value:this.get(l.value)}}}}entries(){let c=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{let l=c.next();if(l.done)return l;let u=this.get(l.value);return{done:!1,value:[l.value,u]}}}}[Symbol.iterator](){return this.entries()}}function t(a,c){return new e(a,c)}function r(a){a.copy_||(a.assigned_=new Map,a.copy_=new Map(a.base_))}class o extends Set{constructor(c,l){super(),this[ge]={type_:3,parent_:l,scope_:l?l.scope_:vc(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return Pt(this[ge]).size}has(c){let l=this[ge];return i(l),l.copy_?!!(l.copy_.has(c)||l.drafts_.has(c)&&l.copy_.has(l.drafts_.get(c))):l.base_.has(c)}add(c){let l=this[ge];return i(l),this.has(c)||(s(l),io(l),l.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let l=this[ge];return i(l),s(l),io(l),l.copy_.delete(c)||(l.drafts_.has(c)?l.copy_.delete(l.drafts_.get(c)):!1)}clear(){let c=this[ge];i(c),Pt(c).size&&(s(c),io(c),c.copy_.clear())}values(){let c=this[ge];return i(c),s(c),c.copy_.values()}entries(){let c=this[ge];return i(c),s(c),c.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(c,l){let u=this.values(),p=u.next();for(;!p.done;)c.call(l,p.value,p.value,this),p=u.next()}}function n(a,c){return new o(a,c)}function s(a){a.copy_||(a.copy_=new Set,a.base_.forEach(c=>{if(ao(c)){let l=wi(c,a);a.drafts_.set(c,l),a.copy_.add(l)}else a.copy_.add(c)}))}function i(a){a.revoked_&&gr(3,JSON.stringify(Pt(a)))}kS("MapSet",{proxyMap_:t,proxySet_:n})}var zt=new SS,Sc=zt.produce,Lue=zt.produceWithPatches.bind(zt),Nue=zt.setAutoFreeze.bind(zt),Mue=zt.setUseStrictShallowCopy.bind(zt),Cue=zt.setUseStrictIteration.bind(zt),Iue=zt.applyPatches.bind(zt),Aue=zt.createDraft.bind(zt),Fue=zt.finishDraft.bind(zt);ab();var cb=e=>{let t=0;for(let r of e)if(r&&(r.exists||(t+=(r.linked?.length??0)+(r.projectLinked?.length??0),t>1)))return!1;return t<2},lb=(e,t)=>Sc(e,r=>{if(!r)return t;if(r.updated<t.updated){let{lines:o,linked:n,projectLinked:s,...i}=t;Object.assign(r,i),Pm(t)||(r.lines=o),n&&(r.linked??=n),s&&(r.projectLinked??=s);return}Pm(r)&&!Pm(t)&&(r.lines=t.lines),t.linked&&(t.isLinkedCorrect||!r.isLinkedCorrect&&(r.linked?.length??0)<=t.linked.length)&&(r.linked=t.linked),t.projectLinked&&(r.projectLinked=t.projectLinked)}),Pm=e=>e.lines[0].id==="dummy";var pb=(e,t)=>{let r=new Map,o=ce(t.title);for(let c of t.links){let l=Om(e,c);l.linked=[o],r.set(be(e,c),l)}let n=be(e,o),s=t.projectLinks.map(c=>{let l=wc(c);return be(l.project,l.titleLc)}),i={...Lc(e,t),linked:[],projectLinked:[]};r.set(n,i);let a=t.links.map(c=>ce(c));for(let c of t.relatedPages.links1hop){c.linksLc.includes(o)&&i.linked.push(c.titleLc);for(let f of c.linksLc.filter(m=>a.includes(m))){let m=be(e,f),h=r.get(m)??Om(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=be(e,c.titleLc),u=Lc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}for(let c of t.relatedPages.projectLinks1hop){let l=be(c.projectName,c.titleLc);s.includes(l)||i.projectLinked.push(l);let u=Lc(c.projectName,c),p=r.get(l)?.projectLinked;p&&(u.projectLinked=p),r.set(l,u)}i.isLinkedCorrect=!0;for(let c of t.relatedPages.links2hop){for(let f of c.linksLc){let m=be(e,f),h=r.get(m)??Om(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=be(e,c.titleLc),u=Lc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}return r},Lc=(e,t)=>({project:e,titleLc:"titleLc"in t?t.titleLc:ce(t.title),exists:"persistent"in t?t.persistent:!0,descriptions:"descriptions"in t?t.descriptions??[]:[],image:t.image,lines:"lines"in t?t.lines:[t.title,...t.descriptions??[]].map(r=>({text:r,id:"dummy",userId:"dummy",updated:t.updated,created:t.updated})),updated:t.updated,isLinkedCorrect:!1}),Om=(e,t)=>({project:e,titleLc:ce(t),exists:!1,descriptions:[],image:null,lines:[{text:t,id:"dummy",userId:"dummy",updated:0,created:0}],updated:0,isLinkedCorrect:!1});var Nc=Ao("ScrapBubble:bubble.ts"),Sm=new Map,Mc=new Set,Lm=bc();function*mb(e){for(let t of e)yield Sm.get(t)}var fb=(e,t)=>Lm.on(e,t),db=(e,t)=>Lm.off(e,t),hb=async(e,t,r,o)=>{let n=[];for(let s of[...t].reverse()){let i=be(s,e);Mc.has(i)||n.push(NS(s,e,r,o))}await Promise.all(n)},ub=0,NS=async(e,t,r,o)=>{let n=be(e,t);if(Mc.has(n))return;Mc.add(n);let s=ub++,i=${s} Check update ${n};Nc.time(i);try{let a=ur.toRequest(e,t,{followRename:!0,projects:[...r]});for await(let[c,l]of xc(a,{ignoreSearch:!0,saveFailedResponse:!0})){Nc.debug(${s}${c} ${n});let u=await ur.fromResponse(l);if(K(u)){let p=pb(e,S(u));for(let[f,m]of p){let h=Sm.get(f),g=lb(h,m);g&&h!==g&&(Sm.set(f,g),Lm.dispatch(f,m))}}if(o?.ignoreFetch===!0||c==="cache"&&!Ux(l,o?.maxAge??60))break}}catch(a){Nc.error(a)}finally{Mc.delete(n),Nc.timeEnd(i),ub--}};var gb=Ao("ScrapBubble:useBubbleData.ts"),Zn=e=>{let[t,r]=Q(Nm(e));return te(()=>{r(Nm(e));let o,n=()=>{clearTimeout(o),o=setTimeout(()=>{gb.debug(Update ${e.length} pages),r(Nm(e))},10)};return e.forEach(s=>fb(s,n)),()=>e.forEach(s=>db(s,n))},e),t},Nm=e=>{let t=[...mb(e)].flatMap(r=>r?[r]:[]);return gb.debug(Required: ${e.length} pages, ${t.length} found,t),t};var yb=({source:e,linked:t,externalLinked:r,projectsForSort:o,...n})=>{let s=H(()=>[...t.keys(),...r.keys()],[t,r]),i=Zn(s),a=H(()=>[...o],[o]),c=H(()=>{let u=(p,f)=>{let m=a.indexOf(p.project),h=a.indexOf(f.project);return m===h?f.updated-p.updated:m<0?1:h<0?-1:m-h};return[...i].sort(u)},[i,a]),l=H(()=>({bottom:${e.position.bottom}px,maxWidth:${e.position.maxWidth}px,..."left"in e.position?{left:${e.position.left}px}:{right:${e.position.right}px}}),[e.position]);return d("ul",{className:"card-bubble",style:l,onClick:n.onClick,children:c.map(({project:u,titleLc:p,lines:[{text:f}],descriptions:m,image:h})=>{let g=be(u,p),y=t.get(g)??r.get(g);return d("li",{children:d(Kx,{project:u,title:f,linkTo:y,descriptions:m,thumbnail:h??"",...n})},g)})})};var es=e=>{e:if(e.pathType==="root"){let[,r="",o=""]=e.href.match(/\/([\w\-]+)(?:\/?|\/(.*))$/)??["","",""];if(r==="")break e;let[,n]=o?.match?.(/#([a-f\d]{24,32})$/)??["",""];return o===""?{project:r}:n===""?{project:r,title:o}:{project:r,title:o.slice(0,-1-n.length),hash:n}}let[,t]=e.href.match(/#([a-f\d]{24,32})$/)??["",""];return t===""?{title:e.href}:{title:e.href.slice(0,-1-t.length),hash:t}};var Mm=(e,t)=>t.some(r=>{let o=!e.project;switch(r.type){case"hashTag":return o&&ce(r.href)===e.titleLc;case"link":{if(r.pathType=="absolute"||r.pathType==="relative"!==o)return!1;let{project:n,title:s=""}=es({pathType:r.pathType,href:r.href});return o?!n&&ce(s)===e.titleLc:n===e.project&&ce(s)===e.titleLc}case"quote":case"strong":case"decoration":return Mm(e,r.nodes)}});var Fo=Qs({title:"",project:"",whiteList:new Set,bubble:()=>{},hide:()=>{},delay:0,prefetch:()=>{}}),bb=({lines:e,project:t,title:r,whiteList:o,noIndent:n,hash:s,linkTo:i,...a})=>{let c=H(()=>e.flatMap(m=>typeof m=="string"?[]:[m.id]),[e]),l=H(()=>{let m=0;return at(e.map(h=>typeof h=="string"?h:h.text).join(
),{hasTitle:!0}).map(h=>{switch(h.type){case"title":case"line":return{...h,id:c[m++]};case"codeBlock":{let g=m;return m+=h.content.split(
).length+1,{...h,ids:c.slice(g,m)}}case"table":{let g=m;return m+=h.cells.length+1,{...h,ids:c.slice(g,m)}}}})},[e,c]),u=H(()=>{if(s&&c.includes(s))return s;if(i)return l.find(m=>m.type!=="line"?!1:Mm(i,m.nodes))?.id},[l,c,s,i?.project,i?.titleLc]),p=dt(null);te(()=>{if(!u)return;let m=p.current?.querySelector(data-id="${u}"),h=globalThis.scrollY;m?.scrollIntoView?.({block:"center"}),globalThis.scroll(0,h)},[u]);let f=yn(t);return d("div",{className:"lines","data-theme":f,ref:p,children:d(Fo.Provider,{value:{project:t,title:r,whiteList:o,...a},children:l.map(m=>{switch(m.type){case"title":return d(ee,{children:[d(rs,{index:m.id,indent:0,noIndent:n,permalink:m.id===u,children:d("a",{className:"page-link",type:"link",href:/${t}/${se(m.text)},rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",children:m.text})},m.id),d("hr",{})]});case"codeBlock":return d(MS,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"table":return d(CS,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"line":return d(rs,{index:m.id,indent:m.indent,noIndent:n,permalink:m.id===u,children:m.nodes.length>0?m.nodes.map(h=>d(ts,{node:h},h.raw)):d("br",{})},m.id)}})})})},rs=({index:e,indent:t,noIndent:r,children:o,permalink:n})=>d("div",{className:line${n?" permalink":""},"data-id":e,"data-indent":t,style:{"margin-left":r?"":${1*t}em},children:o}),MS=({block:{fileName:e,content:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=eo(Fo),[a,c]=Q(""),l=D(async u=>{u.preventDefault(),u.stopPropagation();try{await navigator.clipboard.writeText(t),c("Copied"),await Se(1e3),c("")}catch(p){alert(Failed to copy the code block
Error: ${p})}},[t]);return d(ee,{children:[d(rs,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"code-block",children:[d("span",{className:"code-block-start",children:d("a",{href:/api/code/${s}/${se(i)}/${e},target:"_blank",children:e})}),d("span",{className:"copy",title:"Copy",onClick:l,children:a})]})}),d(ee,{children:t.split(
).map((u,p)=>d(rs,{index:o[p+1],indent:r,permalink:o[p+1]===n,children:d("code",{className:"code-block",children:u})}))})]})},CS=({block:{fileName:e,cells:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=eo(Fo);return d(ee,{children:[d(rs,{index:o[0],indent:r,permalink:o[0]===n,children:d("span",{className:"table-block",children:d("span",{className:"table-block-start",children:d("a",{href:/api/table/${s}/${se(i)}/${e}.csv,target:"_blank",children:e})})})}),d(ee,{children:t.map((a,c)=>d(rs,{index:o[c+1],indent:r,permalink:o[c+1]===n,children:d("span",{className:"table-block table-block-row",children:a.map((l,u)=>d("span",{className:cell col-${u},children:l.map(p=>d(ts,{node:p},p.raw))}))})}))})]})},ts=({node:e})=>{switch(e.type){case"code":return d("code",{className:"code",children:e.text});case"formula":return d(IS,{node:e});case"commandLine":return d(FS,{node:e});case"helpfeel":return d("code",{className:"helpfeel",children:[d("span",{className:"prefix",children:"?"})," ",d("span",{className:"entry",children:e.text})]});case"quote":return d("blockquote",{className:"quote",children:e.nodes.map(t=>d(ts,{node:t},t.raw))});case"strong":return d("strong",{children:e.nodes.map(t=>d(ts,{node:t},t.raw))});case"decoration":return d(AS,{node:e});case"plain":case"blank":return d(ee,{children:e.text});case"hashTag":return d($S,{node:e});case"link":return d(jS,{node:e});case"googleMap":return d(DS,{node:e});case"icon":return d(xb,{node:e});case"strongIcon":return d(xb,{node:e,strong:!0});case"image":return d(US,{node:e});case"strongImage":return d("img",{className:"image strong-image",src:e.src});case"numberList":return d(ee,{children:[${e.number}. ,e.nodes.map(t=>d(ts,{node:t},t.raw))]})}},IS=({node:{formula:e}})=>{let{ref:t,error:r}=yc(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},AS=({node:{decos:e,nodes:t}})=>d("span",{className:e.map(r=>deco-${r}).join(" "),children:t.map(r=>d(ts,{node:r},r.raw))}),FS=({node:e})=>{let[t,r]=Q(""),o=D(async n=>{n.preventDefault(),n.stopPropagation();try{await navigator.clipboard.writeText(e.text),r("Copied"),await Se(1e3),r("")}catch(s){alert(Failed to copy the code block
Error: ${s})}},[e.text]);return d(ee,{children:[d("code",{className:"cli",children:[d("span",{className:"prefix",children:e.symbol})," ",d("span",{className:"command",children:e.text})]}),d("span",{className:"tool-buttons",children:d("span",{title:"Copy",className:"copy",onClick:o,children:t})})]})},DS=({node:{place:e,latitude:t,longitude:r,zoom:o}})=>d("span",{className:"pointing-device-map",children:d("a",{href:https://www.google.com/maps/search/${e}/@${t},${r},${o}z,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"google-map",src:/api/google-map/static-map?center=${t}%2C${r}&markers=${e}&zoom=${o}&_csrf=${globalThis._csrf}})})}),xb=({node:{pathType:e,path:t},strong:r})=>{let{project:o}=eo(Fo),[n,s]=e==="relative"?[o,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[o,t],i=se(s);return d("a",{href:/${n}/${i},rel:n===scrapbox.Project.name?"route":"noopener noreferrer",target:n===scrapbox.Project.name?"":"_blank",children:d("img",{className:r?"icon strong-icon":"icon",alt:s,src:/api/pages/${n}/${i}/icon})})},US=({node:{link:e,src:t}})=>{let r=e||(/https:\/\/gyazo\.com\/[^\/]+\/thumb\/1000/.test(t)?t.slice(0,-11):t);return d("a",{className:e?"link":"",href:r,rel:"noopner noreferrer",target:"_blank",children:d("img",{className:"image",src:t})})},$S=({node:{href:e}})=>{let{project:t}=eo(Fo),r=Eb(t,e),o=wb(t,e,"hashtag");return d("a",{href:/${t}/${se(e)},className:page-link${r?" empty-page-link":""},type:"hashTag",rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank",onPointerEnter:o,children:["#",e]})},jS=({node:{pathType:e,...t}})=>{switch(e){case"relative":case"root":return d(BS,{pathType:e,href:t.href});case"absolute":{let r=Nx({pathType:e,...t});switch(r.type){case"youtube":return d(HS,{...r});case"vimeo":return d(WS,{...r});case"spotify":return d(qS,{...r});case"anchor-fm":return d(GS,{...r});case"audio":return d(zS,{...r});case"video":return d(KS,{...r});case"absoluteLink":return d("a",{className:"link",href:r.href,rel:"noopener noreferrer",target:"_blank",children:r.content||r.href})}}}},BS=({pathType:e,href:t})=>{let{project:r}=eo(Fo),{project:o=r,title:n,hash:s=""}=es({pathType:e,href:t}),i=wb(o,n,"link",s),a=Eb(o,n??"");return d("a",{className:page-link${n!==void 0&&a?" empty-page-link":""},type:"link",href:/${o}${n===void 0?"":/${se(n)}${s===""?"":#${s}}},rel:o===scrapbox.Project.name?"route":"noopener noreferrer",target:o===scrapbox.Project.name?"":"_blank",onPointerEnter:i,children:t})},HS=e=>{e.params.append("autoplay","0");let t=e.pathType==="list"?https://www.youtube.com/embed/?${e.params.toString()}&list=${e.listId}:https://www.youtube.com/embed/${e.videoId}?${e.params.toString()};return d("div",{className:"iframe-video-player",children:d("iframe",{src:t,allowFullScreen:!0})})},WS=({videoId:e})=>d("div",{className:"iframe-video-player",children:d("iframe",{src:https://player.vimeo.com/video/${e},allowFullScreen:!0})}),qS=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:spotify type-${e.pathType},src:https://open.spotify.com/embed/${e.pathType}/${e.videoId},allowFullScreen:!0})}),GS=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:"anchor-fm",src:e.href.replace("/episodes/","/embed/episodes/"),allowFullScreen:!0})}),zS=e=>e.content===""?d("audio",{className:"audio-player",preload:"none",controls:!0,src:e.href}):d(VS,{...e}),VS=({href:e,content:t})=>{let r=dt(null),o=D(()=>{r.current?.paused?(r.current.currentTime=0,r.current.play()):r.current?.pause?.()},[]);return d("span",{className:"audio-link",children:[d("a",{href:e,rel:"noopener noreferrer",target:"_blank",children:t}),d("span",{className:"play",onClick:o,children:"♬"}),d("audio",{preload:"none",src:e,ref:r})]})},KS=({href:e})=>d("div",{className:"video-player",children:d("video",{class:"video",style:{display:"inline-block"},controls:!0,loop:!0,src:e})}),Eb=(e,t)=>{let{whiteList:r}=eo(Fo),o=H(()=>(r.has(e)?[...r]:[e,...r]).map(s=>be(s,t)),[r,e]),n=Zn(o);return H(()=>cb(n),n)},wb=(e,t,r,o)=>{let{delay:n,bubble:s,prefetch:i}=eo(Fo);return D(async({currentTarget:a})=>{t&&(i(e,t),await Xn(a,n)&&s({project:e,title:t,hash:o,type:r,position:Jn(a)}))},[e,t,o,r,n,i,s])};var Rb=({pages:e,onClick:t,source:r,whiteList:o,...n})=>{let[s,i]=Q(be(e[0].project,e[0].titleLc)),a=H(()=>({top:${r.position.top}px,maxWidth:${r.position.maxWidth}px,..."left"in r.position?{left:${r.position.left}px}:{right:${r.position.right}px}}),[r.position]);return d("div",{className:"text-bubble",style:a,onClick:t,children:[e.length>1&&d("div",{role:"tablist",children:e.map(c=>d(YS,{project:c.project,titleLc:c.titleLc,selected:s===be(c.project,c.titleLc),tabSelector:i},be(c.project,c.titleLc)))}),e.map(c=>d(XS,{selected:s===be(c.project,c.titleLc),...c,title:c.lines[0].text,hash:r.hash,linkTo:r.linkTo,whiteList:o,...n},be(c.project,c.titleLc)))]})},YS=({project:e,titleLc:t,tabSelector:r,selected:o})=>{let n=D(()=>r(be(e,t)),[e,t]),s=yn(e);return d("button",{type:"button",role:"tab","aria-selected":o,"data-theme":s,tabIndex:-1,onClick:n,children:e})},XS=({selected:e,...t})=>{let r=yn(t.project);return d("div",{role:"tabpanel","data-theme":r,hidden:!e,children:d(bb,{...t})})};var vb=Ao("ScrapBubble:Bubble.tsx"),kb=({source:e,parentTitles:t,whiteList:r,...o})=>{let n=H(()=>r.has(e.project)?new Set([e.project,...r]):new Set([e.project]),[r,e.project]),[s,i,a]=QS(e,n,r,t);return d(ee,{children:[JS(a)&&d(Rb,{pages:a,source:e,whiteList:r,onClick:o.hide,...o}),d(yb,{linked:s,externalLinked:i,onClick:o.hide,source:e,projectsForSort:n,...o})]})},JS=e=>e.length>0,QS=(e,t,r,o)=>{let[[n,s,i],a]=Q([new Map,new Map,[]]),c=H(()=>{let p=[...t].map(f=>be(f,e.title));return vb.debug("projects",p),p},[t,e.title]),l=Zn(c),u=H(()=>o.map(p=>ce(p)),[o]);return Ha(()=>{let p=new Map,f=new Map,m=[];for(let h of l){let g={project:h.project,titleLc:h.titleLc};for(let x of h.projectLinked??[]){let{project:w,titleLc:R}=wc(x);u.includes(R)&&r.has(w)||f.has(x)||f.set(x,g)}if(!r.has(h.project))continue;let y={titleLc:h.titleLc};for(let x of h.linked??[]){if(u.includes(x))continue;let w=be(h.project,x);p.has(w)||p.set(w,y)}u.includes(h.titleLc)||h.exists&&m.push(h)}a(Sc(h=>{vb.debug(depth: ${u.length}, bubbled from ${be(e.project,e.title)}, bubbles,,l,"before",h[0],"internal cards,",p,"external cards",f);for(let g of h[0].keys())p.has(g)||h[0].delete(g);for(let[g,y]of p)h[0].set(g,y);for(let g of h[1].keys())f.has(g)||h[1].delete(g);for(let[g,y]of f)h[1].set(g,y);h[2]=m}))},[l,r,u]),[n,s,i]};var Tb=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var _b=e=>{let t=H(()=>Tb(e.style,import.meta.url),[e.style]);return d(ee,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var Pb=String.raw*{box-sizing:border-box}a{background-color:transparent;text-decoration:none;cursor:pointer}img{display:inline-block;max-width:100%;max-height:100px}code{font-family:var(--code-text-font, Menlo, Monaco, Consolas, "Courier New", monospace);font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}blockquote{background-color:var(--quote-bg-color, rgba(0,0,0,.05));display:block;border-left:solid 4px #a0a0a0;padding-left:4px;margin:0}strong{font-weight:700}iframe{display:inline-block;margin:3px 0;vertical-align:middle;max-width:100%;width:640px;height:360px;border:0}audio{display:inline-block;vertical-align:middle;white-space:initial;max-width:100%}.formula{margin:auto 6px}.formula.error code{color:#fd7373}.katex-display{display:inline-block!important;margin:0!important;text-align:inherit!important}.error .katex-display{display:none}.cli{border-radius:4px}.cli .prefix{color:#9c6248}.helpfeel{background-color:#fbebdd;border-radius:4px;padding:3px!important}.helpfeel .prefix{color:#f17c00}.helpfeel .entry{color:#cc5020}.code-block{display:block;line-height:1.7em;background-color:var(--code-bg, rgba(0,0,0,.04))}.code-block-start{font-family:Menlo,Monaco,Consolas,Courier New,monospace;color:#342d9c;background-color:#ffcfc6;font-size:.9em;padding:1px 2px}.code-block-start a{color:#342d9c;text-decoration:underline}code.code-block,.table-block.table-block-row{padding-left:1em}.copy{font-family:"Font Awesome 5 Free";cursor:pointer}.table-block{white-space:nowrap}.table-block-start{padding:1px 2px;font-size:.9em;background-color:#ffcfc6}.table-block-start a{color:#342d9c;text-decoration:underline}.cell{margin:0;padding:0 2px 0 8px;box-sizing:content-box;display:inline-block;white-space:pre}.cell:nth-child(odd){background-color:#0000000a}.cell:nth-child(2n){background-color:#0000000f}.strong-image{max-height:100%}.icon{height:11px;vertical-align:middle}.strong-icon{height:13.2px}.tool-button{margin-left:1em;cursor:pointer;font-size:.9em}.deco-\/{font-style:italic}.deco-\*-1{font-weight:700}.deco-\*-2{font-weight:700;font-size:1.2em}.deco-\*-3{font-weight:700;font-size:1.44em}.deco-\*-4{font-weight:700;font-size:1.73em}.deco-\*-5{font-weight:700;font-size:2.07em}.deco-\*-6{font-weight:700;font-size:2.49em}.deco-\*-7{font-weight:700;font-size:3em}.deco-\*-8{font-weight:700;font-size:3.58em}.deco-\*-9{font-weight:700;font-size:4.3em}.deco-\*-10{font-weight:700;font-size:5.16em}.deco--{text-decoration:line-through}.deco-_{text-decoration:underline}.page-link{color:var(--page-link-color, #5e8af7)}a.page-link:hover{color:var(--page-link-hover-color, #2d67f5)}.empty-page-link{color:var(--empty-page-link-color, #fd7373)}a.empty-page-link:hover{color:var(--empty-page-link-hover-color, #fd7373)}.link{color:var(--page-link-color, #5e8af7);text-decoration:underline}a.link:hover{color:var(--page-link-color-hover-color, #2d67f5)}.link img{padding-bottom:3px;border-style:none none solid;border-width:1.5px;border-color:#8fadf9}.permalink{background-color:var(--line-permalink-color, rgba(234,218,74,.75))}.status-bar{display:inline-block;position:absolute;background-color:var(--page-bg, #fefefe);cursor:default}.status-bar>*{border:1px solid var(--status-bar-border-color, #a9aaaf)}.status-bar.top-left{top:0;left:0}.status-bar.top-left>*{border-top:none;border-left:none}.status-bar.top-left :last-of-type{border-bottom-right-radius:3px}.status-bar.top-right{top:0;right:0}.status-bar.top-right>*{border-top:none;border-right:none}.status-bar.top-right :last-of-type{border-bottom-left-radius:3px}.status-bar.bottom-right{bottom:0;right:0}.status-bar.bottom-right>*{border-bottom:none;border-right:none}.status-bar.bottom-right :last-of-type{border-top-left-radius:3px}.status-bar.bottom-left{bottom:0;left:0}.status-bar.bottom-left>*{border-bottom:none;border-left:none}.status-bar.bottom-left :last-of-type{border-top-right-radius:3px}.text-bubble{font-size:11px;line-height:1.42857;user-select:text;position:absolute;color:var(--page-text-color, #4a4a4a);box-shadow:0 6px 12px #0000002d;display:flex;flex-direction:column;z-index:9000;&.no-scroll{overflow-y:hidden}data-theme=default-dark{--text-bubble-border-color: hsl(0, 0%, 39%)}data-theme=default-minimal{--text-bubble-border-color: hsl(0, 0%, 89%)}data-theme=paper-light{--text-bubble-border-color: hsl(53, 8%, 58%)}data-theme=paper-dark-dark{--text-bubble-border-color: hsl(203, 42%, 17%)}data-theme=blue{--text-bubble-border-color: hsl(227, 68%, 62%)}data-theme=purple{--text-bubble-border-color: hsl(267, 39%, 60%)}data-theme=green{--text-bubble-border-color: hsl(136, 29%, 50%)}data-theme=orange{--text-bubble-border-color: hsl(43, 71%, 51%)}data-theme=red{--text-bubble-border-color: hsl(4, 58%, 56%)}data-theme=spring{--text-bubble-border-color: hsl(72, 64%, 57%)}data-theme=kyoto{--text-bubble-border-color: hsl(331, 21%, 26%)}data-theme=newyork{--text-bubble-border-color: hsl(176, 29%, 67%)}role=tabpanel{padding:5px 0 5px 5px;border-radius:4px;background-color:var(--page-bg, #fefefe);max-height:80vh;overflow-y:auto}role=tabpanel,button{border:1px solid var(--text-bubble-border-color, hsl(221, 15%, 25%))}button{cursor:default;color:inherit;font-size:inherit;line-height:inherit;background-color:var(--page-bg, #fefefe);border-radius:4px 4px 0 0}buttonaria-selected=true{background-color:var(--text-bubble-border-color, hsl(221, 15%, 25%))}}.project-badge{text-decoration:none;color:var(--tool-text-color, #363c49)}.related-page-carddata-theme=default-dark{--card-title-bg: hsl(0, 0%, 39%)}.related-page-carddata-theme=default-minimal{--card-title-bg: hsl(0, 0%, 89%)}.related-page-carddata-theme=paper-light{--card-title-bg: hsl(53, 8%, 58%)}.related-page-carddata-theme=paper-dark-dark{--card-title-bg: hsl(203, 42%, 17%)}.related-page-carddata-theme=blue{--card-title-bg: hsl(227, 68%, 62%)}.related-page-carddata-theme=purple{--card-title-bg: hsl(267, 39%, 60%)}.text-bubbledata-theme=green{--card-title-bg: hsl(136, 29%, 50%)}.related-page-carddata-theme=orange{--card-title-bg: hsl(43, 71%, 51%)}.related-page-carddata-theme=red{--card-title-bg: hsl(4, 58%, 56%)}.related-page-carddata-theme=spring{--card-title-bg: hsl(72, 64%, 57%)}.related-page-carddata-theme=kyoto{--card-title-bg: hsl(331, 21%, 26%)}.related-page-carddata-theme=newyork{--card-title-bg: hsl(176, 29%, 67%)}.related-page-card{display:block;position:relative;height:inherit;width:inherit;overflow:hidden;text-overflow:ellipsis;font-family:Roboto,Helvetica,Arial,Hiragino Sans,sans-serif;background-color:var(--card-bg, #fff);color:var(--card-title-color, #555);word-break:break-word;text-decoration:none}.related-page-card:hover{box-shadow:var(--card-box-hover-shadow, 0 2px 0 rgba(0,0,0,.23))}.related-page-card:focus{outline:0;box-shadow:0 0 0 3px #66afe999;border-color:#66afe9;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.related-page-card.hover{opacity:0;position:absolute;width:100%;height:100%;top:0;left:0;background-color:var(--card-hover-bg, rgba(0,0,0,.05));mix-blend-mode:multiply;z-index:1;transition:background-color .1s}.related-page-card:hover .hover{opacity:1}.related-page-card:active .hover{opacity:1;background-color:var(--card-active-bg, rgba(0,0,0,.1))}.related-page-card .content{height:calc(100% - 5px);width:inherit;display:flex;flex-direction:column;overflow:hidden}.related-page-card .content .header{width:100%;color:#396bdd;text-overflow:ellipsis;border-top:var(--card-title-bg, #f2f2f3) solid 10px;padding:8px 10px}.related-page-card .content .header .title{font-size:11px;line-height:16px;font-weight:700;max-height:48px;color:var(--card-title-color, #363c49);margin:0;overflow:hidden;display:block;-webkit-line-clamp:3;-webkit-box-orient:vertical;text-overflow:ellipsis}.related-page-card .content .description{line-height:16px;padding:8px 10px 0;font-size:10px;white-space:pre-line;column-count:1;column-gap:2em;column-width:10em;height:inherit;color:var(--card-description-color, gray);flex-shrink:16;overflow:hidden}.related-page-card .content .thumbnail{display:block;width:100%;margin:0 auto;padding:0 5px}.related-page-card .content .description p{margin:0;display:block}.related-page-card .content .description code{font-family:Menlo,Monaco,Consolas,Courier New,monospace;font-size:90%;color:var(--code-color, #342d9c);background-color:var(--code-bg, rgba(0,0,0,.04));padding:0;white-space:pre-wrap;word-wrap:break-word}.related-page-card .content .description .icon{height:9px;vertical-align:middle}.related-page-card .content .description .page-link{background-color:transparent;text-decoration:none;cursor:pointer;color:var(--page-link-color, #5e8af7)}.card-bubble{background-color:var(--page-bg, #FFF);box-shadow:0 2px 2px #00000024,0 3px 1px -2px #0003,0 1px 5px #0000001f;position:absolute;max-width:80vw;box-sizing:content-box;z-index:9000;font-size:11px;line-height:1.42857;display:flex;padding:0;margin:0;list-style:none;overflow-x:auto;overflow-y:visible}.card-bubble li{display:block;position:relative;float:none;margin:5px;box-sizing:border-box;box-shadow:var(--card-box-shadow, 0 2px 0 rgba(0,0,0,.12));border-radius:2px;width:120px;height:120px}
;var Ob=e=>e instanceof HTMLSpanElement&&e.matches(".line-title .text"),Cc=e=>e instanceof HTMLAnchorElement&&e.classList.contains("page-link");var Sb=()=>{let[e,t]=Q([{bubble:o=>r(0,o),hide:()=>r(0)}]),r=D((o,n)=>{t(([s,...i])=>[s,...n?[...i.slice(0,o),n===i.at(o)?.source?i.at(o):{source:n,parentTitles:[scrapbox.Page.title??"",...i.slice(0,o).map(a=>a.source.title)],bubble:a=>r(o+1,a),hide:()=>r(o+1)}]:[...i.slice(0,o)]])},[]);return e};var Cm=(e,t,r,o,n)=>{te(()=>(e.addEventListener(t,r,o),()=>e.removeEventListener(t,r,o)),[e,t,o,...n??[]])};var Im="scrap-bubble",Lb=({delay:e,whiteList:t,watchList:r,style:o})=>{let[{bubble:n,hide:s},...i]=Sb(),a=D((c,l)=>hb(l,t.has(c)?t:new Set([c]),r),[t,r]);return Cm(document,"pointerenter",async c=>{let l=c.target;if(!Cc(l)&&!Ob(l))return;let{project:u=scrapbox.Project.name,title:p,hash:f=""}=Cc(l)?es({pathType:"root",href:${new URL(l.href).pathname}${new URL(l.href).hash}}):{project:scrapbox.Project.name,title:scrapbox.Page.title};if(u==="")return;let m=decodeURIComponent(p??"");a(u,m),await Xn(l,e)&&n({project:u,title:m,hash:f,position:Jn(l),type:ZS(l)})},{capture:!0},[e,t,r]),Cm(document,"click",c=>{c.target.dataset.userscriptName!==Im&&s()},{capture:!0},[s]),te(()=>(scrapbox.addListener("page:changed",s),()=>scrapbox.removeListener("page:changed",s)),[s]),d(ee,{children:[d("link",{rel:"stylesheet",href:https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${gc}/katex.min.css}),d("style",{children:Pb}),d(_b,{style:o}),i.map(c=>d(kb,{...c,whiteList:t,delay:e,prefetch:a},be(c.source.project,c.source.title)))]})},ZS=e=>Cc(e)?e.type==="link"?"link":"hashtag":"title";var Nb=async e=>{let{delay:t=500,whiteList:r=[],watchList:o=(await Mx()).slice(0,100),style:n="",debug:s=!1}=e??{};$x(s);let i=document.createElement("div");i.dataset.userscriptName=Im,document.body.append(i);let a=i.attachShadow({mode:"open"});Tt(d(Lb,{delay:t,whiteList:new Set([scrapbox.Project.name,...r]),watchList:new Set(o),style:n}),a)};var eL=["takker-memex","takker-private","takker","takker-books","villagepump"],bn=[];switch(scrapbox.Project.name){case"hub":case"villagepump":case"verbalizing-community":bn.push("villagepump","hub","verbalizing-community");break;case"programming-notes":case"customize":case"scrapboxlab":bn.push("programming-notes","customize","scrapboxlab");break;case"sta":bn.push("sta-taskmanagement");break;case"sta-taskmanagement":case"taskmanagement":bn.push("sta-taskmanagement","taskmanagement");break;case"plurality-japanese":bn.push("nishio","tkgshn");case"takker-books":bn.push("work4ai");break}Nb({delay:/mobile/i.test(navigator.userAgent)?300:500,whiteList:[...eL,...bn],style:@import "/api/code/takker/kakeruの背景を白にするUserCSS/style.css";
@import "/api/code/takker/アイコン記法を画像記法っぽくするUserCSS/style2.css";});var Mb=e=>{{let r=e.match(/^([^(]+)\(([^)]+)\)$/);if(r)return{fileName:r[1],lang:r[2]}}let t=e.split(".").pop();return t===void 0?{fileName:e,lang:e}:{fileName:e,lang:t}};var os={};oa(os,{getTitle:()=>og,parse:()=>at});var Cb=(e,t,r)=>{if(r.length===0)return[];let o=r.map(a=>a.text).join(
),n=at(o,{hasTitle:!0}),s=new Map,i=0;for(let a of n)switch(a.type){case"title":case"line":{i++;break}case"table":i+=a.cells.length+1;break;case"codeBlock":{let{fileName:c,lang:l}=Mb(a.fileName),u=s.get(c);s.set(c,{path:u?.path??https://scrapbox.io/api/code/${e}/${se(t)}/${se(c)},lang:u?.lang??l,startIds:[...u?.startIds??[],r[i].id]}),i+=a.content.split(
).length+1;break}}return s.values()};function Fm(e){let t=o=>{if(o===null)r.write8(0);else if(typeof o=="boolean")r.write8(1),r.write8(+o);else if(typeof o=="number")r.write8(2),r.write32(o|0);else if(typeof o=="string")r.write8(3),r.write(Sr(o));else if(o instanceof Uint8Array)r.write8(4),r.write(o);else if(o instanceof Array){r.write8(5),r.write32(o.length);for(let n of o)t(n)}else{let n=Object.keys(o);r.write8(6),r.write32(n.length);for(let s of n)r.write(Sr(s)),t(o[s])}},r=new Ic;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),Am(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function Ib(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return ns(r.read());case 4:return r.read();case 5:{let i=r.read32(),a=[];for(let c=0;c<i;c++)a.push(t());return a}case 6:{let i=r.read32(),a={};for(let c=0;c<i;c++)a[ns(r.read())]=t();return a}default:throw new Error("Invalid packet")}},r=new Ic(e),o=r.read32(),n=(o&1)===0;o>>>=1;let s=t();if(r.ptr!==e.length)throw new Error("Invalid packet");return{id:o,isRequest:n,value:s}}var Ic=class{constructor(t=new Uint8Array(1024)){this.buf=t}len=0;ptr=0;_write(t){if(this.len+t>this.buf.length){let r=new Uint8Array((this.len+t)*2);r.set(this.buf),this.buf=r}return this.len+=t,this.len-t}write8(t){let r=this._write(1);this.buf[r]=t}write32(t){let r=this._write(4);Am(this.buf,t,r)}write(t){let r=this._write(4+t.length);Am(this.buf,t.length,r),this.buf.set(t,r+4)}_read(t){if(this.ptr+t>this.buf.length)throw new Error("Invalid packet");return this.ptr+=t,this.ptr-t}read8(){return this.buf[this._read(1)]}read32(){return Dm(this.buf,this._read(4))}read(){let t=this.read32(),r=new Uint8Array(t),o=this._read(r.length);return r.set(this.buf.subarray(o,o+t)),r}},Sr,ns,Ab;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;Sr=r=>e.encode(r),ns=r=>t.decode(r),Ab='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(Sr("")instanceof Uint8Array))throw new Error(Invariant violation: "${Ab} instanceof Uint8Array" is incorrectly false
This indicates that your JavaScript environment is broken. You cannot use
esbuild in this environment because esbuild relies on this invariant. This
is not a problem with esbuild. You need to fix your environment instead.
);function Dm(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function Am(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var vi="0.24.0";var pt=JSON.stringify,Fb="warning",Db="silent";function Ub(e){if(Ot(e,"target"),e.indexOf(",")>=0)throw new Error(Invalid target: ${e});return e}var Dc=()=>null,Ue=e=>typeof e=="boolean"?null:"a boolean",V=e=>typeof e=="string"?null:"a string",Uc=e=>e instanceof RegExp?null:"a RegExp object",wn=e=>typeof e=="number"&&e===(e|0)?null:"an integer",Bb=e=>typeof e=="function"?null:"a function",We=e=>Array.isArray(e)?null:"an array",yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",rL=e=>typeof e=="object"&&e!==null?null:"an array or an object";var $b=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",Hb=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",oL=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",nL=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",Wb=e=>typeof e=="string"||e instanceof Uint8Array?null:"a string or a Uint8Array";function k(e,t,r,o){let n=e[r];if(t[r+""]=!0,n===void 0)return;let s=o(n);if(s!==null)throw new Error(${pt(r)} must be ${s});return n}function Rt(e,t,r){for(let o in e)if(!(o in t))throw new Error(Invalid option ${r}: ${pt(o)})}function qb(e){let t;if(e!==void 0){t=Object.create(null);for(let r in e){let o=e[r];if(typeof o=="string"||o===!1)t[r]=o;else throw new Error(Expected ${pt(r)} in mangle cache to map to either a string or false)}}return t}function $c(e,t,r,o,n){let s=k(t,r,"color",Ue),i=k(t,r,"logLevel",V),a=k(t,r,"logLimit",wn);s!==void 0?e.push(--color=${s}):o&&e.push("--color=true"),e.push(--log-level=${i||n}),e.push(--log-limit=${a||0})}function Ot(e,t,r){if(typeof e!="string")throw new Error(Expected value for ${t}${r!==void 0?" "+pt(r):""} to be a string, got ${typeof e} instead);return e}function Gb(e,t,r){let o=k(t,r,"legalComments",V),n=k(t,r,"sourceRoot",V),s=k(t,r,"sourcesContent",Ue),i=k(t,r,"target",nL),a=k(t,r,"format",V),c=k(t,r,"globalName",V),l=k(t,r,"mangleProps",Uc),u=k(t,r,"reserveProps",Uc),p=k(t,r,"mangleQuoted",Ue),f=k(t,r,"minify",Ue),m=k(t,r,"minifySyntax",Ue),h=k(t,r,"minifyWhitespace",Ue),g=k(t,r,"minifyIdentifiers",Ue),y=k(t,r,"lineLimit",wn),x=k(t,r,"drop",We),w=k(t,r,"dropLabels",We),R=k(t,r,"charset",V),b=k(t,r,"treeShaking",Ue),E=k(t,r,"ignoreAnnotations",Ue),T=k(t,r,"jsx",V),I=k(t,r,"jsxFactory",V),F=k(t,r,"jsxFragment",V),A=k(t,r,"jsxImportSource",V),N=k(t,r,"jsxDev",Ue),P=k(t,r,"jsxSideEffects",Ue),_=k(t,r,"define",yr),C=k(t,r,"logOverride",yr),$=k(t,r,"supported",yr),j=k(t,r,"pure",We),q=k(t,r,"keepNames",Ue),B=k(t,r,"platform",V),Y=k(t,r,"tsconfigRaw",oL);if(o&&e.push(--legal-comments=${o}),n!==void 0&&e.push(--source-root=${n}),s!==void 0&&e.push(--sources-content=${s}),i&&(Array.isArray(i)?e.push(--target=${Array.from(i).map(Ub).join(",")}):e.push(--target=${Ub(i)})),a&&e.push(--format=${a}),c&&e.push(--global-name=${c}),B&&e.push(--platform=${B}),Y&&e.push(--tsconfig-raw=${typeof Y=="string"?Y:JSON.stringify(Y)}),f&&e.push("--minify"),m&&e.push("--minify-syntax"),h&&e.push("--minify-whitespace"),g&&e.push("--minify-identifiers"),y&&e.push(--line-limit=${y}),R&&e.push(--charset=${R}),b!==void 0&&e.push(--tree-shaking=${b}),E&&e.push("--ignore-annotations"),x)for(let G of x)e.push(--drop:${Ot(G,"drop")});if(w&&e.push(--drop-labels=${Array.from(w).map(G=>Ot(G,"dropLabels")).join(",")}),l&&e.push(--mangle-props=${l.source}),u&&e.push(--reserve-props=${u.source}),p!==void 0&&e.push(--mangle-quoted=${p}),T&&e.push(--jsx=${T}),I&&e.push(--jsx-factory=${I}),F&&e.push(--jsx-fragment=${F}),A&&e.push(--jsx-import-source=${A}),N&&e.push("--jsx-dev"),P&&e.push("--jsx-side-effects"),_)for(let G in _){if(G.indexOf("=")>=0)throw new Error(Invalid define: ${G});e.push(--define:${G}=${Ot(_G,"define",G)})}if(C)for(let G in C){if(G.indexOf("=")>=0)throw new Error(Invalid log override: ${G});e.push(--log-override:${G}=${Ot(CG,"log override",G)})}if($)for(let G in $){if(G.indexOf("=")>=0)throw new Error(Invalid supported: ${G});let X=$[G];if(typeof X!="boolean")throw new Error(Expected value for supported ${pt(G)} to be a boolean, got ${typeof X} instead);e.push(--supported:${G}=${X})}if(j)for(let G of j)e.push(--pure:${Ot(G,"pure")});q&&e.push("--keep-names")}function sL(e,t,r,o,n){let s=[],i=[],a=Object.create(null),c=null,l=null;$c(s,t,a,r,o),Gb(s,t,a);let u=k(t,a,"sourcemap",Hb),p=k(t,a,"bundle",Ue),f=k(t,a,"splitting",Ue),m=k(t,a,"preserveSymlinks",Ue),h=k(t,a,"metafile",Ue),g=k(t,a,"outfile",V),y=k(t,a,"outdir",V),x=k(t,a,"outbase",V),w=k(t,a,"tsconfig",V),R=k(t,a,"resolveExtensions",We),b=k(t,a,"nodePaths",We),E=k(t,a,"mainFields",We),T=k(t,a,"conditions",We),I=k(t,a,"external",We),F=k(t,a,"packages",V),A=k(t,a,"alias",yr),N=k(t,a,"loader",yr),P=k(t,a,"outExtension",yr),_=k(t,a,"publicPath",V),C=k(t,a,"entryNames",V),$=k(t,a,"chunkNames",V),j=k(t,a,"assetNames",V),q=k(t,a,"inject",We),B=k(t,a,"banner",yr),Y=k(t,a,"footer",yr),G=k(t,a,"entryPoints",rL),X=k(t,a,"absWorkingDir",V),J=k(t,a,"stdin",yr),le=k(t,a,"write",Ue)??n,oe=k(t,a,"allowOverwrite",Ue),kt=k(t,a,"mangleCache",yr);if(a.plugins=!0,Rt(t,a,in ${e}() call),u&&s.push(--sourcemap${u===!0?"":=${u}}),p&&s.push("--bundle"),oe&&s.push("--allow-overwrite"),f&&s.push("--splitting"),m&&s.push("--preserve-symlinks"),h&&s.push("--metafile"),g&&s.push(--outfile=${g}),y&&s.push(--outdir=${y}),x&&s.push(--outbase=${x}),w&&s.push(--tsconfig=${w}),F&&s.push(--packages=${F}),R){let W=[];for(let Ee of R){if(Ot(Ee,"resolve extension"),Ee.indexOf(",")>=0)throw new Error(Invalid resolve extension: ${Ee});W.push(Ee)}s.push(--resolve-extensions=${W.join(",")})}if(_&&s.push(--public-path=${_}),C&&s.push(--entry-names=${C}),$&&s.push(--chunk-names=${$}),j&&s.push(--asset-names=${j}),E){let W=[];for(let Ee of E){if(Ot(Ee,"main field"),Ee.indexOf(",")>=0)throw new Error(Invalid main field: ${Ee});W.push(Ee)}s.push(--main-fields=${W.join(",")})}if(T){let W=[];for(let Ee of T){if(Ot(Ee,"condition"),Ee.indexOf(",")>=0)throw new Error(Invalid condition: ${Ee});W.push(Ee)}s.push(--conditions=${W.join(",")})}if(I)for(let W of I)s.push(--external:${Ot(W,"external")});if(A)for(let W in A){if(W.indexOf("=")>=0)throw new Error(Invalid package name in alias: ${W});s.push(--alias:${W}=${Ot(AW,"alias",W)})}if(B)for(let W in B){if(W.indexOf("=")>=0)throw new Error(Invalid banner file type: ${W});s.push(--banner:${W}=${Ot(BW,"banner",W)})}if(Y)for(let W in Y){if(W.indexOf("=")>=0)throw new Error(Invalid footer file type: ${W});s.push(--footer:${W}=${Ot(YW,"footer",W)})}if(q)for(let W of q)s.push(--inject:${Ot(W,"inject")});if(N)for(let W in N){if(W.indexOf("=")>=0)throw new Error(Invalid loader extension: ${W});s.push(--loader:${W}=${Ot(NW,"loader",W)})}if(P)for(let W in P){if(W.indexOf("=")>=0)throw new Error(Invalid out extension: ${W});s.push(--out-extension:${W}=${Ot(PW,"out extension",W)})}if(G)if(Array.isArray(G))for(let W=0,Ee=G.length;W<Ee;W++){let Ct=G[W];if(typeof Ct=="object"&&Ct!==null){let Vr=Object.create(null),Kr=k(Ct,Vr,"in",V),Nr=k(Ct,Vr,"out",V);if(Rt(Ct,Vr,"in entry point at index "+W),Kr===void 0)throw new Error('Missing property "in" for entry point at index '+W);if(Nr===void 0)throw new Error('Missing property "out" for entry point at index '+W);i.push([Nr,Kr])}else i.push(["",Ot(Ct,"entry point at index "+W)])}else for(let W in G)i.push([W,Ot(G[W],"entry point",W)]);if(J){let W=Object.create(null),Ee=k(J,W,"contents",Wb),Ct=k(J,W,"resolveDir",V),Vr=k(J,W,"sourcefile",V),Kr=k(J,W,"loader",V);Rt(J,W,'in "stdin" object'),Vr&&s.push(--sourcefile=${Vr}),Kr&&s.push(--loader=${Kr}),Ct&&(l=Ct),typeof Ee=="string"?c=Sr(Ee):Ee instanceof Uint8Array&&(c=Ee)}let Oe=[];if(b)for(let W of b)W+="",Oe.push(W);return{entries:i,flags:s,write:le,stdinContents:c,stdinResolveDir:l,absWorkingDir:X,nodePaths:Oe,mangleCache:qb(kt)}}function iL(e,t,r,o){let n=[],s=Object.create(null);$c(n,t,s,r,o),Gb(n,t,s);let i=k(t,s,"sourcemap",Hb),a=k(t,s,"sourcefile",V),c=k(t,s,"loader",V),l=k(t,s,"banner",V),u=k(t,s,"footer",V),p=k(t,s,"mangleCache",yr);return Rt(t,s,in ${e}() call),i&&n.push(--sourcemap=${i===!0?"external":i}),a&&n.push(--sourcefile=${a}),c&&n.push(--loader=${c}),l&&n.push(--banner=${l}),u&&n.push(--footer=${u}),{flags:n,mangleCache:qb(p)}}function zb(e){let t={},r={didClose:!1,reason:""},o={},n=0,s=0,i=new Uint8Array(16*1024),a=0,c=R=>{let b=a+R.length;if(b>i.length){let T=new Uint8Array(b*2);T.set(i),i=T}i.set(R,a),a+=R.length;let E=0;for(;E+4<=a;){let T=Dm(i,E);if(E+4+T>a)break;E+=4,h(i.subarray(E,E+T)),E+=T}E>0&&(i.copyWithin(0,E,a),a-=E)},l=R=>{r.didClose=!0,R&&(r.reason=": "+(R.message||R));let b="The service was stopped"+r.reason;for(let E in o)o[E](b,null);o={}},u=(R,b,E)=>{if(r.didClose)return E("The service is no longer running"+r.reason,null);let T=n++;o[T]=(I,F)=>{try{E(I,F)}finally{R&&R.unref()}},R&&R.ref(),e.writeToStdin(Fm({id:T,isRequest:!0,value:b}))},p=(R,b)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(Fm({id:R,isRequest:!1,value:b}))},f=async(R,b)=>{try{if(b.command==="ping"){p(R,{});return}if(typeof b.key=="number"){let E=t[b.key];if(!E)return;let T=E[b.command];if(T){await T(R,b);return}}throw new Error("Invalid command: "+b.command)}catch(E){let T=[En(E,e,null,void 0,"")];try{p(R,{errors:T})}catch{}}},m=!0,h=R=>{if(m){m=!1;let E=String.fromCharCode(...R);if(E!==vi)throw new Error(Cannot start service: Host version "${vi}" does not match binary version ${pt(E)});return}let b=Ib(R);if(b.isRequest)f(b.id,b.value);else{let E=o[b.id];delete o[b.id],b.value.error?E(b.value.error,{}):E(null,b.value)}};return{readFromStdout:c,afterClose:l,service:{buildOrContext:({callName:R,refs:b,options:E,isTTY:T,defaultWD:I,callback:F})=>{let A=0,N=s++,P={},_={ref(){++A===1&&b&&b.ref()},unref(){--A===0&&(delete t[N],b&&b.unref())}};t[N]=P,_.ref(),aL(R,N,u,p,_,e,P,E,T,I,(C,$)=>{try{F(C,$)}finally{_.unref()}})},transform:({callName:R,refs:b,input:E,options:T,isTTY:I,fs:F,callback:A})=>{let N=Vb(),P=_=>{try{if(typeof E!="string"&&!(E instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:C,mangleCache:$}=iL(R,T,I,Db),j={command:"transform",flags:C,inputFS:_!==null,input:_!==null?Sr(_):typeof E=="string"?Sr(E):E};$&&(j.mangleCache=$),u(b,j,(q,B)=>{if(q)return A(new Error(q),null);let Y=ss(B.errors,N),G=ss(B.warnings,N),X=1,J=()=>{if(--X===0){let le={warnings:G,code:B.code,map:B.map,mangleCache:void 0,legalComments:void 0};"legalComments"in B&&(le.legalComments=B?.legalComments),B.mangleCache&&(le.mangleCache=B?.mangleCache),A(null,le)}};if(Y.length>0)return A(ki("Transform failed",Y,G),null);B.codeFS&&(X++,F.readFile(B.code,(le,oe)=>{le!==null?A(le,null):(B.code=oe,J())})),B.mapFS&&(X++,F.readFile(B.map,(le,oe)=>{le!==null?A(le,null):(B.map=oe,J())})),J()})}catch(C){let $=[];try{$c($,T,{},I,Db)}catch{}let j=En(C,e,N,void 0,"");u(b,{command:"error",flags:$,error:j},()=>{j.detail=N.load(j.detail),A(ki("Transform failed",[j],[]),null)})}};if((typeof E=="string"||E instanceof Uint8Array)&&E.length>1024*1024){let _=P;P=()=>F.writeFile(E,_)}P(null)},formatMessages:({callName:R,refs:b,messages:E,options:T,callback:I})=>{if(!T)throw new Error(Missing second argument in ${R}() call);let F={},A=k(T,F,"kind",V),N=k(T,F,"color",Ue),P=k(T,F,"terminalWidth",wn);if(Rt(T,F,in ${R}() call),A===void 0)throw new Error(Missing "kind" in ${R}() call);if(A!=="error"&&A!=="warning")throw new Error(Expected "kind" to be "error" or "warning" in ${R}() call);let _={command:"format-msgs",messages:co(E,"messages",null,"",P),isWarning:A==="warning"};N!==void 0&&(_.color=N),P!==void 0&&(_.terminalWidth=P),u(b,_,(C,$)=>{if(C)return I(new Error(C),null);I(null,$.messages)})},analyzeMetafile:({callName:R,refs:b,metafile:E,options:T,callback:I})=>{T===void 0&&(T={});let F={},A=k(T,F,"color",Ue),N=k(T,F,"verbose",Ue);Rt(T,F,in ${R}() call);let P={command:"analyze-metafile",metafile:E};A!==void 0&&(P.color=A),N!==void 0&&(P.verbose=N),u(b,P,(_,C)=>{if(_)return I(new Error(_),null);I(null,C.result)})}}}}function aL(e,t,r,o,n,s,i,a,c,l,u){let p=Vb(),f=e==="context",m=(y,x)=>{let w=[];try{$c(w,a,{},c,Fb)}catch{}let R=En(y,s,p,void 0,x);r(n,{command:"error",flags:w,error:R},()=>{R.detail=p.load(R.detail),u(ki(f?"Context failed":"Build failed",[R],[]),null)})},h;if(typeof a=="object"){let y=a.plugins;if(y!==void 0){if(!Array.isArray(y))return m(new Error('"plugins" must be an array'),"");h=y}}if(h&&h.length>0){if(s.isSync)return m(new Error("Cannot use plugins in synchronous API calls"),"");cL(t,r,o,n,s,i,a,h,p).then(y=>{if(!y.ok)return m(y.error,y.pluginName);try{g(y.requestPlugins,y.runOnEndCallbacks,y.scheduleOnDisposeCallbacks)}catch(x){m(x,"")}},y=>m(y,""));return}try{g(null,(y,x)=>x([],[]),()=>{})}catch(y){m(y,"")}function g(y,x,w){let R=s.hasFS,{entries:b,flags:E,write:T,stdinContents:I,stdinResolveDir:F,absWorkingDir:A,nodePaths:N,mangleCache:P}=sL(e,a,c,Fb,R);if(T&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let _={command:"build",key:t,entries:b,flags:E,write:T,stdinContents:I,stdinResolveDir:F,absWorkingDir:A||l,nodePaths:N,context:f};y&&(_.plugins=y),P&&(_.mangleCache=P);let C=(q,B)=>{let Y={errors:ss(q.errors,p),warnings:ss(q.warnings,p),outputFiles:void 0,metafile:void 0,mangleCache:void 0},G=Y.errors.slice(),X=Y.warnings.slice();q.outputFiles&&(Y.outputFiles=q.outputFiles.map(pL)),q.metafile&&(Y.metafile=JSON.parse(q.metafile)),q.mangleCache&&(Y.mangleCache=q.mangleCache),q.writeToStdout!==void 0&&console.log(ns(q.writeToStdout).replace(/\n$/,"")),x(Y,(J,le)=>{if(G.length>0||J.length>0){let oe=ki("Build failed",G.concat(J),X.concat(le));return B(oe,null,J,le)}B(null,Y,J,le)})},$,j;f&&(i["on-end"]=(q,B)=>new Promise(Y=>{C(B,(G,X,J,le)=>{let oe={errors:J,warnings:le};j&&j(G,X),$=void 0,j=void 0,o(q,oe),Y()})})),r(n,_,(q,B)=>{if(q)return u(new Error(q),null);if(!f)return C(B,(X,J)=>(w(),u(X,J)));if(B.errors.length>0)return u(ki("Context failed",B.errors,B.warnings),null);let Y=!1,G={rebuild:()=>($||($=new Promise((X,J)=>{let le;j=(kt,Oe)=>{le||(le=()=>kt?J(kt):X(Oe))};let oe=()=>{r(n,{command:"rebuild",key:t},(Oe,W)=>{Oe?J(new Error(Oe)):le?le():oe()})};oe()})),$),watch:(X={})=>new Promise((J,le)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');Rt(X,{},"in watch() call"),r(n,{command:"watch",key:t},Oe=>{Oe?le(new Error(Oe)):J(void 0)})}),serve:(X={})=>new Promise((J,le)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let oe={},kt=k(X,oe,"port",wn),Oe=k(X,oe,"host",V),W=k(X,oe,"servedir",V),Ee=k(X,oe,"keyfile",V),Ct=k(X,oe,"certfile",V),Vr=k(X,oe,"fallback",V),Kr=k(X,oe,"onRequest",Bb);Rt(X,oe,"in serve() call");let Nr={command:"serve",key:t,onRequest:!!Kr};kt!==void 0&&(Nr.port=kt),Oe!==void 0&&(Nr.host=Oe),W!==void 0&&(Nr.servedir=W),Ee!==void 0&&(Nr.keyfile=Ee),Ct!==void 0&&(Nr.certfile=Ct),Vr!==void 0&&(Nr.fallback=Vr),r(n,Nr,(Ud,v0)=>{if(Ud)return le(new Error(Ud));Kr&&(i["serve-request"]=(k0,T0)=>{Kr(T0.args),o(k0,{})}),J(v0)})}),cancel:()=>new Promise(X=>{if(Y)return X();r(n,{command:"cancel",key:t},()=>{X()})}),dispose:()=>new Promise(X=>{if(Y)return X();Y=!0,r(n,{command:"dispose",key:t},()=>{X(),w(),n.unref()})})};n.ref(),u(null,G)})}}var cL=async(e,t,r,o,n,s,i,a,c)=>{let l=[],u=[],p={},f={},m=[],h=0,g=0,y=[],x=!1;a=[...a];for(let b of a){let E={};if(typeof b!="object")throw new Error(Plugin at index ${g} must be an object);let T=k(b,E,"name",V);if(typeof T!="string"||T==="")throw new Error(Plugin at index ${g} is missing a name);try{let I=k(b,E,"setup",Bb);if(typeof I!="function")throw new Error("Plugin is missing a setup function");Rt(b,E,on plugin ${pt(T)});let F={name:T,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};g++;let N=I({initialOptions:i,resolve:(P,_={})=>{if(!x)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof P!="string")throw new Error("The path to resolve must be a string");let C=Object.create(null),$=k(_,C,"pluginName",V),j=k(_,C,"importer",V),q=k(_,C,"namespace",V),B=k(_,C,"resolveDir",V),Y=k(_,C,"kind",V),G=k(_,C,"pluginData",Dc),X=k(_,C,"with",yr);return Rt(_,C,"in resolve() call"),new Promise((J,le)=>{let oe={command:"resolve",path:P,key:e,pluginName:T};if($!=null&&(oe.pluginName=$),j!=null&&(oe.importer=j),q!=null&&(oe.namespace=q),B!=null&&(oe.resolveDir=B),Y!=null)oe.kind=Y;else throw new Error('Must specify "kind" when calling "resolve"');G!=null&&(oe.pluginData=c.store(G)),X!=null&&(oe.with=lL(X,"with")),t(o,oe,(kt,Oe)=>{kt!==null?le(new Error(kt)):J({errors:ss(Oe.errors,c),warnings:ss(Oe.warnings,c),path:Oe.path,external:Oe.external,sideEffects:Oe.sideEffects,namespace:Oe.namespace,suffix:Oe.suffix,pluginData:c.load(Oe.pluginData)})})})},onStart(P){let _='This error came from the "onStart" callback registered here:',C=Ac(new Error(_),n,"onStart");l.push({name:T,callback:P,note:C}),F.onStart=!0},onEnd(P){let _='This error came from the "onEnd" callback registered here:',C=Ac(new Error(_),n,"onEnd");u.push({name:T,callback:P,note:C}),F.onEnd=!0},onResolve(P,_){let C='This error came from the "onResolve" callback registered here:',$=Ac(new Error(C),n,"onResolve"),j={},q=k(P,j,"filter",Uc),B=k(P,j,"namespace",V);if(Rt(P,j,in onResolve() call for plugin ${pt(T)}),q==null)throw new Error("onResolve() call is missing a filter");let Y=h++;p[Y]={name:T,callback:_,note:$},F.onResolve.push({id:Y,filter:q.source,namespace:B||""})},onLoad(P,_){let C='This error came from the "onLoad" callback registered here:',$=Ac(new Error(C),n,"onLoad"),j={},q=k(P,j,"filter",Uc),B=k(P,j,"namespace",V);if(Rt(P,j,in onLoad() call for plugin ${pt(T)}),q==null)throw new Error("onLoad() call is missing a filter");let Y=h++;f[Y]={name:T,callback:_,note:$},F.onLoad.push({id:Y,filter:q.source,namespace:B||""})},onDispose(P){m.push(P)},esbuild:n.esbuild});N&&await N,y.push(F)}catch(I){return{ok:!1,error:I,pluginName:T}}}s["on-start"]=async(b,E)=>{c.clear();let T={errors:[],warnings:[]};await Promise.all(l.map(async({name:I,callback:F,note:A})=>{try{let N=await F();if(N!=null){if(typeof N!="object")throw new Error(Expected onStart() callback in plugin ${pt(I)} to return an object);let P={},_=k(N,P,"errors",We),C=k(N,P,"warnings",We);Rt(N,P,from onStart() callback in plugin ${pt(I)}),_!=null&&T.errors.push(...co(_,"errors",c,I,void 0)),C!=null&&T.warnings.push(...co(C,"warnings",c,I,void 0))}}catch(N){T.errors.push(En(N,n,c,A&&A(),I))}})),r(b,T)},s["on-resolve"]=async(b,E)=>{let T={},I="",F,A;for(let N of E.ids)try{({name:I,callback:F,note:A}=p[N]);let P=await F({path:E.path,importer:E.importer,namespace:E.namespace,resolveDir:E.resolveDir,kind:E.kind,pluginData:c.load(E.pluginData),with:E.with});if(P!=null){if(typeof P!="object")throw new Error(Expected onResolve() callback in plugin ${pt(I)} to return an object);let _={},C=k(P,_,"pluginName",V),$=k(P,_,"path",V),j=k(P,_,"namespace",V),q=k(P,_,"suffix",V),B=k(P,_,"external",Ue),Y=k(P,_,"sideEffects",Ue),G=k(P,_,"pluginData",Dc),X=k(P,_,"errors",We),J=k(P,_,"warnings",We),le=k(P,_,"watchFiles",We),oe=k(P,_,"watchDirs",We);Rt(P,_,from onResolve() callback in plugin ${pt(I)}),T.id=N,C!=null&&(T.pluginName=C),$!=null&&(T.path=$),j!=null&&(T.namespace=j),q!=null&&(T.suffix=q),B!=null&&(T.external=B),Y!=null&&(T.sideEffects=Y),G!=null&&(T.pluginData=c.store(G)),X!=null&&(T.errors=co(X,"errors",c,I,void 0)),J!=null&&(T.warnings=co(J,"warnings",c,I,void 0)),le!=null&&(T.watchFiles=Fc(le,"watchFiles")),oe!=null&&(T.watchDirs=Fc(oe,"watchDirs"));break}}catch(P){T={id:N,errors:[En(P,n,c,A&&A(),I)]};break}r(b,T)},s["on-load"]=async(b,E)=>{let T={},I="",F,A;for(let N of E.ids)try{({name:I,callback:F,note:A}=f[N]);let P=await F({path:E.path,namespace:E.namespace,suffix:E.suffix,pluginData:c.load(E.pluginData),with:E.with});if(P!=null){if(typeof P!="object")throw new Error(Expected onLoad() callback in plugin ${pt(I)} to return an object);let _={},C=k(P,_,"pluginName",V),$=k(P,_,"contents",Wb),j=k(P,_,"resolveDir",V),q=k(P,_,"pluginData",Dc),B=k(P,_,"loader",V),Y=k(P,_,"errors",We),G=k(P,_,"warnings",We),X=k(P,_,"watchFiles",We),J=k(P,_,"watchDirs",We);Rt(P,_,from onLoad() callback in plugin ${pt(I)}),T.id=N,C!=null&&(T.pluginName=C),$ instanceof Uint8Array?T.contents=$:$!=null&&(T.contents=Sr($)),j!=null&&(T.resolveDir=j),q!=null&&(T.pluginData=c.store(q)),B!=null&&(T.loader=B),Y!=null&&(T.errors=co(Y,"errors",c,I,void 0)),G!=null&&(T.warnings=co(G,"warnings",c,I,void 0)),X!=null&&(T.watchFiles=Fc(X,"watchFiles")),J!=null&&(T.watchDirs=Fc(J,"watchDirs"));break}}catch(P){T={id:N,errors:[En(P,n,c,A&&A(),I)]};break}r(b,T)};let w=(b,E)=>E([],[]);u.length>0&&(w=(b,E)=>{(async()=>{let T=[],I=[];for(let{name:F,callback:A,note:N}of u){let P,_;try{let C=await A(b);if(C!=null){if(typeof C!="object")throw new Error(Expected onEnd() callback in plugin ${pt(F)} to return an object);let $={},j=k(C,$,"errors",We),q=k(C,$,"warnings",We);Rt(C,$,from onEnd() callback in plugin ${pt(F)}),j!=null&&(P=co(j,"errors",c,F,void 0)),q!=null&&(_=co(q,"warnings",c,F,void 0))}}catch(C){P=[En(C,n,c,N&&N(),F)]}if(P){T.push(...P);try{b.errors.push(...P)}catch{}}if(_){I.push(..._);try{b.warnings.push(..._)}catch{}}}E(T,I)})()});let R=()=>{for(let b of m)setTimeout(()=>b(),0)};return x=!0,{ok:!0,requestPlugins:y,runOnEndCallbacks:w,scheduleOnDisposeCallbacks:R}};function Vb(){let e=new Map,t=0;return{clear(){e.clear()},load(r){return e.get(r)},store(r){if(r===void 0)return-1;let o=t++;return e.set(o,r),o}}}function Ac(e,t,r){let o,n=!1;return()=>{if(n)return o;n=!0;try{let s=(e.stack+"").split(
);s.splice(1,1);let i=Kb(t,s,r);if(i)return o={text:e.message,location:i},o}catch{}}}function En(e,t,r,o,n){let s="Internal error",i=null;try{s=(e&&e.message||e)+""}catch{}try{i=Kb(t,(e.stack+"").split(
),"")}catch{}return{id:"",pluginName:n,text:s,location:i,notes:o?[o]:[],detail:r?r.store(e):-1}}function Kb(e,t,r){let o=" at ";if(e.readFileSync&&!t[0].startsWith(o)&&t[1].startsWith(o))for(let n=1;n<t.length;n++){let s=t[n];if(s.startsWith(o))for(s=s.slice(o.length);;){let i=/^(?:new |async )?\S+ \((.*)\)$/.exec(s);if(i){s=i[1];continue}if(i=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(s),i){s=i[1];continue}if(i=/^(\S+):(\d+):(\d+)$/.exec(s),i){let a;try{a=e.readFileSync(i[1],"utf8")}catch{break}let c=a.split(/\r\n|\r|\n|\u2028|\u2029/)[+i[2]-1]||"",l=+i[3]-1,u=c.slice(l,l+r.length)===r?r.length:0;return{file:i[1],namespace:"file",line:+i[2],column:Sr(c.slice(0,l)).length,length:Sr(c.slice(l,l+u)).length,lineText:c+
+t.slice(1).join(
),suggestion:""}}break}}return null}function ki(e,t,r){let o=5;e+=t.length<1?"": with ${t.length} error${t.length<2?"":"s"}:+t.slice(0,o+1).map((s,i)=>{if(i===o)return
...;if(!s.location)return
error: ${s.text};let{file:a,line:c,column:l}=s.location,u=s.pluginName?plugin: ${s.pluginName} :"";return
${a}:${c}:${l}: ERROR: ${u}${s.text}}).join("");let n=new Error(e);for(let[s,i]of[["errors",t],["warnings",r]])Object.defineProperty(n,s,{configurable:!0,enumerable:!0,get:()=>i,set:a=>Object.defineProperty(n,s,{configurable:!0,enumerable:!0,value:a})});return n}function ss(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function jb(e,t,r){if(e==null)return null;let o={},n=k(e,o,"file",V),s=k(e,o,"namespace",V),i=k(e,o,"line",wn),a=k(e,o,"column",wn),c=k(e,o,"length",wn),l=k(e,o,"lineText",V),u=k(e,o,"suggestion",V);if(Rt(e,o,t),l){let p=l.slice(0,(a&&a>0?a:0)+(c&&c>0?c:0)+(r&&r>0?r:80));!/[\x7F-\uFFFF]/.test(p)&&!/\n/.test(l)&&(l=p)}return{file:n||"",namespace:s||"",line:i||0,column:a||0,length:c||0,lineText:l||"",suggestion:u||""}}function co(e,t,r,o,n){let s=[],i=0;for(let a of e){let c={},l=k(a,c,"id",V),u=k(a,c,"pluginName",V),p=k(a,c,"text",V),f=k(a,c,"location",$b),m=k(a,c,"notes",We),h=k(a,c,"detail",Dc),g=in element ${i} of "${t}";Rt(a,c,g);let y=[];if(m)for(let x of m){let w={},R=k(x,w,"text",V),b=k(x,w,"location",$b);Rt(x,w,g),y.push({text:R||"",location:jb(b,g,n)})}s.push({id:l||"",pluginName:u||o,text:p||"",location:jb(f,g,n),notes:y,detail:r?r.store(h):-1}),i++}return s}function Fc(e,t){let r=[];for(let o of e){if(typeof o!="string")throw new Error(${pt(t)} must be an array of strings);r.push(o)}return r}function lL(e,t){let r=Object.create(null);for(let o in e){let n=e[o];if(typeof n!="string")throw new Error(key ${pt(o)} in object ${pt(t)} must be a string);r[o]=n}return r}function pL({path:e,contents:t,hash:r}){let o=null;return{path:e,contents:t,hash:r,get text(){let n=this.contents;return(o===null||n!==t)&&(t=n,o=ns(n)),o}}}var Xb=vi,Bc=e=>Hc().build(e),Jb=(e,t)=>Hc().transform(e,t),Qb=(e,t)=>Hc().formatMessages(e,t),Zb=(e,t)=>Hc().analyzeMetafile(e,t);var Rn,Yb,jc,Hc=()=>{if(jc)return jc;throw Rn?new Error('You need to wait for the promise returned from "initialize" to be resolved before calling this'):new Error('You need to call "initialize" before calling this')},Wc=e=>{let t=e.wasm,r=e.worker;if(Rn)throw new Error('Cannot call "initialize" more than once');return Rn=uL(t,r),Rn.catch(()=>{Rn=void 0}),Rn},uL=async(e,t)=>{let r=new Worker(t.toString(),{type:"module"}),o,n,s=new Promise((c,l)=>{o=c,n=l});r.onmessage=({data:c})=>{r.onmessage=({data:l})=>i(l),c?n(c):o()},r.postMessage(e);let{readFromStdout:i,service:a}=zb({writeToStdin(c){r.postMessage(c)},isSync:!1,hasFS:!1,esbuild:{build:Bc,transform:Jb,formatMessages:Qb,analyzeMetafile:Zb,version:Xb,initialize:Wc}});await s,Yb=()=>{r.terminate(),Rn=void 0,Yb=void 0,jc=void 0},jc={build:c=>new Promise((l,u)=>a.buildOrContext({callName:"build",refs:null,options:c,isTTY:!1,defaultWD:"/",callback:(p,f)=>p?u(p):l(f)})),transform:(c,l)=>new Promise((u,p)=>a.transform({callName:"transform",refs:null,input:c,options:l||{},isTTY:!1,fs:{readFile(f,m){m(new Error("Internal error"),null)},writeFile(f,m){m(null)}},callback:(f,m)=>f?p(f):u(m)})),formatMessages:(c,l)=>new Promise((u,p)=>a.formatMessages({callName:"formatMessages",refs:null,messages:c,options:l,callback:(f,m)=>f?p(f):u(m)})),analyzeMetafile:(c,l)=>new Promise((u,p)=>a.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof c=="string"?c:JSON.stringify(c),options:l,callback:(f,m)=>f?p(f):u(m)}))}};self.Deno||(self.Deno={build:{os:"linux"},errors:{AlreadyExists:Error},env:{get:()=>{}},permissions:{query:()=>Promise.resolve("denied")},cwd:()=>location.href});function eE(){let e=globalThis,t=e.process?.platform;if(typeof t=="string")return t.startsWith("win");let r=e.Deno?.build?.os;return typeof r=="string"?r==="windows":e.navigator?.platform?.startsWith("Win")??!1}var ut=eE();function St(e){if(typeof e!="string")throw new TypeError(Path must be a string, received "${JSON.stringify(e)}")}function Um(e,t){if(t.length>=e.length)return e;let r=e.length-t.length;for(let o=t.length-1;o>=0;--o)if(e.charCodeAt(r+o)!==t.charCodeAt(o))return e;return e.slice(0,-t.length)}function $m(e,t,r=0){let o=!1,n=e.length;for(let s=e.length-1;s>=r;--s)if(t(e.charCodeAt(s))){if(o){r=s+1;break}}else o||(o=!0,n=s+1);return e.slice(r,n)}function jm(e,t){if(St(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(Suffix must be a string, received "${JSON.stringify(t)}")}function qc(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError(URL must be a file URL: received "${e.protocol}");return e}function lo(e){return e=qc(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function is(e,t){if(e.length<=1)return e;let r=e.length;for(let o=e.length-1;o>0&&t(e.charCodeAt(o));o--)r=o;return e.slice(0,r)}function xr(e){return e===47}function Bm(e,t=""){e instanceof URL&&(e=lo(e)),jm(e,t);let r=$m(e,xr),o=is(r,xr);return t?Um(o,t):o}function Br(e){return e===47||e===92}function po(e){return e>=97&&e<=122||e>=65&&e<=90}function vn(e){e=qc(e);let t=decodeURIComponent(e.pathname.replace(/\//g,"\\").replace(/%(?![0-9A-Fa-f]{2})/g,"%25")).replace(/^\\*([A-Za-z]:)(\\|$)/,"$1\\");return e.hostname!==""&&(t=\\\\${e.hostname}${t}),t}var Ti=ut?"\\":"/";function Wm(e){e instanceof URL&&(e=lo(e)),St(e);let t=-1,r=0,o=-1,n=!0,s=0;for(let i=e.length-1;i>=0;--i){let a=e.charCodeAt(i);if(xr(a)){if(!n){r=i+1;break}continue}o===-1&&(n=!1,o=i+1),a===46?t===-1?t=i:s!==1&&(s=1):t!==-1&&(s=-1)}return t===-1||o===-1||s===0||s===1&&t===o-1&&t===r+1?"":e.slice(t,o)}function cs(e){return ut?vn(e):lo(e)}function qm(e){return St(e),e.length>0&&xr(e.charCodeAt(0))}function Gm(e){St(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return Br(r)?!0:!!(po(r)&&t>2&&e.charCodeAt(1)===58&&Br(e.charCodeAt(2)))}var TL={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function zc(e){return e.replaceAll(/[\s]/g,t=>TL[t]??t)}function nE(e){if(!qm(e))throw new TypeError(Path must be absolute: received "${e}");let t=new URL("file:///");return t.pathname=zc(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}function sE(e){if(!Gm(e))throw new TypeError(Path must be absolute: received "${e}");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=zc(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError(Invalid hostname: "${o.hostname}");return o}function kn(e){return ut?sE(e):nE(e)}function Vc(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function Kc(e){let t={},r=Object.keys(e).sort((o,n)=>n.length-o.length);for(let o of r)t[o]=e[o];return t}function iE(e){return Vc(e)&&(e.imports!==void 0?Vm(e.imports):!0)&&(e.scopes!==void 0?Km(e.scopes):!0)}function Vm(e){return Vc(e)}function Km(e){return Vc(e)&&Object.values(e).every(t=>Ym(t))}function Ym(e){return Vc(e)}function Yc(e){try{return new URL(e),!0}catch{return!1}}function cE(e,t){let r={};for(let[o,n]of Object.entries(e)){let s=LL(o,t);if(s===null)continue;if(typeof n!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let i=Xm(n,t);if(i===null){console.warn("the address was invalid."),r[s]=null;continue}if(o.endsWith("/")&&!Hr(i).endsWith("/")){console.warn("an invalid address was given for the specifier key specifierKey; since specifierKey ended in a slash, the address needs to as well."),r[s]=null;continue}r[s]=Hr(i)}return Kc(r)}function Hr(e){return e.href}function SL(e,t){let r={};for(let[n,s]of Object.entries(e)){if(!Ym(s))throw new TypeError("the value of the scope with prefix scopePrefix needs to be an object.");let i;try{i=new URL(n,t)}catch{console.warn("the scope prefix URL was not parseable.");continue}let a=Hr(i);r[a]=cE(s,t)}let o={};for(let n of Object.keys(r))o[n]=Kc(r[n]);return Kc(o)}function LL(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=Xm(e,t);return r!==null?Hr(r):e}function Xm(e,t){if(t&&(e.startsWith("/")||e.startsWith("./")||e.startsWith("../")))try{return new URL(e,t)}catch{return null}try{return new URL(e)}catch{return null}}var NL=["ftp","file","http","https","ws","wss"];function ML(e){return NL.some(t=>Hr(e).startsWith(t))}function aE(e,t,r){for(let[o,n]of Object.entries(r))if(o===e){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Yc(n))throw new TypeError("resolutionResult must be an URL.");return n}else if(o.endsWith("/")&&e.startsWith(o)&&(t===null||ML(t))){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Yc(n))throw new TypeError("resolutionResult must be an URL.");let s=e.slice(o.length);if(!n.endsWith("/"))throw new TypeError('resolutionResult does not end with "/"');try{let i=new URL(s,n);if(!Yc(i))throw new TypeError("url must be an URL.");if(!Hr(i).startsWith(n))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return Hr(i)}catch{throw new TypeError("resolution of normalizedSpecifier was blocked since the afterPrefix portion could not be URL-parsed relative to the resolutionResult mapped to by the specifierKey prefix.")}}return null}function Jm(e,t){let r={};if(!iE(e))throw new TypeError("the top-level value needs to be a JSON object.");let{imports:o,scopes:n}=e;if(o!==void 0){if(!Vm(o))throw new TypeError('"imports" top-level key needs to be an object.');r=cE(o,t)}let s={};if(n!==void 0){if(!Km(n))throw new TypeError('"scopes" top-level key needs to be an object.');s=SL(n,t)}return Object.keys(e).find(i=>i!=="imports"&&i!=="scopes")&&console.warn("an invalid top-level key was present in the import map."),{imports:r,scopes:s}}function lE(e,{imports:t={},scopes:r={}},o){let n=Hr(o),s=Xm(e,o),i=s!==null?Hr(s):e;for(let[c,l]of Object.entries(r))if(c===n||c.endsWith("/")&&n.startsWith(c)){let u=aE(i,s,l);if(u!==null)return u}let a=aE(i,s,t);if(a!==null)return a;if(s!==null)return Hr(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}var Xc=class extends Error{constructor(t){super(t),this.name="AssertionError"}};function Qm(e,t=""){if(!e)throw new Xc(t)}function uE(e,{allowTrailingComma:t=!0}={}){if(new.target)throw new TypeError("parse is not a constructor");return new Zm(e,{allowTrailingComma:t}).parse()}var pE=globalThis.JSON.parse,Zm=class{#o=new Set( \r
);#r=new Set([..."[]{}:,/",...this.#o]);#t;#e;#i;#a;constructor(t,r){this.#t=${t},this.#e=this.#t.length,this.#i=this.#m(),this.#a=r}parse(){let t=this.#s(),r=this.#p(t),{done:o,value:n}=this.#i.next();if(!o)throw new SyntaxError(Uo(n));return r}#s(){let{done:t,value:r}=this.#i.next();if(t)throw new SyntaxError("Unexpected end of JSONC input");return r}*#m(){for(let t=0;t<this.#e;t++)if(!this.#o.has(this.#t[t])){if(this.#t[t]==="/"&&this.#t[t+1]==="*"){t+=2;let r=!1;for(;t<this.#e;t++)if(this.#t[t]==="*"&&this.#t[t+1]==="/"){r=!0;break}if(!r)throw new SyntaxError("Unexpected end of JSONC input");t++;continue}if(this.#t[t]==="/"&&this.#t[t+1]==="/"){for(t+=2;t<this.#e&&!(this.#t[t]===
||this.#t[t]==="\r");t++);continue}switch(this.#t[t]){case"{":yield{type:"BeginObject",position:t};break;case"}":yield{type:"EndObject",position:t};break;case"[":yield{type:"BeginArray",position:t};break;case"]":yield{type:"EndArray",position:t};break;case":":yield{type:"NameSeparator",position:t};break;case",":yield{type:"ValueSeparator",position:t};break;case'"':{let r=t,o=!1;for(t++;t<this.#e&&!(this.#t[t]==='"'&&!o);t++)o=this.#t[t]==="\\"&&!o;yield{type:"String",sourceText:this.#t.substring(r,t+1),position:r};break}default:{let r=t;for(;t<this.#e&&!this.#r.has(this.#t[t]);t++);t--,yield{type:"NullOrTrueOrFalseOrNumber",sourceText:this.#t.substring(r,t+1),position:r}}}}}#p(t){switch(t.type){case"BeginObject":return this.#f();case"BeginArray":return this.#n();case"NullOrTrueOrFalseOrNumber":return this.#g(t);case"String":return this.#h(t);default:throw new SyntaxError(Uo(t))}}#f(){let t={};for(let r=!0;;r=!1){let o=this.#s();if((r||this.#a.allowTrailingComma)&&o.type==="EndObject")return t;if(o.type!=="String")throw new SyntaxError(Uo(o));let n=this.#h(o),s=this.#s();if(s.type!=="NameSeparator")throw new SyntaxError(Uo(s));let i=this.#s();Object.defineProperty(t,n,{value:this.#p(i),writable:!0,enumerable:!0,configurable:!0});let a=this.#s();if(a.type==="EndObject")return t;if(a.type!=="ValueSeparator")throw new SyntaxError(Uo(a))}}#n(){let t=[];for(let r=!0;;r=!1){let o=this.#s();if((r||this.#a.allowTrailingComma)&&o.type==="EndArray")return t;t.push(this.#p(o));let n=this.#s();if(n.type==="EndArray")return t;if(n.type!=="ValueSeparator")throw new SyntaxError(Uo(n))}}#h(t){let r;try{r=pE(t.sourceText)}catch{throw new SyntaxError(Uo(t))}return Qm(typeof r=="string"),r}#g(t){if(t.sourceText==="null")return null;if(t.sourceText==="true")return!0;if(t.sourceText==="false")return!1;let r;try{r=pE(t.sourceText)}catch{throw new SyntaxError(Uo(t))}return Qm(typeof r=="number"),r}};function Uo({type:e,sourceText:t,position:r}){let o="";switch(e){case"BeginObject":o="{";break;case"EndObject":o="}";break;case"BeginArray":o="[";break;case"EndArray":o="]";break;case"NameSeparator":o=":";break;case"ValueSeparator":o=",";break;case"NullOrTrueOrFalseOrNumber":case"String":o=30<t.length?${t.slice(0,30)}...:t;break;default:throw new Error("unreachable")}returnUnexpected token ${o} in JSONC at position ${r}}function Qc(e){if(e.protocol==="file:")return{path:cs(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}}async function ef(e){let t=await Deno.readTextFile(e),r=uE(t);if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(Deno config at ${e} must be an object);if("imports"in r&&(typeof r.imports!="object"||r.imports===null||Array.isArray(r.imports)))throw new Error(Deno config at ${e} has invalid "imports" key);if("scopes"in r&&(typeof r.scopes!="object"||r.scopes===null||Array.isArray(r.scopes)))throw new Error(Deno config at ${e} has invalid "scopes" key);if("lock"in r&&typeof r.lock!="boolean"&&typeof r.lock!="string")throw new Error(Deno config at ${e} has invalid "lock" key);if("importMap"in r&&typeof r.importMap!="string")throw new Error(Deno config at ${e} has invalid "importMap" key);return r}function mE(e){if(e.imports!==void 0){let t=[];for(let[r,o]of Object.entries(e.imports))if(t.push([r,o]),!r.endsWith("/")&&o&&(o.startsWith("jsr:")||o.startsWith("npm:"))&&!e.imports[r+"/"]){let n=r+"/",s=o.slice(0,4)+"/"+o.slice(o[4]==="/"?5:4)+"/";t.push([n,s])}e.imports=Object.fromEntries(t)}}var IL=${Ti}node_modules${Ti},AL=${Ti}node_modules;function Jc(e){return e.includes(IL)||e.endsWith(AL)}function tf(e){return(e.namespace===""||e.namespace==="file")&&(Jc(e.resolveDir)||Jc(e.path)||Jc(e.importer))}function rf(e={}){return{name:"deno-resolver",setup(t){let r=null,o=(t.initialOptions.external??[]).map(n=>new RegExp("^"+n.replace(/[-/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*")+"$"));t.onStart(async function(){let s;if(e.importMapURL===void 0&&e.configPath!==void 0){let i=await ef(e.configPath);if(i.imports!==void 0||i.scopes!==void 0){let a={imports:i.imports,scopes:i.scopes};mE(a),r=Jm(a,kn(e.configPath))}else i.importMap!==void 0&&(s=new URL(i.importMap,kn(e.configPath)).href)}else e.importMapURL!==void 0&&(s=e.importMapURL);if(s){let i=await fetch(s),a=await i.json();r=Jm(a,new URL(i.url))}}),t.onResolve({filter:/.*/},async function(s){if(tf(s))return;let i;if(s.importer!==""){if(s.namespace==="")throw new Error("[assert] namespace is empty");i=new URL(${s.namespace}:${s.importer})}else if(s.resolveDir!=="")i=new URL(${kn(s.resolveDir).href}/);else return;let a;if(r!==null){let p=lE(s.path,r,new URL(i));a=new URL(p)}else a=new URL(s.path,i);for(let p of o)if(p.test(a.href))return{path:a.href,external:!0};let{path:c,namespace:l}=Qc(a);return await t.resolve(c,{namespace:l,kind:s.kind})})}}}var ube=new TextEncoder;var FL=[],DL=[],of="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";for(let e=0,t=of.length;e<t;++e)FL[e]=of[e],DL[of.charCodeAt(e)]=e;var Mbe=Deno.env.get("DENO_REGISTRY_URL")??"https://jsr.io";var GL=await Deno.permissions.query({name:"run"}).then(e=>e.state!=="granted")?"portable":"native";var fE=rf;var dE=e=>!!(zL.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),zL=["i.gyazo.com","t.gyazo.com","scrapbox.io","api.openai.com","*.openai.azure.com","maps.googleapis.com","upload.gyazo.com","storage.googleapis.com","sentry.io"];var hE=e=>{if(e.protocol==="file:")return{path:cs(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},nf=e=>e.namespace==="file"?kn(e.path):new URL(${e.namespace}:${e.path});var gE=(e,t)=>{let r=Vs(VL(e),()=>({name:"NotFoundError",message:"Source map URL is not found"}));if(O(r))return r;let{url:o,start:n,end:s}=S(r);return URL.canParse(o,t)?L({url:new URL(o,t),start:n,end:s}):M({name:"InvalidURLError",message:Invalid URL: ${o}})},VL=e=>{for(let t of e.matchAll(/\/([*/])[#@] *sourceMappingURL=/g)){let r=t.index+t[0].length,o=e.length,n=r;for(;n<o&&e.charCodeAt(n)>32;)n++;if(n!==r&&(t[1]==="/"||e.indexOf("*/",n)>0))return{url:e.slice(r,n),start:r,end:n}}};var KL=["base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx"],yE=e=>KL.includes(e),xE=e=>/^js|^ts|css$/.test(e),bE=e=>{let t=e.url,r=Bm(t);if(yE(r))return r;if(r==="mjs")return"js";let o=new URL(t);o.search="",o.hash="";let n=Wm(o.href).slice(1);if(yE(n))return n;if(n==="mjs")return"js";let i=(e.headers.get("Content-Type")??"text/plain").split(";")[0]?.trim?.()??"text/plain";return YL(i)},YL=e=>{let t=e.split("/")[1]??"plain";if(/(?:^plain$|^xml|^svg|^x?html)/.test(t))return"text";if(t.startsWith("json"))return"json";switch(t){case"javascript":return"js";case"typescript":return"ts";case"css":return"css";default:return"text"}};function Zc(e,t){if(isNaN(e)||isNaN(t))throw new Error("Cannot compare against non-numbers");return e===t?0:e<t?-1:1}function RE(e=[],t=[]){return e.length&&!t.length?-1:!e.length&&t.length?1:0}function af(e=[],t=[]){let r=Math.max(e.length,t.length);for(let o=0;o<r;o++){let n=e[o],s=t[o];if(n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(typeof n=="string"&&typeof s=="number")return 1;if(typeof n=="number"&&typeof s=="string"||n<s)return-1;if(n>s)return 1}return 0}var ls="0|[1-9]\\d*",XL="\\d*[a-zA-Z-][a-zA-Z0-9-]*",JL=(?<major>${ls})\\.(?<minor>${ls})\\.(?<patch>${ls}),EE=(?:${ls}|${XL}),vE=(?:-(?<prerelease>${EE}(?:\\.${EE})*)),wE="[0-9A-Za-z-]+",kE=(?:\\+(?<buildmetadata>${wE}(?:\\.${wE})*)),TE=v?${JL}${vE}?${kE}?,_E=new RegExp(^${TE}$),PE="(?:<|>)?=?",QL="x|X|\\*",sf=${ls}|${QL},el=v=\\s*(?<major>${sf})(?:\\.(?<minor>${sf})(?:\\.(?<patch>${sf})${vE}?${kE}?)?)?,OE=new RegExp(^(?<operator>~>?|\\^|${PE})\\s*${el}$),SE=new RegExp(^(?<operator>${PE})\\s*(${TE})$|^$);function cf(e){return typeof e=="number"&&!Number.isNaN(e)&&(!Number.isFinite(e)||0<=e&&e<=Number.MAX_SAFE_INTEGER)}var lf=256;var ZL=new RegExp(^${ls}$);function sr(e){return e.split(".").filter(Boolean).map(t=>{if(ZL.test(t)){let r=Number(t);if(cf(r))return r}return t})}function uo(e){return e.split(".").filter(Boolean)}function tl(e,t){let r=Number(e);if(!cf(r))throw new TypeError(t);return r}function Tn(e){return Number.isNaN(e.major)&&Number.isNaN(e.minor)&&Number.isNaN(e.patch)&&(e.prerelease===void 0||e.prerelease.length===0)&&(e.build===void 0||e.build.length===0)}function br(e,t){return e===t?0:Zc(e.major,t.major)||Zc(e.minor,t.minor)||Zc(e.patch,t.patch)||RE(e.prerelease,t.prerelease)||af(e.prerelease,t.prerelease)}function pf(e){return e.toFixed(0)}function _n(e){let t=pf(e.major),r=pf(e.minor),o=pf(e.patch),n=e.prerelease?.join(".")??"",s=e.build?.join(".")??"";return[[${t}.${r}.${o},n].filter(c=>c).join("-"),s].filter(c=>c).join("+")}function eN(e,t){if(Tn(t))return!0;let r=br(e,t);switch(t.operator){case"=":case void 0:return r===0;case"!=":return r!==0;case">":return r>0;case"<":return r<0;case">=":return r>=0;case"<=":return r<=0}}function rl(e,t){for(let r of t)if(!eN(e,r))return!1;if(!e.prerelease?.length)return!0;for(let r of t){if(Tn(r)||!r.prerelease?.length)continue;let{major:o,minor:n,patch:s}=r;if(e.major===o&&e.minor===n&&e.patch===s)return!0}return!1}function ol(e,t){return t.some(r=>rl(e,r))}var nl={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},ps={operator:void 0,...nl};function LE(e,t){return br(e,t)>0}function _i(e,t){let r;for(let o of e)ol(o,t)&&(r=r&&LE(r,o)?r:o);return r}function tN(e){let r=e.match(SE)?.groups;if(!r)return null;let{operator:o}=r;return{operator:o||void 0,...nl}}function Pe(e){return!e||e.toLowerCase()==="x"||e==="*"}function rN(e){if(!Pe(e.major))return Pe(e.minor)?{operator:">=",major:+e.major,minor:0,patch:0,prerelease:[],build:[]}:Pe(e.patch)?{operator:">=",major:+e.major,minor:+e.minor,patch:0,prerelease:[],build:[]}:{operator:">=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:e.prerelease?sr(e.prerelease):[],build:[]}}function oN(e){if(!Pe(e.major))return Pe(e.minor)?{operator:"<",major:+e.major+1,minor:0,patch:0,prerelease:[],build:[]}:Pe(e.patch)?{operator:"<",major:+e.major,minor:+e.minor+1,patch:0,prerelease:[],build:[]}:e.prerelease?{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:sr(e.prerelease),build:[]}:{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:[],build:[]}}function nN(e){let t=e.match(new RegExp(^${el})),r=t?.groups;if(!r)return null;let o=t[0].length,n=e.slice(o).match(/^\s+-\s+/);if(!n)return null;let s=n[0].length,a=e.slice(o+s).match(new RegExp(^${el}\\s*$))?.groups,c=rN(r),l=oN(a);return[c,l].filter(Boolean)}function sN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ps];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return n===0?[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];let a=sr(e.prerelease??"");return n===0?s===0?[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s,patch:i+1}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]:[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n+1,minor:0,patch:0}]}function iN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ps];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=sr(e.prerelease??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]}function aN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return o?[{operator:"<",major:n,minor:0,patch:0}]:[{operator:"<",major:n,minor:0,patch:0}];if(o)return[{operator:"<",major:n,minor:s,patch:0}];let a=sr(e.prerelease??""),c=uo(e.build??"");return[{operator:"<",major:n,minor:s,patch:i,prerelease:a,build:c}]}function cN(e){let t=Pe(e.minor),r=Pe(e.patch),o=+e.major,n=+e.minor,s=+e.patch;if(t)return[{operator:"<",major:o+1,minor:0,patch:0}];if(r)return[{operator:"<",major:o,minor:n+1,patch:0}];let i=sr(e.prerelease??""),a=uo(e.build??"");return[{operator:"<=",major:o,minor:n,patch:s,prerelease:i,build:a}]}function lN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[{operator:"<",major:0,minor:0,patch:0}];if(r)return[{operator:">=",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s+1,patch:0}];let a=sr(e.prerelease??""),c=uo(e.build??"");return[{operator:">",major:n,minor:s,patch:i,prerelease:a,build:c}]}function pN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ps];if(r)return[{operator:">=",major:n,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0}];let a=sr(e.prerelease??""),c=uo(e.build??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a,build:c}]}function uN(e){let t=Pe(e.major),r=Pe(e.minor),o=Pe(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[ps];if(r)return[{operator:">=",major:n,minor:0,patch:0},{operator:"<",major:n+1,minor:0,patch:0}];if(o)return[{operator:">=",major:n,minor:s,patch:0},{operator:"<",major:n,minor:s+1,patch:0}];let a=sr(e.prerelease??""),c=uo(e.build??"");return[{operator:e.operator==="="?"=":void 0,major:n,minor:s,patch:i,prerelease:a,build:c}]}function mN(e){let t=e.match(OE)?.groups;if(!t)return tN(e);switch(t.operator){case"^":return sN(t);case"~":case"~>":return iN(t);case"<":return aN(t);case"<=":return cN(t);case">":return lN(t);case">=":return pN(t);default:return uN(t)}}function fN(e){return e.split(/\s+/).flatMap(mN)}function NE(e){let t=e.replaceAll(/(?<=[<>=~^])(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>nN(r)||fN(r));if(t.some(r=>r.includes(null)))throw new TypeError(Cannot parse version range: range "${e}" is invalid);return t}function uf(e){if(typeof e!="string")throw new TypeError(Cannot parse version as version must be a string: received ${typeof e});if(e.length>lf)throw new TypeError(Cannot parse version as version length is too long: length is ${e.length}, max length is ${lf});e=e.trim();let t=e.match(_E)?.groups;if(!t)throw new TypeError(Cannot parse version: ${e});let r=tl(t.major,Cannot parse version ${e}: invalid major version),o=tl(t.minor,Cannot parse version ${e}: invalid minor version),n=tl(t.patch,Cannot parse version ${e}: invalid patch version),s=t.prerelease?sr(t.prerelease):[],i=t.buildmetadata?uo(t.buildmetadata):[];return{major:r,minor:o,patch:n,prerelease:s,build:i}}function mf(e){try{return NE(e)}catch{return}}function ff(e){try{return uf(e)}catch{return}}var Pi={operator:void 0,major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]};var $o=async e=>{try{let t=await fetch(e);return t.ok?L([t,!1]):M({name:"HTTPError",message:${t.status} ${t.statusText},response:t})}catch(t){if(t instanceof TypeError)return M({name:"NetworkError",message:t.message,request:e});if(t instanceof DOMException)return M({name:"AbortError",message:t.message,request:e});throw t}};var df="https://jsr.io",ME=async(e,t)=>{let r=await(t?.fetch??$o)(new Request(${t?.endpoint??df}/${e}/meta.json),t?.cacheFirst);return ae(r,([o])=>o.json())};var CE=async(e,t,r)=>{let o=await(r?.fetch??$o)(new Request(${r?.endpoint??df}/${e}/${t}_meta.json),r?.cacheFirst);return ae(o,([n])=>n.json())};var IE=async(e,t)=>{let r=await(t?.fetch??$o)(new Request(${t?.endpoint??"https://registry.npmjs.org"}/${e}),t?.cacheFirst);return ae(r,([o])=>o.json())};var DE=(e,t)=>({name:"InvalidPackageVersionError",message:No version of ${e.name} satisfies "${e.tag??"*"}" (available: ${t.slice(0,10).join(", ")}${t.length>10?, ... (${t.length-10} more versions):""}),packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableVersions:t}),sl=(e,t)=>({name:"InvalidEntryPointError",message:${e.entryPoint} is not a valid entry point for ${e.name}@${e.tag??"*"} (available: ${t.join(", ")}),packageName:e.name,range:e.range,tag:e.tag,entryPoint:e.entryPoint,availableEntryPoints:t}),UE=async(e,t)=>{if(t?.resolvedVersions){let c=new Map(t.resolvedVersions.get(e.name)??[]),l=_i([...c.keys()],e.range);if(l){let u=c.get(l)??Oi,p=u[e.entryPoint];return typeof p!="string"&&console.log(p),p?L(AE(e.name,_n(l),p)):M(sl(e,Object.keys(u)))}}let r=await IE(e.name,t);if(O(r))return r;let o=S(r),n=new Map(Object.entries(o.versions).flatMap(([c,{exports:l}])=>{let u=ff(c);return u?[[u,l??Oi]]:[]})),s=_i([...n.keys()],e.range);if(!s)return M(DE(e,Object.keys(o.versions)));let i={...Oi};for(let c of Object.keys(n.get(s)??Oi))i[c]=c;let a=i[e.entryPoint];return a?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[s,i]]),L(AE(e.name,_n(s),a))):M(sl(e,Object.keys(i)))},AE=(e,t,r)=>new URL(r,https://esm.sh/${e}@${t}/),$E=async(e,t)=>{if(t?.resolvedVersions){let a=new Map(t.resolvedVersions.get(e.name)??[]),c=_i([...a.keys()],e.range);if(c){let l=a.get(c)??Oi,u=l[e.entryPoint];return u?L(FE(e.name,_n(c),u)):M(sl(e,Object.keys(l)))}}let r=await dN(e,t);if(O(r))return r;let o=S(r),n=await CE(e.name,_n(o),t);if(O(n))return n;let s=S(n).exports,i=s[e.entryPoint];return i?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[o,s]]),L(FE(e.name,_n(o),i))):M(sl(e,Object.keys(S(n).exports)))},FE=(e,t,r)=>new URL(r,https://jsr.io/${e}/${t}/),dN=async(e,t)=>{let r=await ME(e.name,t);if(O(r))return r;let o=S(r),n=Object.keys(o.versions).flatMap(i=>{let a=ff(i);return a?[a]:[]}),s=_i(n,e.range);return s?L(s):M(DE(e,Object.keys(o.versions)))},Oi={".":"./"};var hN=e=>({name:"OnlyScopeProvidedError",specifier:e}),jE=e=>({name:"PackageNotFoundError",specifier:e}),BE=e=>{if(e.protocol!=="npm:")return M({name:"NotNpmProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0,o,n;if(t[r]==="@"){let p=t.indexOf("/",r);if(p===-1)return M(hN(e));o=t.indexOf("/",p+1),n=t.indexOf("@",p+1)}else o=t.indexOf("/",r),n=t.indexOf("@",r);if(o===-1&&(o=t.length),n===-1&&(n=t.length),n=Math.min(n,o),r===n)return M(jE(e));let s=t.slice(r,n),i=decodeURIComponent(t.slice(n+1,o)),a=i?mf(i)??[[Pi]]:[[Pi]],c=t.slice(o+1),l=c?./${c}:".",u={name:s,range:a,entryPoint:l};return i&&(u.tag=i),L(u)},HE=e=>{if(e.protocol!=="jsr:")return M({name:"NotJsrProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0;if(t[r]!=="@")return M({name:"ScopeNotFoundError",specifier:e});let o=t.indexOf("/",r);if(o===-1)return M(jE(e));let n=t.indexOf("/",o+1),s=t.indexOf("@",o+1);n===-1&&(n=t.length),s===-1&&(s=t.length),s=Math.min(s,n);let i=t.slice(r,s),a=decodeURIComponent(t.slice(s+1,n)),c=a?mf(a)??[[Pi]]:[[Pi]],l=t.slice(n+1),u=l?./${l}:".",p={name:i,range:c,entryPoint:u};return a&&(p.tag=a),L(p)};var WE=e=>new Promise((t,r)=>{let o=new FileReader;o.addEventListener("load",()=>{let n=o.result,s=n.indexOf(";");n.startsWith("; charset=utf-8",s)?t(${n.slice(0,s)}${n.slice(s+15)}):t(n)}),o.addEventListener("error",()=>r(o.error)),o.readAsDataURL(e)});var zE=e=>{let t=new Map,r=async o=>{let n=o.namespace==="npm",s=(n?BE:HE)(nf(o));if(O(s)){let a=Z(s);return{errors:[{text:a.name,detail:a}]}}let i=await(n?UE:$E)(S(s),{resolvedVersions:t,...e});if(O(i)){let a=Z(i);return{errors:[{text:${a.name} ${a.message},detail:a}]}}return hE(S(i))};return{name:"remote-loader",setup({onLoad:o,onResolve:n,initialOptions:s}){for(let i of[...qE,...GE])n({filter:/.*/,namespace:i.slice(0,-1)},gN);n({filter:/.*/,namespace:"npm"},r),n({filter:/.*/,namespace:"jsr"},r);for(let i of qE)o({filter:/.*/,namespace:i.slice(0,-1)},a=>yN(nf(a),{...e,sourcemap:s.sourcemap!==!1&&s.sourcemap!==void 0}));for(let i of GE)o({filter:/.*/,namespace:i.slice(0,-1)},()=>{throw new Error(${i} import is not supported yet.)})}}},gN=e=>({path:e.path,namespace:e.namespace}),qE=["http:","https:","data:"],GE=["node:"],yN=async(e,t)=>{let r=t.reload?t.reload===!0?!1:!t.reload.some(l=>l.test(e)):!0,o=t.fetch??$o,n=await o(new Request(e),r);if(O(n))return{errors:[{text:${Z(n).message} Failed to fetch ${e},detail:Z(n)}]};let[s,i]=S(n),a=bE(s);t.onProgress?.({path:e,done:s.clone().blob().then(l=>({size:l.size,loader:a,isCache:i}))});let c=await s.blob();if(t.sourcemap&&xE(a)){let l=await c.text(),u=gE(l,e);if(K(u)){let{url:p,start:f,end:m}=S(u);if(p.protocol!=="data:"){let h=await o(new Request(p),r);if(O(h))return{contents:l,loader:a,warnings:[{text:${Z(h).message} Failed to fetch the source map URL,notes:[{text:Source map URL: ${p}},{text:Original URL: ${e}}],detail:Z(h)}]};let g=await S(h)[0].blob().then(WE);return{contents:l.slice(0,f)+g+l.slice(m),loader:a}}}}return{contents:new Uint8Array(await c.arrayBuffer()),loader:a}};var Ni=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(e,t,r,o,n,s){this.type=e,this.name=t,this.prefix=r,this.value=o,this.suffix=n,this.modifier=s}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},xN=/[$_\p{ID_Start}]/u,bN=/[$_\u200C\u200D\p{ID_Continue}]/u,gf=".*";function EN(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function YE(e,t=!1){let r=[],o=0;for(;o<e.length;){let n=e[o],s=function(i){if(!t)throw new TypeError(i);r.push({type:"INVALID_CHAR",index:o,value:e[o++]})};if(n==="*"){r.push({type:"ASTERISK",index:o,value:e[o++]});continue}if(n==="+"||n==="?"){r.push({type:"OTHER_MODIFIER",index:o,value:e[o++]});continue}if(n==="\\"){r.push({type:"ESCAPED_CHAR",index:o++,value:e[o++]});continue}if(n==="{"){r.push({type:"OPEN",index:o,value:e[o++]});continue}if(n==="}"){r.push({type:"CLOSE",index:o,value:e[o++]});continue}if(n===":"){let i="",a=o+1;for(;a<e.length;){let c=e.substr(a,1);if(a===o+1&&xN.test(c)||a!==o+1&&bN.test(c)){i+=e[a++];continue}break}if(!i){s(Missing parameter name at ${o});continue}r.push({type:"NAME",index:o,value:i}),o=a;continue}if(n==="("){let i=1,a="",c=o+1,l=!1;if(e[c]==="?"){s(Pattern cannot start with "?" at ${c});continue}for(;c<e.length;){if(!EN(e[c],!1)){s(Invalid character '${ec}' at ${c}.),l=!0;break}if(e[c]==="\\"){a+=e[c++]+e[c++];continue}if(e[c]===")"){if(i--,i===0){c++;break}}else if(e[c]==="("&&(i++,e[c+1]!=="?")){s(Capturing groups are not allowed at ${c}),l=!0;break}a+=e[c++]}if(l)continue;if(i){s(Unbalanced pattern at ${o});continue}if(!a){s(Missing pattern at ${o});continue}r.push({type:"REGEX",index:o,value:a}),o=c;continue}r.push({type:"CHAR",index:o,value:e[o++]})}return r.push({type:"END",index:o,value:""}),r}function XE(e,t={}){let r=YE(e);t.delimiter??="/#?",t.prefixes??="./";let o=^${Er(t.delimiter)}+?,n=[],s=0,i=0,a="",c=new Set,l=R=>{if(i<r.length&&r[i].type===R)return r[i++].value},u=()=>l("OTHER_MODIFIER")??l("ASTERISK"),p=R=>{let b=l(R);if(b!==void 0)return b;let{type:E,index:T}=r[i];throw new TypeError(Unexpected ${E} at ${T}, expected ${R})},f=()=>{let R="",b;for(;b=l("CHAR")??l("ESCAPED_CHAR");)R+=b;return R},m=R=>R,h=t.encodePart||m,g="",y=R=>{g+=R},x=()=>{g.length&&(n.push(new Ni(3,"","",h(g),"",3)),g="")},w=(R,b,E,T,I)=>{let F=3;switch(I){case"?":F=1;break;case"*":F=0;break;case"+":F=2;break}if(!b&&!E&&F===3){y(R);return}if(x(),!b&&!E){if(!R)return;n.push(new Ni(3,"","",h(R),"",F));return}let A;E?E==="*"?A=gf:A=E:A=o;let N=2;A===o?(N=1,A=""):A===gf&&(N=0,A="");let P;if(b?P=b:E&&(P=s++),c.has(P))throw new TypeError(Duplicate name '${P}'.);c.add(P),n.push(new Ni(N,P,h(R),A,h(T),F))};for(;i<r.length;){let R=l("CHAR"),b=l("NAME"),E=l("REGEX");if(!b&&!E&&(E=l("ASTERISK")),b||E){let I=R??"";t.prefixes.indexOf(I)===-1&&(y(I),I=""),x();let F=u();w(I,b,E,"",F);continue}let T=R??l("ESCAPED_CHAR");if(T){y(T);continue}if(l("OPEN")){let I=f(),F=l("NAME"),A=l("REGEX");!F&&!A&&(A=l("ASTERISK"));let N=f();p("CLOSE");let P=u();w(I,F,A,N,P);continue}x(),p("END")}return n}function Er(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function VE(e){return e&&e.ignoreCase?"ui":"u"}function wN(e,t,r){return JE(XE(e,r),t,r)}function us(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function JE(e,t,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let o=r.start?"^":"";for(let a of e){if(a.type===3){a.modifier===3?o+=Er(a.value):o+=(?:${Er(a.value)})${us(a.modifier)};continue}t&&t.push(a.name);let c=^${Er(r.delimiter)}+?,l=a.value;if(a.type===1?l=c:a.type===0&&(l=gf),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?o+=(${l})${us(a.modifier)}:o+=((?:${l})${us(a.modifier)});continue}if(a.modifier===3||a.modifier===1){o+=(?:${Er(a.prefix)}(${l})${Er(a.suffix)}),o+=us(a.modifier);continue}o+=(?:${Er(a.prefix)},o+=((?:${l})(?:,o+=Er(a.suffix),o+=Er(a.prefix),o+=(?:${l}))*)${Er(a.suffix)}),a.modifier===0&&(o+="?")}let n=${Er(r.endsWith)}|$,s=${Er(r.delimiter)};if(r.end)return r.strict||(o+=${s}?),r.endsWith.length?o+=(?=${n}):o+="$",new RegExp(o,VE(r));r.strict||(o+=(?:${s}(?=${n}))?);let i=!1;if(e.length){let a=e[e.length-1];a.type===3&&a.modifier===3&&(i=r.delimiter.indexOf(a)>-1)}return i||(o+=(?=${s}|${n})),new RegExp(o,VE(r))}var Bo={delimiter:"",prefixes:"",sensitive:!0,strict:!0},RN={delimiter:".",prefixes:"",sensitive:!0,strict:!0},vN={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function kN(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function QE(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function TN(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function ZE(e){return!e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var ew=["ftp","file","http","https","ws","wss"];function tw(e){if(!e)return!0;for(let t of ew)if(e.test(t))return!0;return!1}function _N(e,t){if(e=QE(e,"#"),t||e==="")return e;let r=new URL("https://example.com");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):""}function PN(e,t){if(e=QE(e,"?"),t||e==="")return e;let r=new URL("https://example.com");return r.search=e,r.search?r.search.substring(1,r.search.length):""}function ON(e,t){return t||e===""?e:ZE(e)?nw(e):ow(e)}function SN(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function LN(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function NN(e,t,r){if(r||e==="")return e;if(t&&!ew.includes(t))return new URL(${t}:${e}).pathname;let o=e[0]=="/";return e=new URL(o?e:"/-"+e,"https://example.com").pathname,o||(e=e.substring(2,e.length)),e}function MN(e,t,r){return rw(t)===e&&(e=""),r||e===""?e:sw(e)}function CN(e,t){return e=TN(e,":"),t||e===""?e:yf(e)}function rw(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function yf(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(Invalid protocol '${e}'.)}function IN(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function AN(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function ow(e){if(e==="")return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(Invalid hostname '${e}');let t=new URL("https://example.com");return t.hostname=e,t.hostname}function nw(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(Invalid IPv6 hostname '${e}');return e.toLowerCase()}function sw(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(Invalid port '${e}'.)}function FN(e){if(e==="")return e;let t=new URL("https://example.com");return t.pathname=e[0]!=="/"?"/-"+e:e,e[0]!=="/"?t.pathname.substring(2,t.pathname.length):t.pathname}function DN(e){return e===""?e:new URL(data:${e}).pathname}function UN(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function $N(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var jN=class{#o;#r=[];#t={};#e=0;#i=1;#a=0;#s=0;#m=0;#p=0;#f=!1;constructor(e){this.#o=e}get result(){return this.#t}parse(){for(this.#r=YE(this.#o,!0);this.#e<this.#r.length;this.#e+=this.#i){if(this.#i=1,this.#r[this.#e].type==="END"){if(this.#s===0){this.#g(),this.#u()?this.#n(9,1):this.#d()?this.#n(8,1):this.#n(7,0);continue}else if(this.#s===2){this.#y(5);continue}this.#n(10,0);break}if(this.#m>0)if(this.#_())this.#m-=1;else continue;if(this.#T()){this.#m+=1;continue}switch(this.#s){case 0:this.#w()&&this.#y(1);break;case 1:if(this.#w()){this.#S();let e=7,t=1;this.#R()?(e=2,t=3):this.#f&&(e=2),this.#n(e,t)}break;case 2:this.#b()?this.#y(3):(this.#E()||this.#d()||this.#u())&&this.#y(5);break;case 3:this.#v()?this.#n(4,1):this.#b()&&this.#n(5,1);break;case 4:this.#b()&&this.#n(5,1);break;case 5:this.#P()?this.#p+=1:this.#O()&&(this.#p-=1),this.#k()&&!this.#p?this.#n(6,1):this.#E()?this.#n(7,0):this.#d()?this.#n(8,1):this.#u()&&this.#n(9,1);break;case 6:this.#E()?this.#n(7,0):this.#d()?this.#n(8,1):this.#u()&&this.#n(9,1);break;case 7:this.#d()?this.#n(8,1):this.#u()&&this.#n(9,1);break;case 8:this.#u()&&this.#n(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="")}#n(e,t){switch(this.#s){case 0:break;case 1:this.#t.protocol=this.#l();break;case 2:break;case 3:this.#t.username=this.#l();break;case 4:this.#t.password=this.#l();break;case 5:this.#t.hostname=this.#l();break;case 6:this.#t.port=this.#l();break;case 7:this.#t.pathname=this.#l();break;case 8:this.#t.search=this.#l();break;case 9:this.#t.hash=this.#l();break;case 10:break}this.#s!==0&&e!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(e)&&(this.#t.pathname??=this.#f?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&e===9&&(this.#t.search??="")),this.#h(e,t)}#h(e,t){this.#s=e,this.#a=this.#e+t,this.#e+=t,this.#i=0}#g(){this.#e=this.#a,this.#i=0}#y(e){this.#g(),this.#s=e}#x(e){return e<0&&(e=this.#r.length-e),e<this.#r.length?this.#r[e]:this.#r[this.#r.length-1]}#c(e,t){let r=this.#x(e);return r.value===t&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#w(){return this.#c(this.#e,":")}#R(){return this.#c(this.#e+1,"/")&&this.#c(this.#e+2,"/")}#b(){return this.#c(this.#e,"@")}#v(){return this.#c(this.#e,":")}#k(){return this.#c(this.#e,":")}#E(){return this.#c(this.#e,"/")}#d(){if(this.#c(this.#e,"?"))return!0;if(this.#r[this.#e].value!=="?")return!1;let e=this.#x(this.#e-1);return e.type!=="NAME"&&e.type!=="REGEX"&&e.type!=="CLOSE"&&e.type!=="ASTERISK"}#u(){return this.#c(this.#e,"#")}#T(){return this.#r[this.#e].type=="OPEN"}#_(){return this.#r[this.#e].type=="CLOSE"}#P(){return this.#c(this.#e,"[")}#O(){return this.#c(this.#e,"]")}#l(){let e=this.#r[this.#e],t=this.#x(this.#a).index;return this.#o.substring(t,e.index)}#S(){let e={};Object.assign(e,Bo),e.encodePart=yf;let t=wN(this.#l(),void 0,e);this.#f=tw(t)}},hf=["protocol","username","password","hostname","port","pathname","search","hash"],jo="*";function KE(e,t){if(typeof e!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function mo(e,t){return t?Li(e):e}function Si(e,t,r){let o;if(typeof t.baseURL=="string")try{o=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=mo(o.protocol.substring(0,o.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=mo(o.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=mo(o.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=mo(o.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=mo(o.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=mo(o.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=mo(o.search.substring(1,o.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=mo(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(invalid baseURL '${t.baseURL}'.)}if(typeof t.protocol=="string"&&(e.protocol=CN(t.protocol,r)),typeof t.username=="string"&&(e.username=LN(t.username,r)),typeof t.password=="string"&&(e.password=SN(t.password,r)),typeof t.hostname=="string"&&(e.hostname=ON(t.hostname,r)),typeof t.port=="string"&&(e.port=MN(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,o&&!kN(e.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(e.pathname=mo(o.pathname.substring(0,n+1),r)+e.pathname)}e.pathname=NN(e.pathname,e.protocol,r)}return typeof t.search=="string"&&(e.search=PN(t.search,r)),typeof t.hash=="string"&&(e.hash=_N(t.hash,r)),e}function Li(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function BN(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function HN(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",o=^${BN(t.delimiter)}+?,n=/[$_\u200C\u200D\p{ID_Continue}]/u,s="";for(let i=0;i<e.length;++i){let a=e[i];if(a.type===3){if(a.modifier===3){s+=Li(a.value);continue}s+={${Li(a.value)}}${us(a.modifier)};continue}let c=a.hasCustomName(),l=!!a.suffix.length||!!a.prefix.length&&(a.prefix.length!==1||!t.prefixes.includes(a.prefix)),u=i>0?e[i-1]:null,p=i<e.length-1?e[i+1]:null;if(!l&&c&&a.type===1&&a.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let f=p.value.length>0?p.value[0]:"";l=n.test(f)}else l=!p.hasCustomName();if(!l&&!a.prefix.length&&u&&u.type===3){let f=u.value[u.value.length-1];l=t.prefixes.includes(f)}l&&(s+="{"),s+=Li(a.prefix),c&&(s+=:${a.name}),a.type===2?s+=(${a.value}):a.type===1?c||(s+=(${o})):a.type===0&&(!c&&(!u||u.type===3||u.modifier!==3||l||a.prefix!=="")?s+="*":s+=(${r})),a.type===1&&c&&a.suffix.length&&n.test(a.suffix[0])&&(s+="\\"),s+=Li(a.suffix),l&&(s+="}"),a.modifier!==3&&(s+=us(a.modifier))}return s}var iw=class{#o;#r={};#t={};#e={};#i={};#a=!1;constructor(e={},t,r){try{let o;if(typeof t=="string"?o=t:r=t,typeof e=="string"){let a=new jN(e);if(a.parse(),e=a.result,o===void 0&&typeof e.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");e.baseURL=o}else{if(!e||typeof e!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(o)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let n={ignoreCase:r.ignoreCase===!0},s={pathname:jo,protocol:jo,username:jo,password:jo,hostname:jo,port:jo,search:jo,hash:jo};this.#o=Si(s,e,!0),rw(this.#o.protocol)===this.#o.port&&(this.#o.port="");let i;for(i of hf){if(!(i in this.#o))continue;let a={},c=this.#o[i];switch(this.#t[i]=[],i){case"protocol":Object.assign(a,Bo),a.encodePart=yf;break;case"username":Object.assign(a,Bo),a.encodePart=IN;break;case"password":Object.assign(a,Bo),a.encodePart=AN;break;case"hostname":Object.assign(a,RN),ZE(c)?a.encodePart=nw:a.encodePart=ow;break;case"port":Object.assign(a,Bo),a.encodePart=sw;break;case"pathname":tw(this.#r.protocol)?(Object.assign(a,vN,n),a.encodePart=FN):(Object.assign(a,Bo,n),a.encodePart=DN);break;case"search":Object.assign(a,Bo,n),a.encodePart=UN;break;case"hash":Object.assign(a,Bo,n),a.encodePart=$N;break}try{this.#i[i]=XE(c,a),this.#r[i]=JE(this.#i[i],this.#t[i],a),this.#e[i]=HN(this.#i[i],a),this.#a=this.#a||this.#i[i].some(l=>l.type===2)}catch{throw new TypeError(invalid ${i} pattern '${this.#oi}'.)}}}catch(o){throw new TypeError(Failed to construct 'URLPattern': ${o.message})}}test(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return!1;try{typeof e=="object"?r=Si(r,e,!1):r=Si(r,KE(e,t),!1)}catch{return!1}let o;for(o of hf)if(!this.#r[o].exec(r[o]))return!1;return!0}exec(e={},t){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof e!="string"&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return;try{typeof e=="object"?r=Si(r,e,!1):r=Si(r,KE(e,t),!1)}catch{return null}let o={};t?o.inputs=[e,t]:o.inputs=[e];let n;for(n of hf){let s=this.#r[n].exec(r[n]);if(!s)return null;let i={};for(let[a,c]of this.#t[n].entries())if(typeof c=="string"||typeof c=="number"){let l=s[a+1];i[c]=l}o[n]={input:r[n]??"",groups:i}}return o}static compareComponent(e,t,r){let o=(a,c)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(a[l]<c[l])return-1;if(a[l]!==c[l])return 1}return 0},n=new Ni(3,"","","","",3),s=new Ni(0,"","","","",3),i=(a,c)=>{let l=0;for(;l<Math.min(a.length,c.length);++l){let u=o(a[l],c[l]);if(u)return u}return a.length===c.length?0:o(a[l]??n,c[l]??n)};return!t.#e[e]&&!r.#e[e]?0:t.#e[e]&&!r.#e[e]?i(t.#i[e],[s]):!t.#e[e]&&r.#e[e]?i([s],r.#i[e]):i(t.#i[e],r.#i[e])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#a}};globalThis.URLPattern||(globalThis.URLPattern=iw);var aw,cw=async(e,t)=>(aw??=Wc({wasm:e,worker:t}),await aw,async r=>{let{outputFiles:o}=await Bc({entryPoints:[r],format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[fE(),zE({fetch:WN,reload:[new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"})]})],write:!1});return{contents:o[0].text}}),WN=async(e,t)=>{let r=dE(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let o=await xf(e);if(o)return o}try{let o=await r(e);return o.ok?(r===GM_fetch&&!e.url.startsWith("data:")&&await rc(e,o),L([o,!1])):await xf(e)??M({name:"HTTPError",message:${o.status} ${o.statusText},response:o})}catch(o){let n=await xf(e);if(n)return n;if(o instanceof TypeError)return M({name:"NetworkError",message:o.message,request:e});if(o instanceof DOMException)return M({name:"AbortError",message:o.message,request:e});throw o}},xf=async e=>{if(e.url.startsWith("data:"))return;let t=await Oo(e);if(t)return t.url||Object.defineProperty(t,"url",{value:e.url}),L([t,!0])};var lw=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e);var pw=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},uw=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},mw=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},fw=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var dw=()=>{let e;return{show:(o,{x:n,y:s})=>{e=qN(),e.append(GN(o)),e.style.visibility="hidden",document.body.append(e);let{height:i}=e.getBoundingClientRect();e.style.top=${s-i}px,e.style.left=${n}px,e.style.removeProperty("visibility")},hide:async()=>{e?.classList?.remove?.("in"),await new Promise(o=>setTimeout(o,150)),e?.remove?.()}}},qN=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},GN=e=>{let t=document.createElement("pre");return t.classList.add("tooltip-inner"),t.style.textAlign="unset",t.style.maxWidth="70vw",t.style.margin="unset",t.innerText=e,t};var hw=()=>{let e=document.createElement("a");e.classList.add("tool-btn"),e.type="button",e.setAttribute("aria-haspopup","true");let t=!1,{show:r,hide:o}=dw();return{component:e,setStatus:async(s,i)=>{switch(e.textContent="",await o(),s){case"loading":e.append(mw());break;case"pass":e.append(pw());break;case"fail":e.append(uw());break;case"none":break}i!==void 0&&s!=="none"?(e.style.removeProperty("pointer-events"),e.onclick=async()=>{if(t)await o();else{let{top:a,left:c}=e.getBoundingClientRect();r(i,{y:a+globalThis.scrollY,x:c})}t=!t}):e.style.pointerEvents="none"}}};var gw=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(fw()),t.addEventListener("click",e),t};var yw=e=>{let{component:t,setStatus:r}=hw(),o=document.createElement("div");return o.style.position="absolute",o.style.left="-2em",o.style.zIndex="1",o.style.display="flex",o.style.flexFlow="column",o.append(gw(e),t),{menu:o,setStatus:r}};function xw(e){return new Promise(t=>setTimeout(t,e))}function bw(e,t){let{trailing:r=!1,interval:o=0}=t??{},n,s=!1,i=l=>{n?.resolve?.({executed:!1}),n=l},a=()=>{let{...l}=n;return n=void 0,l},c=async()=>{if(s||!n)return;s=!0,o>0&&await xw(o);let{parameters:l,resolve:u,reject:p}=a();try{let f=await e(...l);s=!1,u({result:f,executed:!0})}catch(f){s=!1,p(f)}finally{r?await c():(i(),await Promise.resolve())}};return(...l)=>new Promise((u,p)=>{i({parameters:l,resolve:u,reject:p}),c()})}var Ew,ww=async(e,t)=>{let r=[],n=bw(async()=>{r.forEach(({menu:i,setStatus:a})=>{a("none"),i.remove()});let s=Cb(scrapbox.Project.name,scrapbox.Page.title??"",Dt());for(let i of s){let a=i.lang.toLowerCase();if(lw(a))for(let c of i.startIds){let l=document.getElementById(L${c}),{menu:u,setStatus:p}=yw(async()=>{await p("loading");try{Ew??=await cw(e,t);let{contents:f}=await Ew(i.path);console.debug("execute:",f),await Function(return (async()=>{${f}})())(),await p("pass")}catch(f){console.error(f),await p("fail",${f})}});r.push({menu:u,setStatus:p}),l?.insertBefore?.(u,l?.firstElementChild)}}await Promise.resolve()},{interval:100,trailing:!0});return await n(),scrapbox.addListener("lines:changed",n),()=>{scrapbox.removeListener("lines:changed",n),r.forEach(({menu:s,setStatus:i})=>{i("none"),s.remove()})}};function VN(e,t){for(var r in t)e[r]=t[r];return e}function Rw(e,t){for(var r in e)if(r!=="__source"&&!(r in t))return!0;for(var o in t)if(o!=="__source"&&e[o]!==t[o])return!0;return!1}function al(e,t){var r=t(),o=Q({t:{__:r,u:t}}),n=o[0].t,s=o[1];return Ha(function(){n.__=r,n.u=t,bf(n)&&s({t:n})},[e,r,t]),te(function(){return bf(n)&&s({t:n}),e(function(){bf(n)&&s({t:n})})},[e]),r}function bf(e){try{return!((t=e.__)===(r=e.u())&&(t!==0||1/t==1/r)||t!=t&&r!=r)}catch{return!0}var t,r}function vw(e,t){this.props=e,this.context=t}(vw.prototype=new kr).isPureReactComponent=!0,vw.prototype.shouldComponentUpdate=function(e,t){return Rw(this.props,e)||Rw(this.state,t)};var kw=re.__b;re.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),kw&&kw(e)};var fke=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;var KN=re.__e;re.__e=function(e,t,r,o){if(e.then){for(var n,s=t;s=s.__;)if((n=s.__c)&&n.__c)return t.__e==null&&(t.__e=r.__e,t.__k=r.__k),n.__c(e,t)}KN(e,t,r,o)};var Tw=re.unmount;function Nw(e,t,r){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(o){typeof o.__c=="function"&&o.__c()}),e.__c.__H=null),(e=VN({},e)).__c!=null&&(e.__c.__P===r&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(o){return Nw(o,t,r)})),e}function Mw(e,t,r){return e&&r&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(o){return Mw(o,t,r)}),e.__c&&e.__c.__P===t&&(e.__e&&r.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=r)),e}function Ef(){this.__u=0,this.o=null,this.__b=null}function Cw(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function il(){this.i=null,this.l=null}re.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Tw&&Tw(e)},(Ef.prototype=new kr).__c=function(e,t){var r=t.__c,o=this;o.o==null&&(o.o=[]),o.o.push(r);var n=Cw(o.__v),s=!1,i=function(){s||o.__z||(s=!0,r.__R=null,n?n(c):c())};r.__R=i;var a=r.__P;r.__P=null;var c=function(){if(!--o.__u){if(o.state.__a){var l=o.state.__a;o.__v.__k[0]=Mw(l,l.__c.__P,l.__c.__O)}var u;for(o.setState({__a:o.__b=null});u=o.o.pop();)u.__P=a,u.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(i,i)},Ef.prototype.componentWillUnmount=function(){this.o=[]},Ef.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),o=this.__v.__k[0].__c;this.__v.__k[0]=Nw(this.__b,r,o.__O=o.__P)}this.__b=null}var n=t.__a&&Zr(ee,null,e.fallback);return n&&(n.__u&=-33),[Zr(ee,null,t.__a?null:e.children),n]};var _w=function(e,t,r){if(++r[1]===r[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(r=e.i;r;){for(;r.length>3;)r.pop()();if(r[1]<r[0])break;e.i=r=r[2]}};(il.prototype=new kr).__a=function(e){var t=this,r=Cw(t.__v),o=t.l.get(e);return o[0]++,function(n){var s=function(){t.props.revealOrder?(o.push(n),_w(t,e,o)):n()};r?r(s):s()}},il.prototype.render=function(e){this.i=null,this.l=new Map;var t=_o(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var r=t.length;r--;)this.l.set(t[r],this.i=[1,0,this.i]);return e.children},il.prototype.componentDidUpdate=il.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,r){_w(e,r,t)})};var YN=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,XN=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,JN=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,QN=/[A-Z0-9]/g,ZN=typeof document<"u",e1=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};kr.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(kr.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Pw=re.event;re.event=function(e){return Pw&&(e=Pw(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Iw,t1={configurable:!0,get:function(){return this.class}},Ow=re.vnode;re.vnode=function(e){typeof e.type=="string"&&function(t){var r=t.props,o=t.type,n={},s=o.indexOf("-")==-1;for(var i in r){var a=r[i];if(!(i==="value"&&"defaultValue"in r&&a==null||ZN&&i==="children"&&o==="noscript"||i==="class"||i==="className")){var c=i.toLowerCase();i==="defaultValue"&&"value"in r&&r.value==null?i="value":i==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?i="ondblclick":c!=="onchange"||o!=="input"&&o!=="textarea"||e1(r.type)?c==="onfocus"?i="onfocusin":c==="onblur"?i="onfocusout":JN.test(i)&&(i=c):c=i="oninput":s&&XN.test(i)?i=i.replace(QN,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&n[i=c]&&(i="oninputCapture"),n[i]=a}}o=="select"&&(n.multiple&&Array.isArray(n.value)&&(n.value=_o(r.children).forEach(function(l){l.props.selected=n.value.indexOf(l.props.value)!=-1})),n.defaultValue!=null&&(n.value=_o(r.children).forEach(function(l){l.props.selected=n.multiple?n.defaultValue.indexOf(l.props.value)!=-1:n.defaultValue==l.props.value}))),r.class&&!r.className?(n.class=r.class,Object.defineProperty(n,"className",t1)):r.className&&(n.class=n.className=r.className),t.props=n}(e),e.$$typeof=YN,Ow&&Ow(e)};var Sw=re.__r;re.__r=function(e){Sw&&Sw(e),Iw=e.__c};var Lw=re.diffed;re.diffed=function(e){Lw&&Lw(e);var t=e.props,r=e.__e;r!=null&&e.type==="textarea"&&"value"in t&&t.value!==r.value&&(r.value=t.value==null?"":t.value),Iw=null};var Aw=({title:e,projects:t,selected:r,confirm:o})=>d("div",{className:candidate${r?" selected":""},children:[d(r1,{title:e,confirm:o}),t.map(n=>d(o1,{project:n.name,title:e,mark:n.mark,confirm:n.confirm}))]}),r1=({title:e,confirm:t})=>d("a",{className:"button",tabIndex:0,role:"menuitem",href:./${se(e)},onClick:Fw(t),children:e}),o1=({project:e,title:t,mark:r,confirm:o})=>{let n=Fw(o);return r===""?null:d("a",{className:"mark",tabIndex:0,href:../${e}/${se(t)},onClick:n,title:/${e}/${se(t)},children:r instanceof URL?d("img",{src:r.href}):${r}})},Fw=e=>D(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var Dw=(e,t)=>{let[r,o]=Q(null),n=D(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[0]);let u=e.findIndex(p=>t(p)===l);return t(c?.cyclic?e[(u+1)%e.length]:e.at(u+1)??e[0])}),[e,t]),s=D(c=>o(l=>{if(e.length===0)return null;if(l===null)return t(e[e.length-1]);let u=e.findIndex(p=>t(p)===l);return u<0?t(e[e.length-1]):t(c?.cyclic?e[(u-1+e.length)%e.length]:e.at(u-1)??e[e.length-1])}),[e,t]),i=D(()=>o(e.length===0?null:t(e[0])),[e,t]),a=D(()=>o(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:n,prev:s,selectFirst:i,selectLast:a}};var Uw=e=>{let[t,r]=Q(null),o=H(()=>{let n=t?.getBoundingClientRect?.(),i=ri(e.line,e.char)?.getBoundingClientRect?.();return!i||!n?{}:{top:${i.bottom-n.top}px,left:${i?.left??0-n.left}px,right:${n.right-(i?.left??0)}px}},[t,e.line,e.char]);return{updateStandardElement:r,...o}};var Rf="enableProjectsOnSuggestion",$w=(e,t)=>{let[r,o]=Q(cl([...e],t)),n=D((s,i)=>{n1(s,i,e,t),o(cl([...e],t))},[e,t.enableSelfProjectOnStart]);return te(()=>{let s=i=>{i.key===Rf&&o(cl([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:n}},wf=!0,cl=(e,t)=>{try{let r=localStorage.getItem(Rf);if(r===null)return ll(e),e;let o=JSON.parse(r);return Array.isArray(o)&&o.every(n=>typeof n=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?o:o.includes(scrapbox.Project.name)?wf?o:o.filter(n=>n!==scrapbox.Project.name):wf?[...o,scrapbox.Project.name]:o:(ll(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return ll(e),e}},n1=(e,t,r,o)=>{let n=cl([...r],o);o.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(wf=t),ll(t?[...n,e]:n.filter(s=>s!==e))},ll=e=>localStorage.setItem(Rf,JSON.stringify(e));var jw=()=>H(()=>document.documentElement.dataset.os??"",[]);var Mi=(e,t)=>{if(e instanceof URL)return e;try{return new URL(e)}catch(r){if(!(r instanceof TypeError))throw r;if(!t||!/^\.\/|^\.\.\/|^\//.test(e))return e;try{return new URL(e,t)}catch(o){if(!(o instanceof TypeError))throw o;return e}}};var Bw=({progress:e})=>d("div",{className:"progress",style:background: linear-gradient(to right, var(--select-suggest-border-color, #eee) ${(e*100).toPrecision(3)}%, transparent ${(e*100).toPrecision(3)}%)});var Ww=({position:e,start:t,enableSelfProjectOnStart:r,projects:o,...n})=>{let{projects:s,set:i}=$w(o,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:c,left:l,right:u}=Uw({line:e.line,char:t}),p=jw();return d(ee,{children:[d(i1,{itemCount:n.items.length,enableProjects:s,projects:o,top:c,right:u,set:i,os:p,...n}),d(s1,{updateStandardElement:a,start:t,enableProjects:s,projects:o,top:c,left:l,os:p,...n})]})},s1=({start:e,updateStandardElement:t,confirmAfter:r,cancel:o,query:n,enableProjects:s,projects:i,items:a,top:c,left:l,progress:u,callback:p,limit:f,mark:m,os:h})=>{let g=D((N,P,_)=>{let C=[${P?/${P}/${N}:N}${_?.icon?".icon":""}];r(($,{line:j})=>[${...$.slice(0,e).join("")}${C}${...$.slice(e+...n.length).join("")},{line:j,char:e+[...C].length}])},[e,n]),y=H(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),x=H(()=>{let N=[];for(let P of a){if(N.length===f)break;P.projects.some(_=>s.includes(_))&&N.push({title:P.title,projects:P.projects.flatMap(_=>s.includes(_)?[{name:_,mark:y?Mi(m[_]??"",import.meta.url)||_[0]:"",confirm:C=>g(P.title,_,C)}]:[]),confirm:_=>g(P.title,void 0,_)})}return N},[s,y,a,f,m,g]),{selectedId:w,next:R,prev:b,selectLast:E,selectFirst:T}=Dw(x,Hw),I=D(N=>w===null?!1:(x.find(P=>Hw(P)===w)?.confirm?.(N),!0),[w,x]);te(()=>p(x.length===0?void 0:{selectNext:N=>(R(N),!0),selectPrev:N=>(b(N),!0),selectFirst:()=>(T(),!0),selectLast:()=>(E(),!0),confirm:I,cancel:()=>(o(),!0)}),[p,x.length,R,b,T,E,I]);let F=H(()=>x.length>0&&c!=null&&l!=null?{top:c,left:l}:{display:"none"},[x.length,c,l]),A=D(N=>{if(!N){t(N);return}let P=N.parentNode;if(!(P instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(P.host.parentElement)},[t]);return d("div",{ref:A,className:"container candidates","data-os":h,style:F,children:[x.map(N=>d(Aw,{...N,selected:w===N.title},N.title)),a.length>f&&d("div",{className:"counter",children:${a.length-f} more links}),d(Bw,{progress:u})]})},i1=({enableProjects:e,projects:t,projectScore:r,mark:o,itemCount:n,top:s,right:i,set:a,os:c,freezeUntil:l})=>{let u=H(()=>[...t].sort((f,m)=>(r.get(m)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:Mi(o[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),ht().focus()})}]:[]),[t,r,e,o]),p=H(()=>n>0&&s!=null&&i!=null&&t.size>1?{top:s,right:i}:{display:"none"},[s,i,n,t.size]);return d("div",{className:"container projects","data-os":c,style:p,children:u.map(f=>d(a1,{...f},f.name))})},a1=e=>d("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name,children:e.mark instanceof URL?d("img",{src:e.mark.href}):${e.mark}}),Hw=e=>e.title;var qw=e=>{let t=H(()=>Mi(e.style,import.meta.url),[e.style]);return d(ee,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var Gw=()=>d("style",{children:.container {
position: absolute;
margin-top: 14px;
max-height: 80vh;
z-index: 301;
background-color: var(--select-suggest-bg, #111);
font-family: var(--select-suggest-font-family, "Open Sans", Helvetica, Arial, "Hiragino Sans", sans-serif);
font-size: 14px;
color: var(--select-suggest-text-color, #eee);
border-radius: 4px;
}
.candidates {
max-width: 80vw;
}
.candidates:not(data-os*="android"):not(data-os*="ios") {
font-size:11px;
}
.projects {
margin-right: 4px;
display: grid;
grid-template-rows: repeat(4, min-content);
grid-auto-flow: column;
direction: rtl;
}
.projects:is(data-os*="android", data-os*="ios") > * {
padding: 6px;
}
.candidates > :not(:first-child) {
border-top: 1px solid var(--select-suggest-border-color, #eee);
}
.candidates > *{
line-height: 1.2em;
padding: 0.5em 10px;
}
.candidate {
display: flex;
}
a {
display: block;
text-decoration: none;
color: inherit;
}
a:not(.mark) {
width: 100%;
}
.selected a {
background-color: var(--select-suggest-selected-bg, #222);
text-decoration: underline
}
img {
height: 1.3em;
width: 1.3em;
position: relative;
object-fit: cover;
object-position: 0% 0%;
}
.disabled {
filter: grayscale(1.0) opacity(0.5);
}
.counter {
color: var(--select-suggest-information-text-color, #aaa);
font-size: 80%;
font-style: italic;
}
.progressstyle {
padding: unset;
border: unset;
height: 0.5px;
transition: background 0.1s;
}});function*zw(e){if(!("nodes"in e))return;let t=0;function*r(o){for(let n of Array.isArray(o)?o:[o]){if(typeof n=="string"){t+=[...n].length;continue}switch(n.type){case"link":yield{whole:n.unit.whole,start:t},t+=[...n.unit.whole].length;break;case"indent":case"quote":t+=[...n.unit.tag].length,yield*r(n.children);break;case"deco":t+=[...n.unit.deco].length+2,yield*r(n.children),t++;break;case"strong":t+=2,yield*r(n.children),t+=2;break;default:t+=[...n.unit.whole].length;break}}}yield*r(e.nodes)}var Vw=(e,t)=>{if(t.type==="unlock"){if(!e.lock)return e;let{lock:i,...a}=e;return{...a}}if(e.lock)return e;switch(t.type){case"lock":{let{lock:i,...a}=e;return{lock:!0,...a}}case"enable":return e.type==="disabled"&&e.isManuallyDisabled?{type:"ready"}:e;case"disable":return e.type==="disabled"&&e.isManuallyDisabled?e:{type:"disabled",isManuallyDisabled:!0}}if(e.type==="disabled")return e.isManuallyDisabled||!t.lines?e:{type:"ready"};if(t.type==="cancel")return e.type==="completion"?{type:"cancelled",context:e.context}:e;if(!t.lines)return{type:"disabled"};let r=Math.min(t.range.start.char,t.range.end.char),o=Math.max(t.range.start.char,t.range.end.char),n=t.lines?t.range.start.line!==t.range.end.line?
:[...t.lines[t.range.start.line].text].slice(r,o).join(""):"";if(l1(t.lines[t.position.line],n)&&e.type!=="cancelled")return{type:"completion",context:"selection",query:n,start:r,position:t.position};if(n!=="")return e.type==="completion"?{type:"ready"}:e;let s=c1(t.lines[t.position.line],t.position.char);return s?e.type==="cancelled"&&e.context==="input"?e:e.type==="completion"||t.type==="lines:changed"?{type:"completion",context:"input",query:s.whole,start:s.start,position:t.position}:e.type==="ready"?e:{type:"ready"}:e.type==="ready"?e:{type:"ready"}},c1=(e,t)=>{for(let{whole:r,start:o}of zw(e))if(!(t<=o||o+[...r].length<=t))return{whole:r,start:o}},l1=(e,t)=>!(t.trim()===""||t.includes(
)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var Kw=()=>{let e=dt(scrapbox.Page.lines),t=dt(!1);return te(()=>{let r=()=>{t.current=!0};return scrapbox.addListener("lines:changed",r),scrapbox.addListener("layout:changed",r),()=>{scrapbox.removeListener("lines:changed",r),scrapbox.removeListener("layout:changed",r)}},[]),D(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var p1=Gn("scrapbox-select-suggestion:useLifecycle.ts"),Yw=()=>{let[e,t]=Po(Vw,{type:"ready"}),r=Kw(),o=H(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:c,selection:l}=Wt();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:c.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);te(()=>{let i=()=>{o("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{o("selection:changed")},c=oc();return c.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),c.removeChangeListener(a)}},[]),te(()=>{if(e.context!=="input")return;let i=()=>{o("cursor:changed")},a=So();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[n,s]=Q(e);return n!==e&&(s(e),p1.debug("Detect changes",e)),{state:e,setEnable:D(i=>t({type:i?"enable":"disable"}),[]),cancel:D(()=>t({type:"cancel"}),[]),freezeUntil:D(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:D(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:c,selection:l}=Wt(),u=c.getPosition().line,p=a[u].text,[f,m]=i(p,c.getPosition());l.setRange({start:{line:u,char:0},end:{line:u,char:[...p].length}}),await ct(f),c.setPosition(m),c.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var Xw=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let o=e.matches.map(([i])=>i).sort(),n=t.matches.map(([i])=>i).sort();for(let i=0;i<o.length;i++){let a=o[i]-(n[i]??n.length);if(a!==0)return a}let s=e.title.length-t.title.length;return s!==0?s:t.updated-e.updated};var Qw=Symbol("Comlink.proxy"),u1=Symbol("Comlink.endpoint"),Tf=Symbol("Comlink.releaseProxy"),vf=Symbol("Comlink.finalizer"),ul=Symbol("Comlink.thrown"),Zw=e=>typeof e=="object"&&e!==null||typeof e=="function",m1={canHandle:e=>Zw(e)&&e[Qw],serialize(e){let{port1:t,port2:r}=new MessageChannel;return tR(e,t),[r,[r]]},deserialize(e){return e.start(),_f(e)}},f1={canHandle:e=>Zw(e)&&ul in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},eR=new Map([["proxy",m1],["throw",f1]]);function d1(e,t){for(let r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function tR(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(n){if(!n||!n.data)return;if(!d1(r,n.origin)){console.warn(Invalid origin '${n.origin}' for comlink proxy);return}let{id:s,type:i,path:a}=Object.assign({path:[]},n.data),c=(n.data.argumentList||[]).map(Pn),l;try{let u=a.slice(0,-1).reduce((f,m)=>f[m],e),p=a.reduce((f,m)=>f[m],e);switch(i){case"GET":l=p;break;case"SET":u[a.slice(-1)[0]]=Pn(n.data.value),l=!0;break;case"APPLY":l=p.apply(u,c);break;case"CONSTRUCT":{let f=new p(...c);l=Pf(f)}break;case"ENDPOINT":{let{port1:f,port2:m}=new MessageChannel;tR(e,m),l=b1(f,[f])}break;case"RELEASE":l=void 0;break;default:return}}catch(u){l={value:u,[ul]:0}}Promise.resolve(l).catch(u=>({value:u,[ul]:0})).then(u=>{let[p,f]=dl(u);t.postMessage(Object.assign(Object.assign({},p),{id:s}),f),i==="RELEASE"&&(t.removeEventListener("message",o),rR(t),vf in e&&typeof e[vf]=="function"&&e[vf]())}).catch(u=>{let[p,f]=dl({value:new TypeError("Unserializable return value"),[ul]:0});t.postMessage(Object.assign(Object.assign({},p),{id:s}),f)})}),t.start&&t.start()}function h1(e){return e.constructor.name==="MessagePort"}function rR(e){h1(e)&&e.close()}function _f(e,t){let r=new Map;return e.addEventListener("message",function(o){let{data:n}=o;if(!n||!n.id)return;let s=r.get(n.id);if(s)try{s(n)}finally{r.delete(n.id)}}),kf(e,r,[],t)}function pl(e){if(e)throw new Error("Proxy has been released and is not useable")}function oR(e){return ms(e,new Map,{type:"RELEASE"}).then(()=>{rR(e)})}var ml=new WeakMap,fl="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(ml.get(e)||0)-1;ml.set(e,t),t===0&&oR(e)});function g1(e,t){let r=(ml.get(t)||0)+1;ml.set(t,r),fl&&fl.register(e,t,e)}function y1(e){fl&&fl.unregister(e)}function kf(e,t,r=[],o=function(){}){let n=!1,s=new Proxy(o,{get(i,a){if(pl(n),a===Tf)return()=>{y1(s),oR(e),t.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>s};let c=ms(e,t,{type:"GET",path:r.map(l=>l.toString())}).then(Pn);return c.then.bind(c)}return kf(e,t,[...r,a])},set(i,a,c){pl(n);let[l,u]=dl(c);return ms(e,t,{type:"SET",path:[...r,a].map(p=>p.toString()),value:l},u).then(Pn)},apply(i,a,c){pl(n);let l=r[r.length-1];if(l===u1)return ms(e,t,{type:"ENDPOINT"}).then(Pn);if(l==="bind")return kf(e,t,r.slice(0,-1));let[u,p]=Jw(c);return ms(e,t,{type:"APPLY",path:r.map(f=>f.toString()),argumentList:u},p).then(Pn)},construct(i,a){pl(n);let[c,l]=Jw(a);return ms(e,t,{type:"CONSTRUCT",path:r.map(u=>u.toString()),argumentList:c},l).then(Pn)}});return g1(s,e),s}function x1(e){return Array.prototype.concat.apply([],e)}function Jw(e){let t=e.map(dl);return[t.map(r=>r[0]),x1(t.map(r=>r[1]))]}var nR=new WeakMap;function b1(e,t){return nR.set(e,t),e}function Pf(e){return Object.assign(e,{[Qw]:!0})}function dl(e){for(let[t,r]of eR)if(r.canHandle(e)){let[o,n]=r.serialize(e);return[{type:"HANDLER",name:t,value:o},n]}return[{type:"RAW",value:e},nR.get(e)||[]]}function Pn(e){switch(e.type){case"HANDLER":return eR.get(e.name).deserialize(e.value);case"RAW":return e.value}}function ms(e,t,r,o){return new Promise(n=>{let s=E1();t.set(s,n),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),o)})}function E1(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var fs=Gn("scrapbox-select-suggestion:cancelableSearch.ts"),sR=e=>{let t=_f(e);return{load:async r=>{fs.debug("start loading source");let o=await t.load([...r]);return fs.debug(loaded ${o} candidates),o},search:(r,o)=>w1(r,o??5e3,t.search),[Symbol.dispose]:()=>{t[Tf](),e instanceof MessagePort?e.close():e.terminate(),fs.debug("shared worker closed.")}}},w1=(e,t,r)=>{if(fs.debug("start searching: ",e),!e.trim())return new ReadableStream({start(s){s.close()}});let o=new Date,n=!1;return new ReadableStream({async start(s){try{await r(e,t,Pf((i,a)=>(n||s.enqueue([i,a]),n))),s.close()}catch(i){s.error(i)}finally{n=!0;let a=new Date().getTime()-o.getTime();fs.debug(Comlink search completed for "${e}" in ${a}ms)}},cancel(){n=!0;let i=new Date().getTime()-o.getTime();fs.debug(Comlink search cancelled for "${e}" after ${i}ms)}})};var hl=(e,t)=>{let r=t?.interval??0,o=t?.maxQueued??1/0,n,s,i=[],a=(...c)=>{if(!n)return n=(async()=>{do{await new Promise(m=>{let h=setTimeout(m,r);s=()=>{for(clearTimeout(h);i.length>0;)i.shift()("discarded");m()}});let f=i.pop();if(!f)break;f("delayed")}while(i.length>0);n=void 0})(),new Promise(f=>f(e.call(a,...c,"immediate")));for(;i.length>Math.max(o,0);)i.shift()("discarded");let{promise:l,resolve:u,reject:p}=Promise.withResolvers();return i.push(f=>{try{u(e.call(a,...c,f))}catch(m){p(m)}}),l};return a.clear=()=>{s?.()},Object.defineProperty(a,"ready",{get:()=>n}),a};var Ci=e=>e.query!=="",iR=e=>(t,r)=>{if("query"in r){if(r.query===t.query)return t;let i=Ci(t)?t.job:void 0;if(!r.query)return i?.abort?.(),{query:""};let{run:a,abort:c}=e(r.query),l=i?.abort?.()?.then?.(a)??a();return{query:r.query,job:{done:l,abort:()=>(c(),l)},progress:0,candidates:Ci(t)?t.candidates:[]}}if(!Ci(t))return t;if(!r.candidates){let{progress:i,...a}=t;return i===r.progress?t:{progress:r.progress,...a}}let{candidates:o,progress:n,...s}=t;return o===r.candidates&&n===r.progress?t:{candidates:r.candidates??o,progress:r.progress,...s}};var R1=Gn("scrapbox-select-suggestion:useSearch.ts"),aR=(e,t)=>{let r=H(()=>sR(new SharedWorker(t.workerUrl,{type:"module"}).port),[t.workerUrl]);te(()=>(r.load(t.projects),()=>{using i=r}),[r,t.projects]);let o=D(iR(i=>{let a=!1;return{run:async()=>{let c=hl((u,p)=>{p!=="discarded"&&(a||s(u))},{interval:500,maxQueued:0}),l=[];for await(let[u,p]of r.search(i,1e4)){if(a)return;l=[...l,...u],s({progress:p}),u.length!==0&&c({progress:p,candidates:l})}c({progress:1,candidates:l})},abort:()=>a=!0}}),[r]),[n,s]=Po(o,{query:""});return te(()=>s({query:e}),[e]),H(()=>{if(!Ci(n))return;let[i,a]=v1(n.candidates);return R1.debug("Detect changes",{progress:n.progress,items:a}),{progress:n.progress,projectScore:i,items:a}},[n])},v1=e=>{let t=new Map,r=[];for(let o of e.sort(Xw)){let n=[...o.metadata.keys()];for(let s of n)t.set(s,(t.get(s)??0)+.5**o.dist);r.push({title:o.title,dist:o.dist,projects:n})}return[t,r]};var cR=(e,t)=>{let r=dt({...t});te(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),te(()=>{e(r.current)},[e])};var k1={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},lR=e=>{let{state:t,setEnable:r,...o}=Yw(),n=aR(t.type==="completion"?t.context==="input"?t.query.slice(1,-1):t.query:"",e),[s,i]=Q(),{callback:a,style:c,...l}=e;return cR(a,{enable:D(()=>r(!0),[]),disable:D(()=>r(!1),[]),...t.type!=="completion"||!s?k1:s}),d(ee,{children:[d(Gw,{}),d(qw,{style:c}),t.type==="completion"&&n&&d(Ww,{callback:i,...n,...t,...o,...l})]})};var pR=e=>{let t=document.createElement("div");t.dataset.userscriptName="scrapbox-select-suggestion";let r=t.attachShadow({mode:"open"});document.body.append(t);let{limit:o=5,debug:n=!1,mark:s={},style:i="",enableSelfProjectOnStart:a=!0,workerUrl:c}=e,l=new Set([...a?[scrapbox.Project.name]:[],...e.projects??[scrapbox.Project.name]]);return Ca(n),new Promise(u=>Tt(d(lR,{limit:o,projects:l,mark:s,style:i,callback:u,enableSelfProjectOnStart:a,workerUrl:c}),r))};var ir=e=>e.flatMap(t=>{let r=t.slice(1),o=Math.min(...r.map(n=>n.text.length-n.text.trimStart().length));return r.map(n=>n.text.slice(o))}).join(
).trim();function*uR(e,t){for(let[r,o]of t.entries()){let n=e.get(r);if(n&&ir(n.blocks)===ir(o)){yield{changed:!1,filename:r};continue}yield{changed:!0,filename:r}}for(let r of e.keys())t.has(r)||(yield{changed:!0,filename:r})}var mR=e=>{let t=new Map;if(e.length===0)return t;let r=at(e.map(n=>n.text).join(
),{hasTitle:!0}),o=0;for(let n of r)switch(n.type){case"title":case"line":o++;break;case"table":o+=n.cells.length+1;break;case"codeBlock":{let s=t.get(n.fileName)??[],i=n.content.split(
).length+1;s.push(e.slice(o,o+i)),t.set(n.fileName,s),o+=i;break}}return t};var fR=e=>{let t,r,o=async()=>{for(;t;){let[n,s]=t;t=void 0;try{let i=await e(...n);s({type:"resolve",value:i})}catch(i){s({type:"reject",value:i})}}r=void 0};return(...n)=>{let{resolve:s,promise:i}=Promise.withResolvers();return t?.[1]?.({type:"cancel"}),t=[n,s],r??=o(),i}};var gl=class{constructor(t,r){this._filename=t;this._preview=fR(async(o,n,s)=>(this._dispose=await r(s?{filename:this.filename,before:o,after:n,render:(...i)=>{s.textContent="",s.append(...i)}}:{filename:this.filename,before:o}),!1))}get filename(){return this._filename}get blocks(){return this._blocks??[]}async update(t){if(await this._dispose?.(),!t||ir(t)===""){let a=await this._preview(this.blocks);if(a.type==="cancel")return a;if(a.type==="reject")throw a.value;return this._area?.remove?.(),this._style?.remove?.(),this._area=void 0,this._style=void 0,this._blocks=void 0,{type:"resolve",value:!0}}let r=this.blocks;this._blocks=t,this.makeStyle();let o=this.makeArea(),n=t.at(0)?.at?.(-1)?.id,s=to(n);if(!s)throw new Error("div.lines#L${n}" could not be found.);s.insertAdjacentElement("afterend",o);let i=()=>{let a=s.getElementsByClassName("indent")[0];a instanceof HTMLElement&&(o.style.marginLeft=a.style.marginLeft)};return this._observer?.disconnect?.(),i(),this._observer=new MutationObserver(i),this._observer.observe(s,{childList:!0,subtree:!0}),this._preview(r,t,o)}makeArea(){if(this._area)return this._area;let t=document.createElement("div");return t.classList.add("scrap-run"),t.dataset.filename=this.filename,this._area=t,t}makeStyle(){let t=this.blocks.flatMap(o=>o.slice(1).map(({id:n})=>#L${n})),r=this.blocks.flatMap(o=>o.map(({id:n})=>#L${n}));this._style||(this._style=document.createElement("style"),document.head.append(this._style)),this._style.textContent=.lines:not(:has(:is(${...r.join(",")}).cursor-line)) :is(${...t.join(",")}){display:none}}_blocks;_dispose;_preview;_area;_observer;_style};var dR=({previewers:e})=>{let t=new Map,r=()=>{let s=mR(Dt());for(let{changed:i,filename:a}of uR(t,s)){if(!i)continue;let c=s.get(a),l=t.get(a);if(!l){if(!c)continue;let u=e.find(({when:p})=>p.test(a))?.preview;if(!u)continue;l=new gl(a,u),t.set(a,l)}l.update(c).then(u=>{switch(u.type){case"resolve":u.value&&t.delete(a);return;case"reject":throw u.value;case"cancel":return}})}},o=()=>{if(scrapbox.Layout!=="page"){scrapbox.off("lines:changed",r);return}r(),scrapbox.on("lines:changed",r)};o(),scrapbox.on("page:changed",o);let n=document.createElement("style");return n.textContent=".scrap-run{display:block;width:95%}",document.head.append(n),()=>{scrapbox.off("page:changed",o),n.remove()}};var Ii=e=>{let t=new FileReader,r=new Promise(o=>t.onload=()=>o(t.result));return t.readAsDataURL(e),r};var hR=async e=>{if(!("after"in e))return;let t=ir(e.after),o=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("parsererror");if(o){let i=document.createElement("pre"),a=document.createElement("code");a.innerText=o.innerHTML,i.append(a),e.render(i);return}let n=await Ii(new Blob([t],{type:"image/svg+xml"})),s=document.createElement("img");s.src=n,e.render(s)};var Of={};oa(Of,{default:()=>xR});var eM=Object.create,yR=Object.defineProperty,tM=Object.getOwnPropertyDescriptor,rM=Object.getOwnPropertyNames,oM=Object.getPrototypeOf,nM=Object.prototype.hasOwnProperty,sM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),iM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of rM(t))!nM.call(e,n)&&n!==r&&yR(e,n,{get:()=>t[n],enumerable:!(o=tM(t,n))||o.enumerable});return e},aM=(e,t,r)=>(r=e!=null?eM(oM(e)):{},iM(t||!e||!e.__esModule?yR(r,"default",{value:e,enumerable:!0}):r,e)),cM=sM((e,t)=>{t.exports=o;var r=Object.prototype.toString;function o(n){if(!n)return!1;var s=r.call(n);return s==="[object Function]"||typeof n=="function"&&s!=="[object RegExp]"||typeof window<"u"&&(n===window.setTimeout||n===window.alert||n===window.confirm||n===window.prompt)}}),gR=aM(cM()),xR=gR.default??gR;var Sf={};oa(Sf,{default:()=>wR});var lM=Object.create,ER=Object.defineProperty,pM=Object.getOwnPropertyDescriptor,uM=Object.getOwnPropertyNames,mM=Object.getPrototypeOf,fM=Object.prototype.hasOwnProperty,dM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of uM(t))!fM.call(e,n)&&n!==r&&ER(e,n,{get:()=>t[n],enumerable:!(o=pM(t,n))||o.enumerable});return e},gM=(e,t,r)=>(r=e!=null?lM(mM(e)):{},hM(t||!e||!e.__esModule?ER(r,"default",{value:e,enumerable:!0}):r,e)),yM=dM((e,t)=>{var r=function(n){return n.replace(/^\s+|\s+$/g,"")},o=function(n){return Object.prototype.toString.call(n)==="[object Array]"};t.exports=function(n){if(!n)return{};for(var s=Object.create(null),i=r(n).split(
),a=0;a<i.length;a++){var c=i[a],l=c.indexOf(":"),u=r(c.slice(0,l)).toLowerCase(),p=r(c.slice(l+1));typeof s[u]>"u"?s[u]=p:o(s[u])?s[u].push(p):s[u]=[s[u],p]}return s}}),bR=gM(yM()),wR=bR.default??bR;var xM=(()=>{var e=globalThis;return{default:e}})(),bM=(()=>{var e=(...t)=>Object.assign({},...t);return{default:e}})(),ds=e=>{let t=o=>typeof o.default<"u"?o.default:o,r=o=>Object.assign({__esModule:!0},o);switch(e){case"npm:global/window":return t(xM);case"is-function":return t(Of);case"parse-headers":return t(Sf);case"npm:xtend":return t(bM);default:return console.error('module "'+e+'" not found'),null}},EM=Object.create,vR=Object.defineProperty,wM=Object.getOwnPropertyDescriptor,RM=Object.getOwnPropertyNames,vM=Object.getPrototypeOf,kM=Object.prototype.hasOwnProperty,yl=(e=>typeof ds<"u"?ds:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof ds<"u"?ds:t)[r]}):e)(function(e){if(typeof ds<"u")return ds.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),TM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_M=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of RM(t))!kM.call(e,n)&&n!==r&&vR(e,n,{get:()=>t[n],enumerable:!(o=wM(t,n))||o.enumerable});return e},PM=(e,t,r)=>(r=e!=null?EM(vM(e)):{},_M(t||!e||!e.__esModule?vR(r,"default",{value:e,enumerable:!0}):r,e)),OM=TM((e,t)=>{"use strict";var r=yl("npm:global/window"),o=yl("is-function"),n=yl("parse-headers"),s=yl("npm:xtend");t.exports=l,t.exports.default=l,l.XMLHttpRequest=r.XMLHttpRequest||f,l.XDomainRequest="withCredentials"in new l.XMLHttpRequest?l.XMLHttpRequest:r.XDomainRequest,i(["get","put","post","patch","head","delete"],function(m){l[m==="delete"?"del":m]=function(h,g,y){return g=c(h,g,y),g.method=m.toUpperCase(),u(g)}});function i(m,h){for(var g=0;g<m.length;g++)h(m[g])}function a(m){for(var h in m)if(m.hasOwnProperty(h))return!1;return!0}function c(m,h,g){var y=m;return o(h)?(g=h,typeof m=="string"&&(y={uri:m})):y=s(h,{uri:m}),y.callback=g,y}function l(m,h,g){return h=c(m,h,g),u(h)}function u(m){if(typeof m.callback>"u")throw new Error("callback argument missing");var h=!1,g=function(j,q,B){h||(h=!0,m.callback(j,q,B))};function y(){b.readyState===4&&setTimeout(R,0)}function x(){var j=void 0;if(b.response?j=b.response:j=b.responseText||p(b),_)try{j=JSON.parse(j)}catch{}return j}function w(j){return clearTimeout(C),j instanceof Error||(j=new Error(""+(j||"Unknown XMLHttpRequest Error"))),j.statusCode=0,g(j,$)}function R(){if(!T){var j;clearTimeout(C),m.useXDR&&b.status===void 0?j=200:j=b.status===1223?204:b.status;var q=$,B=null;return j!==0?(q={body:x(),statusCode:j,method:F,headers:{},url:I,rawRequest:b},b.getAllResponseHeaders&&(q.headers=n(b.getAllResponseHeaders()))):B=new Error("Internal XMLHttpRequest Error"),g(B,q,q.body)}}var b=m.xhr||null;b||(m.cors||m.useXDR?b=new l.XDomainRequest:b=new l.XMLHttpRequest);var E,T,I=b.url=m.uri||m.url,F=b.method=m.method||"GET",A=m.body||m.data,N=b.headers=m.headers||{},P=!!m.sync,_=!1,C,$={body:void 0,headers:{},statusCode:0,method:F,url:I,rawRequest:b};if("json"in m&&m.json!==!1&&(_=!0,N.accept||N.Accept||(N.Accept="application/json"),F!=="GET"&&F!=="HEAD"&&(N["content-type"]||N["Content-Type"]||(N["Content-Type"]="application/json"),A=JSON.stringify(m.json===!0?A:m.json))),b.onreadystatechange=y,b.onload=R,b.onerror=w,b.onprogress=function(){},b.onabort=function(){T=!0},b.ontimeout=w,b.open(F,I,!P,m.username,m.password),P||(b.withCredentials=!!m.withCredentials),!P&&m.timeout>0&&(C=setTimeout(function(){if(!T){T=!0,b.abort("timeout");var j=new Error("XMLHttpRequest timeout");j.code="ETIMEDOUT",w(j)}},m.timeout)),b.setRequestHeader)for(E in N)N.hasOwnProperty(E)&&b.setRequestHeader(E,N[E]);else if(m.headers&&!a(m.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in m&&(b.responseType=m.responseType),"beforeSend"in m&&typeof m.beforeSend=="function"&&m.beforeSend(b),b.send(A||null),b}function p(m){try{if(m.responseType==="document")return m.responseXML;var h=m.responseXML&&m.responseXML.documentElement.nodeName==="parsererror";if(m.responseType===""&&!h)return m.responseXML}catch{}return null}function f(){}}),RR=PM(OM()),xl=RR.default??RR;var bl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},dPe=function(){function e(r){this.value=r}function t(r){var o,n;function s(c,l){return new Promise(function(u,p){var f={key:c,arg:l,resolve:u,reject:p,next:null};n?n=n.next=f:(o=n=f,i(c,l))})}function i(c,l){try{var u=r[c](l),p=u.value;p instanceof e?Promise.resolve(p.value).then(function(f){i("next",f)},function(f){i("throw",f)}):a(u.done?"return":"normal",u.value)}catch(f){a("throw",f)}}function a(c,l){switch(c){case"return":o.resolve({value:l,done:!0});break;case"throw":o.reject(l);break;default:o.resolve({value:l,done:!1});break}o=o.next,o?i(o.key,o.arg):n=null}this._invoke=s,typeof r.return!="function"&&(this.return=void 0)}return typeof Symbol=="function"&&Symbol.asyncIterator&&(t.prototype[Symbol.asyncIterator]=function(){return this}),t.prototype.next=function(r){return this._invoke("next",r)},t.prototype.throw=function(r){return this._invoke("throw",r)},t.prototype.return=function(r){return this._invoke("return",r)},{wrap:function(r){return function(){return new t(r.apply(this,arguments))}},await:function(r){return new e(r)}}}(),_R=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},PR=function(){function e(t,r){for(var o=0;o<r.length;o++){var n=r[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),Lf=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}else return Array.from(e)},Ai="";function SM(e){return
<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>
<td align="center">
<div style="display: table-cell; vertical-align: middle;">
<div style="">+e+</div>
</div>
</td></tr></table>
}var LM=
This page requires a browser that supports WebGL.<br/>
<a href="http://get.webgl.org">Click here to upgrade your browser.</a>
,NM=
It does not appear your computer can support WebGL.<br/>
<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>
,MM=1,CM=2;function IM(e,t,r){function o(i){var a=e.parentNode;a&&(a.innerHTML=SM(i))}function n(i,a){typeof r=="function"?r(i):o(a)}if(!window.WebGLRenderingContext)return n(MM,LM),null;var s=AM(e,t);return s?s.getExtension("OES_standard_derivatives"):n(CM,NM),s}function AM(e,t){for(var r=["webgl","experimental-webgl"],o=null,n=0;n<r.length;++n)try{o=e.getContext(r[n],t)}catch{if(o)break}return o}function hs(e,t,r,o){var n=e.gl,s=n.createShader(r);n.shaderSource(s,t),n.compileShader(s);var i=n.getShaderParameter(s,n.COMPILE_STATUS);return i?s:(Ai=n.getShaderInfoLog(s),console.error("*** Error compiling shader "+s+":"+Ai),e.trigger("error",{shader:s,source:t,type:r,error:Ai,offset:o||0}),n.deleteShader(s),null)}function kR(e,t,r,o){for(var n=e.gl,s=n.createProgram(),i=0;i<t.length;++i)n.attachShader(s,t[i]);if(r)for(var a=0;a<r.length;++a)n.bindAttribLocation(s,o?o[a]:a,r[a]);n.linkProgram(s);var c=n.getProgramParameter(s,n.LINK_STATUS);return c?s:(Ai=n.getProgramInfoLog(s),console.log("Error in program linking:"+Ai),n.deleteProgram(s),null)}function Nf(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=[];for(var o in e){var n=e[o],s=void 0;if(t&&(o=t+"."+o),typeof n=="number")r.push({type:"float",method:"1f",name:o,value:n});else if(Array.isArray(n)){if(typeof n[0]=="number")n.length===1?r.push({type:"float",method:"1f",name:o,value:n}):n.length>=2&&n.length<=4?r.push({type:"vec"+n.length,method:n.length+"fv",name:o,value:n}):n.length>4&&r.push({type:"float[]",method:"1fv",name:o+"[0]",value:n});else if(typeof n[0]=="string")r.push({type:"sampler2D",method:"1i",name:o,value:n});else if(Array.isArray(n[0])&&typeof n[0][0]=="number"){if(n[0].length>=2&&n[0].length<=4)for(s=0;s<n.length;s++)r.push({type:"vec"+n[0].length,method:n[s].length+"fv",name:o+"["+s+"]",value:n[s]})}else if(bl(n[0])==="object")for(s=0;s<n.length;s++)r.push.apply(r,Lf(Nf(n[s],o+"["+s+"]")))}else typeof n=="boolean"?r.push({type:"bool",method:"1i",name:o,value:n}):typeof n=="string"?r.push({type:"sampler2D",method:"1i",name:o,value:n}):(typeof n>"u"?"undefined":bl(n))==="object"&&r.push.apply(r,Lf(Nf(n,o)))}return r}function FM(e){var t=e.getBoundingClientRect();return t.top+t.height>0&&t.top<(window.innerHeight||document.documentElement.clientHeight)}function TR(e){return(e&e-1)===0}function DM(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function UM(e,t){return e&&t?e.toString()!==t.toString():!1}function $M(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(),t.status==200?t.responseText:""}function OR(e){var t=new Set;return Object.assign(e,{on:function(r,o){var n={};n[r]=o,t.add(n)},off:function(r,o){if(o){var n={};n[r]=o,t.delete(n)}else{var s=!0,i=!1,a=void 0;try{for(var c=t[Symbol.iterator](),l;!(s=(l=c.next()).done);s=!0){var u=l.value,p=!0,f=!1,m=void 0;try{for(var h=Object.keys(u)[Symbol.iterator](),g;!(p=(g=h.next()).done);p=!0){var y=g.value;if(y===r){t.delete(u);return}}}catch(x){f=!0,m=x}finally{try{!p&&h.return&&h.return()}finally{if(f)throw m}}}}catch(x){i=!0,a=x}finally{try{!s&&c.return&&c.return()}finally{if(i)throw a}}}},listSubscriptions:function(){var r=!0,o=!1,n=void 0;try{for(var s=t[Symbol.iterator](),i;!(r=(i=s.next()).done);r=!0){var a=i.value;console.log(a)}}catch(c){o=!0,n=c}finally{try{!r&&s.return&&s.return()}finally{if(o)throw n}}},subscribe:function(r){t.add(r)},unsubscribe:function(r){t.delete(r)},unsubscribeAll:function(){t.clear()},trigger:function(r){for(var o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];var i=!0,a=!1,c=void 0;try{for(var l=t[Symbol.iterator](),u;!(i=(u=l.next()).done);i=!0){var p=u.value;typeof p[r]=="function"&&p[r].apply(p,Lf(n))}}catch(f){a=!0,c=f}finally{try{!i&&l.return&&l.return()}finally{if(a)throw c}}}})}var Mf=function(){function e(t,r){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};_R(this,e),OR(this),this.gl=t,this.texture=t.createTexture(),this.texture&&(this.valid=!0),this.bind(),this.name=r,this.source=null,this.sourceType=null,this.loading=null,this.setData(1,1,new Uint8Array([0,0,0,255]),{filtering:"linear"}),this.setFiltering(o.filtering),this.load(o)}return PR(e,[{key:"destroy",value:function(){this.valid&&(this.gl.deleteTexture(this.texture),this.texture=null,delete this.data,this.data=null,this.valid=!1)}},{key:"bind",value:function(t){this.valid&&(typeof t=="number"&&e.activeUnit!==t&&(this.gl.activeTexture(this.gl.TEXTURE0+t),e.activeUnit=t),e.activeTexture!==this.texture&&(this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),e.activeTexture=this.texture))}},{key:"load",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.loading=null,typeof t.url=="string"?(this.url===void 0||t.url!==this.url)&&this.setUrl(t.url,t):t.element?this.setElement(t.element,t):t.data&&t.width&&t.height&&this.setData(t.width,t.height,t.data,t)}},{key:"setUrl",value:function(t){var r=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.valid)return this.url=t,this.source=this.url,this.sourceType="url",this.loading=new Promise(function(n,s){var i=t.split(".").pop().toLowerCase(),a=i==="ogv"||i==="webm"||i==="mp4",c=void 0;a?(c=document.createElement("video"),c.autoplay=!0,c.muted=!0,setTimeout(function(){c.play()},1),o.filtering="nearest"):c=new Image,c.onload=function(){try{r.setElement(c,o)}catch(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o)}n(r)},c.onerror=function(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,o),n(r)},DM()&&r.source.slice(0,5)==="data:"||(c.crossOrigin="anonymous"),c.src=r.source,a&&r.setElement(c,o)}),this.loading}},{key:"setData",value:function(t,r,o){var n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.width=t,this.height=r,this.source=o,this.sourceType="data",this.update(n),this.setFiltering(n),this.loading=Promise.resolve(this),this.loading}},{key:"setElement",value:function(t,r){var o=this,n=t;if(typeof t=="string"&&(t=document.querySelector(t)),t instanceof HTMLCanvasElement||t instanceof HTMLImageElement||t instanceof HTMLVideoElement)this.source=t,this.sourceType="element",t instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight,t.addEventListener("canplaythrough",function(){o.intervalID=setInterval(function(){o.update(r)},15)},!0),t.addEventListener("ended",function(){t.currentTime=0,t.play()},!0)):this.update(r),this.setFiltering(r);else{var s="the 'element' parameter (element: "+JSON.stringify(n)+") must be a CSS ";s+="selector string, or a <canvas>, <image> or <video> object",console.log("Texture '"+this.name+"': "+s,r)}return this.loading=Promise.resolve(this),this.loading}},{key:"update",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.valid&&(this.bind(),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,t.UNPACK_FLIP_Y_WEBGL!==!1),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.UNPACK_PREMULTIPLY_ALPHA_WEBGL||!1),this.sourceType==="element"&&(this.source instanceof HTMLCanvasElement||this.source instanceof HTMLVideoElement||this.source instanceof HTMLImageElement&&this.source.complete)?(this.source instanceof HTMLVideoElement?(this.width=this.source.videoWidth,this.height=this.source.videoHeight):(this.width=this.source.width,this.height=this.source.height),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source)):this.sourceType==="data"&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.width,this.height,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.source),this.trigger("loaded",this))}},{key:"setFiltering",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.valid){this.powerOf2=TR(this.width)&&TR(this.height),this.filtering=t.filtering||"linear";var r=this.gl;this.bind(),this.powerOf2?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,t.TEXTURE_WRAP_S||r.REPEAT),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,t.TEXTURE_WRAP_T||r.REPEAT),this.filtering==="mipmap"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR_MIPMAP_LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.generateMipmap(r.TEXTURE_2D)):this.filtering==="linear"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)):this.filtering==="nearest"&&(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST))):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),this.filtering==="mipmap"&&(this.filtering="linear"),this.filtering==="nearest"?(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST)):(r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR)))}}}]),e}();Mf.getMaxTextureSize=function(e){return e.getParameter(e.MAX_TEXTURE_SIZE)};Mf.activeUnit=-1;var SR=function(){function e(t,r,o){var n=this;_R(this,e),OR(this),r=r||{},o=o||{},t.hasAttribute("data-fullscreen")&&(t.getAttribute("data-fullscreen")=="1"||t.getAttribute("data-fullscreen")=="true")?(this.width=window.innerWidth,this.height=window.innerHeight,t.width=window.innerWidth,t.height=window.innerHeight):(this.width=t.clientWidth,this.height=t.clientHeight),this.canvas=t,this.gl=void 0,this.deps={},this.program=void 0,this.textures={},this.buffers={},this.uniforms={},this.vbo={},this.isValid=!1,this.animationFrameRequest=void 0,this.BUFFER_COUNT=0,this.vertexString=r.vertexString||
#ifdef GL_ES
precision mediump float;
#endif
attribute vec2 a_position;
attribute vec2 a_texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
v_texcoord = a_texcoord;
}
,this.fragmentString=r.fragmentString||
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texcoord;
void main(){
gl_FragColor = vec4(0.0);
}
;var s=IM(t,r,o.onError);if(!s)return;if(this.gl=s,this.timeLoad=this.timePrev=performance.now(),this.timeDelta=0,this.forceRender=!0,this.paused=!1,this.realToCSSPixels=window.devicePixelRatio||1,t.style.backgroundColor=r.backgroundColor||"rgba(1,1,1,0)",t.hasAttribute("data-fragment"))this.fragmentString=t.getAttribute("data-fragment");else if(t.hasAttribute("data-fragment-url")){var i=t.getAttribute("data-fragment-url");xl.get(i,function(g,y,x){n.load(x,n.vertexString)})}if(t.hasAttribute("data-vertex"))this.vertexString=t.getAttribute("data-vertex");else if(t.hasAttribute("data-vertex-url")){var a=t.getAttribute("data-vertex-url");xl.get(a,function(g,y,x){n.load(n.fragmentString,x)})}if(this.load(),!this.program)return;var c=s.getAttribLocation(this.program,"a_texcoord");this.vbo.texCoords=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.texCoords),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(c),this.gl.vertexAttribPointer(c,2,s.FLOAT,!1,0,0);var l=s.getAttribLocation(this.program,"a_position");if(this.vbo.vertices=s.createBuffer(),this.gl.bindBuffer(s.ARRAY_BUFFER,this.vbo.vertices),this.gl.bufferData(s.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),s.STATIC_DRAW),this.gl.enableVertexAttribArray(l),this.gl.vertexAttribPointer(l,2,s.FLOAT,!1,0,0),t.hasAttribute("data-textures")){var u=t.getAttribute("data-textures").split(",");for(var p in u)this.setUniform("u_tex"+p,u[p])}var f={x:0,y:0};document.addEventListener("mousemove",function(g){f.x=g.clientX||g.pageX,f.y=g.clientY||g.pageY},!1);var m=this;function h(){m.nMouse>1&&m.setMouse(f),m.resize()&&(m.forceRender=!0),m.render(),m.animationFrameRequest=window.requestAnimationFrame(h)}return this.setMouse({x:0,y:0}),h(),this}return PR(e,[{key:"destroy",value:function(){cancelAnimationFrame(this.animationFrameRequest),this.animated=!1,this.isValid=!1;for(var t in this.textures)t.destroy&&t.destroy();this.textures={};for(var r in this.attribs)this.gl.deleteBuffer(this.attribs[r]);this.gl.useProgram(null),this.gl.deleteProgram(this.program);for(var o in this.buffers){var n=this.buffers[o];this.gl.deleteProgram(n.program)}this.program=null,this.gl=null}},{key:"load",value:function(t,r){var o=this;r&&(this.vertexString=r),t&&(this.fragmentString=t);var n=this.fragmentString.split(/\r?\n/);this.fragmentString=#define PLATFORM_WEBGL
#line 0
,n.forEach(function(g,y){var x=g.trim();if(x.startsWith('#include "lygia')){var w=x.substring(15).replace(/\'|\"|\;|\s/g,"");if(w.endsWith("glsl")){if(o.deps[w]===void 0){var R="https://lygia.xyz"+w;o.deps[w]=$M(R)}o.fragmentString+=o.deps[w]+
#line +(y+1)+
}}else o.fragmentString+=g+
}),this.animated=!1,this.nDelta=(this.fragmentString.match(/u_delta/g)||[]).length,this.nTime=(this.fragmentString.match(/u_time/g)||[]).length,this.nDate=(this.fragmentString.match(/u_date/g)||[]).length,this.nMouse=(this.fragmentString.match(/u_mouse/g)||[]).length,this.animated=this.nDate>1||this.nTime>1||this.nMouse>1;var s=this.fragmentString.search(/sampler2D/g);if(s)for(var i=this.fragmentString.split(
),a=0;a<i.length;a++){var c=i[a].match(/uniform\s*sampler2D\s*([\w]*);\s*\/\/\s*([\w|\:\/\/|\.|\-|\_]*)/i);if(c){var l=c[2].split(".").pop().toLowerCase();c[1]&&c[2]&&(l==="jpg"||l==="jpeg"||l==="png"||l==="ogv"||l==="webm"||l==="mp4")&&this.setUniform(c[1],c[2])}var u=i[a].match(/\s*void\s*main\s*/g);if(u)break}var p=hs(this,this.vertexString,this.gl.VERTEX_SHADER),f=hs(this,this.fragmentString,this.gl.FRAGMENT_SHADER);f?this.isValid=!0:(f=hs(this,void main(){
gl_FragColor = vec4(1.0);
},this.gl.FRAGMENT_SHADER),this.isValid=!1);var m=kR(this,[p,f]);this.gl.useProgram(m),this.gl.deleteShader(p),this.gl.deleteShader(f),this.program=m,this.change=!0,this.BUFFER_COUNT=0;var h=this.getBuffers(this.fragmentString);Object.keys(h).length&&this.loadPrograms(h),this.buffers=h,this.texureIndex=this.BUFFER_COUNT,this.trigger("load",{}),this.forceRender=!0,this.render()}},{key:"test",value:function(t,r,o){var n=this.vertexString,s=this.fragmentString,i=this.paused,a=this.gl.getExtension("EXT_disjoint_timer_query"),c=a.createQueryEXT(),l=this.isValid;(r||o)&&(this.load(r,o),l=this.isValid,this.forceRender=!0,this.render()),this.paused=!0,a.beginQueryEXT(a.TIME_ELAPSED_EXT,c),this.forceRender=!0,this.render(),a.endQueryEXT(a.TIME_ELAPSED_EXT);var u=this;function p(){u.paused=i,(r||o)&&u.load(s,n)}function f(){u.forceRender=!0,u.render();var m=a.getQueryObjectEXT(c,a.QUERY_RESULT_AVAILABLE_EXT),h=u.gl.getParameter(a.GPU_DISJOINT_EXT);if(m&&!h){var g={wasValid:l,frag:r||u.fragmentString,vert:o||u.vertexString,timeElapsedMs:a.getQueryObjectEXT(c,a.QUERY_RESULT_EXT)/1e6};p(),t(g)}else window.requestAnimationFrame(f)}f()}},{key:"loadTexture",value:function(t,r,o){var n=this;o||(o={}),typeof r=="string"?o.url=r:(typeof r>"u"?"undefined":bl(r))==="object"&&r.data&&r.width&&r.height?(o.data=r.data,o.width=r.width,o.height=r.height):(typeof r>"u"?"undefined":bl(r))==="object"&&(o.element=r),this.textures[t]?this.textures[t]&&(this.textures[t].load(o),this.textures[t].on("loaded",function(s){n.forceRender=!0})):(this.textures[t]=new Mf(this.gl,t,o),this.textures[t].on("loaded",function(s){n.forceRender=!0}))}},{key:"refreshUniforms",value:function(){this.uniforms={}}},{key:"setUniform",value:function(t){for(var r={},o=arguments.length,n=Array(o>1?o-1:0),s=1;s<o;s++)n[s-1]=arguments[s];r[t]=n,this.setUniforms(r)}},{key:"setUniforms",value:function(t){var r=Nf(t);for(var o in r)r[o].type==="sampler2D"?this.loadTexture(r[o].name,r[o].value[0]):this.uniform(r[o].method,r[o].type,r[o].name,r[o].value);this.forceRender=!0}},{key:"setMouse",value:function(t){var r=this.canvas.getBoundingClientRect();if(t&&t.x&&t.x>=r.left&&t.x<=r.right&&t.y&&t.y>=r.top&&t.y<=r.bottom){var o=(t.x-r.left)*this.realToCSSPixels,n=this.canvas.height-(t.y-r.top)*this.realToCSSPixels;this.uniform("2f","vec2","u_mouse",o,n)}}},{key:"uniform",value:function(t,r,o){this.uniforms[o]=this.uniforms[o]||{};for(var n=this.uniforms[o],s=arguments.length,i=Array(s>3?s-3:0),a=3;a<s;a++)i[a-3]=arguments[a];var c=UM(n.value,i);if(c||this.change||!n.location||!n.value){n.name=o,n.type=r,n.value=i,n.method="uniform"+t,this.gl.useProgram(this.program),n.location=this.gl.getUniformLocation(this.program,o),this.gl[n.method].apply(this.gl,[n.location].concat(n.value));for(var l in this.buffers){var u=this.buffers[l];this.gl.useProgram(u.program);var p=this.gl.getUniformLocation(u.program,o);this.gl[n.method].apply(this.gl,[p].concat(n.value))}}}},{key:"uniformTexture",value:function(t,r,o){if(this.textures[t]===void 0)this.loadTexture(t,r,o);else{this.uniform("1i","sampler2D",t,this.texureIndex);for(var n in this.buffers){var s=this.buffers[n];this.gl.useProgram(s.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture)}this.gl.useProgram(this.program),this.gl.activeTexture(this.gl.TEXTURE0+this.texureIndex),this.gl.bindTexture(this.gl.TEXTURE_2D,this.textures[t].texture),this.uniform("2f","vec2",t+"Resolution",this.textures[t].width,this.textures[t].height)}}},{key:"resize",value:function(){if(this.width!==this.canvas.clientWidth||this.height!==this.canvas.clientHeight){this.realToCSSPixels=window.devicePixelRatio||1;var t=Math.floor(this.gl.canvas.clientWidth*this.realToCSSPixels),r=Math.floor(this.gl.canvas.clientHeight*this.realToCSSPixels);return(this.gl.canvas.width!==t||this.gl.canvas.height!==r)&&(this.gl.canvas.width=t,this.gl.canvas.height=r,this.gl.viewport(0,0,this.gl.canvas.width,this.gl.canvas.height)),this.width=this.canvas.clientWidth,this.height=this.canvas.clientHeight,this.resizeSwappableBuffers(),!0}else return!1}},{key:"render",value:function(){if(this.visible=FM(this.canvas),this.forceRender||this.change||this.animated&&this.visible&&!this.paused){var t=new Date,r=performance.now();this.timeDelta=(r-this.timePrev)/1e3,this.timePrev=r,this.nDelta>1&&this.uniform("1f","float","u_delta",this.timeDelta),this.nTime>1&&this.uniform("1f","float","u_time",(r-this.timeLoad)/1e3),this.nDate&&this.uniform("4f","float","u_date",t.getFullYear(),t.getMonth(),t.getDate(),t.getHours()*3600+t.getMinutes()*60+t.getSeconds()+t.getMilliseconds()*.001),this.uniform("2f","vec2","u_resolution",this.canvas.width,this.canvas.height);for(var o in this.buffers){var n=this.buffers[o];this.uniform("1i","sampler2D",n.name,n.bundle.input.index)}this.texureIndex=this.BUFFER_COUNT;for(var s in this.textures)this.uniformTexture(s),this.texureIndex++;this.renderPrograms(),this.trigger("render",{}),this.change=!1,this.forceRender=!1}}},{key:"pause",value:function(){this.paused=!0}},{key:"play",value:function(){this.paused=!1}},{key:"renderPrograms",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.render(r,o,s.program,s.name),t.bindFramebuffer(t.FRAMEBUFFER,null)}t.useProgram(this.program),t.drawArrays(t.TRIANGLES,0,6)}},{key:"getBuffers",value:function(t){var r={};return t&&t.replace(/(?:^\s*)((?:#if|#elif)(?:\s*)(defined\s*\(\s*BUFFER_)(\d+)(?:\s*\))|(?:#ifdef)(?:\s*BUFFER_)(\d+)(?:\s*))/gm,function(){var o=arguments[3]||arguments[4];r["u_buffer"+o]={fragment:"#define BUFFER_"+o+
+t}}),r}},{key:"loadPrograms",value:function(t){var r=this,o=this.gl,n=hs(r,r.vertexString,o.VERTEX_SHADER);for(var s in t){var i=t[s],a=hs(r,i.fragment,o.FRAGMENT_SHADER,1);a?r.isValid=!0:(a=hs(r,void main(){
gl_FragColor = vec4(1.0);
},o.FRAGMENT_SHADER),r.isValid=!1);var c=kR(r,[n,a]);i.name=s,i.program=c,i.bundle=r.createSwappableBuffer(r.canvas.width,r.canvas.height,c),o.deleteShader(a)}o.deleteShader(n)}},{key:"createSwappableBuffer",value:function(t,r,o){var n=this.createBuffer(t,r,o),s=this.createBuffer(t,r,o),i=this.gl;return{input:n,output:s,swap:function(){var a=n;n=s,s=a,this.input=n,this.output=s},render:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),i.bindFramebuffer(i.FRAMEBUFFER,this.input.buffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.output.texture,0),i.drawArrays(i.TRIANGLES,0,6),this.swap()},resize:function(a,c,l,u){i.useProgram(l),i.viewport(0,0,a,c),this.input.resize(a,c),this.output.resize(a,c)}}}},{key:"createBuffer",value:function(t,r,o){var n=this.gl,s=this.BUFFER_COUNT;this.BUFFER_COUNT+=2,n.getExtension("OES_texture_float");var i=n.createTexture();n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,i),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,t,r,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE);var a=n.createFramebuffer();return{index:s,texture:i,buffer:a,W:t,H:r,resize:function(c,l){n.bindFramebuffer(n.FRAMEBUFFER,a);var u=Math.min(c,this.W),p=Math.min(l,this.H),f=new Float32Array(u*p*4);n.readPixels(0,0,u,p,n.RGBA,n.FLOAT,f),n.bindFramebuffer(n.FRAMEBUFFER,null);var m=s+1,h=n.createTexture();n.activeTexture(n.TEXTURE0+m),n.bindTexture(n.TEXTURE_2D,h),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,c,l,0,n.RGBA,n.FLOAT,null),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.NEAREST),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texSubImage2D(n.TEXTURE_2D,0,0,0,u,p,n.RGBA,n.FLOAT,f);var g=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.activeTexture(n.TEXTURE0+s),n.bindTexture(n.TEXTURE_2D,h),s=this.index=s,i=this.texture=h,a=this.buffer=g,this.W=c,this.H=l}}}},{key:"resizeSwappableBuffers",value:function(){var t=this.gl,r=t.canvas.width,o=t.canvas.height;t.viewport(0,0,r,o);for(var n in this.buffers){var s=this.buffers[n];s.bundle.resize(r,o,s.program,s.name)}t.useProgram(this.program)}},{key:"version",value:function(){return"0.1.7"}}]),e}();function jM(){var e=document.getElementsByClassName("glslCanvas");if(e.length>0){window.glslCanvases=[];for(var t=0;t<e.length;t++){var r=new SR(e[t]);r.isValid&&window.glslCanvases.push(r)}}}window.addEventListener("load",function(){jM()});var El=SR;var LR=e=>{if(!("after"in e))return Promise.resolve(void 0);let t=document.createElement("canvas");return new El(t).load(ir(e.after)),e.render(t),Promise.resolve(void 0)};var NR=e=>{let t="";for(let r=0;r<e.length;r+=3)r+2===e.length?t+=Cf(e[r],e[r+1],0):r+1===e.length?t+=Cf(e[r],0,0):t+=Cf(e[r],e[r+1],e[r+2]);return t},wl=e=>e<10?String.fromCharCode(48+e):(e-=10,e<26?String.fromCharCode(65+e):(e-=26,e<26?String.fromCharCode(97+e):(e-=26,e===0?"-":e===1?"_":"?"))),Cf=(e,t,r)=>{let o=e>>2,n=(e&3)<<4|t>>4,s=(t&15)<<2|r>>6,i=r&63;return wl(o&63)+wl(n&63)+wl(s&63)+wl(i&63)};var MR=async(e,t="svg")=>{let r=new Blob([new TextEncoder().encode(e)]).stream().pipeThrough(new CompressionStream("deflate")),o=new Uint8Array(await new Response(r).arrayBuffer());returnhttps://www.plantuml.com/plantuml/${t}/~1${NR(o)}};var CR=async e=>{if(!("after"in e))return;let t=document.createElement("img"),r=await MR(ir(e.after));t.src=r,e.render(t)};var If=Promise.resolve({log:new Uint8Array(0)}),Rl,IR=(e,t,r,o)=>(If=(async()=>{await If,Rl??=await BM(t,r);let n=new Promise(i=>{let a=c=>{if(c.data.type==="stdout"){o(c.data.message);return}c.data.type==="compile"&&(i(c.data),Rl.removeEventListener("message",a))};Rl.addEventListener("message",a)}),s={type:"compile",input:e};return Rl.postMessage(s),n})(),If),BM=async(e,t)=>{let r=new Worker(e,{type:"module"}),o=new Promise(s=>{let i=a=>{a.data.type==="asset-url"&&(s(),r.removeEventListener("message",i))};r.addEventListener("message",i)}),n={type:"asset-url",url:${t}};return r.postMessage(n),await o,r};var AR=(e,t)=>async r=>{if(!("after"in r))return;let o=HM(),n="Compile is not started yet. Please wait...",s=l=>{n=[...n.split(
),l].join(
),o.log(n)},i=document.createElement("img"),a=setTimeout(()=>{r.render(o.div),o.log(n)},2e3),{svg:c}=await IR(ir(r.after),e,t,s);if(clearTimeout(a),!c){r.render(o.div),o.log(n);return}i.src=await Ii(new Blob([c],{type:"image/svg+xml"})),r.render(i)},HM=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"}),r=document.createElement("style");r.textContent='*{box-sizing:border-box;}pre{display:block;padding:9.5px;margin:0 0 10px;border:1px solid #ccc;border-radius:4px;height:20em;overflow:auto;font-size:13px;line-height:1.428571429;}pre code{padding:0;font-family:Menlo,Monaco,Consolas,"Courier New",monospace;font-size:inherit;word-break:break-all;word-wrap:break-word;white-space:pre-wrap;color:var(--code-color,#342d9c);background-color: rgba(0,0,0,0);border-radius:0;}',t.append(r);let o=document.createElement("pre"),n=document.createElement("code");return o.append(n),t.append(o),{div:e,log:s=>{n.textContent=s,o.scroll(0,o.scrollHeight)}}};function Qt(e,t){return Ne(e,{...t,weekStartsOn:1})}function On(e,t){let r=v(e,t?.in),o=r.getFullYear(),n=U(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=Qt(n),i=U(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=Qt(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function Fi(e,t){let r=On(e,t),o=U(t?.in||e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Qt(o)}function Af(e,t){let r,o=t?.in;return e.forEach(n=>{!o&&typeof n=="object"&&(o=U.bind(null,n));let s=v(n,o);(!r||r<s||isNaN(+s))&&(r=s)}),U(o,r||NaN)}function Di(e,t,r){let o=lc(e,t)/1e3;return Dr(r?.roundingMethod)(o)}function vl(e){return(t={})=>{let r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}function gs(e){return(t,r)=>{let o=r?.context?String(r.context):"standalone",n;if(o==="formatting"&&e.formattingValues){let i=e.defaultFormattingWidth||e.defaultWidth,a=r?.width?String(r.width):i;n=e.formattingValues[a]||e.formattingValues[i]}else{let i=e.defaultWidth,a=r?.width?String(r.width):e.defaultWidth;n=e.values[a]||e.values[i]}let s=e.argumentCallback?e.argumentCallback(t):t;return n[s]}}var JM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},QM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},ZM={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},eC={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},tC={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},rC={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},oC=(e,t)=>{let r=Number(e),o=r%100;if(o>20||o<10)switch(o%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},nC={ordinalNumber:oC,era:gs({values:JM,defaultWidth:"wide"}),quarter:gs({values:QM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:gs({values:ZM,defaultWidth:"wide"}),day:gs({values:eC,defaultWidth:"wide"}),dayPeriod:gs({values:tC,defaultWidth:"wide",formattingValues:rC,defaultFormattingWidth:"wide"})};function ys(e){return(t,r={})=>{let o=r.width,n=o&&e.matchPatterns[o]||e.matchPatterns[e.defaultMatchWidth],s=t.match(n);if(!s)return null;let i=s[0],a=o&&e.parsePatterns[o]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(a)?iC(a,p=>p.test(i)):sC(a,p=>p.test(i)),l;l=e.valueCallback?e.valueCallback(c):c,l=r.valueCallback?r.valueCallback(l):l;let u=t.slice(i.length);return{value:l,rest:u}}}function sC(e,t){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function iC(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function $R(e){return(t,r={})=>{let o=t.match(e.matchPattern);if(!o)return null;let n=o[0],s=t.match(e.parsePattern);if(!s)return null;let i=e.valueCallback?e.valueCallback(s[0]):s[0];i=r.valueCallback?r.valueCallback(i):i;let a=t.slice(n.length);return{value:i,rest:a}}}var aC=/^(\d+)(th|st|nd|rd)?/i,cC=/\d+/i,lC={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},pC={any:[/^b/i,/^(a|c)/i]},uC={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},mC={any:[/1/i,/2/i,/3/i,/4/i]},fC={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},dC={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},hC={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},gC={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},yC={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},xC={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},bC={ordinalNumber:$R({matchPattern:aC,parsePattern:cC,valueCallback:e=>parseInt(e,10)}),era:ys({matchPatterns:lC,defaultMatchWidth:"wide",parsePatterns:pC,defaultParseWidth:"any"}),quarter:ys({matchPatterns:uC,defaultMatchWidth:"wide",parsePatterns:mC,defaultParseWidth:"any",valueCallback:e=>e+1}),month:ys({matchPatterns:fC,defaultMatchWidth:"wide",parsePatterns:dC,defaultParseWidth:"any"}),day:ys({matchPatterns:hC,defaultMatchWidth:"wide",parsePatterns:gC,defaultParseWidth:"any"}),dayPeriod:ys({matchPatterns:yC,defaultMatchWidth:"any",parsePatterns:xC,defaultParseWidth:"any"})};var EC={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},wC={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},RC={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},KNe={date:vl({formats:EC,defaultWidth:"full"}),time:vl({formats:wC,defaultWidth:"full"}),dateTime:vl({formats:RC,defaultWidth:"full"})};function Ff(e,t){let r=v(e,t?.in),o=+Qt(r)-+Fi(r);return Math.round(o/Jo)+1}function jR(e,t){let r=v(e,t?.in).getDay();return r===0?7:r}function Df(e){return Math.trunc(+v(e)/1e3)}function WR(e,t,r){let o=v(e,r?.in),n=Ff(o,r)-t;return o.setDate(o.getDate()-n*7),o}function bs(e,t,r){let o=xt(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=v(e,r?.in),i=s.getDay(),a=(t%7+7)%7,c=7-n,l=t<0||t>6?t-(i+c)%7:(a+c)%7-(i+c)%7;return ke(s,l,r)}function qR(e,t,r){let o=v(e,r?.in),n=jR(o,r),s=t-n;return ke(o,s,r)}var MC=class{subPriority=0;validate(e,t){return!0}},CC=class extends MC{constructor(e,t,r,o,n){super(),this.value=e,this.validateValue=t,this.setValue=r,this.priority=o,n&&(this.subPriority=n)}validate(e,t){return this.validateValue(e,this.value,t)}set(e,t,r){return this.setValue(e,t,this.value,r)}};var de=class{run(e,t,r,o){let n=this.parse(e,t,r,o);return n?{setter:new CC(n.value,this.validate,this.set,this.priority,this.subPriority),rest:n.rest}:null}validate(e,t,r){return!0}},IC=class extends de{priority=140;parse(e,t,r){switch(t){case"G":case"GG":case"GGG":return r.era(e,{width:"abbreviated"})||r.era(e,{width:"narrow"});case"GGGGG":return r.era(e,{width:"narrow"});default:return r.era(e,{width:"wide"})||r.era(e,{width:"abbreviated"})||r.era(e,{width:"narrow"})}}set(e,t,r){return t.era=r,e.setFullYear(r,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["R","u","t","T"]},Ze={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},Wr={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function et(e,t){return e&&{value:t(e.value),rest:e.rest}}function $e(e,t){let r=t.match(e);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function qr(e,t){let r=t.match(e);if(!r)return null;if(r[0]==="Z")return{value:0,rest:t.slice(1)};let o=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,s=r[3]?parseInt(r[3],10):0,i=r[5]?parseInt(r[5],10):0;return{value:o*(n*Lo+s*Ar+i*ac),rest:t.slice(r[0].length)}}function GR(e){return $e(Ze.anyDigitsSigned,e)}function qe(e,t){switch(e){case 1:return $e(Ze.singleDigit,t);case 2:return $e(Ze.twoDigits,t);case 3:return $e(Ze.threeDigits,t);case 4:return $e(Ze.fourDigits,t);default:return $e(new RegExp("^\\d{1,"+e+"}"),t)}}function kl(e,t){switch(e){case 1:return $e(Ze.singleDigitSigned,t);case 2:return $e(Ze.twoDigitsSigned,t);case 3:return $e(Ze.threeDigitsSigned,t);case 4:return $e(Ze.fourDigitsSigned,t);default:return $e(new RegExp("^-?\\d{1,"+e+"}"),t)}}function Uf(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function zR(e,t){let r=t>0,o=r?t:1-t,n;if(o<=50)n=e||100;else{let s=o+50,i=Math.trunc(s/100)*100,a=e>=s%100;n=e+i-(a?100:0)}return r?n:1-n}function VR(e){return e%400===0||e%4===0&&e%100!==0}var AC=class extends de{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(e,t,r){let o=n=>({year:n,isTwoDigitYear:t==="yy"});switch(t){case"y":return et(qe(4,e),o);case"yo":return et(r.ordinalNumber(e,{unit:"year"}),o);default:return et(qe(t.length,e),o)}}validate(e,t){return t.isTwoDigitYear||t.year>0}set(e,t,r){let o=e.getFullYear();if(r.isTwoDigitYear){let s=zR(r.year,o);return e.setFullYear(s,0,1),e.setHours(0,0,0,0),e}let n=!("era"in t)||t.era===1?r.year:1-r.year;return e.setFullYear(n,0,1),e.setHours(0,0,0,0),e}},FC=class extends de{priority=130;parse(e,t,r){let o=n=>({year:n,isTwoDigitYear:t==="YY"});switch(t){case"Y":return et(qe(4,e),o);case"Yo":return et(r.ordinalNumber(e,{unit:"year"}),o);default:return et(qe(t.length,e),o)}}validate(e,t){return t.isTwoDigitYear||t.year>0}set(e,t,r,o){let n=Qo(e,o);if(r.isTwoDigitYear){let i=zR(r.year,n);return e.setFullYear(i,0,o.firstWeekContainsDate),e.setHours(0,0,0,0),Ne(e,o)}let s=!("era"in t)||t.era===1?r.year:1-r.year;return e.setFullYear(s,0,o.firstWeekContainsDate),e.setHours(0,0,0,0),Ne(e,o)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]},DC=class extends de{priority=130;parse(e,t){return kl(t==="R"?4:t.length,e)}set(e,t,r){let o=U(e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Qt(o)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]},UC=class extends de{priority=130;parse(e,t){return kl(t==="u"?4:t.length,e)}set(e,t,r){return e.setFullYear(r,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]},$C=class extends de{priority=120;parse(e,t,r){switch(t){case"Q":case"QQ":return qe(t.length,e);case"Qo":return r.ordinalNumber(e,{unit:"quarter"});case"QQQ":return r.quarter(e,{width:"abbreviated",context:"formatting"})||r.quarter(e,{width:"narrow",context:"formatting"});case"QQQQQ":return r.quarter(e,{width:"narrow",context:"formatting"});default:return r.quarter(e,{width:"wide",context:"formatting"})||r.quarter(e,{width:"abbreviated",context:"formatting"})||r.quarter(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=1&&t<=4}set(e,t,r){return e.setMonth((r-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]},jC=class extends de{priority=120;parse(e,t,r){switch(t){case"q":case"qq":return qe(t.length,e);case"qo":return r.ordinalNumber(e,{unit:"quarter"});case"qqq":return r.quarter(e,{width:"abbreviated",context:"standalone"})||r.quarter(e,{width:"narrow",context:"standalone"});case"qqqqq":return r.quarter(e,{width:"narrow",context:"standalone"});default:return r.quarter(e,{width:"wide",context:"standalone"})||r.quarter(e,{width:"abbreviated",context:"standalone"})||r.quarter(e,{width:"narrow",context:"standalone"})}}validate(e,t){return t>=1&&t<=4}set(e,t,r){return e.setMonth((r-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]},BC=class extends de{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(e,t,r){let o=n=>n-1;switch(t){case"M":return et($e(Ze.month,e),o);case"MM":return et(qe(2,e),o);case"Mo":return et(r.ordinalNumber(e,{unit:"month"}),o);case"MMM":return r.month(e,{width:"abbreviated",context:"formatting"})||r.month(e,{width:"narrow",context:"formatting"});case"MMMMM":return r.month(e,{width:"narrow",context:"formatting"});default:return r.month(e,{width:"wide",context:"formatting"})||r.month(e,{width:"abbreviated",context:"formatting"})||r.month(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=0&&t<=11}set(e,t,r){return e.setMonth(r,1),e.setHours(0,0,0,0),e}},HC=class extends de{priority=110;parse(e,t,r){let o=n=>n-1;switch(t){case"L":return et($e(Ze.month,e),o);case"LL":return et(qe(2,e),o);case"Lo":return et(r.ordinalNumber(e,{unit:"month"}),o);case"LLL":return r.month(e,{width:"abbreviated",context:"standalone"})||r.month(e,{width:"narrow",context:"standalone"});case"LLLLL":return r.month(e,{width:"narrow",context:"standalone"});default:return r.month(e,{width:"wide",context:"standalone"})||r.month(e,{width:"abbreviated",context:"standalone"})||r.month(e,{width:"narrow",context:"standalone"})}}validate(e,t){return t>=0&&t<=11}set(e,t,r){return e.setMonth(r,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]},WC=class extends de{priority=100;parse(e,t,r){switch(t){case"w":return $e(Ze.week,e);case"wo":return r.ordinalNumber(e,{unit:"week"});default:return qe(t.length,e)}}validate(e,t){return t>=1&&t<=53}set(e,t,r,o){return Ne(uc(e,r,o),o)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]},qC=class extends de{priority=100;parse(e,t,r){switch(t){case"I":return $e(Ze.week,e);case"Io":return r.ordinalNumber(e,{unit:"week"});default:return qe(t.length,e)}}validate(e,t){return t>=1&&t<=53}set(e,t,r){return Qt(WR(e,r))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]},GC=[31,28,31,30,31,30,31,31,30,31,30,31],zC=[31,29,31,30,31,30,31,31,30,31,30,31],VC=class extends de{priority=90;subPriority=1;parse(e,t,r){switch(t){case"d":return $e(Ze.date,e);case"do":return r.ordinalNumber(e,{unit:"date"});default:return qe(t.length,e)}}validate(e,t){let r=e.getFullYear(),o=VR(r),n=e.getMonth();return o?t>=1&&t<=zC[n]:t>=1&&t<=GC[n]}set(e,t,r){return e.setDate(r),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]},KC=class extends de{priority=90;subpriority=1;parse(e,t,r){switch(t){case"D":case"DD":return $e(Ze.dayOfYear,e);case"Do":return r.ordinalNumber(e,{unit:"date"});default:return qe(t.length,e)}}validate(e,t){let r=e.getFullYear();return VR(r)?t>=1&&t<=366:t>=1&&t<=365}set(e,t,r){return e.setMonth(0,r),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]},YC=class extends de{priority=90;parse(e,t,r){switch(t){case"E":case"EE":case"EEE":return r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});case"EEEEE":return r.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});default:return r.day(e,{width:"wide",context:"formatting"})||r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=0&&t<=6}set(e,t,r,o){return e=bs(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]},XC=class extends de{priority=90;parse(e,t,r,o){let n=s=>{let i=Math.floor((s-1)/7)*7;return(s+o.weekStartsOn+6)%7+i};switch(t){case"e":case"ee":return et(qe(t.length,e),n);case"eo":return et(r.ordinalNumber(e,{unit:"day"}),n);case"eee":return r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});case"eeeee":return r.day(e,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"});default:return r.day(e,{width:"wide",context:"formatting"})||r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"})}}validate(e,t){return t>=0&&t<=6}set(e,t,r,o){return e=bs(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]},JC=class extends de{priority=90;parse(e,t,r,o){let n=s=>{let i=Math.floor((s-1)/7)*7;return(s+o.weekStartsOn+6)%7+i};switch(t){case"c":case"cc":return et(qe(t.length,e),n);case"co":return et(r.ordinalNumber(e,{unit:"day"}),n);case"ccc":return r.day(e,{width:"abbreviated",context:"standalone"})||r.day(e,{width:"short",context:"standalone"})||r.day(e,{width:"narrow",context:"standalone"});case"ccccc":return r.day(e,{width:"narrow",context:"standalone"});case"cccccc":return r.day(e,{width:"short",context:"standalone"})||r.day(e,{width:"narrow",context:"standalone"});default:return r.day(e,{width:"wide",context:"standalone"})||r.day(e,{width:"abbreviated",context:"standalone"})||r.day(e,{width:"short",context:"standalone"})||r.day(e,{width:"narrow",context:"standalone"})}}validate(e,t){return t>=0&&t<=6}set(e,t,r,o){return e=bs(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]},QC=class extends de{priority=90;parse(e,t,r){let o=n=>n===0?7:n;switch(t){case"i":case"ii":return qe(t.length,e);case"io":return r.ordinalNumber(e,{unit:"day"});case"iii":return et(r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o);case"iiiii":return et(r.day(e,{width:"narrow",context:"formatting"}),o);case"iiiiii":return et(r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o);default:return et(r.day(e,{width:"wide",context:"formatting"})||r.day(e,{width:"abbreviated",context:"formatting"})||r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o)}}validate(e,t){return t>=1&&t<=7}set(e,t,r){return e=qR(e,r),e.setHours(0,0,0,0),e}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]},ZC=class extends de{priority=80;parse(e,t,r){switch(t){case"a":case"aa":case"aaa":return r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"});case"aaaaa":return r.dayPeriod(e,{width:"narrow",context:"formatting"});default:return r.dayPeriod(e,{width:"wide",context:"formatting"})||r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,t,r){return e.setHours(Uf(r),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]},eI=class extends de{priority=80;parse(e,t,r){switch(t){case"b":case"bb":case"bbb":return r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"});case"bbbbb":return r.dayPeriod(e,{width:"narrow",context:"formatting"});default:return r.dayPeriod(e,{width:"wide",context:"formatting"})||r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,t,r){return e.setHours(Uf(r),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]},tI=class extends de{priority=80;parse(e,t,r){switch(t){case"B":case"BB":case"BBB":return r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"});case"BBBBB":return r.dayPeriod(e,{width:"narrow",context:"formatting"});default:return r.dayPeriod(e,{width:"wide",context:"formatting"})||r.dayPeriod(e,{width:"abbreviated",context:"formatting"})||r.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,t,r){return e.setHours(Uf(r),0,0,0),e}incompatibleTokens=["a","b","t","T"]},rI=class extends de{priority=70;parse(e,t,r){switch(t){case"h":return $e(Ze.hour12h,e);case"ho":return r.ordinalNumber(e,{unit:"hour"});default:return qe(t.length,e)}}validate(e,t){return t>=1&&t<=12}set(e,t,r){let o=e.getHours()>=12;return o&&r<12?e.setHours(r+12,0,0,0):!o&&r===12?e.setHours(0,0,0,0):e.setHours(r,0,0,0),e}incompatibleTokens=["H","K","k","t","T"]},oI=class extends de{priority=70;parse(e,t,r){switch(t){case"H":return $e(Ze.hour23h,e);case"Ho":return r.ordinalNumber(e,{unit:"hour"});default:return qe(t.length,e)}}validate(e,t){return t>=0&&t<=23}set(e,t,r){return e.setHours(r,0,0,0),e}incompatibleTokens=["a","b","h","K","k","t","T"]},nI=class extends de{priority=70;parse(e,t,r){switch(t){case"K":return $e(Ze.hour11h,e);case"Ko":return r.ordinalNumber(e,{unit:"hour"});default:return qe(t.length,e)}}validate(e,t){return t>=0&&t<=11}set(e,t,r){return e.getHours()>=12&&r<12?e.setHours(r+12,0,0,0):e.setHours(r,0,0,0),e}incompatibleTokens=["h","H","k","t","T"]},sI=class extends de{priority=70;parse(e,t,r){switch(t){case"k":return $e(Ze.hour24h,e);case"ko":return r.ordinalNumber(e,{unit:"hour"});default:return qe(t.length,e)}}validate(e,t){return t>=1&&t<=24}set(e,t,r){let o=r<=24?r%24:r;return e.setHours(o,0,0,0),e}incompatibleTokens=["a","b","h","H","K","t","T"]},iI=class extends de{priority=60;parse(e,t,r){switch(t){case"m":return $e(Ze.minute,e);case"mo":return r.ordinalNumber(e,{unit:"minute"});default:return qe(t.length,e)}}validate(e,t){return t>=0&&t<=59}set(e,t,r){return e.setMinutes(r,0,0),e}incompatibleTokens=["t","T"]},aI=class extends de{priority=50;parse(e,t,r){switch(t){case"s":return $e(Ze.second,e);case"so":return r.ordinalNumber(e,{unit:"second"});default:return qe(t.length,e)}}validate(e,t){return t>=0&&t<=59}set(e,t,r){return e.setSeconds(r,0),e}incompatibleTokens=["t","T"]},cI=class extends de{priority=30;parse(e,t){let r=o=>Math.trunc(o*Math.pow(10,-t.length+3));return et(qe(t.length,e),r)}set(e,t,r){return e.setMilliseconds(r),e}incompatibleTokens=["t","T"]},lI=class extends de{priority=10;parse(e,t){switch(t){case"X":return qr(Wr.basicOptionalMinutes,e);case"XX":return qr(Wr.basic,e);case"XXXX":return qr(Wr.basicOptionalSeconds,e);case"XXXXX":return qr(Wr.extendedOptionalSeconds,e);default:return qr(Wr.extended,e)}}set(e,t,r){return t.timestampIsSet?e:U(e,e.getTime()-fr(e)-r)}incompatibleTokens=["t","T","x"]},pI=class extends de{priority=10;parse(e,t){switch(t){case"x":return qr(Wr.basicOptionalMinutes,e);case"xx":return qr(Wr.basic,e);case"xxxx":return qr(Wr.basicOptionalSeconds,e);case"xxxxx":return qr(Wr.extendedOptionalSeconds,e);default:return qr(Wr.extended,e)}}set(e,t,r){return t.timestampIsSet?e:U(e,e.getTime()-fr(e)-r)}incompatibleTokens=["t","T","X"]},uI=class extends de{priority=40;parse(e){return GR(e)}set(e,t,r){return[U(e,r*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"},mI=class extends de{priority=20;parse(e){return GR(e)}set(e,t,r){return[U(e,r),{timestampIsSet:!0}]}incompatibleTokens="*"},XIe={G:new IC,y:new AC,Y:new FC,R:new DC,u:new UC,Q:new $C,q:new jC,M:new BC,L:new HC,w:new WC,I:new qC,d:new VC,D:new KC,E:new YC,e:new XC,c:new JC,i:new QC,a:new ZC,b:new eI,B:new tI,h:new rI,H:new oI,K:new nI,k:new sI,m:new iI,s:new aI,S:new cI,X:new lI,x:new pI,t:new uI,T:new mI};var KR=(e,t,r=0,o=[])=>{let[n,s]=Q("uninitialized"),[i,a]=Q({ok:!0,value:t}),c=D(e,o);return te(()=>{(async()=>{let l=setTimeout(()=>s("pending"),r);try{let u=await c();if(u===void 0)return;a({ok:!0,value:u})}catch(u){a({ok:!1,value:u})}finally{clearTimeout(l),s("resolved")}})()},[c,r,...o]),i.ok?{result:i.value,state:n}:{result:i.value,state:"rejected"}};var YR=e=>{let t=e.flatMap(({changes:n,created:s,userId:i})=>n.flatMap(a=>{let c=xI(a,i,s);return c?[c]:[]})),r=[...new Set(t.map(({created:n})=>n))].sort();return{history:t.reduce((n,s)=>{if(s.type==="insert"){let a=new Map;a.set(s.created,{text:s.text,type:s.type,userId:s.userId});let c={id:s.id,snapshots:a};if(s.parentId==="_end")return[...n,c];let l=n.findIndex(({id:u})=>u===s.parentId);return l<0?(console.warn("[scrapbox-snapshot@0.1.0] The parent line the snapshot would insert before is not found. change: ",s),[...n,c]):[...n.slice(0,l),c,...n.slice(l)]}let i=n.findIndex(({id:a})=>a===s.id);return i<0?(console.warn("[scrapbox-snapshot@0.1.0] The line data to be append the change is not found. change: ",s),n):(n[i].snapshots.set(s.created,{text:s.type==="update"?s.text:void 0,type:s.type,userId:s.userId}),n)},[]),range:r}},xI=(e,t,r)=>{if("_insert"in e)return{type:"insert",id:e.lines.id,parentId:e._insert,text:e.lines.text,userId:t,created:r};if("_update"in e)return{type:"update",id:e._update,text:e.lines.text,userId:t,created:r};if("_delete"in e)return{type:"delete",id:e._delete,userId:t,created:r}};var Zt=e=>{let{fetch:t=(n,s)=>globalThis.fetch(n,s),baseURL:r="https://scrapbox.io/",...o}=e;return{fetch:t,baseURL:r,...o}};var er=e=>connect.sid=${e};var bI=(e,t,r)=>{let{sid:o,baseURL:n,head:s}=Zt(r??{});return new Request(${n}api/commits/${e}/${t}?head=${s??""},o?{headers:{Cookie:er(o)}}:void 0)},XR=(e,t,r)=>Zt(r??{}).fetch(bI(e,t,r));var QR=async(e,t)=>{let r=await XR(e,t);if(!r.ok)throw new Error(Failed to fetch commits for ${e}/${t}: ${r.statusText},{cause:r});return YR((await r.json()).commits)};var ZR=()=>{let e=document.createElement("div");e.dataset.userscriptName="takker99/scrapbox-history-slider";let t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>Tt(d(RI,{getController:o=>r(o)}),t))},RI=({getController:e})=>{let[t,r]=Q(!0),o=D(()=>r(!1),[]),n=D(()=>r(!0),[]),s=D(()=>r(h=>!h),[]);te(()=>e({open:o,close:n,toggle:s}),[e]);let i=D(h=>{h.target instanceof HTMLElement&&h.target.id==="background"&&n()},[]),{state:a,result:c}=KR(async()=>{if(t||scrapbox.Layout!=="page")return;let h=await QR(scrapbox.Project.name,scrapbox.Page.id);return{range:h.range,getSnapshot:g=>h.history.flatMap(({snapshots:y})=>{let x=y.get(g);if(x)return x.text===void 0?[]:[x.text];let w=Math.max(...[...y.keys()].filter(b=>b<g));if(w===g)return[];let R=y.get(w)?.text;return R===void 0?[]:[R]})}},{range:[],getSnapshot:()=>[]},1e3,[t]),[l,u]=Q(0),[p,f]=Q(0);te(()=>{if(a!=="resolved")return;let h=Math.max(0,c.range.length-1);u(h),f(h)},[c]);let m=D(h=>f(parseInt(h.currentTarget.value)),[]);return d(ee,{children:[d("style",{children:'.modal{position:fixed;inset:0;z-index:1050;background-color:#000c;display:flex;flex-direction:column;align-items:center;row-gap:10px;padding:10px}.closed{display:none}.modal>*{color:var(--page-text-color, #4a4a4a);background-color:var(--page-bg, #fefefe);border:2px solid var(--body-bg, #dcdde0);border-radius:4px;padding:5px;width:calc(var(--item-width, 100%) - 10px)}@media (min-width: 768px){.modal{padding:30px}}.controller{display:flex;flex-direction:row-reverse;gap:.2em}input{width:100%}time{white-space:nowrap}.viewer{overflow-y:scroll}pre{width:100%;font-family:var(--history-slider-pre-font, Menlo,Monaco,Consolas,"Courier New",monospace);word-break:break-all;word-wrap:break-word;white-space:pre-wrap}'}),d("div",{id:"background",className:modal${t?" closed":""},onClick:i,children:[d("div",{className:"controller",children:[d("button",{type:"button",className:"close-button",onClick:n,children:"x"}),a==="resolved"&&c.range.length===0&&d("span",{className:"not-found",children:"no history found."}),a!=="rejected"&&c.range.length>0&&d(ee,{children:[d("input",{type:"range",max:l,min:"0",step:"1",value:p,title:lt(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),onInput:m}),d("time",{dateTime:lt(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),children:lt(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss")})]})]}),a!=="rejected"?d("div",{className:"viewer",children:d("pre",{children:c.getSnapshot(c.range[p]).join(
)})}):d("div",{className:"error viewer",children:Error: ${JSON.stringify(c)}})]})]})};var fo=()=>/mobile/i.test(navigator.userAgent);function ev(e){return Ye(e)?L(e):(K(e),e)}var vI=Object.defineProperty,kI=(e,t)=>{for(var r in t)vI(e,r,{get:t[r],enumerable:!0})},TI={};kI(TI,{andThen:()=>Xp,andThenAsync:()=>Jp,inspect:()=>Qp,map:()=>Zp,mapAsync:()=>eu,mapOr:()=>tu,mapOrAsync:()=>ru,mapOrElse:()=>ou,mapOrElseAsync:()=>nu,okOr:()=>su,okOrElse:()=>Vs,okOrElseAsync:()=>iu,orElse:()=>au,orElseAsync:()=>cu,toNullable:()=>lu,toResultErr:()=>pu,toResultOk:()=>Oa,toUndefinable:()=>uu,transposeToResult:()=>ev,unwrapOr:()=>Ks,unwrapOrElse:()=>mu,unwrapOrElseAsync:()=>fu});function tv(e,t){return rt(e)?e:t(e)}async function rv(e,t){return rt(e)?null:await t(e)}function ov(e,t){return je(e)&&t(e),e}function nv(e,t){if(rt(e))return e;let r=t(e);return ot(r,cr)}async function sv(e,t){if(rt(e))return null;let r=await t(e);return ot(r,cr)}function iv(e,t,r){let o,n;return e!==null?(o=r(e),n=cr):(o=t,n=Bn),ot(o,n)}async function av(e,t,r){if(rt(e))return ot(t,Bn);let o=await r(e);return ot(o,cr)}function cv(e,t,r){let o,n;return je(e)?(o=r(e),n=cr):(o=t(),n=Eo),ot(o,n)}async function lv(e,t,r){let o,n;return je(e)?(o=await r(e),n=cr):(o=await t(),n=Eo),ot(o,n)}function pv(e,t){return je(e)?L(e):M(t)}function uv(e,t){if(je(e))return L(e);let r=t();return M(r)}async function mv(e,t){if(je(e))return L(e);let r=await t();return M(r)}function fv(e,t){return e!==null?e:t()}async function dv(e,t){return je(e)?e:await t()}function hv(e){return rt(e)?M(void 0):L(e)}function gv(e){return rt(e)?L(void 0):M(e)}function yv(e){if(!rt(e))return e}function xv(e){return rt(e)?L(null):(K(e),e)}function bv(e,t){return je(e)?e:ot(t,Bn)}function Ev(e,t){if(je(e))return e;let r=t();return ot(r,Eo)}async function wv(e,t){if(je(e))return e;let r=await t();return ot(r,Eo)}var _I=Object.defineProperty,PI=(e,t)=>{for(var r in t)_I(e,r,{get:t[r],enumerable:!0})},OI={};PI(OI,{andThen:()=>tv,andThenAsync:()=>rv,inspect:()=>ov,map:()=>nv,mapAsync:()=>sv,mapOr:()=>iv,mapOrAsync:()=>av,mapOrElse:()=>cv,mapOrElseAsync:()=>lv,okOr:()=>pv,okOrElse:()=>uv,okOrElseAsync:()=>mv,orElse:()=>fv,orElseAsync:()=>dv,toResultErr:()=>gv,toResultOk:()=>hv,toUndefinable:()=>yv,transposeToResult:()=>xv,unwrapOr:()=>bv,unwrapOrElse:()=>Ev,unwrapOrElseAsync:()=>wv});function Rv(e,t){return st(e)?e:t(e)}async function vv(e,t){return st(e)?void 0:await t(e)}function kv(e,t){return nt(e)&&t(e),e}function Tv(e,t){if(st(e))return e;let r=t(e);return it(r,lr)}async function _v(e,t){if(st(e))return;let r=await t(e);return it(r,lr)}function Pv(e,t,r){let o,n;return e!==void 0?(o=r(e),n=lr):(o=t,n=Hn),it(o,n)}async function Ov(e,t,r){if(st(e))return it(t,Hn);let o=await r(e);return it(o,lr)}function Sv(e,t,r){let o,n;return e!==void 0?(o=r(e),n=lr):(o=t(),n=wo),it(o,n)}async function Lv(e,t,r){let o,n;return nt(e)?(o=await r(e),n=lr):(o=await t(),n=wo),it(o,n)}function Nv(e,t){return nt(e)?L(e):M(t)}function Mv(e,t){if(nt(e))return L(e);let r=t();return M(r)}async function Cv(e,t){if(nt(e))return L(e);let r=await t();return M(r)}function Iv(e,t){return e!==void 0?e:t()}async function Av(e,t){return nt(e)?e:await t()}function Fv(e){return st(e)?null:e}function Dv(e){return st(e)?M(void 0):L(e)}function Uv(e){return st(e)?L(void 0):M(e)}function $v(e){return st(e)?L(void 0):(K(e),e)}function jv(e,t){return nt(e)?e:it(t,Hn)}function Bv(e,t){if(nt(e))return e;let r=t();return it(r,wo)}async function Hv(e,t){if(nt(e))return e;let r=await t();return it(r,wo)}var SI=Object.defineProperty,LI=(e,t)=>{for(var r in t)SI(e,r,{get:t[r],enumerable:!0})},NI={};LI(NI,{andThen:()=>Rv,andThenAsync:()=>vv,inspect:()=>kv,map:()=>Tv,mapAsync:()=>_v,mapOr:()=>Pv,mapOrAsync:()=>Ov,mapOrElse:()=>Sv,mapOrElseAsync:()=>Lv,okOr:()=>Nv,okOrElse:()=>Mv,okOrElseAsync:()=>Cv,orElse:()=>Iv,orElseAsync:()=>Av,toNullable:()=>Fv,toResultErr:()=>Uv,toResultOk:()=>Dv,transposeToResult:()=>$v,unwrapOr:()=>jv,unwrapOrElse:()=>Bv,unwrapOrElseAsync:()=>Hv});var Tl=class{#o=[];#r;#t;constructor(t){if(t<=0||!Number.isSafeInteger(t))throw new RangeError(size must be a positive safe integer, got ${t});this.#r=t,this.#t=t}get locked(){return this.#r===0}get waiterCount(){return this.#o.length}acquire(){if(this.#r>0)return this.#r-=1,Promise.resolve();{let{promise:t,resolve:r}=Promise.withResolvers();return this.#o.push(r),t}}release(){let t=this.#o.shift();t?t():this.#r<this.#t&&(this.#r+=1)}};var _l=class{#o;constructor(t){this.#o=new Tl(t)}get locked(){return this.#o.locked}get waiterCount(){return this.#o.waiterCount}async lock(t){await this.#o.acquire();try{return await t()}finally{this.#o.release()}}};async function*Wv(e,t){if(e.length===0||e.every(({before:n,after:s})=>n===s))return;let r=S(await It()),o=new _l(5);try{yield*new ReadableStream({async start(n){let s=[];for(let i of e){if(i.before===i.after){n.enqueue({link:i,projectCount:0,replaced:0,done:!0});continue}let a=0,c=0,l=[];for(let u of new Set(t))l.push(o.lock(async()=>{let p=await MI(i,u,r);if(O(p)){n.error(CI(Z(p)));return}a++,c+=S(p),n.enqueue({link:i,projectCount:a,replaced:c,done:!1})}));s.push(Promise.all(l).then(()=>n.enqueue({link:i,projectCount:a,replaced:c,done:!0})))}await Promise.all(s),n.close()}})}finally{await At(r)}}var MI=async(e,t,r)=>{let[o]=await Promise.all([Na(t,e.before,e.after),Le(t,e.before,(n,{persistent:s})=>{if(s)return[e.after,...n.map(i=>i.text).slice(1)]},{socket:r})]);return o},ho=e=>e.split(
).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),CI=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var qv=e=>at(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return II(r);case"table":return AI(r);case"line":return FI(r)}}).map(r=>r).join(
),II=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},AI=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[${o}table:${e},...t.map(n=>${o} ${n.map(s=>s.map(i=>Ui(i)).join("")).join(" ")})]},FI=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${Ui(r)}).join("")}],Ui=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Ui(t)).join("")};case"strong":return${e.nodes.map(t=>Ui(t)).join("")};case"decoration":{let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return[${t?${t} :""}${e.nodes.map(r=>Ui(r)).join("")}]}case"hashTag":return e.href;case"link":return e.pathType==="absolute"?e.raw:e.href;default:return e.raw}};scrapbox.PopupMenu.addButton({title:e=>ho(e).length>0?"":"",onClick:e=>{let t=qv(e);if(e!=t)return t}});var Gv=e=>!e.includes(
)&&/\[[^\]]+\]/.test(e);scrapbox.PopupMenu.addButton({title:e=>Gv(e)?"[][]":"",onClick:e=>{if(!Gv(e))return;let t=e.replaceAll("[","").replaceAll("]","");return(async()=>{let{render:r,dispose:o}=Fe();try{let n=scrapbox.Project.name;r({type:"spinner"},{type:"text",text:create /${n}/${t}}),await Le(n,t,([{text:s}],{persistent:i})=>{if(!i)return[s,e]}),r({type:"check-circle"},{type:"text",text:create /${n}/${t}})}catch(n){if(console.error(n),!(n instanceof Error))throw n;r({type:"exclamation-triangle"},{type:"text",text:${n.name} ${n.message}})}finally{await Se(2e3),o()}})(),${t}}});var Vv=(e,t)=>{switch(e.type){case"title":return"";case"codeBlock":return[e.fileName,
\\`\`${WI(e.fileName)},e.content,"\n"].join(
);case"table":return DI(e);case"line":return $I(e,t)}},DI=e=>{let t=[e.fileName],r=Math.max(...e.cells.map(o=>o.length));return e.cells.forEach((o,n)=>{t.push(| ${o.map(s=>s.map(i=>Rs(i)).join("")).join(" | ")} |),n===0&&t.push(|${" -- |".repeat(r)})}),t.join(
)},UI=" ",$I=(e,t)=>{let r=e.nodes.map(n=>Rs(n,{section:e.indent===t})).join("").trim();if(r==="")return"";if(e.indent===t)return r;let o=UI.repeat(e.indent-t-1);return/^\d+\. /.test(r)||(o+="- "),o+r},Rs=(e,t)=>{let{section:r=!1}=t??{};switch(e.type){case"quote":return> ${e.nodes.map(o=>Rs(o)).join("")};case"helpfeel":return\? ${e.text}\`;case"image":case"strongImage":return![image](${e.src});case"icon":case"strongIcon":return"/icons/hr","/scrapboxlab/hr".includes(e.path)?"---":"";case"strong":return**${e.nodes.map(o=>Rs(o)).join("")}**;case"formula":return$${e.formula}$;case"decoration":{let o=e.nodes.map(n=>Rs(n)).join("");return e.decos.includes("/")&&(o=*${o}*),r?(e.decos.includes("*-3")&&(o=`# ${o}
),e.decos.includes("*-2")&&(o=## ${o}
),e.decos.includes("*-1")&&(o=### ${o}
)):e.decos.some(n=>/\*-/.test(n[0]))&&(o=**${o}**),e.decos.includes("~")&&(o=~~${o}~~),o}case"code":return\${e.text}\`;case"commandLine":return\`${e.symbol} ${e.text}\`;case"link":switch(e.pathType){case"root":{let,o,...n=e.href.split("/");return[${e.href}](https://scrapbox.io/${o}/${zv(n.join("/"))})}case"relative":return[${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${zv(e.href)});default:return e.content===""? ${e.href} :[${e.content}](${e.href})}case"googleMap":return[${e.place}](${e.url});case"hashTag":return[#${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${e.href});case"numberList":return${e.number}. ${e.nodes.map(o=>Rs(o)).join("")};case"blank":case"plain":return e.text}},zv=e=>...e.map((t,r)=>t===" "?"_":!jI.includes(t)||r===e.length-1&&BI.includes(t)?encodeURIComponent(t):t).join(""),jI='@$&+=:;",',BI=':;",',HI=[{extensions:"javascript","js",fileType:"javascript"},{extensions:"typescript","ts",fileType:"typescript"},{extensions:"cpp","hpp",fileType:"cpp"},{extensions:"c","cc","h",fileType:"c"},{extensions:"cs","csharp",fileType:"cs"},{extensions:"markdown","md",fileType:"markdown"},{extensions:"htm","html",fileType:"html"},{extensions:"json",fileType:"json"},{extensions:"xml",fileType:"xml"},{extensions:"yaml","yml",fileType:"yaml"},{extensions:"toml",fileType:"toml"},{extensions:"ini",fileType:"ini"},{extensions:"tex","sty",fileType:"tex"},{extensions:"svg",fileType:"svg"}],WI=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return HI.find(r=>r.extensions.includes(t))?.fileType??""};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{(async()=>{try{let t=os.parse(e,{hasTitle:!1}),r=Math.min(...t.map(o=>o.indent));await navigator.clipboard.writeText(t.map(o=>Vv(o,r)).join(`
))}catch(t){alert(Failed to copy:
${JSON.stringify(t)})}})()}});var Kv=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var Yv=()=>qI(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),qI=(e,t)=>{if(e)return Kv(e,t),e};var Xv=()=>{let e=Yv();if(!e)throw new Error("div.status-bar can't be found");let t=document.createElement("div");return e.append(t),{render:(...r)=>{t.textContent="";let o=Jv(...r);o&&t.append(o)},dispose:()=>t.remove(),[Symbol.dispose]:()=>t.remove()}},Jv=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[YI()];case"check-circle":return[XI()];case"exclamation-triangle":return[JI()];case"text":return[Ol(o.text)];case"group":{let n=Jv(...o.items);return n?[n]:[]}}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},Ol=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},YI=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Ol(e)},XI=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Ol(e)},JI=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Ol(e)};var jf=(e,...t)=>{let r=t.reduce((o,n)=>ve(o)?o:o instanceof Promise?o.then(s=>ve(s)?s:n(s)):n(o),e);return r instanceof Promise?r.then(o=>${o}):${r}};var vs=e=>e.ok?L(e):M({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var Qv=e=>window.GM_fetch?.(https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x)?.then?.(t=>ae(vs(t),r=>r.json()));function Nt(e){return e.val}function jt(e){return e.err}var Zv=" must not return ",ZI="transformer",eA="recoverer",tA="defaultValue",ks=ZI+Zv,go="called with ",Ts=tA+" must not be ",_s=eA+Zv;var rA="Ok",ek="Err",tk=go+ek,oA=go+rA,nA="Carrying E in "+ek+" instead of throwing it directly. See .cause",Bf="an instance of Error of the current realm.",YJe="The thrown value is not "+Bf,XJe="The contained E should be "+Bf,sA="This .cause is not "+Bf;function vt(e){return e.ok}function Ce(e){return{ok:!0,val:e,err:null}}function ie(e){return!e.ok}function Mt(e){return{ok:!1,val:null,err:e}}function Te(e){return rk(e,tk)}function rk(e,t){if(ie(e))throw new TypeError(t);return e.val}function $i(e,t){if(ie(e))return e;let r=Nt(e),o=t(r);return Ce(o)}async function Ge(e,t){if(ie(e))return e;let r=Nt(e),o=await t(r);return Ce(o)}async function tt(e,t){if(vt(e))return e;let r=jt(e),o=await t(r);return Mt(o)}async function Sl(e,t){if(vt(e))return e;let r=jt(e);return await t(r)}var Ll="null",cZe=ks+Ll,cA=go+Ll,lZe=Ts+Ll,pZe=_s+Ll;var Nl="undefined",hZe=ks+Nl,lA=go+Nl,gZe=Ts+Nl,yZe=_s+Nl;var ze=e=>e.ok?Ce(e):Mt({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var nk=async(e,t)=>{let r=new Request(e,t);try{return Ce(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return Mt({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return Mt({name:"NetworkError",message:o.message,request:r});throw o}};var Ie=e=>{let{fetch:t=nk,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var sk=e=>{let{sid:t,hostName:r}=Ie(e??{});return new Request(https://${r}/api/users/me,t?{headers:{Cookie:Ve(t)}}:void 0)},ik=e=>Ge(ze(e),async t=>await t.json()),ak=(()=>{let e=async t=>{let{fetch:r,...o}=Ie(t??{}),n=await r(sk(o));return ie(n)?n:ik(Te(n))};return e.toRequest=sk,e.fromResponse=ik,e})();var Ve=e=>connect.sid=${e},yo=async e=>{let t=e?.csrf??globalThis._csrf;return t?Ce(t):$i(await ak(e),r=>r.csrfToken)};var Bt=async(e,t)=>{let r=e.response.clone(),o=Go(t);try{let n=await r.json();if(!Ro(n))return;if(r.status===422){if(!ve(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!ve(n.message)?void 0:n.name==="NotLoggedInError"?!Ro(n.detals)||!ve(n.detals.project)||!zs(mA)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},mA=Go(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var Ml="null or undefined",Ps=ks+Ml,fA=go+Ml,Hf=Ts+Ml,Cl=_s+Ml;function Gr(e){return e==null}function Il(e){return Gr(e)?Mt(void 0):Ce(e)}var ck=(e,t)=>{let{sid:r,hostName:o}=Ie(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:Ve(r)}}:void 0)},lk=async e=>Ge(await tt(ze(e),async t=>await Bt(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),pk=(()=>{let e=async(t,r)=>{let{fetch:o}=Ie(r??{}),n=ck(t,r),s=await o(n);return ie(s)?s:lk(Te(s))};return e.toRequest=ck,e.fromResponse=lk,e})();var uk=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=Ie(t??{}),s=await yo(t);if(ie(s))return s;let i=new Request(https://${o}/api/embed-text/url?url=${encodeURIComponent(${e})},{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":Te(s),...r?{Cookie:Ve(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return ie(a)?a:Ge(await tt(ze(Te(a)),async c=>await Bt(c,["SessionError","BadRequestError","InvalidURLError"])??c),async c=>{let{title:l}=await c.json();return l})};var mk=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=Ie(t??{}),s=await yo(t);if(ie(s))return s;let i=new Request(https://${o}/api/embed-text/twitter?url=${encodeURIComponent(${e})},{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":Te(s),...r?{Cookie:Ve(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return ie(a)?a:tt(await Ge(ze(Te(a)),c=>c.json()),async c=>c.response.status===422?{name:"InvalidURLError",message:(await c.response.json()).message}:await Bt(c,["SessionError","BadRequestError"])??c)};var fk=async e=>{let{fetch:t,sid:r,hostName:o,gyazoTeamsName:n}=Ie(e??{}),s=new Request(https://${o}/api/login/gyazo/oauth-upload/token${n??gyazoTeamsName=${n}:""},r?{headers:{Cookie:Ve(r)}}:void 0),i=await t(s);return ie(i)?i:Ge(await tt(ze(Te(i)),async a=>await Bt(a,["NotLoggedInError"])??a),a=>a.json().then(c=>c.token))};var dk=async(e,t,r)=>{let o=${vu(Ru(await e.arrayBuffer()))},n=await hA(e,t,o,r);if(ie(n))return n;let s=Te(n);if("embedUrl"in s)return Ce(s);let i=await gA(s.signedUrl,e,r);return ie(i)?i:yA(t,s.fileId,o,r)},hA=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=Ie(o??{}),c={md5:r,size:e.size,contentType:e.type,name:e.name},l=await Sl(Il(a),()=>yo(o));if(ie(l))return l;let u=new Request(https://${s}/api/gcs/${t}/upload-request,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":Te(l),...n?{Cookie:Ve(n)}:{}}}),p=await i(u);return ie(p)?p:Ge(await tt(ze(Te(p)),async f=>f.response.status===402?{name:"FileCapacityError",message:(await f.response.json()).message}:f),f=>f.json())},gA=async(e,t,r)=>{let{sid:o,fetch:n}=Ie(r??{}),s=await n(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...o?{Cookie:Ve(o)}:{}}});return ie(s)?s:$i(await tt(ze(Te(s)),async i=>i.response.headers.get("Content-Type")?.includes?.("/xml")?{name:"GCSError",message:await i.response.text()}:i),()=>{})},yA=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=Ie(o??{}),c=await Sl(Il(a),()=>yo(o));if(ie(c))return c;let l=new Request(https://${s}/api/gcs/${e}/verify,{method:"POST",body:JSON.stringify({md5:r,fileId:t}),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":Te(c),...n?{Cookie:Ve(n)}:{}}}),u=await i(l);return ie(u)?u:Ge(await tt(ze(Te(u)),async p=>p.response.status===404?{name:"NotFoundError",message:(await p.response.json()).message}:p),p=>p.json())};var hk=(e,t)=>{let r=new FormData;return r.append("data",e),r.append("metadata",JSON.stringify({app:"Gyazo",title:e.name})),GM_fetch(https://gif.gyazo.com/${t?.teams?"teams":"gif"}/upload,{method:"POST",body:r,credentials:"include",headers:{Origin:"https://gyazo.com","sec-fetch-site":"same-site"},referrer:"https://gyazo.com/"})};var Al="",gk=!1,Fl=new Map,yk=async(e,t,r,o)=>{let n=Fl.get(e.href);if(n)return n;if(e.hostname==="video.twimg.com"||${e}.endsWith(".svg")){let l=await GM_fetch(e);if(!l.ok)return;let u=l.headers.get("content-type")?.split?.(";")?.[0]??${e}.endsWith(".mp4")?"video/mp4":"video/webm",p=new File([await l.blob()],o||${t},{type:u});if(u==="video/mp4"){let h=await hk(p);if(h.ok){let g=new URL(await h.text());return Fl.set(e.href,g),g}}let f=await dk(p,r);if(O(f))throw Error(Z(f).name);let m=new URL(S(f).embedUrl);return Fl.set(e.href,m),m}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(gk){if(!Al)return}else{let l=await fk();if(gk=!0,O(l)){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(Al=S(l)||"",!Al){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let i=await Og(await s.blob(),{accessToken:Al,refererURL:t,description:o});if(!i.ok)throw new Error(Gyazo upload failed: ${i.status} ${i.statusText});let a=await i.json(),c=new URL(a.permalink_url);return Fl.set(e.href,c),c};var Ek=[["&","&amp;"],["<","&lt;"],[">","&gt;"],['"',"&quot;"],["'","&#39;"]],xA=Object.fromEntries([...Ek.map(([e,t])=>[t,e]),["&apos;","'"],["&nbsp;"," "]]),bA=new Map(Ek),yit=new RegExp([${...bA.keys().join("")}],"g");var EA={entityList:xA},wA=1114111,RA=/&#([0-9]+);/g,vA=/&#x(\p{AHex}+);/gu,xk=new WeakMap;function Wf(e,t={}){let{entityList:r}={...EA,...t},o=xk.get(r);return o||(o=new RegExp((${Object.keys(r).sort((n,s)=>s.length-n.length).join("|")}),"g"),xk.set(r,o)),e.replaceAll(o,n=>r[n]).replaceAll(RA,(n,s)=>bk(s,10)).replaceAll(vA,(n,s)=>bk(s,16))}function bk(e,t){let r=parseInt(e,t);return r>wA?"�":String.fromCodePoint(r)}var Dl=e=>{let t={name:e.user.name,screenName:e.user.screen_name},r=new Date(e.created_at),o=[...e.entities.hashtags?.map?.(i=>({type:"hashtag",...i}))??[],...e.entities.symbols?.map?.(i=>({type:"symbol",...i}))??[],...e.entities.user_mentions?.map?.(i=>({type:"mention",name:i.name,screenName:i.screen_name,indices:i.indices}))??[],...e.entities.urls?.map?.(i=>{let a={type:"url",indices:i.indices,url:new URL(i.expanded_url)};if(e.card&&e.card?.url===i.url){let{description:c,title:l}=e.card.binding_values,u="STRING";c?.type===u&&(a.description=c.string_value),l?.type===u&&(a.title=l.string_value)}return a})??[],...e.entities.media?.map?.(i=>({type:"media",indices:i.indices,media:e.mediaDetails?.flatMap?.(a=>a.url===i.url?[{type:a.type,url:new URL(a.video_info?.variants?.sort?.((c,l)=>(l.bitrate??0)-(c.bitrate??0))?.[0].url??a.media_url_https)}]:[])??[]}))??[]].sort((i,a)=>i.indices[0]-a.indices[0]),n=[];{let i=0,a=e.text;for(let{indices:c,...l}of o){let u=[...a].slice(0,c[0]-i).join("");n.push({type:"plain",text:Wf(u)}),n.push(l),a=[...a].slice(c[1]-i).join(""),i=c[1]}a&&n.push({type:"plain",text:Wf(a)})}let s={id:e.id_str,content:n,author:t,posted:r,replyCount:"reply_count"in e?e.reply_count:e.conversation_count};return e.self_thread&&(s.rootId=e.self_thread.id_str),e.in_reply_to_status_id_str&&(s.replyId=e.in_reply_to_status_id_str),e.parent&&(s.replyTo=Dl(e.parent)),e.quoted_tweet&&(s.quote=Dl(e.quoted_tweet)),s};var kA=["landing","product","enterprise","pricing","try-enterprise","contact","terms","privacy","jp-commercial-act","support","case","features","business","auth","login","logout","oauth2","_","api","app.html","assets","file","files","billing","billings","config","feed","index","io","new","opensearch","project","projects","search","setting","settings","setup-profile","slide","socket.io","stream","user","users"],Ul=(e=scrapbox.Project.name,t=location.host)=>r=>{if(r.host!==t)return r;let[,o,n]=r.pathname.match(/^\/([\w\d][\w\d-]{0,22}[\w\d])(?:\/?|\/(.+))$/)??[];return!o||kA.includes(o)?r:n?o===e?${decodeURIComponent(n)}:/${o}/${decodeURIComponent(n)}:/${o}};var wk=(e=TA)=>t=>{let[,r]=t.href.match(/^https:\/\/(?:www\.|mobile\.|m\.|)(?:twitter|x)\.com\/[A-Za-z0-9_]*\/(?:status|statuses)\/(\d+)/)??[];return r?(async()=>{let o=await(Qv(r)??mk(t.href));if(O(o))throw Z(o);let n=S(o);return e("images"in n?{...n,id:r}:n,t)})():t},TA=async e=>{if("images"in e)return ji(e);let{quote:t,replyTo:r,...o}=Dl(e);return[...r?[...(await ji(r)).split(
).map(n=> > ${n}),...r.quote?(await ji(r.quote)).split(
).map(n=> > ${n}):[]]:[],...(await ji(o)).split(
).map(n=>> ${n}),...t?(await ji(t)).split(
).map(n=>> > ${n}):[]].join(
)},ji=async e=>{let t=new URL(https://twitter.com/${"author"in e?e.author.screenName:e.screenName}/status/${e.id});if("images"in e)return[> @${Bi(e.screenName)} ${t.origin}${t.pathname},...e.description?.split?.(
)?.map?.(n=>> ${Bi(n)})??["> [/ no description provided]"],...e.images.length>0?[> ${e.images.map(n=>[${n}])}]:[]].join(
);let r=e.content,o=e.author.screenName;return[@${Bi(o)} ${t},...(await Promise.all(r.map(async n=>{switch(n.type){case"plain":return n.text;case"hashtag":return #${n.text} ;case"symbol":return #$${n.text} ;case"mention":return@${n.screenName};case"media":{let s=[],i=1;for(;i<n.media.length;i+=2)s.push([${await qf(n.mediai-1,t)}] [${await qf(n.mediai,t)}]);return i===n.media.length&&s.push([${await qf(n.mediai-1,t)}]),
${s.join(`
`)}
}case"url":return${Ul()(n.url)} }}))).join("").split(
)].join(
)},$l="",_A=async()=>{if($l)return $l;let e=await pk(scrapbox.Project.name);if(O(e))throw new Error(Z(e).name);return $l=S(e).id,$l},qf=async(e,t)=>await yk(e.url,t,await _A(),"")??e.url,Bi=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]]\s*/g," ").trim();var Rk=e=>window.GM_fetch?.(https://t.co/${e})?.then?.(t=>ae(vs(t),async r=>{let o=new DOMParser().parseFromString(await r.text(),"text/html");try{return new URL(o.title)}catch(n){if(n instanceof TypeError)return;throw n}}));var vk=e=>{let t=window.GM_fetch;if("bit.ly","amzn.to","amzn.asia","goo.gl","s.nikkei.com","apple.co","nico.ms","w.wiki".includes(e.hostname)&&t)return t(e).then(o=>o.ok?new URL(o.url):e);if(e.hostname!=="t.co")return e;let r=Rk(e.pathname.slice(1));return r?r.then(o=>Gs(o,()=>e,n=>n??e)):e};var kk=e=>{if(!e.pathname.startsWith("/wiki/"))return e;if(!/^\w+\.wikipedia\.org$/.test(e.hostname)){let,n=e.hostname.match(/^(\w+)\.m\.wikipedia\.org$/)??[];if(!n)return e;e.hostname=${n}.wikipedia.org}let t=decodeURIComponent(e.pathname.slice(6)),r=e.hash?decodeURIComponent(e.hash.slice(1)):"",o=${e.origin}/wiki/${t};return r?[${r} | ${t} - Wikipedia ${o}#${r}]:[${t} - Wikipedia ${o}]};var Tk=e=>{if(e.hostname!=="www.wikiwand.com")return e;let,t,r=e.pathname.match(/^\/(^\/+)\/(^\/+)/)??[];return!t||!r||(e.hostname=${t}.wikipedia.org,e.pathname=/wiki/${r},e.hash=e.hash.startsWith("#/")?#${e.hash.slice(2)}:e.hash),e};var Gf=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var _k=/charset=(^;+)/,Pk=e=>window.GM_fetch?.(${e})?.then?.(t=>ae(vs(t),async r=>{let o=r.headers.get("content-type")?.match?.(_k)?.1??await PA(r.clone());return new TextDecoder(o).decode(await r.arrayBuffer())})),PA=async e=>{let t=new DOMParser().parseFromString(await e.text(),"text/html");return t.querySelector("metacharset")?.getAttribute?.("charset")??t.querySelector('metahttp-equiv="content-type"')?.getAttribute?.("content")?.match?.(_k)?.1??"utf-8"};var jl=(e=zf)=>async t=>e(await OA(t),t),zf=(e,t)=>{let r=(ve(e)?e:e.title).replace(/\s/g," ").replaceAll("","[").replaceAll("","]");return r?[${t.hash?${decodeURIComponent(t.hash.slice(1))} | :""}${r} ${t}]:${t}},OA=async e=>{let t=Pk(e);if(!t){let o=await uk(e);if(O(o))throw Z(o);return S(o)}let r=await t;if(O(r))throw Z(r);return new DOMParser().parseFromString(S(r),"text/html")};var Ok=e=>{if(!/^(?:www\.)?amazon(?:\.co|com)?\.(?:au|br|ca|fr|de|in|it|jp|mx|nl|sg|es|tr|ae|uk|cn)$/.test(e.hostname))return e;let,t=e.pathname.match(/\/dp\/(\w\d+)/)??e.pathname.match(/\/gp\/product\/(\w\d+)/)??e.pathname.match(/\/exec\/obidos\/asin\/(\w\d+)/)??e.pathname.match(/\/o\/ASIN\/(\w\d+)/)??[];return t&&(e.hash="",e.search="",e.pathname=/dp/${t}),e};var Sk=e=>{if(!/(?:0-9a-z-\.)?gyazo\.com/.test(e.hostname))return e;let,t=e.pathname.match(/^\/(0-9a-f{32})(?:\/raw)?$/)??[];return t?[https://gyazo.com/${t}]:e};var Lk=(e,...t)=>{if(e instanceof URL)return jf(new URL(e),...t);let r=0,o=0,n=0,s=!1,i=e.split(/(https?:\/\/\S+)/g).map(u=>{if(!/^https?:\/\/\S+$/.test(u))return u;r++;try{let p=jf(new URL(u),...t);return ve(p)?(o++,p):(s=!0,p,u)}catch(p){return console.error(p),n++,u}});if(!s)return i.join("");let{render:a,dispose:c}=Xv(),l=()=>a({type:"spinner"},{type:"text",text:URL: ${o}/${r} converted, ${n} failed});return l(),Promise.all(i.map(async u=>{if(ve(u))return u;try{let p=await u0;return o++,p}catch(p){return console.error(p),n++,u1}finally{l()}})).then(u=>(a({type:"check-circle"},{type:"text",text:URL: ${o}/${r} converted, ${n} failed}),u.join(""))).finally(()=>{setTimeout(c,1e3)})};var Nk=e=>{if(!/^(?:\w+\.nicovideo\.jp|nico\.ms)$/.test(e.hostname))return e;let t=e.pathname.match(/(?:sm|nm|so|ca|ax|yo|nl|ig|na|cw|za-e|om|sk|yk|lv)\d{1,14}$/)?.0;return t?[https://nicothumb2img.vercel.app/image/${t}#.png https://nico.ms/${t}]:e};var Mk=e=>e.hostname!=="catalog.he.u-tokyo.ac.jp"||!e.pathname.startsWith("/detail")||!e.searchParams.get("code")||!e.searchParams.has("year")?e:jl(SA)(e),SA=(e,t)=>{if(typeof e=="string")return zf(e,t);let r=e.getElementsByClassName("code-cell")1.children1.textContent,o=[...e.getElementsByClassName("semester-cell")1.children].map(a=>a.textContent.trim()),n=Bi(e.getElementsByClassName("name-cell")1.textContent.trim()),s=e.getElementsByClassName("period-cell")1.textContent.trim().split("、").map(a=>a.replace(/(.)曜(\d)限/,"$1$2")),i=e.getElementsByClassName("catalog-page-detail-sub-table-row")0.lastElementChild?.textContent?.trim?.()??0;return${o.join("")} ${s.join("")} ${n} ${i}[. ${t}]};var Ck=e=>at(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return LA(r);case"table":return NA(r);case"line":return MA(r)}}).map(r=>r).join(`
),LA=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},NA=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[${o}table:${e},...t.map(n=>${o} ${n.map(s=>s.map(i=>i.raw).join("")).join(" ")})]},MA=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${Hi(r)}).join("")}],Hi=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Hi(t)).join("")};case"helpfeel":return-? ${e.text};case"commandLine":return-${e.symbol} ${e.text};case"icon":case"strongIcon":case"image":case"strongImage":case"formula":case"code":case"googleMap":return e.raw;case"strong":return${e.nodes.map(t=>Hi(t)).join("")};case"decoration":{e.decos.includes("-")||e.decos.push("-");let t=e.decos.map(r=>{let o=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return o>0?"*".repeat(o):r}).join("");return[${t?${t} :""}${e.nodes.map(r=>Hi(r)).join("")}]}case"link":switch(e.pathType){case"root":case"relative":return${e.href};case"absolute":return[- ${e.content?${e.content} :""}${e.href}]]}case"hashTag":return#${e.href};case"numberList":return${e.number}. ${e.nodes.map(t=>Hi(t)).join("")};case"blank":case"plain":return${e.text}}};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=Ck(e);if(e!==t)return t}});var Vf=e=>{let t=e.indexOf(
);if(t<0)return;let r=e.slice(0,t).split(
).map(s=>{let[i="",a=""]=s.split(" => ",2);return[i,a]});if(r.length===0)return;let o=e.slice(t+2).split(
);if(o.length===0)return;for(let[s,i]of r){let a=s.match(/^\/(.*?)\/([gimy]*)$/);if(a){let c=new RegExp(a[1],a[2]);o=o.map(l=>l.replace(c,i.replaceAll("\\n",
)))}else o=o.map(c=>c.replaceAll(s,i.replaceAll("\\n",
)))}let n=${e.slice(0,t+2)}${o.join(`
)};if(e!==n)return n};scrapbox.PopupMenu.addButton({title:e=>Vf(e)?"replace":"",onClick:e=>{let t=Vf(e);if(t!==void 0)return t}});var Ik=e=>{let t=document.createElement("div"),r=t.attachShadow({mode:"open"}),o=document.createElement("style");o.textContent="dialog::backdrop{background-color:#000c}dialog{flex-direction:column;align-items:center;row-gap:10px;padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset}dialogopen{display:flex}dialog>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}@media (min-width: 768px){dialog{padding:30px 0}}.container{display:flex;padding:5px;gap:0.2em;flex-direction:column;width:100%;}.button-container{flex-direction:unset;}.button-container>*{flex:1;}",r.append(o);let n=document.createElement("dialog");n.insertAdjacentHTML("beforeend",`
<div class="container">
Replace Links:
<textarea class="editor"></textarea>
<div class="container button-container">
<button class="cancel">cancel</button>
<button class="replace">replace</button>
</div>
</div>
),r.append(n);let s=n.querySelector(".editor");s.rows=e.length,s.value=e.join(
);let i=()=>{n.style.minWidth=${Math.max(...s.value.split(`
).map(u=>[...u].length))+6}em};i(),s.addEventListener("input",i);let a=n.querySelector(".cancel"),c=n.querySelector(".replace"),l=new Promise(u=>{let p=()=>{u({convert:!1}),t.remove()};n.addEventListener("close",p),n.addEventListener("click",p),a.addEventListener("click",p),c.addEventListener("click",()=>{let f=s.value.split(`
);u({convert:!0,links:e.flatMap((m,h)=>m===f[h]||m===""||!f[h]?[]:[{before:m,after:f[h]??m}])}),t.remove()}),n.querySelector(".container").addEventListener("click",f=>{f.stopPropagation()})});return document.body.append(t),n.showModal(),l};var Ak=async(e,t)=>{let r=ho(e),o=await Ik([...new Set(r)]);if(!o.convert||o.links.length===0)return;let n=new Map(o.links.map(s=>[s.before,Fe()]));for await(let{link:s,projectCount:i,replaced:a,done:c}of Wv(o.links,t)){let l=n.get(s.before);if(l){if(c){l.render({type:"check-circle"},{type:"text",text:"${s.after}", ${a}l. ${i}p.}),setTimeout(()=>l.dispose(),1e3);continue}l.render({type:"spinner"},{type:"text",text:"${s.after}", ${a}l. ${i}p.})}}};var Fk=async(e,t)=>{let r=ho(e)[0];if(!r)return;let o=window.prompt(Replace "${r}" to this in ${t.map(a=>"/${a}").join(", ")},r)?.replace?.(/[\[\]\n]/g," ")??"";if(o==="")return;let{render:n,dispose:s}=Fe(),i=S(await It());try{n({type:"spinner"},{type:"text",text:Replacing links in ${t.length} projects...});let a=0,l=(await Promise.all(t.map(async u=>{let[p]=await Promise.all([Na(u,r,o),Le(u,r,(f,{persistent:m})=>{if(m)return[o,...f.map(h=>h.text).slice(1)]},{socket:i})]);if(O(p))throw n({type:"exclamation-triangle"},{type:"text",text:${Z(p).name} ${Z(p).message}}),CA(Z(p));return a++,n({type:"spinner"},{type:"text",text:Replacing links in ${t.length-a} projects...}),S(p)}))).reduce((u,p)=>u+p,0);n({type:"check-circle"},{type:"text",text:Successfully replaced ${l} links.})}finally{await At(i),setTimeout(s,1e3)}},CA=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var Dk=e=>{let t=[scrapbox.Project.name,...e];scrapbox.PopupMenu.addButton({title:r=>{let o=ho(r).length;return o>1?"update links":o===1?"update a link":""},onClick:r=>{let o=ho(r).length;o>1?Ak(r,t):o===1&&Fk(r,t)}})};scrapbox.PopupMenu.addButton({title:e=>/[\n..。]/.test(e)?"\\n":"",onClick:e=>e.replace(/(\w)\n(\w)/g,"$1 $2").replaceAll(
,"").replaceAll(".",.
).replaceAll(".",.
).replaceAll("。",。
)});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/[a-z0-9]+/.test(e)?globalThis.GM_fetch?"copy Gyazo OCR":"open Gyazo":"",onClick:async e=>{let t=e.match(/https:\/\/(?:thumb\.|i\.)?gyazo\.com\/([a-z0-9]+)/)?.[1];if(!t)return;if(!globalThis.GM_fetch){window.open(https://gyazo.com/${t});return}let o=(await(await GM_fetch(https://gyazo.com/${t}.json)).json()).metadata?.ocr?.description;if(o)try{await navigator.clipboard.writeText(o)}catch(n){console.error(n),alert(${n.name} ${n.message})}}});scrapbox.PopupMenu.addButton({title:e=>/https:\/\/gyazo\.com\/[a-z0-9]+/.test(e)?"":"",onClick:e=>{let t=e.match(/https:\/\/gyazo\.com\/([a-z0-9]+)/)?.[1];t&&window.open(https://gyazo.com/${t}/transform)}});var Uk=e=>{let t="",r=0;for(let o of e)if(o.type!=="title"){if(o.indent>r)for(let n=r;n<o.indent;n++)t+=Wi(${n!==r?"\\item":""}\\begin{itemize},n*2)+
;if(o.indent<r)for(let n=r;n>o.indent;n--)t+=Wi("\\end{itemize}",(n-1)*2)+
;r=o.indent,t+=Wi(${r>0?"\\item ":""}${IA(o)},r*2)+
}for(let o=r;o>0;o--)t+=Wi("\\end{itemize}",(o-1)*2)+
;return t},IA=e=>{switch(e.type){case"codeBlock":return AA(e);case"table":return FA(e);case"line":return DA(e)}},AA=e=>\\begin{lstlisting}language=${tr($A(e.fileName))},caption=${tr(e.fileName)},label=lang:${e.fileName},numbers=left
${e.content}
\\end{lstlisting},FA=e=>{let t=\\caption{${tr(e.fileName)}}\\label{table:${tr(e.fileName)}},r=Math.max(...e.cells.map(n=>n.length)),o=e.cells.map(n=> ${n.map(s=>s.map(i=>Os(i)).join("")).join(" & ")}\\\\);return\\begin{table}htbp
${t}
\\centering
\\begin{tabular}{${"c".repeat(r)}}
${o.length===0?"":o.length===1?` \\toprule
${o.join(`
`)}
\\bottomrule: \\toprule
${o0}
\\midrule
${o.slice(1).join(`
`)}
\\bottomrule`}
\\end{tabular}
\\end{table}},DA=e=>e.nodes.map(t=>Os(t)).join(""),Os=e=>{switch(e.type){case"quote":return\\begin{quote}
${Wi(e.nodes.map(t=>Os(t)).join(""),2)}
\\end{quote};case"image":case"strongImage":return\\begin{figure}hbtp
iamge:\\url{${e.src}}
\\end{figure};case"icon":case"strongIcon":return\\textit{${tr(e.path)}};case"strong":return\\textbf{${e.nodes.map(t=>Os(t)).join("")}};case"formula":return$${e.formula}$;case"decoration":{let t=e.nodes.map(r=>Os(r)).join("");return e.decos.includes("/")&&(t=\\textit{${t}}),e.decos.some(r=>/\*-/.test(r[0]))&&(t=\\textbf{${t}}),e.decos.includes("_")&&(t=\\uline{${t}}),e.decos.includes("-")&&(t=\\sout{${t}}),t}case"numberList":return${e.number}. ${e.nodes.map(t=>Os(t)).join("")};case"helpfeel":return\\lstinline!? ${tr(e.text)}!;case"code":return\\lstinline!${tr(e.text)}!;case"commandLine":return\\lstinline!${tr(e.symbol)} ${tr(e.text)}!;case"link":return e.pathType==="absolute"?e.content===""?\\url{${e.href}}:\\href{${e.href}}{${tr(e.content)}}:tr(e.href);case"googleMap":return\\href{${e.url}}{${tr(e.place)}};case"hashTag":return tr(#${e.href});case"blank":case"plain":return tr(e.text)}},UA=[{extensions:["javascript","js"],fileType:"javascript"},{extensions:["typescript","ts"],fileType:"typescript"},{extensions:["cpp","hpp"],fileType:"C++"},{extensions:["c","cc","h"],fileType:"C"},{extensions:["cs","csharp"],fileType:"cs"},{extensions:["markdown","md"],fileType:"markdown"},{extensions:["htm","html"],fileType:"html"},{extensions:["json"],fileType:"json"},{extensions:["xml"],fileType:"xml"},{extensions:["yaml","yml"],fileType:"yaml"},{extensions:["toml"],fileType:"toml"},{extensions:["ini"],fileType:"ini"},{extensions:["tex","sty"],fileType:"tex"},{extensions:["svg"],fileType:"svg"}],$A=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return UA.find(r=>r.extensions.includes(t))?.fileType??""},tr=e=>e.replaceAll("\\","\\textbackslash ").replaceAll("#","\\#").replaceAll("%","\\%").replaceAll("$","\\$").replaceAll("&","\\&").replaceAll("~","\\textasciitilde ").replaceAll("^","\\textasciicircum ").replaceAll("_","\\_").replaceAll("{","\\{").replaceAll("}","\\}").replaceAll("|","\\textbar ").replaceAll("<","\\textless ").replaceAll(">","\\textgreater "),Wi=(e,t)=>e.split(
).map(r=>${" ".repeat(t)}${r}).join(
);scrapbox.PopupMenu.addButton({title:"TeX",onClick:e=>{navigator.clipboard.writeText(Uk(at(e))).catch(t=>{console.error(t),alert(${t.name} ${t.message}
${t.stack})})}});var Bl="https://keicho.herokuapp.com/api/";var $k=async(e,t)=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let r=await window.GM_fetch(${Bl}web/,{mode:"cors",method:"POST",body:JSON.stringify({user:"nobody",talk:t,text:e}),headers:{"Content-Type":"application/json"}});if(!r.ok)return{ok:!1,value:{name:"ResponseError",res:r}};let o=await r.json();return{ok:!0,value:{text:o.text,buttons:o.buttons,canInput:o.can_input}}};var jk=()=>{let{popupMenu:e,render:t}=jA();iy()?.append?.(e);let r=So(),o=()=>{requestAnimationFrame(()=>{let n=document.getElementsByClassName("cursor")[0];e.style.top=${parseInt(n.style.top)+parseInt(n.style.height)+4}px})};return r.addChangeListener(o),{render:t,visible:()=>!e.hidden,open:()=>e.hidden=!1,close:()=>e.hidden=!0,toggle:()=>e.hidden=!e.hidden,dispose:()=>{e.remove(),r.removeChangeListener(o)}}},jA=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});t.innerHTML=
<style>
:host {
position: absolute;
left: 0px;
width:100%;
z-index:300;
user-select:none;
font-family:"Open Sans",Helvetica,Arial,"Hiragino Sans",sans-serif;
pointer-events:none
}
.button-container {
position: relative;
display:inline-block;
max-width:70vw;
min-width:80px;
text-align:center;
background-color:#111;
padding:0 1px;
border-radius:4px;
pointer-events:auto
}
htmldata-os*='android' .button-container {
max-width:90vw
}
htmldata-os*='ios' .button-container {
max-width:90vw
}
.button {
font-size:11px;
color:#eee;
cursor:pointer;
display:inline-block;
padding:0 5px
}
.button:not(:first-of-type) {
border:0;
border-left:1px solid #eee
}
.button.selected {
background-color:#222;
text-decoration:underline
}
htmldata-os*='android' .button {
font-size:13px;
padding:6px;
min-width:12vw
}
htmldata-os*='ios' .button{
font-size:13px;
padding:6px;
min-width:12vw
}
.button div.icon {
height:2em;
max-width:10em;
display:inline-block;
overflow:hidden;
margin-left:1px;
vertical-align:top
}
.button div.icon img {
max-height:100%;
vertical-align:unset
}
</style>
<div class="button-container"></div>
;let r=t.lastElementChild;return{popupMenu:e,render:(...o)=>{r.textContent="",r.append(...o.map(({text:n,onClick:s})=>{let i=document.createElement("div");return i.classList.add("button"),i.textContent=n,s&&i.addEventListener("click",()=>s()),i}))}}};var Bk=async(e="normal")=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let t=await window.GM_fetch(${Bl}web/create/?mode=${e},{mode:"cors"});return t.ok?{ok:!0,value:await t.text()}:{ok:!1,value:{name:"ResponseError",res:t}}};var Hk=e=>https://keicho.netlify.app/#talk=${e};var Wk=e=>{let t=e.split(
),r=t[1]??t[0],o=e===t[0]?"":t[0];return o?[o.trim(),r].join(
):r};var Hl=async(e,t,r)=>{let o=So(),n=o.lines.findIndex(i=>i.id===t.id);n<0&&(n=o.lines.findIndex(i=>i.text===t.text)),n<0&&(n=Math.min(r,Math.max(0,o.lines.length-1)));let s=o.lines[n].text;return oc().clear(),o.setPosition({line:n,char:[...s].length}),await ct(
${e}),o.getPosition().line};var qk=e=>at(e,{hasTitle:!1}).map(t=>{if(t.type==="title")return t.text.trimEnd();let r=" ".repeat(t.indent);switch(t.type){case"codeBlock":return[${r}${t.fileName},...t.content.split(
).map(o=>${r} ${o})].join(
).trimEnd();case"table":return[${r}${t.fileName},...t.cells.map(o=>${r} ${o.flatMap(n=>n.map(s=>Wl(s))).join(" ")})].join(
).trimEnd();case"line":return${r}${t.nodes.map(o=>Wl(o)).join("")}.trimEnd()}}).join(
),Wl=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Wl(t)).join("")};case"helpfeel":case"commandLine":return e.raw;case"strongImage":case"image":case"strongIcon":case"icon":case"googleMap":return"";case"strong":case"decoration":case"numberList":return e.nodes.map(t=>Wl(t)).join("");case"formula":return\\(${e.formula}\\);case"code":return ${e.text} ;case"blank":case"plain":return e.raw;case"hashTag":return e.href;case"link":switch(e.pathType){case"absolute":return e.content? ${e.content} :"";case"root":return e.href.split("/").pop()??"";case"relative":return e.href}}};var Ss=e=>/^[((]/.test(e);var zk=async e=>{let t=scrapbox.Page.lines;if(!t)return;let{cursor:r,selection:o}=Wt(),n=e?.entire||o.hasSelectionAll(),s=n?t.map(_=>_.text).join(
):o.getSelectedText(),i=e?.botIcon??"[/nishio/nisbot.icon]",{render:a,visible:c,open:l,close:u,dispose:p}=jk();u();let f=new Set,m=()=>{p();for(let _ of f)_()},h=_=>f.add(_),g={text:"Exit",onClick:m},y=e?.talkId||Gk(s)||(n?"":Gk(t.slice(0,1+r.getPosition().line).map(_=>_.text).join(
))),x=!y;if(!y){let _=Bk(e?.mode),C=setTimeout(()=>{a({text:"Start talking..."}),l();let j=0;C=setInterval(()=>{a({text:Start talking${".".repeat(j%3)}}),j++},1e3)},1e3),$=await _;if(clearTimeout(C),!$.ok){if($.value.name==="GMFetchNotAvailableError"){alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc.");return}if($.value.name==="ResponseError"){a({text:Error: ${$.value.res.status} ${$.value.res.statusText}},g),l(),console.error(Error: ${$.value.res.status} ${$.value.res.statusText},await $.value.res.text());return}return}y=$.value}let w=y,R=o.normalizeOrder(o.getRange()),b=n?t.length-1:R.end.line,E=t[b],T=n?"":" ".repeat(Math.min(...t.slice(R.start.line,R.end.line+1).map(_=>or(_.text)))),I=async _=>{let C=await $k(_,w);if(!C.ok)switch(C.value.name){case"ResponseError":return a({text:Error: ${C.value.res.status} ${C.value.res.statusText}},g),l(),console.error(Error: ${C.value.res.status} ${C.value.res.statusText},await C.value.res.text()),C;case"GMFetchNotAvailableError":return alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc."),C}return C},F="",A=async _=>{let C=qk(_).split(
).map(B=>B.trim()).join(
).trim();C.startsWith(F)&&(C=C.slice(F.length));let $=C.split(
);if($.length===0)return;if($.every(B=>Ss(B))&&(F=C),$.filter(B=>!Ss(B)).length<2){let B,Y;for(let G of $){if(Y=await I(G),!Y.ok)return Y;Ss(G)||(B=Y)}return B??Y}let q=0;{let B;for(;q<$.length&&Ss($[q]);q++)if(B=await I($[q]),!B.ok)return B}{let B=await I("まず聞いて");if(!B.ok)return B}for(;q<$.length&&!Ss($[q]);q++){let B=await I($[q]);if(!B.ok)return B}return await I("おしまい")},N=async _=>{if(scrapbox.Layout!=="page"||_==="")return;let C=A(_),$=setTimeout(()=>{a({text:"Asking..."}),l();let G=0;$=setInterval(()=>{a({text:Asking${".".repeat(G%3)}}),G++},1e3)},1e3),j=await C;if(clearTimeout($),!j||!j.ok)return;let{text:q,buttons:B}=j.value,Y=Wk(q);if(Y.trim()){let G=${T}${i}${Y.includes(`
)?
${Y.split(`
).map(X=> ${T}${X}).join(
)}:Y}
${T};b=await Hl(G,E,b),E=t[b]}a({text:"Send",onClick:P},{text:"🙂",onClick:()=>ct("🙂")},{text:"🙁",onClick:()=>ct("🙁")},...B.map(G=>({text:G,onClick:async()=>{b=await Hl(G,E,b),E=t[b],await N(G)}})),g),l()},P=async()=>{if(scrapbox.Layout!=="page")return;let _=scrapbox.Page.lines,C=r.getPosition().line,[$,j,q]=BA(_,C,i);$!==""&&(b=q,E=_[b],T=" ".repeat(Math.min(..._.slice(j,q+1).map(B=>or(B.text)))),await N($))};return x&&(b=await Hl(Hk(w),E,b),E=t[b]),await N(s),{ask:P,open:l,close:u,visible:c,exit:m,onExit:h}},Gk=e=>{for(let t of e.split(
).reverse()){let r=t.match(/https?:\/\/keicho\.netlify\.app\/#talk=(\w+)/)?.[1];if(r)return r}},BA=(e,t,r)=>{let o=Math.max(e.findLastIndex((s,i)=>i<t&&s.text.trim().startsWith(r)),1),n=o+Yo(o,e)+1;return[e.slice(n,t+1).map(s=>s.text.trim()).join(
).trim(),n,t]};scrapbox.PopupMenu.addButton({title:"",onClick:e=>${e}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>$ ${e}});var Vk=[un,mn,fn];scrapbox.PopupMenu.addButton({title:e=>{let t=ro({project:scrapbox.Project.name,mode:"noopen",hooks:Vk});return!t||t.hookName.includes("default")?"":t.hookName.includes("task")?"":t.hookName.includes("split")?"":""},onClick:()=>{let e=window.prompt("Create a new page at",scrapbox.Project.name);e&&ro({project:e,mode:"noopen",hooks:Vk})?.()}});scrapbox.PopupMenu.addButton({title:e=>/(https?:\/\/[^\s]+)/g.test(e)?"":"",onClick:e=>{let t=e.replace(/(https?:\/\/[^\s]+)/g,"[$1#.jpg]");if(e!==t)return t}});scrapbox.PopupMenu.addButton({title:"S",onClick:e=>{window.open(https://scrapbox.io/${scrapbox.Project.name}/search/page?q=${e})}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(
);window.open(https://www.google.com/search?q=${encodeURIComponent(t)})}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=o=>[...o].some(n=>n.charCodeAt(0)>255),r=e.split(/\n/).map(o=>o.replace(/\[(.*)\]/g,"$1")).join(
).trim().replace(/\s+/g,"+");t(r)?window.open(https://www.ldoceonline.com/search/japanese-english/direct/?q=${encodeURIComponent(r)}):window.open(https://www.oxfordlearnersdictionaries.com/search/english/?q=${encodeURIComponent(r)})}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[(.*)\]/g,"$1")).join(
);window.open(https://www.google.com/search?q=${encodeURIComponent(t)}+site:scrapbox.io)}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>${e}});scrapbox.PopupMenu.addButton({title:"🖍",onClick:e=>${e}});scrapbox.PopupMenu.addButton({title:e=>/\$([^$]+)\$/.test(e)?"L":"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\$([^$]+)\$/g,"[$ $1]")).join(
);if(e!=t)return t}});var HA=[Gf,vk,Gf,Tk,Ok,Ul(),Sk,wk(),Mk,kk,e=>{if(e.hostname!=="ekitan.com"||!/^\/transit\/(?:route|first|last)\//.test(e.pathname))return e;let t=e.searchParams.get("dt"),r=e.searchParams.get("tm"),o=e.searchParams.get("sr"),n=new URL(e);return n.search="",t&&n.searchParams.append("dt",t),n.pathname.startsWith("/transit/route/")&&(r&&n.searchParams.append("tm",r),o&&n.searchParams.append("sr",o)),n},e=>{if(e.host!==location.host||!e.pathname.startsWith("/api/code/"))return e;let t=encodeURIComponent(${e.origin}${e.pathname});return${e}.endsWith(".svg")?${e}:${e}.endsWith(".mlt")?${e}:e},e=>{if(e.hostname==="raw.githubusercontent.com")return${e};if(e.hostname!=="github.com")return e;let[t,r,o]=e.pathname.match(/^\/([^\\]+)\/([^\\]+)\/blob\/(.+)$/)?.slice?.(1)??[];if(!t||!r||!o)return e;let[,n,s]=e.hash.match(/L(\d+)-L(\d+)/)??e.hash.match(/L(\d+)/)??[];return[https://code2svg.vercel.app/svg/${n&&s?L${n}-${s}/:n?L${n}/:""}https://raw.githubusercontent.com/${t}/${r}/${o}#.svg ${e}]},e=>e.hostname==="github.com"?${e}:e,Nk,jl()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=Lk(e,...HA);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return ct(r)})}});Dk(["takker","takker-memex","takker-private","takker-books"]);if(!/mobile/i.test(navigator.userAgent)){let e=(t,r)=>{t.trim()!==""&&zk({mode:r}).then(o=>{if(!o)return;let{ask:n,visible:s,onExit:i}=o,a=c=>{!s()||c.key!=="Enter"||!c.ctrlKey||c.altKey||c.shiftKey||(c.preventDefault(),c.stopPropagation(),n())};ht().addEventListener("keydown",a),i(()=>ht().removeEventListener("keydown",a))})};scrapbox.PopupMenu.addButton({title:()=>"🤖",onClick:t=>e(t)})}var qi=(e,t)=>t.map(r=>r.replace(/@yyyy-MM-dd HH:mm:ss@/g,lt(e,"yyyy-MM-dd HH:mm:ss")).replace(/@yyyy-MM-dd@/g,lt(e,"yyyy-MM-dd")).replace(/@yyyy-MM-dd(?:([+-])(\d+)(w?))?(?:\((Sun|Mon|Tue|Wed|Thu|Fri|Sat)\))?@/g,(o,n,s,i,a)=>{let c=n?n==="+"?ke(e,parseInt(s)*(i==="w"?7:1)):Yt(e,parseInt(s)*(i==="w"?7:1)):e;return lt(a?ke(Ne(c),WA(a)):c,"yyyy-MM-dd")}).replace(/@yyyy-ww@/g,${ci(e)}-w${${Mo(e)}.padStart(2,"0")}).replace(/@yyyy-ww([+-])(\d+)(w?)@/g,(o,n,s,i)=>{let a=n==="+"?ke(e,parseInt(s)*(i==="w"?7:1)):Yt(e,parseInt(s)*(i==="w"?7:1));return${ci(a)}-w${${Mo(a)}.padStart(2,"0")}}).replace(/@yyyy@/g,${ci(e)}).replace(/@yyyy([+-])(\d+)y@/g,(o,n,s)=>{let i=parseInt(s);return${ci(e)+(n==="+"?i:-i)}})),WA=e=>{switch(e){case"Sun":return 0;case"Mon":return 1;case"Tue":return 2;case"Wed":return 3;case"Thu":return 4;case"Fri":return 5;default:return 6}};var Yk=async(e,t,r,o=new Date(2023,1,3))=>{if(scrapbox.Project.name!==e)return()=>{};let n=scrapbox.Project.pages;await new Promise(l=>{let u=setInterval(()=>{if(n.length===0){n=scrapbox.Project.pages;return}clearInterval(u),l()},2e3)});let s=async()=>{let l=new Date,u={start:o,end:ke(l,1)},{render:p,dispose:f}=Fe(),m;try{let h=await Kk(t),g=await Kk(r),y=ai(u).filter(b=>{let E=qi(b,h)[0],T=n.find(I=>I.title===E);return!T||!T.exists}),x=ax(u).filter(b=>{let E=qi(b,g)[0],T=n.find(I=>I.title===E);return!T||!T.exists});if(y.length===0&&x.length===0)return;let w=y.length+x.length;p({type:"spinner"},{type:"text",text:create ${w} review pages...});let R=await It();if(O(R))throw Z(R);m=S(R);for(let b of[...y.map(E=>qi(E,h)),...x.map(E=>qi(E,g))])await Le(e,b[0],(E,T)=>T.persistent?void 0:b,m?{socket:m}:{}),w--,p({type:"spinner"},{type:"text",text:create ${w} review pages...});p({type:"check-circle"},{type:"text",text:created ${y.length+x.length} review pages.}),o=l}catch(h){p({type:"exclamation-triangle"},{type:"text",text:h instanceof Error?${h.name} ${h.message}:"Unknown error! (see developper console)"}),console.error(h)}finally{m&&await At(m),await Se(1e3),f()}},i=s(),a=new Date,c=setInterval(()=>{let l=new Date;yt(a,l)||(a=l,i.then(()=>i=s()))},1e4);return()=>(clearTimeout(c),i)},Kk=async e=>{let t=await Ma(e[0],e[1],e[2]);if(O(t)){let o=new Error;throw o.name=Z(t).name,o.message=${Z(t).message} at fetching /${e0}/${e1}/${e2},o}let r=S(t).split(
);if(r.length===0)throw new Error(template "/${e0}/${e1}/${e2}" is empty!);return r};var qA=class{__unenv__=!0;_currentStore;_enterStore;_enabled=!0;getStore(){return this._currentStore??this._enterStore}disable(){this._enabled=!1}enable(){this._enabled=!0}enterWith(e){this._enterStore=e}run(e,t,...r){this._currentStore=e;let o=t(...r);return this._currentStore=void 0,o}exit(e,...t){let r=this._currentStore;this._currentStore=void 0;let o=e(...t);return this._currentStore=r,o}static snapshot(){throw new Error("[unenv] AsyncLocalStorage.snapshot is not implemented!")}},olt=globalThis.AsyncLocalStorage||qA,GA=Symbol("init"),zA=Symbol("before"),VA=Symbol("after"),KA=Symbol("destroy"),YA=Symbol("promiseResolve"),nlt=class{__unenv__=!0;_enabled=!1;_callbacks={};constructor(e={}){this._callbacks=e}enable(){return this._enabled=!0,this}disable(){return this._enabled=!1,this}get[GA](){return this._callbacks.init}get[zA](){return this._callbacks.before}get[VA](){return this._callbacks.after}get[KA](){return this._callbacks.destroy}get[YA](){return this._callbacks.promiseResolve}};var XA=function(){return 0};var slt=Object.assign(Object.create(null),{NONE:0,DIRHANDLE:1,DNSCHANNEL:2,ELDHISTOGRAM:3,FILEHANDLE:4,FILEHANDLECLOSEREQ:5,BLOBREADER:6,FSEVENTWRAP:7,FSREQCALLBACK:8,FSREQPROMISE:9,GETADDRINFOREQWRAP:10,GETNAMEINFOREQWRAP:11,HEAPSNAPSHOT:12,HTTP2SESSION:13,HTTP2STREAM:14,HTTP2PING:15,HTTP2SETTINGS:16,HTTPINCOMINGMESSAGE:17,HTTPCLIENTREQUEST:18,JSSTREAM:19,JSUDPWRAP:20,MESSAGEPORT:21,PIPECONNECTWRAP:22,PIPESERVERWRAP:23,PIPEWRAP:24,PROCESSWRAP:25,PROMISE:26,QUERYWRAP:27,QUIC_ENDPOINT:28,QUIC_LOGSTREAM:29,QUIC_PACKET:30,QUIC_SESSION:31,QUIC_STREAM:32,QUIC_UDP:33,SHUTDOWNWRAP:34,SIGNALWRAP:35,STATWATCHER:36,STREAMPIPE:37,TCPCONNECTWRAP:38,TCPSERVERWRAP:39,TCPWRAP:40,TTYWRAP:41,UDPSENDWRAP:42,UDPWRAP:43,SIGINTWATCHDOG:44,WORKER:45,WORKERHEAPSNAPSHOT:46,WRITEWRAP:47,ZLIB:48,CHECKPRIMEREQUEST:49,PBKDF2REQUEST:50,KEYPAIRGENREQUEST:51,KEYGENREQUEST:52,KEYEXPORTREQUEST:53,CIPHERREQUEST:54,DERIVEBITSREQUEST:55,HASHREQUEST:56,RANDOMBYTESREQUEST:57,RANDOMPRIMEREQUEST:58,SCRYPTREQUEST:59,SIGNREQUEST:60,TLSWRAP:61,VERIFYREQUEST:62}),JA=100,QA=class{__unenv__=!0;type;_asyncId;_triggerAsyncId;constructor(e,t=XA()){this.type=e,this._asyncId=-1*JA++,this._triggerAsyncId=typeof t=="number"?t:t?.triggerAsyncId}static bind(e,t,r){return new Kf(t??"anonymous").bind(e)}bind(e,t){let r=(...o)=>this.runInAsyncScope(e,t,...o);return r.asyncResource=this,r}runInAsyncScope(e,t,...r){return e.apply(t,r)}emitDestroy(){return this}asyncId(){return this._asyncId}triggerAsyncId(){return this._triggerAsyncId}},Kf=globalThis.AsyncResource||QA;function ZA(e){return new Error(unenv ${e} is not implemented yet!)}function rd(e){return Object.assign(()=>{throw ZA(e)},{__unenv__:!0})}var Ns=10,eF=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),oT=(e,t)=>e,Ms=Error,tF=Error,Ln=Error,ql=Error,rF=Error,Zf=Symbol.for("nodejs.rejection"),zr=Symbol.for("kCapture"),Yf=Symbol.for("events.errorMonitor"),Ls=Symbol.for("shapeMode"),Gl=Symbol.for("events.maxEventTargetListeners"),oF=Symbol.for("kEnhanceStackBeforeInspector"),nF=Symbol.for("nodejs.watermarkData"),Xf=Symbol.for("kEventEmitter"),Sn=Symbol.for("kAsyncResource"),sF=Symbol.for("kFirstEventParam"),ed=Symbol.for("kResistStopPropagation"),Xk=Symbol.for("events.maxEventTargetListenersWarned"),zl=class Gi{_events=void 0;_eventsCount=0;_maxListeners=Ns;[zr]=!1;[Ls]=!1;static captureRejectionSymbol=Zf;static errorMonitor=Yf;static kMaxEventTargetListeners=Gl;static kMaxEventTargetListenersWarned=Xk;static usingDomains=!1;static get on(){return cF}static get once(){return lF}static get getEventListeners(){return pF}static get getMaxListeners(){return uF}static get addAbortListener(){return nT}static get EventEmitterAsyncResource(){return iF}static get EventEmitter(){return Gi}static setMaxListeners(t=Ns,...r){if(r.length===0)Ns=t;else for(let o of r)if(iT(o))o[Gl]=t,o[Xk]=!1;else if(typeof o.setMaxListeners=="function")o.setMaxListeners(t);else throw new Ln("eventTargets",["EventEmitter","EventTarget"],o)}static listenerCount(t,r){if(typeof t.listenerCount=="function")return t.listenerCount(r);Gi.prototype.listenerCount.call(t,r)}static init(){throw new Error("EventEmitter.init() is not implemented.")}static get captureRejections(){return this[zr]}static set captureRejections(t){this[zr]=t}static get defaultMaxListeners(){return Ns}static set defaultMaxListeners(t){Ns=t}constructor(t){this._events===void 0||this._events===Object.getPrototypeOf(this)._events?(this._events={__proto__:null},this._eventsCount=0,this[Ls]=!1):this[Ls]=!0,this._maxListeners=this._maxListeners||void 0,t?.captureRejections?this[zr]=!!t.captureRejections:this[zr]=Gi.prototype[zr]}setMaxListeners(t){return this._maxListeners=t,this}getMaxListeners(){return od(this)}emit(t,...r){let o=t==="error",n=this._events;if(n!==void 0)o&&n[Yf]!==void 0&&this.emit(Yf,...r),o=o&&n.error===void 0;else if(!o)return!1;if(o){let i;if(r.length>0&&(i=r[0]),i instanceof Error){try{let l={};Error.captureStackTrace?.(l,Gi.prototype.emit),Object.defineProperty(i,oF,{__proto__:null,value:Function.prototype.bind(fF,this,i,l),configurable:!0})}catch{}throw i}let a;try{a=oT(i)}catch{a=i}let c=new tF(a);throw c.context=i,c}let s=n[t];if(s===void 0)return!1;if(typeof s=="function"){let i=s.apply(this,r);i!=null&&Zk(this,i,t,r)}else{let i=s.length,a=nd(s);for(let c=0;c<i;++c){let l=a[c].apply(this,r);l!=null&&Zk(this,l,t,r)}}return!0}addListener(t,r){return eT(this,t,r,!1),this}on(t,r){return this.addListener(t,r)}prependListener(t,r){return eT(this,t,r,!0),this}once(t,r){return this.on(t,tT(this,t,r)),this}prependOnceListener(t,r){return this.prependListener(t,tT(this,t,r)),this}removeListener(t,r){let o=this._events;if(o===void 0)return this;let n=o[t];if(n===void 0)return this;if(n===r||n.listener===r)this._eventsCount-=1,this[Ls]?o[t]=void 0:this._eventsCount===0?this._events={__proto__:null}:(delete o[t],o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){let s=-1;for(let i=n.length-1;i>=0;i--)if(n[i]===r||n[i].listener===r){s=i;break}if(s<0)return this;s===0?n.shift():yF(n,s),n.length===1&&(o[t]=n[0]),o.removeListener!==void 0&&this.emit("removeListener",t,r)}return this}off(t,r){return this.removeListener(t,r)}removeAllListeners(t){let r=this._events;if(r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events={__proto__:null},this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events={__proto__:null}:delete r[t]),this[Ls]=!1,this;if(arguments.length===0){for(let n of Reflect.ownKeys(r))n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events={__proto__:null},this._eventsCount=0,this[Ls]=!1,this}let o=r[t];if(typeof o=="function")this.removeListener(t,o);else if(o!==void 0)for(let n=o.length-1;n>=0;n--)this.removeListener(t,o[n]);return this}listeners(t){return rT(this,t,!0)}rawListeners(t){return rT(this,t,!1)}eventNames(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}listenerCount(t,r){let o=this._events;if(o!==void 0){let n=o[t];if(typeof n=="function")return r!=null?r===n||r===n.listener?1:0:1;if(n!==void 0){if(r!=null){let s=0;for(let i=0,a=n.length;i<a;i++)(n[i]===r||n[i].listener===r)&&s++;return s}return n.length}}return 0}},iF=class extends zl{constructor(e){let t;typeof e=="string"?(t=e,e=void 0):t=e?.name||new.target.name,super(e),this[Sn]=new aF(this,t,e)}emit(e,...t){if(this[Sn]===void 0)throw new Ms("EventEmitterAsyncResource");let{asyncResource:r}=this;return Array.prototype.unshift(t,super.emit,this,e),Reflect.apply(r.runInAsyncScope,r,t)}emitDestroy(){if(this[Sn]===void 0)throw new Ms("EventEmitterAsyncResource");this.asyncResource.emitDestroy()}get asyncId(){if(this[Sn]===void 0)throw new Ms("EventEmitterAsyncResource");return this.asyncResource.asyncId()}get triggerAsyncId(){if(this[Sn]===void 0)throw new Ms("EventEmitterAsyncResource");return this.asyncResource.triggerAsyncId()}get asyncResource(){if(this[Sn]===void 0)throw new Ms("EventEmitterAsyncResource");return this[Sn]}},aF=class extends Kf{constructor(e,t,r){super(t,r),this[Xf]=e}get eventEmitter(){if(this[Xf]===void 0)throw new Ms("EventEmitterReferencingAsyncResource");return this[Xf]}},cF=function(e,t,r={}){let o=r.signal;if(o?.aborted)throw new ql(void 0,{cause:o?.reason});let n=r.highWaterMark??r.highWatermark??Number.MAX_SAFE_INTEGER,s=r.lowWaterMark??r.lowWatermark??1,i=new Qk,a=new Qk,c=!1,l=null,u=!1,p=0,f=Object.setPrototypeOf({next(){if(p){let E=i.shift();return p--,c&&p<s&&(e.resume?.(),c=!1),Promise.resolve(Qf(E,!1))}if(l){let E=Promise.reject(l);return l=null,E}return u?b():new Promise(function(E,T){a.push({resolve:E,reject:T})})},return(){return b()},throw(E){if(!E||!(E instanceof Error))throw new Ln("EventEmitter.AsyncIterator","Error",E);R(E)},[Symbol.asyncIterator](){return this},[nF]:{get size(){return p},get low(){return s},get high(){return n},get isPaused(){return c}}},eF),{addEventListener:m,removeAll:h}=gF();m(e,t,r[sF]?w:function(...E){return w(E)}),t!=="error"&&typeof e.on=="function"&&m(e,"error",R);let g=r?.close;if(g?.length)for(let E of g)m(e,E,b);let y=o?nT(o,x):null;return f;function x(){R(new ql(void 0,{cause:o?.reason}))}function w(E){a.isEmpty()?(p++,!c&&p>n&&(c=!0,e.pause?.()),i.push(E)):a.shift().resolve(Qf(E,!1))}function R(E){a.isEmpty()?l=E:a.shift().reject(E),b()}function b(){y?.[Symbol.dispose](),h(),u=!0;let E=Qf(void 0,!0);for(;!a.isEmpty();)a.shift().resolve(E);return Promise.resolve(E)}},lF=async function(e,t,r={}){let o=r?.signal;if(o?.aborted)throw new ql(void 0,{cause:o?.reason});return new Promise((n,s)=>{let i=u=>{typeof e.removeListener=="function"&&e.removeListener(t,a),o!=null&&zi(o,"abort",l),s(u)},a=(...u)=>{typeof e.removeListener=="function"&&e.removeListener("error",i),o!=null&&zi(o,"abort",l),n(u)},c={__proto__:null,once:!0,[ed]:!0};td(e,t,a,c),t!=="error"&&typeof e.once=="function"&&e.once("error",i);function l(){zi(e,t,a),zi(e,"error",i),s(new ql(void 0,{cause:o?.reason}))}o!=null&&td(o,"abort",l,{__proto__:null,once:!0,[ed]:!0})})},nT=function(e,t){if(e===void 0)throw new Ln("signal","AbortSignal",e);let r;return e.aborted?queueMicrotask(()=>t()):(e.addEventListener("abort",t,{__proto__:null,once:!0,[ed]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[Symbol.dispose](){r?.()}}},pF=function(e,t){if(typeof e.listeners=="function")return e.listeners(t);if(iT(e)){let r=e[kEvents].get(t),o=[],n=r?.next;for(;n?.listener!==void 0;){let s=n.listener?.deref?n.listener.deref():n.listener;o.push(s),n=n.next}return o}throw new Ln("emitter",["EventEmitter","EventTarget"],e)},uF=function(e){if(typeof e?.getMaxListeners=="function")return od(e);if(e?.[Gl])return e[Gl];throw new Ln("emitter",["EventEmitter","EventTarget"],e)},sT=2048,Jf=sT-1,Jk=class{bottom;top;list;next;constructor(){this.bottom=0,this.top=0,this.list=new Array(sT),this.next=null}isEmpty(){return this.top===this.bottom}isFull(){return(this.top+1&Jf)===this.bottom}push(e){this.list[this.top]=e,this.top=this.top+1&Jf}shift(){let e=this.list[this.bottom];return e===void 0?null:(this.list[this.bottom]=void 0,this.bottom=this.bottom+1&Jf,e)}},Qk=class{head;tail;constructor(){this.head=this.tail=new Jk}isEmpty(){return this.head.isEmpty()}push(e){this.head.isFull()&&(this.head=this.head.next=new Jk),this.head.push(e)}shift(){let e=this.tail,t=e.shift();return e.isEmpty()&&e.next!==null&&(this.tail=e.next,e.next=null),t}};function iT(e){return typeof e?.addEventListener=="function"}function Zk(e,t,r,o){if(e[zr])try{let n=t.then;typeof n=="function"&&n.call(t,void 0,function(s){setTimeout(mF,0,e,s,r,o)})}catch(n){e.emit("error",n)}}function mF(e,t,r,o){if(typeof e[Zf]=="function")e[Zf](t,r,...o);else{let n=e[zr];try{e[zr]=!1,e.emit("error",t)}finally{e[zr]=n}}}function od(e){return e._maxListeners===void 0?Ns:e._maxListeners}function fF(e,t){let r="";try{let{name:s}=this.constructor;s!=="EventEmitter"&&(r= on ${s} instance)}catch{}let o=
Emitted 'error' event${r} at:
,n=(t.stack||"").split(
).slice(1);return e.stack+o+n.join(
)}function eT(e,t,r,o){let n,s,i;if(s=e._events,s===void 0?(s=e._events={__proto__:null},e._eventsCount=0):(s.newListener!==void 0&&(e.emit("newListener",t,r.listener??r),s=e._events),i=s[t]),i===void 0)s[t]=r,++e._eventsCount;else if(typeof i=="function"?i=s[t]=o?[r,i]:[i,r]:o?i.unshift(r):i.push(r),n=od(e),n>0&&i.length>n&&!i.warned){i.warned=!0;let a=new rF(Possible EventEmitter memory leak detected. ${i.length} ${String(t)} listeners added to ${oT(e,{depth:-1})}. MaxListeners is ${n}. Use emitter.setMaxListeners() to increase limit,{name:"MaxListenersExceededWarning",emitter:e,type:t,count:i.length});console.warn(a)}return e}function dF(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function tT(e,t,r){let o={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=dF.bind(o);return n.listener=r,o.wrapFn=n,n}function rT(e,t,r){let o=e._events;if(o===void 0)return[];let n=o[t];return n===void 0?[]:typeof n=="function"?r?[n.listener||n]:[n]:r?hF(n):nd(n)}function nd(e){switch(e.length){case 2:return[e[0],e[1]];case 3:return[e[0],e[1],e[2]];case 4:return[e[0],e[1],e[2],e[3]];case 5:return[e[0],e[1],e[2],e[3],e[4]];case 6:return[e[0],e[1],e[2],e[3],e[4],e[5]]}return Array.prototype.slice.call(e)}function hF(e){let t=nd(e);for(let r=0;r<t.length;++r){let o=t[r].listener;typeof o=="function"&&(t[r]=o)}return t}function Qf(e,t){return{value:e,done:t}}function zi(e,t,r,o){if(typeof e.removeListener=="function")e.removeListener(t,r);else if(typeof e.removeEventListener=="function")e.removeEventListener(t,r,o);else throw new Ln("emitter","EventEmitter",e)}function td(e,t,r,o){if(typeof e.on=="function")o?.once?e.once(t,r):e.on(t,r);else if(typeof e.addEventListener=="function")e.addEventListener(t,r,o);else throw new Ln("emitter","EventEmitter",e)}function gF(){let e=[];return{addEventListener(t,r,o,n){td(t,r,o,n),Array.prototype.push(e,[t,r,o,n])},removeAll(){for(;e.length>0;)Reflect.apply(zi,void 0,e.pop())}}}function yF(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}var ult=Symbol.for("nodejs.rejection");var mlt=Symbol.for("events.errorMonitor");var flt=rd("node:events.setMaxListeners"),dlt=rd("node:events.listenerCount"),hlt=rd("node:events.init");var aT=class{fd;isRaw=!1;isTTY=!1;constructor(e){this.fd=e}setRawMode(e){return this.isRaw=e,this}},sd=class{fd;columns=80;rows=24;isTTY=!1;constructor(e){this.fd=e}clearLine(e,t){return t&&t(),!1}clearScreenDown(e){return e&&e(),!1}cursorTo(e,t,r){return r&&typeof r=="function"&&r(),!1}moveCursor(e,t,r){return r&&r(),!1}getColorDepth(e){return 1}hasColors(e,t){return!1}getWindowSize(){return[this.columns,this.rows]}write(e,t,r){e instanceof Uint8Array&&(e=new TextDecoder().decode(e));try{console.log(e)}catch{}return r&&typeof r=="function"&&r(),!1}};function Lt(e){return new Error(unenv ${e} is not implemented yet!)}function Cs(e){return Object.assign(()=>{throw Lt(e)},{__unenv__:!0})}var cT="22.14.0",xF=class lT extends zl{env;hrtime;nextTick;constructor(t){super(),this.env=t.env,this.hrtime=t.hrtime,this.nextTick=t.nextTick;for(let r of[...Object.getOwnPropertyNames(lT.prototype),...Object.getOwnPropertyNames(zl.prototype)]){let o=this[r];typeof o=="function"&&(this[r]=o.bind(this))}}emitWarning(t,r,o){console.warn(${o?[${o}] :""}${r?${r}: :""}${t})}emit(...t){return super.emit(...t)}listeners(t){return super.listeners(t)}#o;#r;#t;get stdin(){return this.#o??=new aT(0)}get stdout(){return this.#r??=new sd(1)}get stderr(){return this.#t??=new sd(2)}#e="/";chdir(t){this.#e=t}cwd(){return this.#e}arch="";platform="";argv=[];argv0="";execArgv=[];execPath="";title="";pid=200;ppid=100;get version(){returnv${cT}}get versions(){return{node:cT}}get allowedNodeEnvironmentFlags(){return new Set}get sourceMapsEnabled(){return!1}get debugPort(){return 0}get throwDeprecation(){return!1}get traceDeprecation(){return!1}get features(){return{}}get release(){return{}}get connected(){return!1}get config(){return{}}get moduleLoadList(){return[]}constrainedMemory(){return 0}availableMemory(){return 0}uptime(){return 0}resourceUsage(){return{}}ref(){}unref(){}umask(){throw Lt("process.umask")}getBuiltinModule(){}getActiveResourcesInfo(){throw Lt("process.getActiveResourcesInfo")}exit(){throw Lt("process.exit")}reallyExit(){throw Lt("process.reallyExit")}kill(){throw Lt("process.kill")}abort(){throw Lt("process.abort")}dlopen(){throw Lt("process.dlopen")}setSourceMapsEnabled(){throw Lt("process.setSourceMapsEnabled")}loadEnvFile(){throw Lt("process.loadEnvFile")}disconnect(){throw Lt("process.disconnect")}cpuUsage(){throw Lt("process.cpuUsage")}setUncaughtExceptionCaptureCallback(){throw Lt("process.setUncaughtExceptionCaptureCallback")}hasUncaughtExceptionCaptureCallback(){throw Lt("process.hasUncaughtExceptionCaptureCallback")}initgroups(){throw Lt("process.initgroups")}openStdin(){throw Lt("process.openStdin")}assert(){throw Lt("process.assert")}binding(){throw Lt("process.binding")}permission={has:Cs("process.permission.has")};report={directory:"",filename:"",signal:"SIGUSR2",compact:!1,reportOnFatalError:!1,reportOnSignal:!1,reportOnUncaughtException:!1,getReport:Cs("process.report.getReport"),writeReport:Cs("process.report.writeReport")};finalization={register:Cs("process.finalization.register"),unregister:Cs("process.finalization.unregister"),registerBeforeExit:Cs("process.finalization.registerBeforeExit")};memoryUsage=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0});mainModule=void 0;domain=void 0;send=void 0;exitCode=void 0;channel=void 0;getegid=void 0;geteuid=void 0;getgid=void 0;getgroups=void 0;getuid=void 0;setegid=void 0;seteuid=void 0;setgid=void 0;setgroups=void 0;setuid=void 0;_events=void 0;_eventsCount=void 0;_exiting=void 0;_maxListeners=void 0;_debugEnd=void 0;_debugProcess=void 0;_fatalException=void 0;_getActiveHandles=void 0;_getActiveRequests=void 0;_kill=void 0;_preload_modules=void 0;_rawDebug=void 0;_startProfilerIdleNotifier=void 0;_stopProfilerIdleNotifier=void 0;_tickCallback=void 0;_disconnect=void 0;_handleQueue=void 0;_pendingMessage=void 0;_channel=void 0;_send=void 0;_linkedBinding=void 0},Vl=Object.create(null),bF=globalThis.process,Is=e=>globalThis.__env__||bF?.env||(e?Vl:globalThis),EF=new Proxy(Vl,{get(e,t){return Is()[t]??Vl[t]},has(e,t){let r=Is();return t in r||t in Vl},set(e,t,r){let o=Is(!0);return o[t]=r,!0},deleteProperty(e,t){let r=Is(!0);return delete r[t],!0},ownKeys(){let e=Is();return Object.keys(e)},getOwnPropertyDescriptor(e,t){let r=Is();if(t in r)return{value:r[t],writable:!0,enumerable:!0,configurable:!0}}}),wF=Object.assign(function(e){let t=Date.now(),r=Math.trunc(t/1e3),o=t%1e3*1e6;if(e){let n=r-e[0],s=o-e[0];return s<0&&(n=n-1,s=1e9+s),[n,s]}return[r,o]},{bigint:function(){return BigInt(Date.now()*1e6)}}),RF=globalThis.queueMicrotask?(e,...t)=>{globalThis.queueMicrotask(e.bind(void 0,...t))}:vF();function vF(){let e=[],t=!1,r,o=-1;function n(){!t||!r||(t=!1,r.length>0?e=[...r,...e]:o=-1,e.length>0&&s())}function s(){if(t)return;let i=setTimeout(n);t=!0;let a=e.length;for(;a;){for(r=e,e=[];++o<a;)r&&r[o]();o=-1,a=e.length}r=void 0,t=!1,clearTimeout(i)}return(i,...a)=>{e.push(i.bind(void 0,...a)),e.length===1&&!t&&setTimeout(s)}}var pT=new xF({env:EF,hrtime:wF,nextTick:RF}),Vi=pT,{abort:_lt,addListener:Plt,allowedNodeEnvironmentFlags:Olt,hasUncaughtExceptionCaptureCallback:Slt,setUncaughtExceptionCaptureCallback:Llt,loadEnvFile:Nlt,sourceMapsEnabled:Mlt,arch:Clt,argv:Ilt,argv0:Alt,chdir:Flt,config:Dlt,connected:Ult,constrainedMemory:$lt,availableMemory:jlt,cpuUsage:Blt,cwd:Hlt,debugPort:Wlt,dlopen:qlt,disconnect:Glt,emit:zlt,emitWarning:Vlt,env:Klt,eventNames:Ylt,execArgv:Xlt,execPath:Jlt,exit:Qlt,finalization:Zlt,features:ept,getBuiltinModule:tpt,getActiveResourcesInfo:rpt,getMaxListeners:opt,hrtime:npt,kill:spt,listeners:ipt,listenerCount:apt,memoryUsage:cpt,nextTick:lpt,on:ppt,off:upt,once:mpt,pid:fpt,platform:dpt,ppid:hpt,prependListener:gpt,prependOnceListener:ypt,rawListeners:xpt,release:bpt,removeAllListeners:Ept,removeListener:wpt,report:Rpt,resourceUsage:vpt,setMaxListeners:kpt,setSourceMapsEnabled:Tpt,stderr:_pt,stdin:Ppt,stdout:Opt,title:Spt,umask:Lpt,uptime:Npt,version:Mpt,versions:Cpt,domain:Ipt,initgroups:Apt,moduleLoadList:Fpt,reallyExit:Dpt,openStdin:Upt,assert:$pt,binding:jpt,send:Bpt,exitCode:Hpt,channel:Wpt,getegid:qpt,geteuid:Gpt,getgid:zpt,getgroups:Vpt,getuid:Kpt,setegid:Ypt,seteuid:Xpt,setgid:Jpt,setgroups:Qpt,setuid:Zpt,permission:eut,mainModule:tut,ref:rut,unref:out,_events:nut,_eventsCount:sut,_exiting:iut,_maxListeners:aut,_debugEnd:cut,_debugProcess:lut,_fatalException:put,_getActiveHandles:uut,_getActiveRequests:mut,_kill:fut,_preload_modules:dut,_rawDebug:hut,_startProfilerIdleNotifier:gut,_stopProfilerIdleNotifier:yut,_tickCallback:xut,_disconnect:but,_handleQueue:Eut,_pendingMessage:wut,_channel:Rut,_send:vut,_linkedBinding:kut}=pT;var kF=Object.create,gT=Object.defineProperty,TF=Object.getOwnPropertyDescriptor,_F=Object.getOwnPropertyNames,PF=Object.getPrototypeOf,OF=Object.prototype.hasOwnProperty,yT=(e=>typeof Wo<"u"?Wo:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Wo<"u"?Wo:t)[r]}):e)(function(e){if(typeof Wo<"u")return Wo.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),xT=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),SF=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of _F(t))!OF.call(e,n)&&n!==r&&gT(e,n,{get:()=>t[n],enumerable:!(o=TF(t,n))||o.enumerable});return e},bT=(e,t,r)=>(r=e!=null?kF(PF(e)):{},SF(t||!e||!e.__esModule?gT(r,"default",{value:e,enumerable:!0}):r,e)),LF=xT((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in Vi&&"node"in Vi.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[yT][0](${"node","util".join(":")})}catch{r=null}t.exports=r}),NF=xT((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in Vi&&"node"in Vi.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[yT][0](${"node","fs".join(":")})}catch{r=null}t.exports=r}),MF={},Kl=CF(globalThis,MF);function CF(e,t){return new Proxy(e,{get(r,o,n){return o in t?t[o]:e[o]},set(r,o,n){return o in t&&delete t[o],e[o]=n,!0},deleteProperty(r,o){let n=!1;return o in t&&(delete t[o],n=!0),o in e&&(delete e[o],n=!0),n},ownKeys(r){let o=Reflect.ownKeys(e),n=Reflect.ownKeys(t),s=new Set(n);return[...o.filter(i=>!s.has(i)),...n]},defineProperty(r,o,n){return o in t&&delete t[o],Reflect.defineProperty(e,o,n),!0},getOwnPropertyDescriptor(r,o){return o in t?Reflect.getOwnPropertyDescriptor(t,o):Reflect.getOwnPropertyDescriptor(e,o)},has(r,o){return o in t||o in e}})}var uT=["debug","info","warning","error","fatal"];function mT(e,t){let r=uT.indexOf(e);if(r<0)throw new TypeError(Invalid log level: ${JSON.stringify(e)}.);let o=uT.indexOf(t);if(o<0)throw new TypeError(Invalid log level: ${JSON.stringify(t)}.);return r-o}function Ki(e=[]){return ET.getLogger(e)}var id=Symbol.for("logtape.rootLogger"),ET=class Ho{static getLogger(t=[]){let r=id in Kl?Kl[id]??null:null;return r==null&&(r=new Ho(null,[]),Kl[id]=r),typeof t=="string"?r.getChild(t):t.length===0?r:r.getChild(t)}constructor(t,r){Object.defineProperty(this,"parent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"children",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sinks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parentSinks",{enumerable:!0,configurable:!0,writable:!0,value:"inherit"}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowestLevel",{enumerable:!0,configurable:!0,writable:!0,value:"debug"}),Object.defineProperty(this,"contextLocalStorage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.parent=t,this.children={},this.category=r,this.sinks=[],this.filters=[]}getChild(t){let r=typeof t=="string"?t:t[0],o=this.children[r],n=o instanceof Ho?o:o?.deref();return n==null&&(n=new Ho(this,[...this.category,r]),this.children[r]="WeakRef"in Kl?new WeakRef(n):n),typeof t=="string"||t.length===1?n:n.getChild(t.slice(1))}reset(){for(;this.sinks.length>0;)this.sinks.shift();for(this.parentSinks="inherit";this.filters.length>0;)this.filters.shift();this.lowestLevel="debug"}resetDescendants(){for(let t of Object.values(this.children))(t instanceof Ho?t:t.deref())?.resetDescendants();this.reset()}with(t){return new IF(this,{...t})}filter(t){for(let r of this.filters)if(!r(t))return!1;return this.filters.length<1?this.parent?.filter(t)??!0:!0}*getSinks(t){if(!(this.lowestLevel===null||mT(t,this.lowestLevel)<0)){if(this.parent!=null&&this.parentSinks==="inherit")for(let r of this.parent.getSinks(t))yield r;for(let r of this.sinks)yield r}}emit(t,r){if(!(this.lowestLevel===null||mT(t.level,this.lowestLevel)<0||!this.filter(t))){for(let o of this.getSinks(t.level))if(!r?.has(o))try{o(t)}catch(n){let s=new Set(r);s.add(o),AF.log("fatal","Failed to emit a log record to sink {sink}: {error}",{sink:o,error:n,record:t},s)}}}log(t,r,o,n){let s=Ho.getLogger().contextLocalStorage?.getStore()??{},i,a=typeof o=="function"?{category:this.category,level:t,timestamp:Date.now(),get message(){return fT(r,this.properties)},rawMessage:r,get properties(){return i==null&&(i={...s,...o()}),i}}:{category:this.category,level:t,timestamp:Date.now(),message:fT(r,{...s,...o}),rawMessage:r,properties:{...s,...o}};this.emit(a,n)}logLazily(t,r,o={}){let n=Ho.getLogger().contextLocalStorage?.getStore()??{},s,i;function a(){if((i==null||s==null)&&(i=r((c,...l)=>(s=c,dT(c,l))),s==null))throw new TypeError("No log record was made.");return[i,s]}this.emit({category:this.category,level:t,get message(){return a()[0]},get rawMessage(){return a()[1]},timestamp:Date.now(),properties:{...n,...o}})}logTemplate(t,r,o,n={}){let s=Ho.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:t,message:dT(r,o),rawMessage:r,timestamp:Date.now(),properties:{...s,...n}})}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},IF=class wT{constructor(t,r){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=t,this.properties=r}get category(){return this.logger.category}get parent(){return this.logger.parent}getChild(t){return this.logger.getChild(t).with(this.properties)}with(t){return new wT(this.logger,{...this.properties,...t})}log(t,r,o,n){this.logger.log(t,r,typeof o=="function"?()=>({...this.properties,...o()}):{...this.properties,...o},n)}logLazily(t,r){this.logger.logLazily(t,r,this.properties)}logTemplate(t,r,o){this.logger.logTemplate(t,r,o,this.properties)}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},AF=ET.getLogger(["logtape","meta"]);function fT(e,t){let r=[],o="";for(let n=0;n<e.length;n++){let s=e.charAt(n),i=e.charAt(n+1);if(s==="{"&&i==="{")o=o+s,n++;else if(s==="}"&&i==="}")o=o+s,n++;else if(s==="{")r.push(o),o="";else if(s==="}"){let a;o.match(/^\s|\s$/)?a=o in t?t[o]:t[o.trim()]:a=t[o],r.push(a),o=""}else o=o+s}return r.push(o),r}function dT(e,t){let r=[];for(let o=0;o<e.length;o++)r.push(e[o]),o<t.length&&r.push(t[o]);return r}var FF=bT(LF()),Yl=FF.default,hT={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},RT="Deno"in globalThis&&"inspect"in globalThis.Deno&&typeof globalThis.Deno.inspect=="function"?(e,t)=>globalThis.Deno.inspect(e,{strAbbreviateSize:1/0,iterableLimit:1/0,...t}):Yl!=null&&"inspect"in Yl&&typeof Yl.inspect=="function"?(e,t)=>Yl.inspect(e,{maxArrayLength:1/0,maxStringLength:1/0,...t}):e=>JSON.stringify(e);function vT(e={}){let t=e.timestamp==null||e.timestamp==="date-time-timezone"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00:00"):e.timestamp==="date-time-tz"?i=>new Date(i).toISOString().replace("T"," ").replace("Z"," +00"):e.timestamp==="date-time"?i=>new Date(i).toISOString().replace("T"," ").replace("Z",""):e.timestamp==="time-timezone"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00:00"):e.timestamp==="time-tz"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z"," +00"):e.timestamp==="time"?i=>new Date(i).toISOString().replace(/.*T/,"").replace("Z",""):e.timestamp==="date"?i=>new Date(i).toISOString().replace(/T.*/,""):e.timestamp==="rfc3339"?i=>new Date(i).toISOString():e.timestamp,r=e.category??"·",o=e.value??RT,n=e.level==null||e.level==="ABBR"?i=>hT[i]:e.level==="abbr"?i=>hT[i].toLowerCase():e.level==="FULL"?i=>i.toUpperCase():e.level==="full"?i=>i:e.level==="L"?i=>i.charAt(0).toUpperCase():e.level==="l"?i=>i.charAt(0):e.level,s=e.format??(({timestamp:i,level:a,category:c,message:l})=>${i} ${a} ${c}: ${l});return i=>{let a="";for(let p=0;p<i.message.length;p++)p%2===0?a+=i.message[p]:a+=o(i.message[p]);let c=t(i.timestamp),l=n(i.level),u=typeof r=="function"?r(i.category):i.category.join(r);return${s({timestamp:c,level:l,category:u,message:a,record:i})}
}}var Put=vT(),ad="\x1B[0m",cd={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},ld={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},DF={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function UF(e={}){let t=e.format,r=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=${r==null?"":ldr}${o==null?"":cdo},s=r==null&&o==null?"":ad,i=typeof e.levelStyle>"u"?"bold":e.levelStyle,a=e.levelColors??DF,c=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,l=e.categoryColor??null,u=${c==null?"":ldc}${l==null?"":cdl},p=c==null&&l==null?"":ad;return vT({timestamp:"date-time-tz",value(f){return RT(f,{colors:!0})},...e,format({timestamp:f,level:m,category:h,message:g,record:y}){let x=a[y.level];return f=${n}${f}${s},m=${i==null?"":ldi}${x==null?"":cdx}${m}${i==null&&x==null?"":ad},t==null?${f} ${m} ${u}${h}:${p} ${g}:t({timestamp:f,level:m,category:${u}${h}${p},message:g,record:y})}})}var Out=UF();var $F=bT(NF()),jF=$F.default;function As(){throw new Error("File sink is not available in the browser.")}var BF={openSync:As,writeSync:As,flushSync:As,closeSync:As,statSync:As,renameSync:As},Nn=jF,Sut=Nn==null?BF:{openSync(e){return Nn.openSync(e,"a")},writeSync:Nn.writeSync,flushSync:Nn.fsyncSync,closeSync:Nn.closeSync,statSync:Nn.statSync,renameSync:Nn.renameSync};async function*kT(e){let t=[],r=[],o=new Map,n=[];for(let s of e)s.isValid&&(s.id?s.isMember||t.push(s.id):r.push(s.name),n.push(s.name),o.set(s.name,s.checked));for(let s=0;s<t.length;s+=50){let i=t.slice(s,s+50);if(i.length===0)break;i.length===1&&i.push(i[0]);let a=await Sa(i);if(O(a)){r=n;break}for(let c of S(a).projects)o.has(c.name)&&(yield L({...c,checked:o.get(c.name)??0}))}for(let s of r){let i=await zo(s);yield K(i)?L({...S(i),checked:o.get(s)??0}):M({...Z(i),project:s})}}var md=(e,t)=>t.some(r=>e instanceof r),TT,_T;function HF(){return TT||(TT=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function WF(){return _T||(_T=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var fd=new WeakMap,pd=new WeakMap,Xl=new WeakMap;function qF(e){let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(Mn(e.result)),n()},i=()=>{o(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)});return Xl.set(t,e),t}function GF(e){if(fd.has(e))return;let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),n()},i=()=>{o(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});fd.set(e,t)}var dd={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return fd.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Mn(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function LT(e){dd=e(dd)}function zF(e){return WF().includes(e)?function(...t){return e.apply(hd(this),t),Mn(this.request)}:function(...t){return Mn(e.apply(hd(this),t))}}function VF(e){return typeof e=="function"?zF(e):(e instanceof IDBTransaction&&GF(e),md(e,HF())?new Proxy(e,dd):e)}function Mn(e){if(e instanceof IDBRequest)return qF(e);if(pd.has(e))return pd.get(e);let t=VF(e);return t!==e&&(pd.set(e,t),Xl.set(t,e)),t}var hd=e=>Xl.get(e);function NT(e,t,{blocked:r,upgrade:o,blocking:n,terminated:s}={}){let i=indexedDB.open(e,t),a=Mn(i);return o&&i.addEventListener("upgradeneeded",c=>{o(Mn(i.result),c.oldVersion,c.newVersion,Mn(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),n&&c.addEventListener("versionchange",l=>n(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}var KF=["get","getKey","getAll","getAllKeys","count"],YF=["put","add","delete","clear"],ud=new Map;function PT(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(ud.get(t))return ud.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,n=YF.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(n||KF.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,n?"readwrite":"readonly"),l=c.store;return o&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),n&&c.done]))[0]};return ud.set(t,s),s}LT(e=>({...e,get:(t,r,o)=>PT(t,r)||e.get(t,r,o),has:(t,r)=>!!PT(t,r)||e.has(t,r)}));var XF=["continue","continuePrimaryKey","advance"],OT={},gd=new WeakMap,MT=new WeakMap,JF={get(e,t){if(!XF.includes(t))return e[t];let r=OT[t];return r||(r=OT[t]=function(...o){gd.set(this,MT.get(this)[t](...o))}),r}};async function*QF(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,JF);for(MT.set(r,t),Xl.set(r,hd(t));t;)yield r,t=await(gd.get(r)||t.continue()),gd.delete(r)}function ST(e,t){return t===Symbol.asyncIterator&&md(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&md(e,[IDBIndex,IDBObjectStore])}LT(e=>({...e,get(t,r,o){return ST(t,r)?QF:e.get(t,r,o)},has(t,r){return ST(t,r)||e.has(t,r)}}));var CT,yd=async()=>{let e=Ki(["@takker/cosense-storage","open"]);return CT??=await NT("scrapbox-storage",4,{upgrade(t,r,o){e.infostart updating DB: ${r} -> ${o};let n=Date.now();for(let a of t.objectStoreNames)t.deleteObjectStore(a);t.createObjectStore("titles",{keyPath:"id"}).createIndex("project","project");let i=t.createObjectStore("projects",{keyPath:"id"});i.createIndex("checked","checked"),i.createIndex("name","name"),e.infofinish updating DB: ${Date.now()-n}ms},blocked(t,r){let o=The database "@takker/cosense-storage"(v${r}) is blocked because the older one (v${t}) is opened in other tabs.
Please close the other tabs and reload this page.;e.error(o),alert(o)},blocking(t,r){let o=The database "@takker/cosense-storage"(v${t}) is blocking the newer one (v${r}) opened.
Please close this page.;e.error(o),alert(o)}}),CT};var IT=(e,t)=>(xd||(xd=new BroadcastChannel(FT),xd.addEventListener("message",r=>AT(r.data))),Jl.set(t,new Set(e).union(Jl.get(t)??new Set)),()=>Jl.delete(t)),bd=(e,t)=>{if((t.added?.size??0)+(t.updated?.size??0)+(t.deleted?.size??0)===0)return;let r={type:"links:changed",project:e,diff:t};AT(r);let o=new BroadcastChannel(FT);o.postMessage(r),o.close()},AT=e=>{for(let[t,r]of Jl)r.has(e.project)&&t(e)},FT="scrapbox-storage-notify",xd,Jl=new Map;var DT=async(e,t)=>{let r=await yd(),o=Ki(["@takker/cosense-storage","check"]),n=new Map;try{{o.debugcheck updates of links...;let i=new Set,a=r.transaction("projects","readwrite"),c=Df(new Date),l=c-600;for await(let f of a.store.index("checked").iterate(IDBKeyRange.lowerBound(l,!0))){let m=f.value;if(m.isValid===!1){i.add(m.id);continue}i.add(m.name);let h=m.checked;if(h+t>c||m?.updating&&h>l)continue;let g=structuredClone(m);g.updating=!0,n.set(m.id,g),f.update(g)}let u=[],p=a.store.index("name");for(let f of e)i.has(f)||u.push(p.get(f).then(m=>{m?.updating&&(m?.checked??0)>l||n.set(f,m??ZF(f))}));if(await Promise.all(u),await a.done,n.size===0){o.debugchecked. No project needs upgrade.;return}o.debugchecked. ${n.size} projects maybe need upgrade.}let s=Df(new Date);for await(let i of kT(n.values())){if(O(i)){let{project:h,name:g}=Z(i);switch(g){default:continue;case"NotFoundError":o.warn("${h}" is not found.);break;case"NotMemberError":o.warn(You are not a member of "${h}".);break;case"NotLoggedInError":o.warn(You are not a member of "${h}" or You are not logged in yet.);break}n.set(h,{id:h,name:h,checked:s,updating:!1,isValid:!1,reason:g});continue}let{checked:a,...c}=S(i);if(c.updated<a){o.debugno updates in "${c.name}",n.set(c.name,{...c,isValid:!0,checked:s,updating:!1});continue}o.debugstart downloading and storing links of "${c.name}";let l=new Set(await r.getAllKeysFromIndex("titles","project",c.name)),u=0,p=0;for await(let h of dg(c.name)){if(O(h)){let{name:w,message:R}=Z(h);o.errorFailed to get links of "${c.name}" with ${w}: ${R};break}let g=S(h),y={},x=r.transaction("titles","readwrite");await Promise.all(g.map(async w=>{let R={...w,project:c.name},b=await x.store.get(w.id);if(!b)return y.added?.set?.(w.id,R)??(y.added=new Map([[w.id,R]])),x.store.add(R);if(l.delete(w.id),!!eD(R,b))return y.updated?.set?.(w.id,[b,R])??(y.updated=new Map([[w.id,[b,R]]])),x.store.put(R)})),await x.done,u+=y.added?.size??0,p+=y.updated?.size??0,o.debugUpdating "/${c.name}": +${u} pages, ~${p} pages,bd(c.name,y)}let f=r.transaction("titles","readwrite"),m=new Map((await Promise.all([...l].map(async h=>{let g=await f.store.get(h);if(!g)return[];let y=[[h,g]];return await f.store.delete(h),y}))).flat());await f.done,o.debugFinish downloading and storing links of "${c.name}",o.debugUpdate "/${c.name}": +${u} pages, ~${p} pages, -${m.size} pages,n.set(c.name,{...c,isValid:!0,checked:s,updating:!1}),bd(c.name,{deleted:m})}}finally{let s=r.transaction("projects","readwrite");await Promise.all([...n].map(([,i])=>(i.updating=!1,s.store.put({...i})))),await s.done}},Ql=async e=>{let t=[...new Set(e)];if(t.length===0)return[];let r=Date.now(),n=(await yd()).transaction("titles","readonly"),s=n.store.index("project"),i=(await Promise.all(t.map(c=>s.getAll(c)))).flat();return await n.done,Ki(["@takker/cosense-storage","load"]).debugRead ${i.length} links from ${t.length} projects in ${Date.now()-r}ms,i},ZF=e=>({name:e,displayName:e,id:"",isValid:!0,publicVisible:!0,isMember:!0,loginStrategies:[],theme:"default",gyazoTeamsName:null,translation:!0,infobox:!0,checked:0,updated:0,created:0,updating:!0}),eD=(e,t)=>e.updated>t.updated||e.links.sort().join()!==t.links.sort().join();var Vt=e=>${e.getFullYear()}-${Or(e.getMonth()+1)}-${Or(e.getDate())},Yi=e=>{let[t,r,o]=e.split("-").map(n=>parseInt(n,10));return{year:t,month:r,date:o}},Xi=e=>${Qo(e)}-w${Or(Mo(e))},Zl=e=>{let[t,r]=e.split("-w").map(o=>parseInt(o,10));return Ne(uc(new Date(t,0,1),r))};var UT="takker-memex",$T=async(e=new Date(2023,0,24))=>{if(scrapbox.Project.name!==UT)return()=>{};let t=scrapbox.Project.pages;await new Promise(i=>{let a=setInterval(()=>{if(t.length===0){t=scrapbox.Project.pages;return}clearInterval(a),i()},2e3)});let r=async()=>{let i=new Date,c=ai({start:e,end:i}).filter(f=>{let m=Pr(f),h=t.find(g=>g.title===m);return!h||!h.exists});if(c.length===0)return;let{render:l,dispose:u}=Fe(),p;try{l({type:"spinner"},{type:"text",text:load tasks for ${c.length} diary pages});let f=new Map,m=new Set,h=c.map(x=>Vt(x));for(let{title:x,links:w,project:R}of await Ql(["takker","takker-memex"]))for(let b of[x,...w]){let E=hr(b);if(!E)continue;if(O(E)){let{name:F,message:A}=Z(E);console.error(/${R}/${b}: ${F} ${A});continue}let T=ce(b);if(m.has(T))continue;m.add(T);let I=S(E);if(I.freshness?.status!=="done")for(let F of c){let A=pn(I,F);if(!A)continue;let N=Vt(A.base);h.includes(N)&&(f.set(N,[...f.get(N)??[],A]),Io(I))}}let g=await It();if(O(g))throw Z(g);p=S(g);let y=0;l({type:"spinner"},{type:"text",text:create 0/${c.length} diary pages...});for(let x of c){let w=Pr(x),R=f.get(Vt(x))?.map?.(T=>xe(T))??[],b=#${lt(x,"yyyy-MM-dd")},E=#${lt(x,"yyyy-MM-dd HH:mm:ss")};await Le(UT,w,(T,{persistent:I})=>{if(I)return;let F=[...T.map(A=>A.text),...R];return F.some(A=>A.includes(b))?an(F):an([...F,E])},{socket:p}),y++,l({type:"spinner"},{type:"text",text:create ${y}/${c.length} diary pages...})}l({type:"check-circle"},{type:"text",text:created ${c.length} diary pages.}),e=i}catch(f){l({type:"exclamation-triangle"},{type:"text",text:f instanceof Error?${f.name} ${f.message}:"Unknown error! (see developper console)"}),console.error(f)}finally{p&&await At(p),await Se(1e3),u()}},o=r(),n=new Date,s=setInterval(()=>{let i=new Date;yt(n,i)||(n=i,o.then(()=>o=r()))},1e4);return()=>(clearTimeout(s),o)};$T(new Date(2024,11,24));var wd=(...e)=>{let t=e.flatMap(o=>{if(typeof o=="string")return[ep(o)];if(Array.isArray(o.type))return[jT(o.type)];switch(o.type){case"text":return[ep(o.text)];case"group":{let n=wd(...o.items);return n?[n]:[]}default:return[jT(o.type)]}});if(t.length===0)return;if(t.length===1)return t[0];let r=document.createElement("span");return r.classList.add("item-group"),r.append(...t),r},ep=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},jT=e=>{if(Array.isArray(e)){let t=document.createElement("span");t.classList.add("fa-stack");let r=Ed(e[0]);r.classList.add("fa-stack-1x");let o=Ed(e[1]);return o.classList.add("fa-stack-1x"),t.append(r,o),ep(t)}return ep(Ed(e))},Ed=e=>{let t=document.createElement("i");switch(e){case"spinner":t.classList.add("fa","fa-spinner");break;case"check-circle":case"gyazo":case"ocr":case"calendar":case"trim":t.classList.add("kamon",kamon-${e});break;case"markdown":case"google":t.classList.add("fab",fa-${e});break;case"copy":case"clipboard":t.classList.add("far",fa-${e});break;default:t.classList.add("fas",fa-${e});break}return t};var{cursor:Rd,selection:vd}=Wt(),HT=e=>{let{className:t,display:r,onClick:o,context:n="page"}=e,s=document.createElement("div");t&&s.classList.add(t),BT(n)||(s.style.display="none");let i=(...l)=>{if(l.length===1&&l[0]===""){s.style.display="none";return}s.textContent="";let u=wd(...l);u&&s.append(u)},a=typeof r=="function"?r({cursor:Rd,selection:vd}):r;return i(...Array.isArray(a)?a:[a]),s.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),o({cursor:Rd,selection:vd,setDisplay:i})}),{status:s,context:n,update:()=>{if(BT(n)?s.removeAttribute("style"):s.style.display="none",typeof r=="function"){let l=r({cursor:Rd,selection:vd});i(...Array.isArray(l)?l:[l])}}}},BT=e=>e!=="stream"?scrapbox.Layout===e:scrapbox.Layout==="list"&&location.pathname.startsWith("/stream");var WT=()=>{let e=document.createElement("style");e.textContent=.status-bar.left {
position: absolute;
top: 0;
left: 0;
max-width: 80vw;
overflow-x: auto;
overflow-y: hidden;
}
.status-bar.left:empty {
display: none;
}
.status-bar.left > div {
border-left: unset;
}
.status-bar.left > div {
border-right: 1px solid var(--tool-light-color, #a9aaaf);
}
.status-bar.left > div:first-of-type {
border-top-left-radius: unset;
}
.status-bar.left > div:last-of-type {
border-top-right-radius: 3px;
},document.head.append(e);let t=document.createElement("div");return t.classList.add("status-bar","left"),document.getElementsByClassName("footer")[0].append(t),t};var kd=new Set,{cursor:tD,selection:rD}=Wt(),oD=WT();var wr=e=>{let t=HT(e);return kd.add(t),oD.append(t.status),()=>{t.status.remove(),kd.delete(t)}},Td=()=>{for(let{update:e}of kd)e()};tD.addChangeListener(()=>Td());rD.addChangeListener(()=>Td());scrapbox.addListener("layout:changed",Td);var qT=async(e,t)=>{try{let r=t.getSelectedText()||gt(e.getPosition().line);if(!r)return;await navigator.clipboard.writeText(r)}catch(r){console.error(r),alert(Faild to copy:
${JSON.stringify(r)})}},GT=async(e,t)=>{try{let r=t.hasSelection(),o=r?t.getRange().start.line:e.getPosition().line,n=r?t.getSelectedText():gt(o);if(!n)return;await navigator.clipboard.writeText(n),r||t.setRange({start:{line:o,char:0},end:{line:o,char:n.length}}),e.focus(),_t("Delete")}catch(r){console.error(r),alert(Faild to cut:
${JSON.stringify(r)})}},zT=async e=>{try{let t=await navigator.clipboard.readText();if(!t)return;e.focus(),await ct(t)}catch(t){console.error(t),alert(Faild to paste:
${JSON.stringify(t)})}},VT=e=>{e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?e.hide():(e.focus(),e.showEditPopupMenu())};globalThis.addEventListener("keydown",e=>{if(e.key!=="i"||e.shiftKey||e.altKey||e.metaKey||!e.ctrlKey||e.isComposing)return;let t=So();t.hasFocus||(e.preventDefault(),t.focus())});var _d=class{get editor(){return document.getElementById("editor")}get lines(){return document.getElementsByClassName("lines")?.[0]}get computeLine(){return document.getElementById("compute-line")}get grid(){return document.getElementsByClassName("related-page-list clearfix")?.[0]?.getElementsByClassName("grid")?.[0]}get cursorLine(){return document.getElementsByClassName("cursor-line")?.[0]}get textInput(){return document.getElementById("text-input")}get cursor(){return document.getElementsByClassName("cursor")?.[0]}get selections(){return document.getElementsByClassName("selections")?.[0]}get popupMenu(){return document.getElementsByClassName("popup-menu")?.[0]}get pageMenus(){return document.getElementsByClassName("page-menu")?.[0]}get pageInfoMenu(){return document.getElementById("page-info-menu")}get pageEditMenu(){return document.getElementById("page-edit-menu")}get pageEditButtons(){return this.pageEditMenu.nextElementSibling.getElementsByTagName("a")}get randomJumpButton(){return document.getElementsByClassName("random-jump-button")?.[0]}get pageCustomButtons(){return document.getElementsByClassName("page-menu-extension")}},KT=new _d;var YT=e=>new Promise(t=>setTimeout(t,e));async function Lr(e,{wait:t=1}={}){let r=KT.textInput;r.focus(),r.value=e;let o=document.createEvent("UIEvent");o.initEvent("input",!0,!1),r.dispatchEvent(o),await YT(t)}if(fo()){let e="Timestamp";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/add-time.png"}),scrapbox.PageMenu(e).addItem({title:"#YYYY-MM-DD HH:mm:ss ",onClick:()=>Lr(qt(new Date,"#yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD HH:mm:ss ",onClick:()=>Lr(qt(new Date,"yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD",onClick:()=>Lr(qt(new Date,"yyyy-MM-dd"))}),scrapbox.PageMenu(e).addItem({title:"HH:mm:ss ",onClick:()=>Lr(qt(new Date,"HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"⬜",onClick:()=>Lr("⬜")}),scrapbox.PageMenu(e).addItem({title:"🚧",onClick:()=>Lr("🚧")}),scrapbox.PageMenu(e).addItem({title:"⌛",onClick:()=>Lr("⌛")}),scrapbox.PageMenu(e).addItem({title:"📝",onClick:()=>Lr("📝")}),scrapbox.PageMenu(e).addItem({title:"✅",onClick:()=>Lr("✅")}),scrapbox.PageMenu(e).addItem({title:"❌",onClick:()=>Lr("❌")})}scrapbox.PageMenu.addItem({title:"Open kakeru",image:"https://i.kakeru.app/15c3b1a40b6b3c2ebd68f33f4c86b3f6-opaque.png",onClick:()=>window.open("https://kakeru.app")});var Ji=e=>{let{fetch:t=(n,s)=>globalThis.fetch(n,s),baseURL:r="https://scrapbox.io/",...o}=e;return{fetch:t,baseURL:r,...o}};var nD=(e,t,r)=>{let{sid:o,baseURL:n,followRename:s,projects:i}=Ji(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(${n}api/pages/${e}/${se(t)}?${a},o?{headers:{Cookie:Re(o)}}:void 0)},Pd=(e,t,r)=>Ji(r??{}).fetch(nD(e,t,r));var Od=e=>{let t=Math.round(e/5),r=Math.floor(t/6),o=Math.floor((t-r*6)/3),n=t-r*6-o*3;return${r>20?🍅x${(e/30).toFixed(1)}:"🍅".repeat(r)}${"🍊".repeat(o)}${"🍓".repeat(n)}};var sD=()=>{let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.right="0",e.style.textAlign="right",e},Fs=new Map,tp,Sd=()=>{for(let r of Fs.values())r.remove();Fs.clear();let e=hl(()=>iD(Dt()),{interval:1e3,maxQueued:0}),t=()=>{e.clear(),e()};if(scrapbox.Layout!=="page"){if(scrapbox.removeListener("lines:changed",t),!tp)return;clearInterval(tp),tp=void 0;return}t(),scrapbox.addListener("lines:changed",t),tp=setInterval(t,60*1e3)},iD=e=>{for(let t of e){let r=bt(t.text);if(!r?.record?.start){Fs.get(t.id)?.remove?.(),Fs.delete(t.id);continue}let o=Fs.get(t.id)??sD();to(t.id)?.append?.(o),Fs.set(t.id,o),o.textContent=Od(No(r.record.end??new Date,r.record.start))}};scrapbox.Project.name==="takker-memex"&&(Sd(),scrapbox.addListener("page:changed",Sd),scrapbox.addListener("lines:changed",Sd));var aD=e=>{let[t,r]=e.reduce((o,{text:n})=>{let s=bt(n);return s?.record?.start?s.record.end?(o[1].push(s.record.end),o):(s.record.start&&o[0].push(s.record.start),o):o},[[],[]]);if(t.length===0&&t.push(...r),t.length!==0)return Af(t)},cD=async(e,t)=>{let[r,o]=await Promise.all([Pd(e,Pr(t),{fetch:XT}),Pd(e,Pr(Yt(t,1)),{fetch:XT})]),n=r.ok?(await r.json()).lines:[];return o.ok&&n.push(...(await o.json()).lines),n},XT=async(e,t)=>{let r=await Oo(new Request(e,t));return!r||Di(new Date,new Date(${r.headers.get("Date")}))>=60?globalThis.fetch(e,t):r},{render:lD}=Fe(),JT=async()=>{let e=aD(await cD("takker-memex",new Date))??Tr(new Date);lD({type:"text",text:Od(No(new Date,e))})};JT();setInterval(JT,60*1e3);async function QT(e,{from:t,to:r,merge:o}){if(t===r)return{success:!0,dup:!1};let n=await ur(t,e);if(O(n))return{success:!1,at:"from",name:Z(n).name,message:Z(n).message};let s=S(n);if(!s.persistent)return{success:!1,at:"from",name:"EmptyPageError",message:"The request page is empty."};let i=await ur(r,e);if(O(i))return{success:!1,at:"to",name:Z(i).name,message:Z(i).message};let a=S(n);return a.persistent&&!o?{success:!1,at:"to",name:"NoEmptyPageError",message:The same page already exists in "/${r}"}:(await Le(r,e,c=>[...c,...s.lines.slice(1)].map(l=>l.text)),await ug(t,e),{success:!0,dup:a.persistent})}var Ld=async()=>{let e=scrapbox.Page.title,t=scrapbox.Project.name,r=globalThis.prompt(Take "/${t}/${e}" from "${t}" to:,"takker");if(!r)return;let{render:o,dispose:n}=Fe();o({type:"spinner"},{type:"text",text:/${t}/${e} → /${r}/${e}});try{let s=await QT(e,{from:t,to:r,merge:!0});if(!s.success){o({type:"exclamation-triangle"},{type:"text",text:${s.name} ${s.message}});return}return o({type:"check-circle"},{type:"text",text:Moved ${s.dup?"and merged ":""}to "/${r}/${e}".}),https://scrapbox.io/${r}/${se(e)}}catch(s){o({type:"exclamation-triangle"},{type:"text",text:s instanceof Error?${s.name} ${s.message}:"Unknown error! (see developper console)"}),console.error(s)}finally{setTimeout(()=>n(),1e3)}};scrapbox.PageMenu.addItem({title:"Transport",onClick:async()=>{await Ld()}});scrapbox.PageMenu.addItem({title:"Transport and Open",onClick:async()=>{let e=await Ld();e&&window.open(e)}});var pD="button.";document.getElementById("editor").addEventListener("click",async e=>{let t=e.target;if(t.tagName==="IMG"&&t.classList.contains("icon")&&t.title.endsWith("-button")){e.preventDefault(),e.stopImmediatePropagation();try{let r=../${encodeURIComponent(t.title)}/${pD},{execute:o}=await import(r);o()}catch(r){console.log(r)}}});scrapbox.PageMenu.addItem({title:"Copy link for Markdown",onClick:()=>{let e=scrapbox.Page.title.replaceAll(" ","_").replace(/[/?#\{}^|<>]/g,t=>encodeURIComponent(t));navigator.clipboard.writeText(${scrapbox.Page.title}(https://${location.hostname}/${scrapbox.Project.name}/${e}${location.hash})).catch(t=>alert(${t.name}: ${t.message}))}});Jr.PageMenu.addMenu({image:"https://img.icons8.com/ios/180/FFFFFF/inbox.png",title:"~task",onClick:()=>{let{cursor:e,selection:t}=Wt(),r=e.getPosition().line,o=t.getSelectedText(),n=o||e.lines[r].text,s=n.split(
).map(i=>i.replace(/^\s*(.+)$/g,$1~@${lt(new Date,"yyyy-MM-dd")})).join(
);o||t.setRange({start:{line:r,char:0},end:{line:r,char:n.length}}),ct(s)}});var Qi=e=>al(...H(()=>{let t={tasks:[],errors:[],load:async()=>{},loading:!1},r=Promise.resolve();return[o=>{t.load=()=>(r=(async()=>{await r,t={...t,loading:!0},o(),await DT(e,60),t={...t,loading:!1},o()})(),r);let n=()=>{r=(async()=>{await r,t={...t,loading:!0},o();let[s,i]=uD(await Ql(e));t={...t,tasks:s,errors:i,loading:!1},o()})()};return n(),IT(e,n)},()=>t]},e)),uD=e=>{let t=new Set,r=[],o=[];for(let{title:n,links:s,project:i}of e)for(let a of[n,...s]){let c=ce(a);if(t.has(c))continue;t.add(c);let l=hr(a);if(l){if(O(l)){o.push({project:i,title:a,...Z(l)});continue}r.push({project:i,title:a,...S(l)})}}return[r,o]};var rp=()=>{let[e,t]=Po(mD,{isOpen:!1,prevOverflowY:""}),r=dt(null),o=D(()=>{t(i=>{r?.current?.showModal?.();let a=r?.current?.open??!1,c=i.isOpen?i.prevOverflowY:document.documentElement.style.overflowY;return document.documentElement.style.overflowY="hidden",{isOpen:a,prevOverflowY:c}})},[]),n=D(()=>{t(i=>{r?.current?.close?.();let a=r?.current?.open??!1;return a?{isOpen:a,prevOverflowY:i.prevOverflowY}:(i.prevOverflowY?document.documentElement.style.overflowY=i.prevOverflowY:document.documentElement.style.removeProperty("overflow-y"),{isOpen:a})})},[]),s=H(()=>{let i;return a=>{if(!a){i?.(),r.current=null;return}let c=new AbortController;a.addEventListener("cancel",n,{signal:c.signal}),a.addEventListener("click",l=>{if(l.target!==l.currentTarget){l.stopPropagation();return}n()},{signal:c.signal}),i=()=>{c.abort()},r.current=a}},[n]);return{isOpen:e.isOpen,open:o,close:n,ref:s}},mD=(e,t)=>{let r=t(e);return e.isOpen===r.isOpen&&e.prevOverflowY===r.prevOverflowY?e:r.isOpen?r:{isOpen:!1}};var Zi=String.raw.fa,.far{font-weight:900;font-family:"Font Awesome 5 Free";-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.far{font-weight:400}.fa-spinner{animation:spin 2s infinite linear}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(359deg)}}.fa-spinner:before{content:"\f110"}.fa-sync:before{content:"\f021"}.fa-bookmark:before{content:"\f02e"}.fa-fw{text-align:center;width:1.25em}.kamon:before{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.kamon-check-circle:before{content:"\e018"}.timeline-wrap{display:flex;flex-direction:column;height:100%;overflow-y:hidden;--timeline-bg: var(--dropdown-menu-bg, #fff);--timeline-text-color: var(--page-text-color, #4a4a4a);--timeline-link-color: var(--page-link-color, #5e8af7);--row-header-width: 40px;--timeline-border-color: #888;--timeline-border: solid 1px var(--timeline-border-color);--timeline-hour-height: 40px;background-color:var(--timeline-bg);color:var(--timeline-text-color);.column-header{flex:none;display:flex;flex-direction:row;.cell{flex:1 1 1px;h2{font-weight:400;margin:0;text-align:center;width:100%}}}.week-container{position:relative;height:100%;overflow-y:auto;scrollbar-width:none;.week{flex:auto;display:flex;width:100%;.borders{.border{height:var(--timeline-hour-height)}.border:after{content:attr(data-time);font-size:10px;text-align:right;border-top:var(--timeline-border);position:absolute;width:100%;margin-top:-1px;pointer-events:none}}.timeline{flex:auto;border-left:var(--timeline-border);position:relative;.indicator{position:absolute;top:calc(var(--start) * 40px - .5px);width:100%;height:1px;background-color:red}.copy{position:absolute;top:1.5em}.event{position:absolute;top:calc(var(--start) * 40px - 1px);height:calc(40px * var(--duration) / 60);outline:none;--event-bg2: var(--timeline-text-color);--event-bg: var(--timeline-bg);--event-bg-ratio: 50%;--event-color-ratio: 0%;--event-border-color-ratio: 0%;background-color:color-mix(in srgb,var(--event-bg) var(--event-bg-ratio),var(--event-bg2));color:color-mix(in srgb,var(--event-bg) var(--event-color-ratio),var(--timeline-text-color));border:var(--timeline-border);border-color:color-mix(in srgb,var(--event-bg) var(--event-border-color-ratio),var(--timeline-border-color));border-radius:4px;overflow:hidden;text-wrap:nowrap;max-width:100%;text-overflow:ellipsis}.eventdata-status=done{--event-bg-ratio: 90%;--event-color-ratio: 50%;--event-border-color-ratio: 50%}.eventdata-status=expired{font-weight:700}a.event{--event-bg2: var(--timeline-link-color);text-decoration:none}}.timeline:first-child{border-right:var(--timeline-border)}}}}.wedget{position:fixed;top:60px;left:10px;max-height:calc(90vh - 60px);max-width:100px;width:calc(100vw / 767 * 100 - 10px);min-width:60px;border:solid 1px #888;border-radius:4px;display:flex;flex-direction:column;background-color:var(--dropdown-menu-bg, #fff);color:var(--page-text-color, #4a4a4a);&:not(.open){display:none}}dialog{flex-direction:column;align-items:center;row-gap:10px;&::backdrop{background-color:#000c}padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset;overflow-y:hidden;&open{display:flex}>*{color:var(--page-text-color, #4a4a4a);background-color:var(--dropdown-menu-bg, #fff);border:1px solid rgba(0,0,0,.2);border-radius:6px}}@media (min-width: 768px){dialog{padding:30px 0;--item-width: 600px}}.result{padding:15px;width:calc(var(--item-width, 100%) - 30px);overflow-y:scroll}.controller{padding:5px;width:calc(var(--item-width, 100%) - 10px);display:flex;flex-wrap:wrap;flex:none;gap:.2em}.progress{flex-grow:1;>*{padding:0 2px}}a{text-decoration:none;color:var(--page-link-color, #5e8af7);&:hover{color:var(--page-link-hover-color, #2d67f5)}}button{cursor:pointer;background:unset;color:unset;border:unset}.copy,.close,.today{font-family:"Font Awesome 5 Free"}.navi{font-family:AppIcons;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-style:normal;font-variant:normal;font-weight:400;text-decoration:none;text-transform:none}.close,.today{font-weight:900}ul{list-style-type:none;word-break:break-all}.task-list li:not(data-freshness^="-"):not(data-freshness="0"){font-weight:700}.scheduler details li{&data-status=done{opacity:.4}&data-status=expired{font-weight:700}}.task-list li{&data-type=deadline .label.type{color:var(--takker-scheduler-label-deadline-color, rgb(255, 75, 0))}&data-type=todo .label.type{color:var(--takker-scheduler-label-todo-color, rgb(246, 170, 0))}&data-type=note .label.type{color:var(--takker-scheduler-label-note-color, rgb(200, 200, 203))}&data-type=up-down .label.type{color:var(--takker-scheduler-label-up-down-color, rgb(77, 196, 255))}}:is(data-page-no=expired,data-page-no=errors) li{opacity:1!important}.scheduler{--takker-scheduler-summary-meter-width: 10em;overflow-y:hidden}.label{display:inline-block;font-size:90%;padding:0 3px}.type{text-align:center;width:2.5em;border:1px solid;border-radius:3px}.freshness{text-align:right;width:2.5em}.start,.duration{text-align:right;width:3em}
;var Ds=({text:e,title:t})=>{let[r,o]=Q(""),n=D(async s=>{s.preventDefault(),s.stopPropagation();try{await navigator.clipboard.writeText(e),o("Copied"),await Se(1e3),o("")}catch(i){alert(Failed to copy the code block
Error:${i instanceof Error?i.message:i}),console.error(i)}},[e]);return d("button",{type:"button",className:"copy",title:t??"Copy",onClick:n,children:r})};var fD=60*60*24*1e3,ZT=(e,t)=>{let r=he(e.refDate),o=(t.getTime()-r.getTime())/fD;switch(r.setHours(0),r.setMinutes(0),e.status){case"done":return-1/0;case"deadline":return o/(e.speed??1);case"todo":return Math.min(o/(e.speed??1),0);case"note":return t.getTime()<r.getTime()?-1/0:-o/(e.speed??1);case"up-down":{let n=e.speed??30;return n*(-1+Math.cos(Math.PI*2*o/n))}}};var t0=(e,t)=>{if(t.score!==e.score)return t.score-e.score;let r=e0(e.freshness),o=e0(t.freshness);return r!==o?o-r:dr(jr(e),jr(t))?-1:1},e0=e=>{switch(e.status){case"todo":return 3;case"note":return 2;case"deadline":return 5;case"up-down":return 1;case"done":return 0}};var ea=({loading:e,onClick:t})=>e?d("div",{children:d("i",{className:"fa fa-spinner"})}):d("button",{type:"button",className:"navi reload",onClick:t,children:""});var Us=()=>{let[e,t]=Q(new Date);return te(()=>{let r=setInterval(()=>t(new Date),6e4);return()=>{clearInterval(r)}},[]),e};var r0=e=>{switch(e){case"todo":return"ToDo";case"note":return"覚書";case"deadline":return"締切";case"up-down":return"浮遊";case"done":return"完了"}};var o0=(e,t)=>new URL(/${e.project}/${se(e.title)},t??location.href);var op=({children:e,project:t,title:r,className:o,...n})=>d("a",{...n,className:[o??"","page-link"].join(" "),type:"link",href:o0({project:t,title:r}).pathname,...t===scrapbox.Project.name?{rel:"route"}:{rel:"noopener noreferrer",target:"_blank"},children:e});var n0=({action:e,pActions:t})=>{let r=H(()=>r0(e.freshness.status),[e.freshness.status]),o=H(()=>Ur(jr(e)).slice(11)||" ",[jr(e)]),n=H(()=>gi(e),[e]),s=Math.floor(Math.round(e.score)/7),i=Us(),a=H(()=>e.executed!==void 0&&tn(Fr(he(e.executed.start),e.executed.duration),i),[e.executed?.start,e.executed?.duration,i]),c=H(()=>[...t,e].map(l=>${l.raw}).join(
),[t,e]);return d("li",{"data-type":e.freshness.status,"data-freshness":e.score.toFixed(0),"data-level":s,...s<0?{style:{opacity:dD(e).toFixed(2)}}:{},children:[d(Ds,{text:c,title:"ここまでコピー"}),d("span",{className:"label type",children:r}),d("i",{className:label far fa-fw${a?" fa-bookmark":""}}),d("span",{className:"label freshness",children:e.score.toFixed(0)}),d("time",{className:"label start",children:o}),d("span",{className:"label duration",children:[n,"m"]}),d(op,{project:e.project,title:e.raw,children:e.name})]})},dD=e=>Math.max(.8*Math.exp(Math.log(8/7)/7*e.score),.05);var s0=(e=Vt(new Date))=>{let[t,r]=Q(e),o=D(()=>{r(s=>{switch(s){case"errors":return"expired";case"expired":return Vt(new Date);default:{let i=he(Yi(s));return i.setDate(i.getDate()+1),Vt(i)}}})},[]),n=D(()=>{r(s=>{let i=Vt(new Date);switch(s){case"errors":return"errors";case"expired":return"errors";case i:return"expired";default:{let a=he(Yi(s));return a.setDate(a.getDate()-1),Vt(a)}}})},[]);return{pageNo:t,next:o,prev:n}};var np=(e,t)=>te(()=>(scrapbox.on(e,t),()=>scrapbox.off(e,t)),[]);var ta=(e,t)=>{let r=dt({...t});te(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),te(()=>{e(r.current)},[e])};var i0=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-workflow@0.0.1/next-action-viewer";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>Tt(d(hD,{getController:o,projects:e}),r))},hD=({getController:e,projects:t})=>{let{tasks:r,errors:o,load:n,loading:s}=Qi(t),{pageNo:i,next:a,prev:c}=s0(),l=H(()=>{if(i==="errors")return o.map(g=>({name:${g.title}
name:${g.name}
message:${g.message},raw:g.title,freshness:{refDate:{year:9999,month:1,date:1},status:"todo"},project:g.project,generated:!0,score:0}));if(i==="expired"){let g=new Date;return r.flatMap(y=>!$r(y)&&dr(Ex(y),Gt(g))&&y.freshness===void 0&&y.recurrence===void 0?[{...y,score:0,freshness:{refDate:y.executed.start,status:"todo"}}]:[]).sort((y,x)=>dr(jr(y),jr(x))?-1:0)}let h=he(Yi(i));return r.flatMap(g=>{if(!g.freshness)return[];if(Io(g))return[];let y=ZT(g.freshness,h);return y>-999?[{...g,score:y}]:[]}).sort(t0)},[r,o,i]),{ref:u,open:p,close:f}=rp();ta(e,{open:p,close:f});let m=H(()=>[i,...l.map(h=> ${h.raw})].join(
),[l,i]);return np("page:changed",f),d(ee,{children:[d("style",{children:Zi}),d("dialog",{ref:u,children:[d("div",{className:"controller",children:[d(Ds,{text:m,title:"Copy All Tasks"}),d("span",{children:i}),d("button",{type:"button",className:"navi left",onClick:c,children:""}),d("button",{type:"button",className:"navi right",onClick:a,children:""}),d(ea,{loading:s,onClick:n}),d("button",{type:"button",className:"close",onClick:f,children:""})]}),d("ul",{className:"result task-list","data-page-no":i,children:l.map((h,g)=>d(n0,{action:h,pActions:l.slice(0,g)},h.raw))})]})]})};var ip=(e,t)=>/${e}/${ce(t)},ra=new Map,Nd=new Map,a0=(e,t)=>{ra.set(e,t);for(let r of Nd.get(e)??[])r(t)},sp=()=>{Cn!==void 0&&(clearInterval(Cn),Cn=void 0);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=ip(e,t);if(!ra.has(r))return;let o=Dt().map(n=>n.text);Cn=setInterval(()=>{ce(t)===ce(o[0])&&(a0(r,o),Cn!==void 0&&(clearInterval(Cn),Cn=void 0))},1e3)},Cn;scrapbox.on("page:changed",()=>{scrapbox.off("lines:changed",sp);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=ip(e,t);ra.has(r)&&scrapbox.on("lines:changed",sp)});var gD=(e,t)=>{let r=ip(e,t),o=ra.get(r);return o||(ra.set(r,[]),ur(e,t).then(n=>{if(O(n))return[];let s=S(n).lines.map(i=>i.text);a0(r,s),t===scrapbox.Page.title&&!scrapbox.listeners("lines:changed").includes(sp)&&scrapbox.on("lines:changed",sp)})),o??[]},c0=(e,t)=>{let[r,o]=Q(gD(e,t));return te(()=>{let n=ip(e,t),s=Nd.get(n)??new Set;return s.add(o),Nd.set(n,s),()=>{s.delete(o)}},[e,t]),r};var Md=e=>e.duration===void 0?void 0:Gt(Fr(he(e.start),e.duration)),Cd=(e,t)=>{let r=he(e.start),o=t.getTime(),n=Math.round((o-r.getTime())/(60*1e3));if(n<=0)return[void 0,e];if(e.duration<=n)return[e,void 0];let s={start:e.start,duration:n};return[s,{start:Md(s),duration:e.duration-n}]};var In=e=>"title"in e,yD=e=>e.record?.duration!==void 0,l0=(e,t)=>In(e)&&e.status==="done"?e.status:yD(e)?In(e)&&e.executed?dr(Gt(t),e.executed.start)?"moved":"expired":"done":dr(Md(e.plan),Gt(t))?In(e)?"expired":"done":"undone";var p0=(e,t)=>{let r=hr(e.title.slice(1,-1));if(!e.plan.start)return;let o={name:r&&K(r)?S(r).name:e.title,plan:{start:Gt(e.plan.start),duration:(e.plan.duration??0)/60}};if(e.record.start&&(o.record={start:Gt(e.record.start)},e.record.end&&(o.record.duration=No(e.record.end,e.record.start))),!r||O(r))return o;let n=S(r),s={...o,title:n.raw,project:t};return n.freshness&&(s.status=n.freshness.status),$r(n)||(s.executed=n.executed),s},Id=(e,t)=>{let r=hc(e);return r!==void 0?{name:e.name,project:t,title:r,executed:e.executed,plan:e.executed,status:e.freshness?.status}:{name:e.name,plan:e.executed}};var u0=(e,t,r)=>{let o=[Ad(e,Yt(t,1),r),Ad(e,t,r),Ad(e,ke(t,1),r)],n=H(()=>o.flat(),o);return H(()=>{let s=Tr(t),i=pc(t);return n.flatMap(a=>{let[,c]=Cd(a.plan,s);if(!c)return[];let[l]=Cd(c,i);if(!l)return[];let{plan:u,...p}=a;return[{plan:l,...p}]}).sort((a,c)=>dr(a.plan.start,c.plan.start)?-1:0)},[n,t])},Ad=(e,t,r)=>{let o=c0(e,Pr(t)),n=H(()=>bD(o,e),[o,e]);return H(()=>n.length!==0?n:xD(t,r),[n,t,r])},xD=(e,t)=>t.flatMap(r=>{if(r.freshness?.status==="done")return[];if($r(r))return[];if(Io(r)){let n=dc(r,e);return n?[Id(n,r.project)]:[]}let o=he(r.executed.start);return yt(o,e)?[Id(r,r.project)]:[]}),bD=(e,t)=>{let r=[];for(let o of rn(e)){if(Co(o))continue;let n=p0(o,t);n&&r.push(n)}return r};var m0=({event:e})=>{let t=H(()=>e.plan.start.hours+e.plan.start.minutes/60,[e.plan.start]),r=H(()=>--start: ${t}; --duration: ${e.plan.duration};,[t,e.plan.duration]),o=Us(),n=H(()=>l0(e,o),[e,o]);return In(e)?d(op,{className:"event","data-status":n,style:r,title:e.title,project:e.project,children:e.name}):d("div",{className:"event","data-status":n,title:e.name,style:r,children:e.name})};var f0=({project:e,date:t,tasks:r})=>{let o=u0(e,t,r),n=H(()=>o.flatMap(a=>In(a)?[${a.title}]:[]).join(
),[o]),s=Us(),i=H(()=>yt(s,t)&&d("div",{className:"indicator",style:--start: ${sx(s)+nx(s)/60}}),[s,t]);return d("div",{className:"timeline",role:"gridcell",children:[o.map(a=>d(m0,{event:a},a.name)),i,d(Ds,{text:n})]})};var Fd=({dateList:e,tasks:t,project:r,hasColumn:o})=>d("div",{className:"timeline-wrap",role:"grid",children:[(o??!0)&&d("div",{className:"column-header",role:"row",children:e.map(n=>d("div",{className:"cell",role:"columnheader",children:d("h2",{children:om(n)})},Vt(n)))}),d("div",{className:"week-container",role:"presentation",children:d("div",{className:"week",role:"presentation",children:[d("div",{className:"borders",children:[...Array(24).keys()].map(n=>d("div",{className:"border","data-time":${Or(n)}:00},n))}),e.map(n=>d(f0,{project:r,date:n,tasks:t},Vt(n)))]})})]});var Dd=(e,t,r)=>{let[o,n]=Q(e),s=D(()=>n(t),[t]),i=D(()=>n(r),[t]),a=D(c=>n(c),[]);return{pageNo:o,next:s,prev:i,jump:a}};var d0=e=>{let t=dt(new Set),[r,o]=Q(e),n=D(()=>{for(let l of t.current)l()},[]),s=D(()=>{o(!0),n()},[]),i=D(()=>o(!1),[]),a=D(()=>o(l=>(l||n(),!l)),[]),c=D(l=>(t.current.add(l),()=>t.current.delete(l)),[]);return{isOpen:r,open:s,close:i,toggle:a,onOpen:c}};var y0=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker-scheduler/weekly-scheduler";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(o=>Tt(d(ED,{getController:o,projects:e,mainProject:e[0]}),r))},x0=(e,t)=>{let r=document.createElement("div");r.dataset.userscriptName="takker-scheduler/timeline-wedget";let o=r.attachShadow({mode:"open"});return document.body.append(r),new Promise(n=>Tt(d(wD,{getController:n,projects:e,mainProject:e[0],open:t}),o))},h0=!1,ED=({getController:e,projects:t,mainProject:r})=>{let{tasks:o,load:n,loading:s}=Qi(t),{pageNo:i,next:a,prev:c,jump:l}=Dd(Xi(new Date),RD,vD),u=H(()=>{let y=Zl(i);return[0,1,2,3,4,5,6].map(x=>ke(y,x))},[i]),{ref:p,open:f,close:m,isOpen:h}=rp();h0||=h,ta(e,{open:f,close:m,isOpen:h}),np("page:changed",m);let g=D(()=>l(Xi(new Date)),[l]);return d(ee,{children:[d("style",{children:Zi}),d("dialog",{ref:p,children:[d("div",{className:"controller",children:[d("span",{children:i}),d("button",{type:"button",className:"navi left",onClick:c,children:""}),d("button",{type:"button",className:"navi right",onClick:a,children:""}),d("button",{type:"button",className:"today",onClick:g,children:""}),d(ea,{loading:s,onClick:n}),d("button",{type:"button",className:"close",onClick:m,children:""})]}),h0&&d("div",{ref:b0,className:"result scheduler","data-page-no":i,children:d(Fd,{dateList:u,tasks:o,project:r})})]})]})},g0=!1,wD=({projects:e,mainProject:t,getController:r,open:o})=>{let{tasks:n,load:s,loading:i}=Qi(e),{pageNo:a,next:c,prev:l,jump:u}=Dd(new Date,kD,TD),p=H(()=>[a],[a]),f=D(()=>u(new Date),[u]),{isOpen:m,open:h,close:g}=d0(o);return g0||=m,ta(r,{open:h,close:g,isOpen:m}),d(ee,{children:[d("style",{children:Zi}),g0&&d("div",{className:wedget${m?" open":""},ref:b0,children:[d("div",{className:"controller",children:[d("span",{children:Vt(a)}),d("button",{type:"button",className:"navi left",onClick:l,children:""}),d("button",{type:"button",className:"navi right",onClick:c,children:""}),d("button",{type:"button",className:"today",onClick:f,children:""}),d(ea,{loading:i,onClick:s})]}),d(Fd,{dateList:p,tasks:n,project:t,hasColumn:!1})]})]})},RD=e=>Xi(Zo(Zl(e),1)),vD=e=>Xi(ix(Zl(e),1)),kD=e=>ke(e,1),TD=e=>Yt(e,1),b0=e=>{let t=e?.getElementsByClassName?.("indicator")?.[0];if(!t)return;let r=globalThis.scrollY;t.scrollIntoView({block:"center"}),globalThis.scroll(0,r)};_g({project:"takker-dist"});Ca(!0);Sg({maxCount:10,accessToken:_D,onClick:async(e,t)=>{try{if(t.ctrlKey){await navigator.clipboard.writeText(e.permalink_url);return}let r=document.getElementById("text-input");if(!r)throw Error("#text-input is not ditected.");r.focus(),r.value=e.permalink_url;let o=new InputEvent("input",{bubbles:!0});r.dispatchEvent(o),await scrapbox.Page.waitForSave()}catch(r){alert(${r}),console.error(r)}}});My().then(e=>{scrapbox.PageMenu.addItem({title:"Fulltext Search",onClick:()=>{e.toggle()}})});var PD="https://scrapbox.io/files/67344295032adf96d1e4c276.wasm",OD="/api/code/takker-dist/for-any-project-min/esbuild-worker.js";(async()=>{let e=new Request(PD),t=await Oo(e);t||(t=await fetch(e),await rc(e,t)),await ww(await WebAssembly.compileStreaming(t),OD)})();(async()=>{let e=[scrapbox.Project.name,"takker","takker-memex","takker-books","takker-private","villagepump","hub","arpla","work4ai","unnamedcamp","unnamed-project","nishio","enchi","rashitamemo","motoso","shokai","masui","rakusai","yuiseki","akiroom","c4j","miyamonz","mrsekut-p","masuilab","kidaaam-92022284","nwtgck","juneboku","marshmallow-rm","sushitecture","sno2wman","inteltank","issac-37765679","blu3mo","yosider","Mijinko","Mijinko-other","scrapbox-drinkup","nota-techconf","customize","scrapboxlab","scrasobox","programming-notes","tus-alpine","tus-alpine-private","guiland","evergreens","fab-wiki"],t=await pR({projects:e,mark:{...Object.fromEntries([["takker","takker"],["takker-memex","takker"],["takker-books","takker-books"],["takker-private","takker-private"],["nishio","nishio"],["rashitamemo","rashita"],["enchi","雑談_2022-04-12~"],["rakusai","rakusai"],["masui","概要"],["shokai","shokai"],["yuiseki","yuiseki"],["akiroom","はじめに"],["inteltank","sawachin"],["motoso","もとそのもと"],["villagepump","井戸端"],["hub","scrapbox.io%2Fhub_について"],["masuilab","増井研に入ったらまずやること"],["marshmallow-rm","読書猿マシュマロ全質問回答"],["miyamonz","miyamonz"],["mrsekut-p","mrsekut"],["kidaaam-92022284","kidooom"],["c4j","Code_for_Japan"],["suto3","suto3"],["blu3mo","blu3mo"],["nwtgck","nwtgck"],["juneboku","juneboku"],["jigsaw","jgs"],["sno2wman","SnO2WMaN"],["sushitecture","hashrock"],["unnamedcamp","知を営む"],["unnamed-project","unnamed-project"],["issac-37765679","cFQ2f7LRuLYP"],["blu3mo","blu3mo"],["yosider","yosider"],["Mijinko","Mijinko_SD"],["Mijinko-other","Mijinko_SD"],["customize","みんなのカスタマイズ"],["scrapboxlab","入会手続き"],["scrasobox","Scrapboxとあそぶ"],["programming-notes","参加する"],["guiland","概要と参加方法"],["work4ai","work4ai"],["evergreens","HOME"],["fab-wiki","fab-wikiに参加する"]].map(([n,s])=>[n,https://scrapbox.io/api/pages/${n}/${s}/icon])),"NDLSH-SB":"📚","scrapbox-drinkup":"https://scrapbox.io/assets/img/page-icon/scrapbox_beaver.png","nota-techconf":"https://i.gyazo.com/727f42bbd9e2534d99d70e6ea90705b3.jpg","plurality-japanese":"⿻"},workerUrl:"/api/code/takker-dist/for-any-project-min/select-suggestion-worker.js",enableSelfProjectOnStart:!0}),r=n=>{n.preventDefault(),n.stopPropagation()},o=()=>document.querySelector(".line .popup-menu")!==null;dm.bind({"<Tab>":n=>{o()||t.selectNext?.({cyclic:!0})&&r(n)},"<S-Tab>":n=>{o()||t.selectPrev?.({cyclic:!0})&&r(n)},"<Enter>":n=>{o()||t.confirm?.()&&r(n)},"<Esc>":n=>{o()||t.cancel?.()&&r(n)}})})();dR({previewers:[{when:/(?:^|\.)svg$/,preview:hR},{when:/(?:^|\.)glsl$/,preview:LR},{when:/(?:^|\.)(?:plantuml|puml|pu)$/,preview:CR},{when:/(?:^|\.)tikz\(tex\)$/,preview:AR("/api/code/takker-dist/for-any-project-min/tex-worker.js","https://scrapbox.io/files/65d1645c19cd8e002433c3df")}]});(async()=>{let{toggle:e}=await ZR();scrapbox.PageMenu.addItem({title:"履歴スライダー",image:"https://1.bp.blogspot.com/-UZtkSEX0wh4/U5l5_dNcEsI/AAAAAAAAhWs/UzJGVzyiX8Y/s800/kaichu_dokei.png",onClick:e})})();Yk("takker",["takker","振り返り(takker-workflow@0.0.1)のtemplate","txt"],["takker","1週間の振り返り(takker-workflow@0.0.1)のtemplate","txt"],new Date(2024,11,24));fo()&&(wr({display:{type:"caret-left"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Qa():Ka()}}),wr({display:{type:"caret-right"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ja():Va()}}),wr({display:{type:"caret-up"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Za():Ya()}}),wr({display:{type:"caret-down"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?ec():Xa()}}),wr({display:{type:"copy"},onClick:async({cursor:e,selection:t})=>await qT(e,t)}),wr({display:{type:"cut"},onClick:async({cursor:e,selection:t})=>await GT(e,t)}),wr({display:{type:"clipboard"},onClick:async({cursor:e})=>await zT(e)}),wr({display:{type:"undo"},onClick:()=>Ey()}),wr({display:{type:"redo"},onClick:()=>wy()}),wr({display:({cursor:e})=>e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?{type:["i-cursor","slash"]}:{type:"i-cursor"},onClick:({cursor:e})=>VT(e)}));if(fo()&&scrapbox.Project.name!=="takker-memex"){let e="task";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/todo-list--v2.png"}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:sn}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>cn({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})})}if(fo()){let e="New Page",t=[un,mn,fn];scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/cut-paper.png"}),scrapbox.PageMenu(e).addItem({title:"New Page",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&ro({project:r,mode:"noopen",hooks:t})?.()}}),scrapbox.PageMenu(e).addItem({title:"New Page and Open",onClick:()=>{let r=window.prompt("Create a new page at",scrapbox.Project.name);r&&ro({project:r,mode:"self",hooks:t})?.()}})}(async()=>{let e="next-action",t=head styledata-userscript-name="${e}";document.querySelector(t)?.remove?.();let r=document.createElement("style");r.dataset.userscriptName=e,r.textContent=
button:is(#${e}, #scheduler).tool-btn::before {
position: absolute;
font: 900 20px/46px "Font Awesome 5 Free";
}
button#${e}.tool-btn::before {
content: "\\f0ae";
}
button#scheduler.tool-btn::before {
content: "\\f073";
font-weight: 400;
}
button:is(#${e}, #scheduler).tool-btn img {
opacity: 0;
},document.head.append(r);let o=["takker-memex","takker"],{open:n}=await i0(o);scrapbox.PageMenu.addMenu({title:e,image:"/assets/img/favicon/apple-touch-icon.png",onClick:n});let s=await y0(o);scrapbox.PageMenu.addMenu({title:"scheduler",image:"/assets/img/favicon/apple-touch-icon.png",onClick:s.open});{let i="takker-scheduler/wedget",a=JSON.parse(localStorage.getItem(i)??"{}"),c=scrapbox.Project.name;a[c]??=!1;let l=await x0(o,a[c]),u=()=>{a[c]=!l.isOpen,l.isOpen?l.close():l.open?.(),localStorage.setItem(i,JSON.stringify(a))};fo()?wr({display:{type:"calendar"},onClick:u}):scrapbox.PageMenu.addItem({title:"toggle wedget",onClick:u})}})();var E0=e=>String(e).padStart(2,"0"),w0=e=>${e.getFullYear()}-${E0(e.getMonth()+1)}-${E0(e.getDate())};for(let e of document.getElementsByClassName("new-button")){let t=#${w0(new Date)};e.href=/${scrapbox.Project.name}/new?body=${encodeURIComponent(`
+t)}}console.log('The hrefs of "New Button" have been changed.');scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=os.parse(e,{hasTitle:!1});if(console.log("Parserd text:"),console.log(t),navigator.clipboard){let r=SD(t).join(`
);console.log(r),navigator.clipboard.writeText(r).catch(o=>console.log(o)),console.log("Copied.")}}});function SD(e){let t=Math.min(...e.map(n=>n.indent)),r=t,o=["<p>"];for(let n of e.filter(s=>s.type==="line")){let s=n.indent-r;s<0&&o.push(...[...Array(-s)].map(a=>"</ul>")),s>0&&o.push(...[...Array(s)].map(a=>'<ul style="margin-top: 5px;margin-bottom: 5px;">'));let i=n.nodes.map(a=>ap(a)).join("");n.indent>t?o.push(<li>${i}</li>):o.push(${i}<br/>),r=n.indent}return o.push(...[...Array(r-t)].map(n=>"</ul>")),o.push("</p>"),o}function ap(e){switch(e.type){case"quote":return<span style="
font-style: italic;
background-color: rgba(128,128,128,0.1);
display: block;
border-left: solid 4px #a0a0a0;
padding-left: 4px;">${e.nodes.map(s=>ap(s)).join("")}</span>;case"image":case"strongImage":return<img src="${e.src}" style="max-width: 50vw;"/>;case"icon":let t="",r="",o="";switch(e.pathType){case"root":r=https://scrapbox.io${e.path},t=https://scrapbox.io/api/pages/${e.path}/icon,o=e.path.replace(/^\/[^\/]+\/(.*)/,"$1");break;case"relative":r=https://scrapbox.io/${scrapbox.Project.name}/${e.path},t=https://scrapbox.io/api/pages/${scrapbox.Project.name}/${e.path}/icon,o=e.path;break}return<a target="_blank" href="${r}"><img style="
height: 1.3em;
vertical-align: top;" src="${t}" alt="${o}" /></a>;case"strongIcon":return"";case"formula":return\\( ${e.formula} \\);case"helpfeel":return"";case"decoration":let n=e.nodes.map(s=>ap(s)).join("");return e.decos.includes("*-4")&&(n=<h4>${n}</h4>),e.decos.includes("*-3")&&(n=<h5>${n}</h5>),e.decos.includes("*-2")&&(n=<h6>${n}</h6>),e.decos.includes("*-1")&&(n=<strong>${n}</strong>),e.decos.includes("/")&&(n=<i>${n}</i>),e.decos.includes("-")&&(n=<strike>${n}</strike>),e.decos.includes("!")&&(n=<pre>${n}</pre>),n;case"strong":return<strong>${e.nodes.map(s=>ap(s)).join("")}</strong>;case"code":return<code>${e.text}</code>;case"commandLine":case"googleMap":return"";case"blank":return<span>${e.text}</span>;case"link":switch(e.pathType){case"root":return<a target="_blank" href="https://scrapbox.io${e.href}">${e.href}</a>;case"relative":return<a target="_blank" href="https://scrapbox.io/${scrapbox.Project.name}/${e.href}">${e.href}</a>;case"absolute":return<a target="_blank" href="${e.href}">${e.content||e.href}</a>}case"hashTag":return<a href="https://scrapbox.io/${scrapbox.Project.name}/${e.href}">#${e.href}</a>;case"plain":return<span>${e.text}</span>}}scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=window.open();t.document.write(<html>
<body>
<textarea spellcheck="true">${e}</textarea>
</body>
</html>),t.document.close()}});scrapbox.PopupMenu.addButton({title:e=>{let t=e.replace(/[\r\n]/g,"").length,r=e.trim().split(/[\r\n\s]+/).length;return${t}c ${r}w},onClick:()=>null});if(fo()){let e="task";scrapbox.PageMenu.addMenu({title:e,image:"https://img.icons8.com/ios/180/FFFFFF/todo-list--v2.png"}),scrapbox.PageMenu.addMenu({title:"Toggle task",image:"https://img.icons8.com/ios/180/FFFFFF/repeat.png",onClick:im}),scrapbox.PageMenu(e).addItem({title:"Add task",image:"https://img.icons8.com/ios/180/FFFFFF/plus-math.png",onClick:li}),scrapbox.PageMenu(e).addItem({title:"Start task",image:"https://img.icons8.com/ios/180/FFFFFF/start--v1.png",onClick:on}),scrapbox.PageMenu(e).addItem({title:"End task",image:"https://img.icons8.com/ios/180/FFFFFF/stop-squared.png",onClick:so}),scrapbox.PageMenu(e).addItem({title:"Posteriori end task",image:"https://img.icons8.com/ios/180/FFFFFF/end--v1.png",onClick:pi}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:async()=>{let[t,r]=LD(),o=Cr().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=hr(i);if(!a||!a.ok)return s;let c=a.value;if(c.freshness?.status==="done")return s;let l=pn(c);return l.title=${i},l?xe(l):s}).join(
);await za(t,r,o),await sn()}}),scrapbox.PageMenu(e).addItem({title:"Walk a day",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:()=>ui()}),scrapbox.PageMenu(e).addItem({title:"Move today",image:"https://img.icons8.com/ios/180/FFFFFF/date-to.png",onClick:()=>mi()}),scrapbox.PageMenu(e).addItem({title:"Format",image:"https://img.icons8.com/ios/180/FFFFFF/sort-by-start-date.png",onClick:()=>di(scrapbox.Project.name,scrapbox.Page.title)}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>cn({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})}),scrapbox.PageMenu(e).addItem({title:"Sync",onClick:()=>window.open("https://script.google.com/macros/s/AKfycbyAgN8nmUXjVXL_tahDzVyyrMzFaI4CJVmIapk8G0GuxxVN-7oUbuDJOf31fP7SFjx9/exec")})}var LD=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=He();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var R0="scrapbox-episopass",cp=!1;scrapbox.PopupMenu.addButton({title:e=>cp?"remove EP":/https:\/\/scrapbox\.io\/files\/\w+\.html/.test(e)?"run EP":"",onClick:async e=>{if(document.getElementById(R0)?.remove(),cp){cp=!1;return}if(!/https:\/\/scrapbox\.io\/files\/\w+\.html/.test(e))return;let t=e.match(/https:\/\/scrapbox\.io(\/files\/\w+\.html)/)[1];try{let o=await(await fetch(t)).text();if(!o.includes("<title>EpisoPass</title>"))return;let n=new Blob([o],{type:"text/html"}),s=URL.createObjectURL(n);document.getElementsByClassName("cursor-line")[0].insertAdjacentHTML("beforeend",<iframe id="${R0}" src="${s}" width="800" height="400"></iframe>`),cp=!0;return}catch(r){console.error("Failed to load an EpisoPass html: ",r)}}});export{wr as addButton,ct as insertText,dm as scrapBindings};
/** @license
* esbuild-wasm@v0.24.0
*
* MIT License
*
* Copyright (c) 2020 Evan Wallace
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*! Bundled license information:
comlink/dist/esm/comlink.mjs:
(**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*)
*/
code:tex-worker.js
var ht=Object.defineProperty;var Ge=(t,e)=>{for(var r in e)ht(t,r,{get:er,enumerable:!0})};var be={};Ge(be,{close:()=>Et,deleteEverything:()=>ue,eof:()=>Rt,eoln:()=>$t,erstat:()=>Lt,executeAsync:()=>xe,get:()=>At,inputln:()=>Mt,pages:()=>C,printBoolean:()=>Pt,printChar:()=>Ut,printFloat:()=>St,printInteger:()=>vt,printNewline:()=>kt,printString:()=>Tt,put:()=>Nt,readFileSync:()=>se,reset:()=>Ft,rewrite:()=>Ct,setConsole:()=>de,setFileLoader:()=>ge,setInput:()=>he,setMemory:()=>me,tex_final_end:()=>ye,writeFileSync:()=>fe});var X={},m=[],re,O="",P=null,G=null,N=null,F=null,W=null,He=null,H=null,C=1100,z=(C-100)*1024*64,gt=C*1024*64,oe=0,I=!1,xt=()=>{W&&(Wz>>2=z+8,Wz+4>>2=gt),F.asyncify_start_unwind(z),oe=oe+1},yt=()=>{F.asyncify_start_rewind(z),F.main()},bt=()=>{oe=oe-1,F.asyncify_stop_rewind()},ue=()=>{m=[],X={},P=null,G=null,N=null,re=void 0,H=null,F=null,W=null,I=!1},fe=(t,e)=>{Xt=e},se=t=>{for(let e of m)if(e.filename==t)return e.content.slice(0,e.position);throw Error(Could not find file ${t})},Be=(t,e)=>{let r=I;I&&(bt(),I=!1);let n=new Uint8Array;if(Xt)n=Xt;else if(e=="r"&&m.findIndex(s=>s.filename==t&&!s.erstat)==-1)return r||t.match(/\.(aux|log|dvi)$/)?(m.push({filename:t,erstat:1}),m.length-1):(xt(),I=!0,setTimeout(async()=>{try{let s=await He(t);Xt=s}catch{}yt()},0),-1);return m.push({filename:t,position:0,position2:0,erstat:0,eoln:!1,content:n,descriptor:m.length}),m.length-1},wt=()=>{},$=(t,e,r,n)=>{for(r===void 0&&(r=0),n===void 0&&(n=e.length-r);n>t.content.length-t.position;){let o=new Uint8Array(1+t.content.length*2);o.set(t.content),t.content=o}t.content.subarray(t.position).set(e.subarray(r,r+n)),t.position+=n},_t=(t,e,r,n,o)=>(r===void 0&&(r=0),n===void 0&&(n=e.length-r),n>t.content.length-o&&(n=t.content.length-o),e.subarray(r).set(t.content.subarray(o,o+n)),n),M=t=>{if(re&&(O+=t,O.indexOf(`
)>=0)){let e=O.split(
);O=e.pop();for(let r of e)r.length&&re(r)}},de=t=>{re=t},me=t=>{P=t,W=new Int32Array(t)},he=(t,e)=>{G=t,e&&(N=e)},ge=t=>{He=t},xe=t=>(F=t,H=Promise.withResolvers(),F.main(),F.asyncify_stop_unwind(),H.promise),Tt=(t,e)=>{let r=t<0?{stdout:!0}:m[t],n=new Uint8Array(P,e,1)[0],o=new Uint8Array(P,e+1,n),s=String.fromCharCode.apply(null,o);if(r.stdout){M(s);return}$(r,new TextEncoder().encode(s))},Pt=(t,e)=>{let r=t<0?{stdout:!0}:m[t],n=e?"TRUE":"FALSE";if(r.stdout){M(n);return}$(r,new TextEncoder().encode(n))},Ut=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(String.fromCharCode(e));return}let n=new Uint8Array(1);n[0]=e,$(r,n)},vt=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(e.toString());return}$(r,new TextEncoder().encode(${e}))},St=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(e.toString());return}$(r,new TextEncoder().encode(${e}))},kt=(t,e)=>{let r=t<0?{stdout:!0}:m[t];if(r.stdout){M(
);return}$(r,new TextEncoder().encode(
))},Ft=(t,e)=>{let r=new Uint8Array(P,e,t),n=String.fromCharCode.apply(null,r);return n=n.replace(/\000+$/g,""),n.startsWith("{")&&(n=n.replace(/^{/g,""),n=n.replace(/}.*/g,"")),n.startsWith('"')&&(n=n.replace(/^"/g,""),n=n.replace(/".*/g,"")),n=n.replace(/ +$/g,""),n=n.replace(/^\*/,""),n=n.replace(/^TeXfonts:/,""),n=="TeXformats:TEX.POOL"&&(n="tex.pool"),n=="TTY:"?(m.push({filename:"stdin",stdin:!0,position:0,position2:0,erstat:0,eoln:!1,content:new TextEncoder().encode(G)}),m.length-1):Be(n,"r")},Ct=(t,e)=>{let r=new Uint8Array(P,e,t),n=String.fromCharCode.apply(null,r);return n=n.replace(/ +$/g,""),n.startsWith('"')&&(n=n.replace(/^"/g,""),n=n.replace(/".*/g,"")),n=="TTY:"?(m.push({filename:"stdout",stdout:!0,erstat:0}),m.length-1):Be(n,"w")},Et=t=>{let e=m[t];e.descriptor&&wt(e.descriptor)},Rt=t=>m[t].eof?1:0,Lt=t=>m[t].erstat,$t=t=>m[t].eoln?1:0,Mt=(t,e,r,n,o,s,a)=>{let i=m[t],c=new Uint8Array(P,r,a),d=new Uint32Array(P,n,4),l=new Uint32Array(P,o,4);l[0]=d[0],e&&!i.eof&&i.eoln&&(i.position2=i.position2+1);let h=i.content.indexOf(10,i.position2);if(h<0&&(h=i.content.length),i.position2>=i.content.length)return i.stdin&&(N&&N(),ye()),i.eof=!0,!1;for(c.subarray(d[0]).set(i.content.subarray(i.position2,h)),l[0]=d[0]+h-i.position2;c[l[0]-1]==32;)l[0]=l[0]-1;return i.position2=h,i.eoln=!0,!0},At=(t,e,r)=>{let n=m[t],o=new Uint8Array(P);if(n.stdin)n.position>=G.length?(o[e]=13,n.eof=!0,N&&N(),ye()):o[e]=G[n.position].charCodeAt(0);else if(n.descriptor){if(_t(n,o,e,r,n.position)==0){o[e]=0,n.eof=!0,n.eoln=!0;return}}else{n.eof=!0,n.eoln=!0;return}n.eoln=!1,o[e]==10&&(n.eoln=!0),o[e]==13&&(n.eoln=!0),n.position=n.position+r},Nt=(t,e,r)=>{let n=m[t],o=new Uint8Array(P);$(n,o,e,r)},ye=()=>{O.length&&M(
),H&&H.resolve()};var we={};Ge(we,{getCurrentDay:()=>Ot,getCurrentMinutes:()=>Dt,getCurrentMonth:()=>zt,getCurrentYear:()=>It});var Dt=()=>{let t=new Date;return 60*t.getHours()+t.getMinutes()},Ot=()=>new Date().getDate(),zt=()=>new Date().getMonth()+1,It=()=>new Date().getFullYear();var Ve,Ye,Ze=async(t,e)=>{Ye??=await e.fileLoader("tex.wasm"),Ve??=new Uint8Array(await e.fileLoader("core.dump"),0,C*65536),fe("input.tex",new TextEncoder().encode(t));let r=new WebAssembly.Memory({initial:C,maximum:C});new Uint8Array(r.buffer,0,C*65536).set(Ve.slice(0)),me(r.buffer),he( input.tex
\\end
),ge(e.fileLoader),e.console&&de(e.console);let o=await WebAssembly.instantiate(Ye,{library:{...be,...we},env:{memory:r}});await xe(o.instance.exports);let s=se("input.log");try{return{dvi:se("input.dvi"),log:s}}catch{return{log:s}}finally{ue()}};async function*qe(t){let e=await new Response(t).arrayBuffer(),r=new DataView(e),n=e.byteLength-4;for(;r.getUint32(n,!0)!==101010256;)n--;let o=n;o+=4,o+=4;let s=r.getUint16(o,!0);o+=2,o+=2,o+=4;let a=r.getUint32(o,!0);o+=4,o=a;for(let i=0;i<s;i++){o+=4,o+=4,o+=4,o+=4,o+=4;let c=r.getUint32(o,!0);o+=4;let d=r.getUint32(o,!0);o+=4;let l=r.getUint16(o,!0);o+=2;let h=r.getUint16(o,!0);o+=2;let w=r.getUint16(o,!0);o+=2,o+=8;let _=r.getUint32(o,!0);o+=4,o+=l+h+w,yield Xt(r,_,c,d)}}var Xt=(t,e,r,n)=>{e+=4,e+=2,e+=2;let o=t.getUint16(e,!0);e+=2,e+=4,e+=4,e+=8;let s=t.getUint16(e,!0);e+=2;let a=t.getUint16(e,!0);e+=2;let i=new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset+e,s));e+=s,e+=a;let c=new Uint8Array(t.buffer,t.byteOffset+e,r);if(o==0)return Ke(i,r,n,c,!0);if(o==8)return Ke(i,r,n,c,!1);throw"unknown compression method: "+o},Ke=(t,e,r,n,o)=>{if(o)return{name:t,csize:e,usize:r,arrayBuffer:()=>Promise.resolve(n),file:()=>Promise.resolve(new File([n],t)),text:()=>Promise.resolve(new TextDecoder().decode(n))};let s,a=async()=>(s??=await Wt(n),s);return{name:t,csize:e,usize:r,arrayBuffer:a,file:async()=>new File([await a()],t),text:async()=>new TextDecoder().decode(await a())}};var zn=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r&1?r=3988292384^r>>>1:r=r>>>1;t[e]=r}return t})();var Wt=t=>new Response(new Response(t).body.pipeThrough(new DecompressionStream("deflate-raw"))).arrayBuffer();var je=async(t,e)=>{let r=await globalThis.caches.keys();for(let n of r.sort().reverse()){let s=await(await caches.open(n)).match(t,e);if(s)return s}},Qe=async(t,e)=>{let n=(await globalThis.caches.keys()).filter(s=>s.startsWith("api")).sort().reverse().at(0);if(!n)return;await(await caches.open(n)).put(t,e.clone())};var Je=[1,0,0,1,0,0],Gt=t=>Math.abs(t[0]-1)<Number.EPSILON&&Math.abs(t[1])<Number.EPSILON&&Math.abs(t[2])<Number.EPSILON&&Math.abs(t[3]-1)<Number.EPSILON&&Math.abs(t[4])<Number.EPSILON&&Math.abs(t[5])<Number.EPSILON;var _e=(t,e,r)=>[t[0]*e,t[1]*e,t[2]*r,t[3]*r,t[4],t[5]],Te=(t,e,r)=>[t[0],t[1],t[2],t[3],t[0]*e+t[2]*r+t[4],t[1]*e+t[3]*r+t[5]],Pe=(t,e)=>{let r=e*Math.PI/180,n=Math.cos(r),o=Math.sin(r);return[t[0]*n+t[2]*o,t[1]*n+t[3]*o,-t[0]*o+t[2]*n,-t[1]*o+t[3]*n,t[4],t[5]]},Ue=t=>Gt(t)?"":transform="matrix(${t.join(" ")})";var et=t=>{let e=new FileReader,r=new Promise(n=>e.onload=()=>n(e.result));return e.readAsDataURL(t),r};var tt=async(t,e)=>(await Promise.all([...t].sort().map(async r=>[r.slice(0,-4),await et(new Blob([await e(r)],{type:"font/truetype"}))]))).map(([r,n])=>@font-face{font-family:${r};src:local(${r}),url(${n})format("truetype");}.${r}{font-family:${r};}).join("");var nt=async(t,e)=>{let r=0,n="black",o=e.svg?1:0,s=[...Je],a="",i=0,c="",d=0,l=0,h=0,w=0,_=new Set;for(let u of t)switch(u.type){case"text":{let p=0,b=0,f="";for(let L of u.text){let y=L.codePointAt(0)??0,pe=u.font.metrics.characters.at(y);if(pe===void 0)throw Error(Could not find font metric for ${y});p+=pe.width,b=Math.max(b,pe.height),f+=String.fromCodePoint(y>=0&&y<=9?161+y:y>=10&&y<=19?173+y-10:y===20?8729:y>=21&&y<=32?184+y-21:y===127?196:y)}let T=u.font.metrics.design_size/1048576*65536/1048576,g=u.left*r,x=p*r*T,v=b*r*T,le=u.top*r;a=u.font.name,i=u.font.metrics.design_size/1048576*u.font.scaleFactor/u.font.designSize;let ne=["#000","black"].includes(n)?"CanvasText":n;if(_.add(${a}.ttf),o<=0){let L=d==u.top&&g>l+2;c+=<span class="text ${a}" style="top:${le-v}pt;left:${g}pt;color:${ne};font-size:${i}pt;"><span ${L?'class="has-space" ':""} style="vertical-align:${-v}pt;">${f}</span></span>
,d=u.top,l=g+x}else{let L=u.top*r;c+=<text alignment-baseline="baseline" y="${L}" x="${g}" fill="${ne}" font-size="${i}" font-family="${a}">${f}</text>
}break}case"rect":{let p=u.height*r,b=u.width*r,f=u.left*r,g=u.top*r-p,x=["#000","black"].includes(n)?"CanvasText":n;c+=o>0?<rect x="${f}" y="${g}" width="${b}" height="${p}" fill="${x}" ${Ue(s)}></rect>
:<span class="rect" style="background: ${x}; top: ${g}pt; left: ${f}pt; width: ${b}pt; height: ${p}pt;"></span>
;break}case"special":break;case"info":{r=u.magnification*u.numerator/1e3/u.denominator*72.27/1e5/2.54;break}case"svg":{let p=u.svg;for(let T of u.svg.matchAll(/<svg\s[^>]+>/g)){let g=T[0];g==="<svg beginpicture>"&&(p=p.replace(g,o>0?"":ve(h,w))),o++}for(let T of u.svg.matchAll(/<\/svg\s[^>]+>/g)){let g=T[0];g==="</svg endpicture>"&&(p=p.replace(g,o===1?"</svg>":"")),o=Math.max(0,o-1)}let b=u.top*r,f=u.left*r;c+=p.replaceAll("{?x}",${f}).replaceAll("{?y}",${b});break}case"papersize":w=u.height,h=u.width;break;case"color":n=u.color;break;case"ps":s=u.interpret(s);break;case"psfile":c+=o>0?u.toSVG(s):${ve(h,w)}${u.toSVG(s)}</svg>};break}for(let u=o;u>0;u--)c+="</svg>";let k=<title>${e.title??"input.tex"}</title>,U=<style>${await tt(_,e.fileLoader)}:root{color-scheme:light dark;background-color:Canvas;color:CanvasText;}.page{position:relative;width:100%;}.text{line-height:0;position:absolute;overflow:visible;}.rect{position:absolute;min-width:1px;min-height:1px;}</style>;return c=c.replace(/("#000"|"black")/g,'"CanvasText"').replace(/("#fff"|"white")/g,'"var(--background-primary, Canvas)"'),e.svg?${ve(h,w)}${k}${U}${c}:<!DOCTYPE html><html><head><meta charset="UTF-8">${k}${U}</head><body>${c}</body></html>},ve=(t,e)=><svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${t}pt" height="${e}pt" viewBox="-72 -72 ${t} ${e}">;var rt=t=>{let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=e.getUint16(0),n=e.getUint16(2),o=e.getUint16(4),s=e.getUint16(6),a={header:Math.max(18,n),character_info:s-o+1,width:e.getUint16(8),height:e.getUint16(10),depth:e.getUint16(12),italic_correction:e.getUint16(14),lig_kern:e.getUint16(16),kern:e.getUint16(18),extensible_character:e.getUint16(20),font_parameter:e.getUint16(22)};if(!(o<=s+1&&s<256))throw new Error(Smallest character code (${o}) must be larger than largest character code (${s}) and largest character code must be less than 256 (actual: ${s}));if(a.extensible_character>256)throw new Error(Extensible character must be less than 256 (actual: ${a.extensible_character}));{let x=6+n+a.character_info+a.width+a.height+a.depth+a.italic_correction+a.lig_kern+a.kern+a.extensible_character+a.font_parameter;if(r!==x)throw new Error(entire_file_length must be ${x} (actual: ${r}))}let i=24,c=x=>[...Array(x).keys()].map(v=>e.getUint32(i+v*4)),d=e.buffer.slice(i,i+a.header*4);i+=a.header*4;let l=c(a.character_info);i+=a.character_info*4;let h=c(a.width);i+=a.width*4;let w=c(a.height);i+=a.height*4;let _=c(a.depth);i+=a.depth*4;let k=c(a.italic_correction);i+=a.italic_correction*4;let U=c(a.lig_kern);i+=a.lig_kern*4;let u=c(a.kern);i+=a.kern*4;let p=c(a.extensible_character);i+=a.extensible_character*4;let b=c(a.font_parameter);i+=a.font_parameter*4;let f=Ht(d),T=Bt(l),g=Yt(b,f.coding_scheme);return{checksum:f.checksum,design_size:f.design_size,family:f.family,face:f.face,ligKernPrograms:Vt(U),characters:T.map(x=>{let{width_index:v,height_index:le,depth_index:ne,italic_index:L}=x,y={width:h[v],height:w.at(le)??0,depth:_.at(ne)??0,italic_correction:k.at(L)??0};switch(x.type){case"lig":y.lig_kern_program=U[x.lig_kern_index];break;case"link":y.next_larger_char=x.next_larger_char;break;case"ext":y.extensible_recipe=p[x.extensible_index];break;default:break}return y}),...g}},Ht=t=>{let e=new DataView(t),r=e.getUint32(0),n=e.getUint32(4),o=e.getUint8(8);if(o>39)throw new Error("Invalid TFM file");let s=new TextDecoder().decode(t.slice(9,9+o)),a=e.getUint8(48);if(a>20)throw new Error("Invalid TFM file");let i=new TextDecoder().decode(t.slice(49,49+a)),c=new Uint8Array(t,68,4),d=c[0],l=c[3];return{checksum:r,design_size:n,coding_scheme:s,family:i,seven_bit_safe_flag:d,face:l}},Bt=t=>t.map(e=>{let r=e>>24,n=e>>20&15,o=e>>16&15,s=e>>10&1118481,a=e>>8&3,i=e&255;switch(a){case 1:return{type:"lig",width_index:r,height_index:n,depth_index:o,italic_index:s,lig_kern_index:i};case 2:return{type:"link",width_index:r,height_index:n,depth_index:o,italic_index:s,next_larger_char:i};case 3:return{type:"ext",width_index:r,height_index:n,depth_index:o,italic_index:s,extensible_index:i};default:return{width_index:r,height_index:n,depth_index:o,italic_index:s}}}),Vt=t=>t.map((e,r)=>{let n=e>>24;if((r===0||r===t.length)&&n===255)throw Error(Font has ${r===0?"right":"left"} boundary char. This is not supported yet.);let o=e>>16&255,s=e>>8&255,a=e&255;if(s>=128){let h=256*(s-128)+a;return{skip_byte:n,next_char:o,op_byte:s,kern:a}}let i=s>>2,c=(s&2)==0,d=(s&1)==0,l=a;return n>=128?{skip_byte:n,next_char:o,op_byte:s,remainder:a}:{skip_byte:n,next_char:o,op_byte:s,kern:a}}),Yt=(t,e)=>{let r=t[0],n=t[1],o=t[2],s=t[3],a=t[4],i=t[5];if(e==="TeX math italic")return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i};let c=t[6];if(e==="TeX math symbols"){let d=t[7],l=t[8],h=t[9],w=t[10],_=t[11],k=t[12],U=t[13],u=t[14],p=t[15],b=t[16],f=t[17],T=t[18],g=t[19],x=t[20],v=t[21];return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i,extra_space:c,num1:d,num2:l,num3:h,denom1:w,denom2:_,sup1:k,sup2:U,sup3:u,sub1:p,sub2:b,supdrop:f,subdrop:T,delim1:g,delim2:x,axis_height:v}}if(e==="TeX math extension"||e==="euler substitutions only"){let d=t[7],l=t.slice(8,13);return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i,extra_space:c,default_rule_thickness:d,big_op_spacing:l}}return{coding_scheme:e,slant:r,spacing:n,space_stretch:o,space_shrink:s,x_height:a,quad:i,extra_space:c}};var Cn=t=>{let e=t[0];if(0<=e&&e<128)return[{opcode:0,c:e},1];if(171<=e&&e<235)return[{opcode:171,k:e-171},1];if(249<e&&e<=255)return[{opcode:138},1];let r=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(e){case 128:case 129:case 130:case 131:{let n=e-128+1;return t.byteLength<n+1?void 0:[{opcode:0,c:Se(t,1,n)},n+1]}case 132:case 137:return t.byteLength<9?void 0:[{opcode:e,a:r.getInt32(1),b:r.getInt32(5)},9];case 133:case 134:case 135:case 136:{let n=e-128+1;return t.byteLength<n+1?void 0:[{opcode:133,c:Se(t,1,n)},n+1]}case 138:case 140:case 141:case 142:return[{opcode:e},1];case 139:return t.byteLength<45?void 0:[{opcode:e,c_0:r.getUint32(1),c_1:r.getUint32(5),c_2:r.getUint32(9),c_3:r.getUint32(13),c_4:r.getUint32(17),c_5:r.getUint32(21),c_6:r.getUint32(25),c_7:r.getUint32(29),c_8:r.getUint32(33),c_9:r.getUint32(37),p:r.getInt32(41)},45];case 143:case 144:case 145:case 146:{let n=e-143+1;return t.byteLength<n+1?void 0:[{opcode:143,b:E(t,1,n)},n+1]}case 147:case 152:return[{opcode:e,b:0},1];case 148:case 149:case 150:case 151:{let n=e-147;return t.byteLength<n+1?void 0:[{opcode:147,b:E(t,1,n)},n+1]}case 153:case 154:case 155:case 156:{let n=e-152;return t.byteLength<n+1?void 0:[{opcode:152,b:E(t,1,n)},n+1]}case 157:case 158:case 159:case 160:{let n=e-157+1;return t.byteLength<n+1?void 0:[{opcode:157,a:E(t,1,n)},n+1]}case 161:case 166:return[{opcode:e,a:0},1];case 162:case 163:case 164:case 165:{let n=e-161;return t.byteLength<n+1?void 0:[{opcode:161,a:E(t,1,n)},n+1]}case 167:case 168:case 169:case 170:{let n=e-166;return t.byteLength<n+1?void 0:[{opcode:166,a:E(t,1,n)},n+1]}case 235:case 236:case 237:case 238:{let n=e-235+1;return t.byteLength<n+1?void 0:[{opcode:171,k:E(t,1,n)},n+1]}case 239:case 240:case 241:case 242:{let n=e-239+1;if(t.byteLength<n+1)return;let o=Se(t,1,n);return t.byteLength<n+1+o?void 0:[{opcode:239,x:t.subarray(n+1,n+1+o),k:o},n+1+o]}case 243:case 244:case 245:case 246:{let n=e-243+1;if(t.byteLength<n+1)return;let o=E(t,1,n);if(t.byteLength<n+15)return;let s=t[n+13],a=t[n+14];return t.byteLength<n+15+s+a?void 0:[{opcode:243,k:o,c:r.getUint32(n+1),s:r.getUint32(n+5),d:r.getUint32(n+9),a:s,l:a,n:new TextDecoder().decode(t.subarray(n+15,n+15+s+a))},n+15+s+a]}case 247:{if(t.byteLength<15)return;let n=t[1],o=t[14];return t.byteLength<15+o?void 0:[{opcode:e,i:n,num:r.getUint32(2),den:r.getUint32(6),mag:r.getUint32(10),x:new TextDecoder().decode(t.subarray(15,15+o)),k:o},15+o]}case 248:return t.byteLength<29?void 0:[{opcode:e,p:r.getUint32(1),num:r.getUint32(5),den:r.getUint32(9),mag:r.getUint32(13),l:r.getUint32(17),u:r.getUint32(21),s:r.getUint16(25),t:r.getUint16(27)},29];case 249:return t.byteLength<6?void 0:[{opcode:e,q:r.getUint32(1),i:r.getUint8(5)},6]}};function*ot(t){let e=t,r=0;for(;r<t.byteLength;){let[n,o]=Cn(e)??[,0];if(r+=o,e=e.subarray(o),!n)break;if(n.opcode===249){if(e.every(s=>s===223))break;throw Error("Only 223 bytes are permitted after the post-postamble.")}yield n}}var Se=(t,e,r)=>[...t.subarray(e,e+r)].reduce((n,o,s)=>n+o*256**(r-s-1),0),E=(t,e,r)=>{switch(r){case 1:return t[e];case 2:{let n=t[e]*256+t[e+1];return n|(n&2**15)*131070}case 3:{let n=t[e]*65536+t[e+1]*256+t[e+2];return n|(n&2**23)*510}case 4:return(t[e]<<24)+t[e+1]*2**16+t[e+2]*2**8+t[e+3]}};var st=()=>{let t=[],e="black";return r=>{let n=new TextDecoder().decode(r.data);if(n.startsWith("color push "))return t.push(e),e=it(n.slice(11)),{type:"color",color:e};if(n.startsWith("color pop")){let o=t.pop();if(!o)throw new Error("Popped from empty color stack");return e=o,{type:"color",color:e}}}},En=t=>${Math.round(t).toString(16)}.padStart(2,"0"),it=t=>{if(t==="gray 0")return"black";if(t==="gray 1")return"white";if(t.startsWith("rgb "))return#${t.split(" ").slice(1).map(e=>En(parseFloat(e)*255)).join("")};if(t.startsWith("gray ")){let e=t.split(" ")[1];return it(rgb ${e} ${e} ${e})}return"black"};var at=()=>{let t="";return(e,r)=>{let n=new TextDecoder().decode(e.data);if(!n.startsWith("dvisvgm:raw "))return;if(t+=n.slice(12),r?.type==="special"){let s=new TextDecoder().decode(r.data);if(e.horizontal===r.horizontal&&e.vertical===r.vertical&&s.startsWith("dvisvgm:raw "))return null}let o=t.replaceAll("{?nl}",
);return t="",{type:"svg",svg:o,left:e.horizontal,top:e.vertical}}};var ct=t=>{let e=new TextDecoder().decode(t.data);if(!e.startsWith("papersize="))return;let[r,n]=e.slice(10).split(",");if(r===void 0||n===void 0)throw Error("Papersize special requires two arguments.");if(!r.endsWith("pt"))throw Error("Papersize special width must be in points.");if(!n.endsWith("pt"))throw Error("Papersize special height must be in points.");return{type:"papersize",width:parseFloat(r.slice(0,-2)),height:parseFloat(n.slice(0,-2))}};var lt=[],pt=(t,e,r,n)=>{let o=[],s={matrix:e,horizontal:r,vertical:n},a={pop:()=>o.pop(),exch:()=>{let i=o.pop(),c=o.pop();i&&o.push(i),c&&o.push(c)},dup:()=>{o.push(o[o.length-1])},mark:()=>o.push(new ze),neg:()=>{let i=o.pop();i&&o.push(new S(-i.value))},add:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(i.value+c.value))},sub:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(c.value-i.value))},mul:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(i.value*c.value))},div:()=>{let i=o.pop(),c=o.pop();i&&c&&o.push(new S(c.value/i.value))},gsave:()=>lt.push([...e]),grestore:()=>{let i=lt.pop();i&&(s.matrix=i)},currentpoint:()=>o.push(new S(s.horizontal),new S(s.vertical)),moveto:()=>{let i=o.pop(),c=o.pop();s.horizontal=c?.value,s.vertical=i?.value},scale:()=>{let i=o.pop(),c=o.pop();c&&i&&(s.matrix=_e(s.matrix,c.value,i.value))},translate:()=>{let i=o.pop(),c=o.pop();c&&i&&(s.matrix=Te(s.matrix,c.value,i.value))},rotate:()=>{let i=o.pop();i&&(s.matrix=Pe(s.matrix,i.value))}};for(let i of Rn(t)){if(/^[+-]?\d+(\.\d*)?$/.test(i)){o.push(new S(i));continue}if(i[0]==="("){o.push(new De(i));continue}if(i==="["){a.mark();continue}if(i==="]"){let c=new Oe,d=o.pop();if(!d)continue;for(;d.name!=="mark";)c.push(d);o.push(c)}if(i[0]==="/"&&o.push(new Ie(i)),i[0]==="{"&&o.push(new Xe(i)),i in a){a[i](void 0);continue}throw Error("Invalid or unimplemented postscript expression")}return s};function*Rn(t){let e="",r=0,n=0,o=t[Symbol.iterator]();for(let s of o){let a;switch(s){case" ":case" ":case
:if(n){e[e.length-1]!==" "&&(e+=" ");continue}if(r){switch(s){case" ":e+=" ";break;case
:e+="\\n";break;case" ":e+="\\t";break}continue}e&&(yield e,e="");continue;case"[":case"]":if(!n&&!r){e&&(yield e),e="",yield s;continue}e+=s;continue;case"{":r||(n==0&&e&&(yield e),++n),e+=s;continue;case"}":if(e+=s,r||(--n,n))continue;yield e,e="";continue;case"(":++r,e&&!n&&r==1&&(yield e),r>1&&(e+="\\"),e+=s;continue;case")":if(--r,r&&(e+="\\"),e+=s,n||r)continue;yield e,e="";continue;case"\\":if(e+=s,a=o.next(),a.done)throw Error("Invalid escape character.");a.done||(e+=a.value);continue;case"/":!n&&!r&&e&&(yield e),e+=s;continue;case"%":do a=o.next();while(!a.done&&a.value!==
);continue;default:e+=s}}e&&(yield e)}var R=class{name;value;constructor(e){this.name=e}},S=class extends R{constructor(e){super("number"),this.value=typeof e=="number"?e:parseFloat(e)}},De=class extends R{constructor(e){super("string"),this.value=e.replace(/^\(|\)$/g,"")}},Oe=class extends R{constructor(e){super("array"),this.value=e||[]}push(e){this.value.push(e)}pop(){return this.value.pop()}},ze=class extends R{constructor(){super("mark"),this.value="-mark-"}},Ie=class extends R{constructor(e){super("identifier"),this.value=e.replace(/^\//,"")}},Xe=class extends R{constructor(e){super("procedure"),this.value=e}};var ut=()=>{let t="";return(e,r)=>{let n=new TextDecoder().decode(e.data);if(!n.startsWith("ps: "))return;if(t+=n.slice(4),r?.type==="special"&&new TextDecoder().decode(r.data).startsWith("ps: "))return null;let o=s=>{let a=pt(t,s,e.horizontal,e.vertical);return e.emitChange({horizontal:a.horizontal,vertical:a.vertical,w:e.w,x:e.x,y:e.y,z:e.z}),a.matrix};return t="",{type:"ps",ps:t,interpret:o}}};async function*ft(t,e){let r=Ln(t,e.tfmLoader),n=await r.next(),o=n.done?void 0:n.value;for(;o;){let s=o,a=await r.next();if(o=a.done?void 0:a.value,s.type==="special"&&e.plugins){let i=!1;for(let c of e.plugins){let d=c(s,o);if(d!==void 0){d!==null&&(yield d),i=!0;break}}i||(yield s);continue}yield s}}async function*Ln(t,e){let r=2,n=254e5,o=473628672,s=1e3,a="",i=0,c=0,d=0,l={horizontal:0,vertical:0,w:0,x:0,y:0,z:0,fontNum:0},h=[],w=new Map,_="",k=ot(t),U=k.next(),u=U.done?void 0:U.value;for(;u;){let p=u,b=k.next();switch(u=b.done?void 0:b.value,p.opcode){case 0:case 133:if(_+=String.fromCharCode(p.c),u?.opcode!==0&&u?.opcode!==133||!u){let f=w.get(l.fontNum);if(!f)throw Error(Font "${l.fontNum}" is not loaded);yield{type:"text",text:_,font:f,top:l.vertical,left:l.horizontal},p.opcode===0&&(l.horizontal+=$n(_,f)),_=""}break;case 132:case 137:p.a>0&&p.b>0&&(yield{type:"rect",left:l.horizontal,top:l.vertical,height:p.a,width:p.b}),p.opcode===132&&(l.horizontal+=p.b);break;case 138:case 140:break;case 139:l.horizontal=0,l.vertical=0,l.w=0,l.x=0,l.y=0,l.z=0,l.fontNum=0,h.splice(0,h.length);break;case 141:h.push({...l});break;case 142:{let f=h.pop();f&&(l.horizontal=f.horizontal,l.vertical=f.vertical,l.w=f.w,l.x=f.x,l.y=f.y,l.z=f.z);break}case 143:l.horizontal+=p.b;break;case 147:p.b!==0&&(l.w=p.b),l.horizontal+=l.w;break;case 152:p.b!==0&&(l.x=p.b),l.horizontal+=l.x;break;case 157:l.vertical+=p.a;break;case 161:p.a!==0&&(l.y=p.a),l.vertical+=l.y;break;case 166:p.a!==0&&(l.z=p.a),l.vertical+=l.z;break;case 171:case 235:case 236:case 237:case 238:l.fontNum=p.k;break;case 239:yield{type:"special",data:p.x,...l,emitChange:f=>{l.horizontal=f.horizontal,l.vertical=f.vertical,l.w=f.w,l.x=f.x,l.y=f.y,l.z=f.z}};break;case 243:{if(w.has(p.k))break;let f=p.n,T=p.s,g=p.d,x=p.c,v=rt(new Uint32Array((await e(${p.n}.tfm)).buffer));w.set(p.k,{name:f,checksum:x,scaleFactor:T,designSize:g,metrics:v});break}case 247:r=p.i,n=p.num,o=p.den,s=p.mag,a=p.x,yield{type:"info",version:r,numerator:n,denominator:o,magnification:s,comment:a};break;case 248:i=p.l,c=p.u,d=p.t;break;case 249:yield{type:"info",version:r,numerator:n,denominator:o,magnification:s,comment:a,maxHeight:i,maxWidth:c,pages:d,dviVersion:p.i};break}}}var $n=(t,e)=>{let r=0;for(let o of t){let s=o.codePointAt(0)??0,a=e.metrics.characters.at(s);if(a===void 0)throw Error(Could not find font metric for ${s});r+=a.width}let n=e.metrics.design_size/1048576*65536/1048576;return r*n*e.scaleFactor/e.designSize};globalThis.onmessage=async t=>{let e=t.data;switch(e.type){case"asset-url":{mt=e.url;let r={type:e.type};globalThis.postMessage(r)}break;case"compile":{let{dvi:r,log:n}=await Ze(e.input,{fileLoader:We,console:c=>{let d={type:"stdout",message:c};globalThis.postMessage(d)}});if(!r){let c={type:e.type,log:n};globalThis.postMessage(c,[n.buffer]);return}let o=[],s=new Set;for await(let c of ft(r,{plugins:[ct,ut(),at(),st()],tfmLoader:We}))o.push(c),c.type==="text"&&s.add(c.font.name);let a=await nt(o,{fileLoader:We,svg:!0}),i={type:e.type,svg:a,log:n};globalThis.postMessage(i,[n.buffer])}break}};var dt,We=async t=>{dt??=await Mn();let e=dt.get(t);if(!e){let r=new Error(File ${t} not found in assets`);throw console.log(r),r}return new Uint8Array(await e())},mt="",Mn=async()=>{let t=new Request(mt),e=await je(t,{ignoreSearch:!0}),r=e??await fetch(t);e||await Qe(t,r);let n=new Map;for await(let{name:o,arrayBuffer:s}of qe(await r.arrayBuffer()))n.set(o,s);return n};
code:esbuild-worker.js
var b="0.24.0";(()=>{let r=()=>{let c=new Error("not implemented");return c.code="ENOSYS",c};if(!globalThis.fs){let c="";globalThis.fs={constants:{O_WRONLY:-1,O_RDWR:-1,O_CREAT:-1,O_TRUNC:-1,O_APPEND:-1,O_EXCL:-1},writeSync(i,s){c+=f.decode(s);let n=c.lastIndexOf(`
);return n!=-1&&(console.log(c.substring(0,n)),c=c.substring(n+1)),s.length},write(i,s,n,o,h,u){if(n!==0||o!==s.length||h!==null){u(r());return}let m=this.writeSync(i,s);u(null,m)},chmod(i,s,n){n(r())},chown(i,s,n,o){o(r())},close(i,s){s(r())},fchmod(i,s,n){n(r())},fchown(i,s,n,o){o(r())},fstat(i,s){s(r())},fsync(i,s){s(null)},ftruncate(i,s,n){n(r())},lchown(i,s,n,o){o(r())},link(i,s,n){n(r())},lstat(i,s){s(r())},mkdir(i,s,n){n(r())},open(i,s,n,o){o(r())},read(i,s,n,o,h,u){u(r())},readdir(i,s){s(r())},readlink(i,s){s(r())},rename(i,s,n){n(r())},rmdir(i,s){s(r())},stat(i,s){s(r())},symlink(i,s,n){n(r())},truncate(i,s,n){n(r())},unlink(i,s){s(r())},utimes(i,s,n,o){o(r())}}}if(globalThis.process||(globalThis.process={getuid(){return-1},getgid(){return-1},geteuid(){return-1},getegid(){return-1},getgroups(){throw r()},pid:-1,ppid:-1,umask(){throw r()},cwd(){throw r()},chdir(){throw r()}}),!globalThis.crypto)throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");if(!globalThis.performance)throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");if(!globalThis.TextEncoder)throw new Error("globalThis.TextEncoder is not available, polyfill required");if(!globalThis.TextDecoder)throw new Error("globalThis.TextDecoder is not available, polyfill required");let y=new TextEncoder("utf-8"),f=new TextDecoder("utf-8");globalThis.Go=class{constructor(){this.argv=["js"],this.env={},this.exit=e=>{e!==0&&console.warn("exit code:",e)},this._exitPromise=new Promise(e=>{this._resolveExitPromise=e}),this._pendingEvent=null,this._scheduledTimeouts=new Map,this._nextCallbackTimeoutID=1;let c=(e,t)=>{this.mem.setUint32(e+0,t,!0),this.mem.setUint32(e+4,Math.floor(t/4294967296),!0)},i=(e,t)=>{this.mem.setUint32(e+0,t,!0)},s=e=>{let t=this.mem.getUint32(e+0,!0),l=this.mem.getInt32(e+4,!0);return t+l*4294967296},n=e=>{let t=this.mem.getFloat64(e,!0);if(t===0)return;if(!isNaN(t))return t;let l=this.mem.getUint32(e,!0);return this._values[l]},o=(e,t)=>{if(typeof t=="number"&&t!==0){if(isNaN(t)){this.mem.setUint32(e+4,2146959360,!0),this.mem.setUint32(e,0,!0);return}this.mem.setFloat64(e,t,!0);return}if(t===void 0){this.mem.setFloat64(e,0,!0);return}let a=this._ids.get(t);a===void 0&&(a=this._idPool.pop(),a===void 0&&(a=this._values.length),this._values[a]=t,this._goRefCounts[a]=0,this._ids.set(t,a)),this._goRefCounts[a]++;let g=0;switch(typeof t){case"object":t!==null&&(g=1);break;case"string":g=2;break;case"symbol":g=3;break;case"function":g=4;break}this.mem.setUint32(e+4,2146959360|g,!0),this.mem.setUint32(e,a,!0)},h=e=>{let t=s(e+0),l=s(e+8);return new Uint8Array(this._inst.exports.mem.buffer,t,l)},u=e=>{let t=s(e+0),l=s(e+8),a=new Array(l);for(let g=0;g<l;g++)a[g]=n(t+g*8);return a},m=e=>{let t=s(e+0),l=s(e+8);return f.decode(new DataView(this._inst.exports.mem.buffer,t,l))},d=Date.now()-performance.now();this.importObject={_gotest:{add:(e,t)=>e+t},gojs:{"runtime.wasmExit":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);this.exited=!0,delete this._inst,delete this._values,delete this._goRefCounts,delete this._ids,delete this._idPool,this.exit(t)},"runtime.wasmWrite":e=>{e>>>=0;let t=s(e+8),l=s(e+16),a=this.mem.getInt32(e+24,!0);fs.writeSync(t,new Uint8Array(this._inst.exports.mem.buffer,l,a))},"runtime.resetMemoryDataView":e=>{e>>>=0,this.mem=new DataView(this._inst.exports.mem.buffer)},"runtime.nanotime1":e=>{e>>>=0,c(e+8,(d+performance.now())*1e6)},"runtime.walltime":e=>{e>>>=0;let t=new Date().getTime();c(e+8,t/1e3),this.mem.setInt32(e+16,t%1e3*1e6,!0)},"runtime.scheduleTimeoutEvent":e=>{e>>>=0;let t=this._nextCallbackTimeoutID;this._nextCallbackTimeoutID++,this._scheduledTimeouts.set(t,setTimeout(()=>{for(this._resume();this._scheduledTimeouts.has(t);)console.warn("scheduleTimeoutEvent: missed timeout event"),this._resume()},s(e+8))),this.mem.setInt32(e+16,t,!0)},"runtime.clearTimeoutEvent":e=>{e>>>=0;let t=this.mem.getInt32(e+8,!0);clearTimeout(this._scheduledTimeouts.get(t)),this._scheduledTimeouts.delete(t)},"runtime.getRandomData":e=>{e>>>=0,crypto.getRandomValues(h(e+8))},"syscall/js.finalizeRef":e=>{e>>>=0;let t=this.mem.getUint32(e+8,!0);if(this._goRefCounts[t]--,this._goRefCounts[t]===0){let l=this._values[t];this._values[t]=null,this._ids.delete(l),this._idPool.push(t)}},"syscall/js.stringVal":e=>{e>>>=0,o(e+24,m(e+8))},"syscall/js.valueGet":e=>{e>>>=0;let t=Reflect.get(n(e+8),m(e+16));e=this._inst.exports.getsp()>>>0,o(e+32,t)},"syscall/js.valueSet":e=>{e>>>=0,Reflect.set(n(e+8),m(e+16),n(e+32))},"syscall/js.valueDelete":e=>{e>>>=0,Reflect.deleteProperty(n(e+8),m(e+16))},"syscall/js.valueIndex":e=>{e>>>=0,o(e+24,Reflect.get(n(e+8),s(e+16)))},"syscall/js.valueSetIndex":e=>{e>>>=0,Reflect.set(n(e+8),s(e+16),n(e+24))},"syscall/js.valueCall":e=>{e>>>=0;try{let t=n(e+8),l=Reflect.get(t,m(e+16)),a=u(e+32),g=Reflect.apply(l,t,a);e=this._inst.exports.getsp()>>>0,o(e+56,g),this.mem.setUint8(e+64,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+56,t),this.mem.setUint8(e+64,0)}},"syscall/js.valueInvoke":e=>{e>>>=0;try{let t=n(e+8),l=u(e+16),a=Reflect.apply(t,void 0,l);e=this._inst.exports.getsp()>>>0,o(e+40,a),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueNew":e=>{e>>>=0;try{let t=n(e+8),l=u(e+16),a=Reflect.construct(t,l);e=this._inst.exports.getsp()>>>0,o(e+40,a),this.mem.setUint8(e+48,1)}catch(t){e=this._inst.exports.getsp()>>>0,o(e+40,t),this.mem.setUint8(e+48,0)}},"syscall/js.valueLength":e=>{e>>>=0,c(e+16,parseInt(n(e+8).length))},"syscall/js.valuePrepareString":e=>{e>>>=0;let t=y.encode(String(n(e+8)));o(e+16,t),c(e+24,t.length)},"syscall/js.valueLoadString":e=>{e>>>=0;let t=n(e+8);h(e+16).set(t)},"syscall/js.valueInstanceOf":e=>{e>>>=0,this.mem.setUint8(e+24,n(e+8)instanceof n(e+16)?1:0)},"syscall/js.copyBytesToGo":e=>{e>>>=0;let t=h(e+8),l=n(e+32);if(!(l instanceof Uint8Array||l instanceof Uint8ClampedArray)){this.mem.setUint8(e+48,0);return}let a=l.subarray(0,t.length);t.set(a),c(e+40,a.length),this.mem.setUint8(e+48,1)},"syscall/js.copyBytesToJS":e=>{e>>>=0;let t=n(e+8),l=h(e+16);if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray)){this.mem.setUint8(e+48,0);return}let a=l.subarray(0,t.length);t.set(a),c(e+40,a.length),this.mem.setUint8(e+48,1)},debug:e=>{console.log(e)}}}}async run(c){if(!(c instanceof WebAssembly.Instance))throw new Error("Go.run: WebAssembly.Instance expected");this._inst=c,this.mem=new DataView(this._inst.exports.mem.buffer),this._values=[NaN,0,null,!0,!1,globalThis,this],this._goRefCounts=new Array(this._values.length).fill(1/0),this._ids=new Map([[0,1],[null,2],[!0,3],[!1,4],[globalThis,5],[this,6]]),this._idPool=[],this.exited=!1;let i=4096,s=d=>{let e=i,t=y.encode(d+"\0");return new Uint8Array(this.mem.buffer,i,t.length).set(t),i+=t.length,i%8!==0&&(i+=8-i%8),e},n=this.argv.length,o=[];this.argv.forEach(d=>{o.push(s(d))}),o.push(0),Object.keys(this.env).sort().forEach(d=>{o.push(s(${d}=${this.envd}))}),o.push(0);let u=i;if(o.forEach(d=>{this.mem.setUint32(i,d,!0),this.mem.setUint32(i+4,0,!0),i+=8}),i>=12288)throw new Error("total length of command line and environment variables exceeds limit");this._inst.exports.run(n,u),this.exited&&this._resolveExitPromise(),await this._exitPromise}_resume(){if(this.exited)throw new Error("Go program has already exited");this._inst.exports.resume(),this.exited&&this._resolveExitPromise()}_makeFuncWrapper(c){let i=this;return function(){let s={id:c,this:this,args:arguments};return i._pendingEvent=s,i._resume(),s.result}}}})();onmessage=({data:r})=>{let y=new TextDecoder,f=globalThis.fs,c="";f.writeSync=(h,u)=>{if(h===1)postMessage(u);else if(h===2){c+=y.decode(u);let m=c.split(
);m.length>1&&console.log(m.slice(0,-1).join(
)),c=m[m.length-1]}else throw new Error("Bad write");return u.length};let i=[],s,n=0;onmessage=({data:h})=>(h.length>0&&(i.push(h),s&&s()),o),f.read=(h,u,m,d,e,t)=>{if(h!==0||m!==0||d!==u.length||e!==null)throw new Error("Bad read");if(i.length===0){s=()=>f.read(h,u,m,d,e,t);return}let l=i[0],a=Math.max(0,Math.min(d,l.length-n));u.set(l.subarray(n,n+a),m),n+=a,n===l.length&&(i.shift(),n=0),t(null,a)};let o=new globalThis.Go;return o.argv=["",--service=${b}],w(r,o).then(h=>{postMessage(null),o.run(h)},h=>{postMessage(h)}),o};async function w(r,y){if(r instanceof WebAssembly.Module)return WebAssembly.instantiate(r,y.importObject);let f=r instanceof Response?r:await fetch(r);if(!f.ok)throw new Error(Failed to download ${JSON.stringify(r)}`);if("instantiateStreaming"in WebAssembly&&/^application\/wasm($|;)/i.test(f.headers.get("Content-Type")||""))return(await WebAssembly.instantiateStreaming(f,y.importObject)).instance;let c=await f.arrayBuffer();return(await WebAssembly.instantiate(c,y.importObject)).instance}
/** @license esbuild-wasm@0.24.0
*
* MIT License
*
* Copyright (c) 2020 Evan Wallace
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
code:select-suggestion-worker.js
var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)r}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Rt=(e,t)=>{if(e.length!==t.length)return!1;let r=...e.sort(),o=...t.sort();return r.every((n,i)=>n===oi)};function wt(e,t={}){let{signal:r,persistent:o=!0}=t;return r?.aborted?Promise.reject(r.reason):new Promise((n,i)=>{let s=()=>{clearTimeout(+a),i(r?.reason)},a=to(()=>{r?.removeEventListener("abort",s),n()},e);if(r?.addEventListener("abort",s,{once:!0}),o===!1)try{Deno.unrefTimer(+a)}catch(c){if(!(c instanceof ReferenceError))throw clearTimeout(+a),c;console.error("persistent option is only available in Deno")}})}var Me=2**31-1;function to(e,t){if(t=Math.trunc(Math.max(t,0)||0),t<=Me){let i=Number(setTimeout(e,t));return{valueOf:()=>i}}let r=Date.now(),o,n=()=>{let i=t-(Date.now()-r);o=i>Me?Number(setTimeout(n,Me)):Number(setTimeout(e,i))};return n(),{valueOf:()=>o}}var _t=Symbol("Comlink.proxy"),ro=Symbol("Comlink.endpoint"),oo=Symbol("Comlink.releaseProxy"),Ue=Symbol("Comlink.finalizer"),me=Symbol("Comlink.thrown"),Tt=e=>typeof e=="object"&&e!==null||typeof e=="function",no={canHandle:e=>Tt(e)&&e_t,serialize(e){let{port1:t,port2:r}=new MessageChannel;return Ee(e,t),[r,r]},deserialize(e){return e.start(),lo(e)}},so={canHandle:e=>Tt(e)&&me in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},xt=new Map("proxy",no],["throw",so);function io(e,t){for(let r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function Ee(e,t=globalThis,r="*"){t.addEventListener("message",function o(n){if(!n||!n.data)return;if(!io(r,n.origin)){console.warn(Invalid origin '${n.origin}' for comlink proxy);return}let{id:i,type:s,path:l}=Object.assign({path:[]},n.data),a=(n.data.argumentList||[]).map(V),c;try{let p=l.slice(0,-1).reduce((f,m)=>fm,e),u=l.reduce((f,m)=>fm,e);switch(s){case"GET":c=u;break;case"SET":p[l.slice(-1)0]=V(n.data.value),c=!0;break;case"APPLY":c=u.apply(p,a);break;case"CONSTRUCT":{let f=new u(...a);c=mo(f)}break;case"ENDPOINT":{let{port1:f,port2:m}=new MessageChannel;Ee(e,m),c=fo(f,f)}break;case"RELEASE":c=void 0;break;default:return}}catch(p){c={value:p,me:0}}Promise.resolve(c).catch(p=>({value:p,me:0})).then(p=>{letu,f=he(p);t.postMessage(Object.assign(Object.assign({},u),{id:i}),f),s==="RELEASE"&&(t.removeEventListener("message",o),Ot(t),Ue in e&&typeof eUe=="function"&&eUe())}).catch(p=>{letu,f=he({value:new TypeError("Unserializable return value"),me:0});t.postMessage(Object.assign(Object.assign({},u),{id:i}),f)})}),t.start&&t.start()}function ao(e){return e.constructor.name==="MessagePort"}function Ot(e){ao(e)&&e.close()}function lo(e,t){let r=new Map;return e.addEventListener("message",function(o){let{data:n}=o;if(!n||!n.id)return;let i=r.get(n.id);if(i)try{i(n)}finally{r.delete(n.id)}}),Ce(e,r,[],t)}function fe(e){if(e)throw new Error("Proxy has been released and is not useable")}function vt(e){return Q(e,new Map,{type:"RELEASE"}).then(()=>{Ot(e)})}var de=new WeakMap,ge="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(de.get(e)||0)-1;de.set(e,t),t===0&&vt(e)});function co(e,t){let r=(de.get(t)||0)+1;de.set(t,r),ge&&ge.register(e,t,e)}function uo(e){ge&&ge.unregister(e)}function Ce(e,t,r=[],o=function(){}){let n=!1,i=new Proxy(o,{get(s,l){if(fe(n),l===oo)return()=>{uo(i),vt(e),t.clear(),n=!0};if(l==="then"){if(r.length===0)return{then:()=>i};let a=Q(e,t,{type:"GET",path:r.map(c=>c.toString())}).then(V);return a.then.bind(a)}return Ce(e,t,...r,l)},set(s,l,a){fe(n);letc,p=he(a);return Q(e,t,{type:"SET",path:...r,l.map(u=>u.toString()),value:c},p).then(V)},apply(s,l,a){fe(n);let c=rr.length-1;if(c===ro)return Q(e,t,{type:"ENDPOINT"}).then(V);if(c==="bind")return Ce(e,t,r.slice(0,-1));letp,u=bt(a);return Q(e,t,{type:"APPLY",path:r.map(f=>f.toString()),argumentList:p},u).then(V)},construct(s,l){fe(n);leta,c=bt(l);return Q(e,t,{type:"CONSTRUCT",path:r.map(p=>p.toString()),argumentList:a},c).then(V)}});return co(i,e),i}function po(e){return Array.prototype.concat.apply([],e)}function bt(e){let t=e.map(he);return[t.map(r=>r0),po(t.map(r=>r1))]}var St=new WeakMap;function fo(e,t){return St.set(e,t),e}function mo(e){return Object.assign(e,{_t:!0})}function he(e){for(lett,rof xt)if(r.canHandle(e)){leto,n=r.serialize(e);return{type:"HANDLER",name:t,value:o},n}return[{type:"RAW",value:e},St.get(e)||[]]}function V(e){switch(e.type){case"HANDLER":return xt.get(e.name).deserialize(e.value);case"RAW":return e.value}}function Q(e,t,r,o){return new Promise(n=>{let i=go();t.set(i,n),e.start&&e.start(),e.postMessage(Object.assign({id:i},r),o)})}function go(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var M=!1;var Nt=e=>Object.fromEntries(...Object.entries(console).map((t,r)=>{if(typeof r!="function")returnt,r;switch(t){case"warn":case"error":return[t,(...o)=>r(%c${e},je,...o)];case"log":case"info":case"debug":return[t,(...o)=>{M!==!0&&(!M||!M.has(e))||r(%c${e},je,...o)}];case"assert":return[t,(o,...n)=>{M!==!0&&(!M||!M.has(e))||r(o,%c${e},je,...n)}];case"time":case"timeEnd":return[t,o=>{M!==!0&&(!M||!M.has(e))||r(${e} ${o})}];default:returnt,(...o)=>{if(!(M!==!0&&(!M||!M.has(e))))return r(...o)}}})),je="color: gray";var ho=class{__unenv__=!0;_currentStore;_enterStore;_enabled=!0;getStore(){return this._currentStore??this._enterStore}disable(){this._enabled=!1}enable(){this._enabled=!0}enterWith(e){this._enterStore=e}run(e,t,...r){this._currentStore=e;let o=t(...r);return this._currentStore=void 0,o}exit(e,...t){let r=this._currentStore;this._currentStore=void 0;let o=e(...t);return this._currentStore=r,o}static snapshot(){throw new Error("unenv AsyncLocalStorage.snapshot is not implemented!")}},hs=globalThis.AsyncLocalStorage||ho,Eo=Symbol("init"),yo=Symbol("before"),Ro=Symbol("after"),wo=Symbol("destroy"),bo=Symbol("promiseResolve"),Es=class{__unenv__=!0;_enabled=!1;_callbacks={};constructor(e={}){this._callbacks=e}enable(){return this._enabled=!0,this}disable(){return this._enabled=!1,this}getEo(){return this._callbacks.init}getyo(){return this._callbacks.before}getRo(){return this._callbacks.after}getwo(){return this._callbacks.destroy}getbo(){return this._callbacks.promiseResolve}};var _o=function(){return 0};var ys=Object.assign(Object.create(null),{NONE:0,DIRHANDLE:1,DNSCHANNEL:2,ELDHISTOGRAM:3,FILEHANDLE:4,FILEHANDLECLOSEREQ:5,BLOBREADER:6,FSEVENTWRAP:7,FSREQCALLBACK:8,FSREQPROMISE:9,GETADDRINFOREQWRAP:10,GETNAMEINFOREQWRAP:11,HEAPSNAPSHOT:12,HTTP2SESSION:13,HTTP2STREAM:14,HTTP2PING:15,HTTP2SETTINGS:16,HTTPINCOMINGMESSAGE:17,HTTPCLIENTREQUEST:18,JSSTREAM:19,JSUDPWRAP:20,MESSAGEPORT:21,PIPECONNECTWRAP:22,PIPESERVERWRAP:23,PIPEWRAP:24,PROCESSWRAP:25,PROMISE:26,QUERYWRAP:27,QUIC_ENDPOINT:28,QUIC_LOGSTREAM:29,QUIC_PACKET:30,QUIC_SESSION:31,QUIC_STREAM:32,QUIC_UDP:33,SHUTDOWNWRAP:34,SIGNALWRAP:35,STATWATCHER:36,STREAMPIPE:37,TCPCONNECTWRAP:38,TCPSERVERWRAP:39,TCPWRAP:40,TTYWRAP:41,UDPSENDWRAP:42,UDPWRAP:43,SIGINTWATCHDOG:44,WORKER:45,WORKERHEAPSNAPSHOT:46,WRITEWRAP:47,ZLIB:48,CHECKPRIMEREQUEST:49,PBKDF2REQUEST:50,KEYPAIRGENREQUEST:51,KEYGENREQUEST:52,KEYEXPORTREQUEST:53,CIPHERREQUEST:54,DERIVEBITSREQUEST:55,HASHREQUEST:56,RANDOMBYTESREQUEST:57,RANDOMPRIMEREQUEST:58,SCRYPTREQUEST:59,SIGNREQUEST:60,TLSWRAP:61,VERIFYREQUEST:62}),To=100,xo=class{__unenv__=!0;type;_asyncId;_triggerAsyncId;constructor(e,t=_o()){this.type=e,this._asyncId=-1*To++,this._triggerAsyncId=typeof t=="number"?t:t?.triggerAsyncId}static bind(e,t,r){return new Be(t??"anonymous").bind(e)}bind(e,t){let r=(...o)=>this.runInAsyncScope(e,t,...o);return r.asyncResource=this,r}runInAsyncScope(e,t,...r){return e.apply(t,r)}emitDestroy(){return this}asyncId(){return this._asyncId}triggerAsyncId(){return this._triggerAsyncId}},Be=globalThis.AsyncResource||xo;function Oo(e){return new Error([unenv] ${e} is not implemented yet!)}function ze(e){return Object.assign(()=>{throw Oo(e)},{__unenv__:!0})}var J=10,vo=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),Ut=(e,t)=>e,X=Error,So=Error,z=Error,ye=Error,No=Error,qe=Symbol.for("nodejs.rejection"),U=Symbol.for("kCapture"),De=Symbol.for("events.errorMonitor"),K=Symbol.for("shapeMode"),Re=Symbol.for("events.maxEventTargetListeners"),ko=Symbol.for("kEnhanceStackBeforeInspector"),Lo=Symbol.for("nodejs.watermarkData"),$e=Symbol.for("kEventEmitter"),H=Symbol.for("kAsyncResource"),Po=Symbol.for("kFirstEventParam"),Ve=Symbol.for("kResistStopPropagation"),kt=Symbol.for("events.maxEventTargetListenersWarned"),we=class ae{_events=void 0;_eventsCount=0;_maxListeners=J;U=!1;K=!1;static captureRejectionSymbol=qe;static errorMonitor=De;static kMaxEventTargetListeners=Re;static kMaxEventTargetListenersWarned=kt;static usingDomains=!1;static get on(){return Io}static get once(){return Mo}static get getEventListeners(){return Uo}static get getMaxListeners(){return Co}static get addAbortListener(){return Ct}static get EventEmitterAsyncResource(){return Ao}static get EventEmitter(){return ae}static setMaxListeners(t=J,...r){if(r.length===0)J=t;else for(let o of r)if(Bt(o))oRe=t,okt=!1;else if(typeof o.setMaxListeners=="function")o.setMaxListeners(t);else throw new z("eventTargets","EventEmitter","EventTarget",o)}static listenerCount(t,r){if(typeof t.listenerCount=="function")return t.listenerCount(r);ae.prototype.listenerCount.call(t,r)}static init(){throw new Error("EventEmitter.init() is not implemented.")}static get captureRejections(){return thisU}static set captureRejections(t){thisU=t}static get defaultMaxListeners(){return J}static set defaultMaxListeners(t){J=t}constructor(t){this._events===void 0||this._events===Object.getPrototypeOf(this)._events?(this._events={__proto__:null},this._eventsCount=0,thisK=!1):thisK=!0,this._maxListeners=this._maxListeners||void 0,t?.captureRejections?thisU=!!t.captureRejections:thisU=ae.prototypeU}setMaxListeners(t){return this._maxListeners=t,this}getMaxListeners(){return Ye(this)}emit(t,...r){let o=t==="error",n=this._events;if(n!==void 0)o&&nDe!==void 0&&this.emit(De,...r),o=o&&n.error===void 0;else if(!o)return!1;if(o){let s;if(r.length>0&&(s=r0),s instanceof Error){try{let c={};Error.captureStackTrace?.(c,ae.prototype.emit),Object.defineProperty(s,ko,{__proto__:null,value:Function.prototype.bind(Bo,this,s,c),configurable:!0})}catch{}throw s}let l;try{l=Ut(s)}catch{l=s}let a=new So(l);throw a.context=s,a}let i=nt;if(i===void 0)return!1;if(typeof i=="function"){let s=i.apply(this,r);s!=null&&At(this,s,t,r)}else{let s=i.length,l=Qe(i);for(let a=0;a<s;++a){let c=la.apply(this,r);c!=null&&At(this,c,t,r)}}return!0}addListener(t,r){return Ft(this,t,r,!1),this}on(t,r){return this.addListener(t,r)}prependListener(t,r){return Ft(this,t,r,!0),this}once(t,r){return this.on(t,It(this,t,r)),this}prependOnceListener(t,r){return this.prependListener(t,It(this,t,r)),this}removeListener(t,r){let o=this._events;if(o===void 0)return this;let n=ot;if(n===void 0)return this;if(n===r||n.listener===r)this._eventsCount-=1,thisK?ot=void 0:this._eventsCount===0?this._events={__proto__:null}:(delete ot,o.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){let i=-1;for(let s=n.length-1;s>=0;s--)if(ns===r||ns.listener===r){i=s;break}if(i<0)return this;i===0?n.shift():Wo(n,i),n.length===1&&(ot=n0),o.removeListener!==void 0&&this.emit("removeListener",t,r)}return this}off(t,r){return this.removeListener(t,r)}removeAllListeners(t){let r=this._events;if(r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events={__proto__:null},this._eventsCount=0):rt!==void 0&&(--this._eventsCount===0?this._events={__proto__:null}:delete rt),thisK=!1,this;if(arguments.length===0){for(let n of Reflect.ownKeys(r))n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events={__proto__:null},this._eventsCount=0,thisK=!1,this}let o=rt;if(typeof o=="function")this.removeListener(t,o);else if(o!==void 0)for(let n=o.length-1;n>=0;n--)this.removeListener(t,on);return this}listeners(t){return Mt(this,t,!0)}rawListeners(t){return Mt(this,t,!1)}eventNames(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}listenerCount(t,r){let o=this._events;if(o!==void 0){let n=ot;if(typeof n=="function")return r!=null?r===n||r===n.listener?1:0:1;if(n!==void 0){if(r!=null){let i=0;for(let s=0,l=n.length;s<l;s++)(ns===r||ns.listener===r)&&i++;return i}return n.length}}return 0}},Ao=class extends we{constructor(e){let t;typeof e=="string"?(t=e,e=void 0):t=e?.name||new.target.name,super(e),thisH=new Fo(this,t,e)}emit(e,...t){if(thisH===void 0)throw new X("EventEmitterAsyncResource");let{asyncResource:r}=this;return Array.prototype.unshift(t,super.emit,this,e),Reflect.apply(r.runInAsyncScope,r,t)}emitDestroy(){if(thisH===void 0)throw new X("EventEmitterAsyncResource");this.asyncResource.emitDestroy()}get asyncId(){if(thisH===void 0)throw new X("EventEmitterAsyncResource");return this.asyncResource.asyncId()}get triggerAsyncId(){if(thisH===void 0)throw new X("EventEmitterAsyncResource");return this.asyncResource.triggerAsyncId()}get asyncResource(){if(thisH===void 0)throw new X("EventEmitterAsyncResource");return thisH}},Fo=class extends Be{constructor(e,t,r){super(t,r),this$e=e}get eventEmitter(){if(this$e===void 0)throw new X("EventEmitterReferencingAsyncResource");return this$e}},Io=function(e,t,r={}){let o=r.signal;if(o?.aborted)throw new ye(void 0,{cause:o?.reason});let n=r.highWaterMark??r.highWatermark??Number.MAX_SAFE_INTEGER,i=r.lowWaterMark??r.lowWatermark??1,s=new Pt,l=new Pt,a=!1,c=null,p=!1,u=0,f=Object.setPrototypeOf({next(){if(u){let y=s.shift();return u--,a&&u<i&&(e.resume?.(),a=!1),Promise.resolve(We(y,!1))}if(c){let y=Promise.reject(c);return c=null,y}return p?C():new Promise(function(y,eo){l.push({resolve:y,reject:eo})})},return(){return C()},throw(y){if(!y||!(y instanceof Error))throw new z("EventEmitter.AsyncIterator","Error",y);F(y)},Symbol.asyncIterator(){return this},Lo:{get size(){return u},get low(){return i},get high(){return n},get isPaused(){return a}}},vo),{addEventListener:m,removeAll:g}=Go();m(e,t,rPo?I:function(...y){return I(y)}),t!=="error"&&typeof e.on=="function"&&m(e,"error",F);let w=r?.close;if(w?.length)for(let y of w)m(e,y,C);let _=o?Ct(o,A):null;return f;function A(){F(new ye(void 0,{cause:o?.reason}))}function I(y){l.isEmpty()?(u++,!a&&u>n&&(a=!0,e.pause?.()),s.push(y)):l.shift().resolve(We(y,!1))}function F(y){l.isEmpty()?c=y:l.shift().reject(y),C()}function C(){_?.Symbol.dispose(),g(),p=!0;let y=We(void 0,!0);for(;!l.isEmpty();)l.shift().resolve(y);return Promise.resolve(y)}},Mo=async function(e,t,r={}){let o=r?.signal;if(o?.aborted)throw new ye(void 0,{cause:o?.reason});return new Promise((n,i)=>{let s=p=>{typeof e.removeListener=="function"&&e.removeListener(t,l),o!=null&&le(o,"abort",c),i(p)},l=(...p)=>{typeof e.removeListener=="function"&&e.removeListener("error",s),o!=null&&le(o,"abort",c),n(p)},a={__proto__:null,once:!0,Ve:!0};He(e,t,l,a),t!=="error"&&typeof e.once=="function"&&e.once("error",s);function c(){le(e,t,l),le(e,"error",s),i(new ye(void 0,{cause:o?.reason}))}o!=null&&He(o,"abort",c,{__proto__:null,once:!0,Ve:!0})})},Ct=function(e,t){if(e===void 0)throw new z("signal","AbortSignal",e);let r;return e.aborted?queueMicrotask(()=>t()):(e.addEventListener("abort",t,{__proto__:null,once:!0,Ve:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,Symbol.dispose(){r?.()}}},Uo=function(e,t){if(typeof e.listeners=="function")return e.listeners(t);if(Bt(e)){let r=ekEvents.get(t),o=[],n=r?.next;for(;n?.listener!==void 0;){let i=n.listener?.deref?n.listener.deref():n.listener;o.push(i),n=n.next}return o}throw new z("emitter","EventEmitter","EventTarget",e)},Co=function(e){if(typeof e?.getMaxListeners=="function")return Ye(e);if(e?.Re)return eRe;throw new z("emitter","EventEmitter","EventTarget",e)},jt=2048,Ge=jt-1,Lt=class{bottom;top;list;next;constructor(){this.bottom=0,this.top=0,this.list=new Array(jt),this.next=null}isEmpty(){return this.top===this.bottom}isFull(){return(this.top+1&Ge)===this.bottom}push(e){this.listthis.top=e,this.top=this.top+1&Ge}shift(){let e=this.listthis.bottom;return e===void 0?null:(this.listthis.bottom=void 0,this.bottom=this.bottom+1&Ge,e)}},Pt=class{head;tail;constructor(){this.head=this.tail=new Lt}isEmpty(){return this.head.isEmpty()}push(e){this.head.isFull()&&(this.head=this.head.next=new Lt),this.head.push(e)}shift(){let e=this.tail,t=e.shift();return e.isEmpty()&&e.next!==null&&(this.tail=e.next,e.next=null),t}};function Bt(e){return typeof e?.addEventListener=="function"}function At(e,t,r,o){if(eU)try{let n=t.then;typeof n=="function"&&n.call(t,void 0,function(i){setTimeout(jo,0,e,i,r,o)})}catch(n){e.emit("error",n)}}function jo(e,t,r,o){if(typeof eqe=="function")eqe(t,r,...o);else{let n=eU;try{eU=!1,e.emit("error",t)}finally{eU=n}}}function Ye(e){return e._maxListeners===void 0?J:e._maxListeners}function Bo(e,t){let r="";try{let{name:i}=this.constructor;i!=="EventEmitter"&&(r= on ${i} instance)}catch{}let o=`
Emitted 'error' event${r} at:
,n=(t.stack||"").split(
).slice(1);return e.stack+o+n.join(
)}function Ft(e,t,r,o){let n,i,s;if(i=e._events,i===void 0?(i=e._events={__proto__:null},e._eventsCount=0):(i.newListener!==void 0&&(e.emit("newListener",t,r.listener??r),i=e._events),s=i[t]),s===void 0)i[t]=r,++e._eventsCount;else if(typeof s=="function"?s=i[t]=o?[r,s]:[s,r]:o?s.unshift(r):s.push(r),n=Ye(e),n>0&&s.length>n&&!s.warned){s.warned=!0;let l=new No(Possible EventEmitter memory leak detected. ${s.length} ${String(t)} listeners added to ${Ut(e,{depth:-1})}. MaxListeners is ${n}. Use emitter.setMaxListeners() to increase limit,{name:"MaxListenersExceededWarning",emitter:e,type:t,count:s.length});console.warn(l)}return e}function Do(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function It(e,t,r){let o={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},n=Do.bind(o);return n.listener=r,o.wrapFn=n,n}function Mt(e,t,r){let o=e._events;if(o===void 0)return[];let n=o[t];return n===void 0?[]:typeof n=="function"?r?[n.listener||n]:[n]:r?$o(n):Qe(n)}function Qe(e){switch(e.length){case 2:return[e[0],e[1]];case 3:return[e[0],e[1],e[2]];case 4:return[e[0],e[1],e[2],e[3]];case 5:return[e[0],e[1],e[2],e[3],e[4]];case 6:return[e[0],e[1],e[2],e[3],e[4],e[5]]}return Array.prototype.slice.call(e)}function $o(e){let t=Qe(e);for(let r=0;r<t.length;++r){let o=t[r].listener;typeof o=="function"&&(t[r]=o)}return t}function We(e,t){return{value:e,done:t}}function le(e,t,r,o){if(typeof e.removeListener=="function")e.removeListener(t,r);else if(typeof e.removeEventListener=="function")e.removeEventListener(t,r,o);else throw new z("emitter","EventEmitter",e)}function He(e,t,r,o){if(typeof e.on=="function")o?.once?e.once(t,r):e.on(t,r);else if(typeof e.addEventListener=="function")e.addEventListener(t,r,o);else throw new z("emitter","EventEmitter",e)}function Go(){let e=[];return{addEventListener(t,r,o,n){He(t,r,o,n),Array.prototype.push(e,[t,r,o,n])},removeAll(){for(;e.length>0;)Reflect.apply(le,void 0,e.pop())}}}function Wo(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}var xs=Symbol.for("nodejs.rejection");var Os=Symbol.for("events.errorMonitor");var vs=ze("node:events.setMaxListeners"),Ss=ze("node:events.listenerCount"),Ns=ze("node:events.init");var Dt=class{fd;isRaw=!1;isTTY=!1;constructor(e){this.fd=e}setRawMode(e){return this.isRaw=e,this}},Ke=class{fd;columns=80;rows=24;isTTY=!1;constructor(e){this.fd=e}clearLine(e,t){return t&&t(),!1}clearScreenDown(e){return e&&e(),!1}cursorTo(e,t,r){return r&&typeof r=="function"&&r(),!1}moveCursor(e,t,r){return r&&r(),!1}getColorDepth(e){return 1}hasColors(e,t){return!1}getWindowSize(){return[this.columns,this.rows]}write(e,t,r){e instanceof Uint8Array&&(e=new TextDecoder().decode(e));try{console.log(e)}catch{}return r&&typeof r=="function"&&r(),!1}};function T(e){return new Error(unenv ${e} is not implemented yet!)}function Z(e){return Object.assign(()=>{throw T(e)},{__unenv__:!0})}var $t="22.14.0",qo=class Gt extends we{env;hrtime;nextTick;constructor(t){super(),this.env=t.env,this.hrtime=t.hrtime,this.nextTick=t.nextTick;for(let r of[...Object.getOwnPropertyNames(Gt.prototype),...Object.getOwnPropertyNames(we.prototype)]){let o=this[r];typeof o=="function"&&(this[r]=o.bind(this))}}emitWarning(t,r,o){console.warn(${o?[${o}] :""}${r?${r}: :""}${t})}emit(...t){return super.emit(...t)}listeners(t){return super.listeners(t)}#t;#r;#o;get stdin(){return this.#t??=new Dt(0)}get stdout(){return this.#r??=new Ke(1)}get stderr(){return this.#o??=new Ke(2)}#e="/";chdir(t){this.#e=t}cwd(){return this.#e}arch="";platform="";argv=[];argv0="";execArgv=[];execPath="";title="";pid=200;ppid=100;get version(){returnv${$t}}get versions(){return{node:$t}}get allowedNodeEnvironmentFlags(){return new Set}get sourceMapsEnabled(){return!1}get debugPort(){return 0}get throwDeprecation(){return!1}get traceDeprecation(){return!1}get features(){return{}}get release(){return{}}get connected(){return!1}get config(){return{}}get moduleLoadList(){return[]}constrainedMemory(){return 0}availableMemory(){return 0}uptime(){return 0}resourceUsage(){return{}}ref(){}unref(){}umask(){throw T("process.umask")}getBuiltinModule(){}getActiveResourcesInfo(){throw T("process.getActiveResourcesInfo")}exit(){throw T("process.exit")}reallyExit(){throw T("process.reallyExit")}kill(){throw T("process.kill")}abort(){throw T("process.abort")}dlopen(){throw T("process.dlopen")}setSourceMapsEnabled(){throw T("process.setSourceMapsEnabled")}loadEnvFile(){throw T("process.loadEnvFile")}disconnect(){throw T("process.disconnect")}cpuUsage(){throw T("process.cpuUsage")}setUncaughtExceptionCaptureCallback(){throw T("process.setUncaughtExceptionCaptureCallback")}hasUncaughtExceptionCaptureCallback(){throw T("process.hasUncaughtExceptionCaptureCallback")}initgroups(){throw T("process.initgroups")}openStdin(){throw T("process.openStdin")}assert(){throw T("process.assert")}binding(){throw T("process.binding")}permission={has:Z("process.permission.has")};report={directory:"",filename:"",signal:"SIGUSR2",compact:!1,reportOnFatalError:!1,reportOnSignal:!1,reportOnUncaughtException:!1,getReport:Z("process.report.getReport"),writeReport:Z("process.report.writeReport")};finalization={register:Z("process.finalization.register"),unregister:Z("process.finalization.unregister"),registerBeforeExit:Z("process.finalization.registerBeforeExit")};memoryUsage=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0});mainModule=void 0;domain=void 0;send=void 0;exitCode=void 0;channel=void 0;getegid=void 0;geteuid=void 0;getgid=void 0;getgroups=void 0;getuid=void 0;setegid=void 0;seteuid=void 0;setgid=void 0;setgroups=void 0;setuid=void 0;_events=void 0;_eventsCount=void 0;_exiting=void 0;_maxListeners=void 0;_debugEnd=void 0;_debugProcess=void 0;_fatalException=void 0;_getActiveHandles=void 0;_getActiveRequests=void 0;_kill=void 0;_preload_modules=void 0;_rawDebug=void 0;_startProfilerIdleNotifier=void 0;_stopProfilerIdleNotifier=void 0;_tickCallback=void 0;_disconnect=void 0;_handleQueue=void 0;_pendingMessage=void 0;_channel=void 0;_send=void 0;_linkedBinding=void 0},be=Object.create(null),Vo=globalThis.process,ee=e=>globalThis.__env__||Vo?.env||(e?be:globalThis),Ho=new Proxy(be,{get(e,t){return ee()[t]??be[t]},has(e,t){let r=ee();return t in r||t in be},set(e,t,r){let o=ee(!0);return o[t]=r,!0},deleteProperty(e,t){let r=ee(!0);return delete r[t],!0},ownKeys(){let e=ee();return Object.keys(e)},getOwnPropertyDescriptor(e,t){let r=ee();if(t in r)return{value:r[t],writable:!0,enumerable:!0,configurable:!0}}}),zo=Object.assign(function(e){let t=Date.now(),r=Math.trunc(t/1e3),o=t%1e3*1e6;if(e){let n=r-e[0],i=o-e[0];return i<0&&(n=n-1,i=1e9+i),[n,i]}return[r,o]},{bigint:function(){return BigInt(Date.now()*1e6)}}),Yo=globalThis.queueMicrotask?(e,...t)=>{globalThis.queueMicrotask(e.bind(void 0,...t))}:Qo();function Qo(){let e=[],t=!1,r,o=-1;function n(){!t||!r||(t=!1,r.length>0?e=[...r,...e]:o=-1,e.length>0&&i())}function i(){if(t)return;let s=setTimeout(n);t=!0;let l=e.length;for(;l;){for(r=e,e=[];++o<l;)r&&r[o]();o=-1,l=e.length}r=void 0,t=!1,clearTimeout(s)}return(s,...l)=>{e.push(s.bind(void 0,...l)),e.length===1&&!t&&setTimeout(i)}}var Wt=new qo({env:Ho,hrtime:zo,nextTick:Yo}),ce=Wt,{abort:Bs,addListener:Ds,allowedNodeEnvironmentFlags:$s,hasUncaughtExceptionCaptureCallback:Gs,setUncaughtExceptionCaptureCallback:Ws,loadEnvFile:qs,sourceMapsEnabled:Vs,arch:Hs,argv:zs,argv0:Ys,chdir:Qs,config:Ks,connected:Js,constrainedMemory:Xs,availableMemory:Zs,cpuUsage:ei,cwd:ti,debugPort:ri,dlopen:oi,disconnect:ni,emit:si,emitWarning:ii,env:ai,eventNames:li,execArgv:ci,execPath:ui,exit:pi,finalization:fi,features:mi,getBuiltinModule:di,getActiveResourcesInfo:gi,getMaxListeners:hi,hrtime:Ei,kill:yi,listeners:Ri,listenerCount:wi,memoryUsage:bi,nextTick:_i,on:Ti,off:xi,once:Oi,pid:vi,platform:Si,ppid:Ni,prependListener:ki,prependOnceListener:Li,rawListeners:Pi,release:Ai,removeAllListeners:Fi,removeListener:Ii,report:Mi,resourceUsage:Ui,setMaxListeners:Ci,setSourceMapsEnabled:ji,stderr:Bi,stdin:Di,stdout:$i,title:Gi,umask:Wi,uptime:qi,version:Vi,versions:Hi,domain:zi,initgroups:Yi,moduleLoadList:Qi,reallyExit:Ki,openStdin:Ji,assert:Xi,binding:Zi,send:ea,exitCode:ta,channel:ra,getegid:oa,geteuid:na,getgid:sa,getgroups:ia,getuid:aa,setegid:la,seteuid:ca,setgid:ua,setgroups:pa,setuid:fa,permission:ma,mainModule:da,ref:ga,unref:ha,_events:Ea,_eventsCount:ya,_exiting:Ra,_maxListeners:wa,_debugEnd:ba,_debugProcess:_a,_fatalException:Ta,_getActiveHandles:xa,_getActiveRequests:Oa,_kill:va,_preload_modules:Sa,_rawDebug:Na,_startProfilerIdleNotifier:ka,_stopProfilerIdleNotifier:La,_tickCallback:Pa,_disconnect:Aa,_handleQueue:Fa,_pendingMessage:Ia,_channel:Ma,_send:Ua,_linkedBinding:Ca}=Wt;var Ko=Object.create,Qt=Object.defineProperty,Jo=Object.getOwnPropertyDescriptor,Xo=Object.getOwnPropertyNames,Zo=Object.getPrototypeOf,en=Object.prototype.hasOwnProperty,Kt=(e=>typeof q<"u"?q:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof q<"u"?q:t)[r]}):e)(function(e){if(typeof q<"u")return q.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Jt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Xo(t))!en.call(e,n)&&n!==r&&Qt(e,n,{get:()=>t[n],enumerable:!(o=Jo(t,n))||o.enumerable});return e},Xt=(e,t,r)=>(r=e!=null?Ko(Zo(e)):{},tn(t||!e||!e.__esModule?Qt(r,"default",{value:e,enumerable:!0}):r,e)),rn=Jt((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ce&&"node"in ce.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Kt][0](${"node","util".join(":")})}catch{r=null}t.exports=r}),on=Jt((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ce&&"node"in ce.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Kt][0](${"node","fs".join(":")})}catch{r=null}t.exports=r}),nn={},_e=sn(globalThis,nn);function sn(e,t){return new Proxy(e,{get(r,o,n){return o in t?t[o]:e[o]},set(r,o,n){return o in t&&delete t[o],e[o]=n,!0},deleteProperty(r,o){let n=!1;return o in t&&(delete t[o],n=!0),o in e&&(delete e[o],n=!0),n},ownKeys(r){let o=Reflect.ownKeys(e),n=Reflect.ownKeys(t),i=new Set(n);return[...o.filter(s=>!i.has(s)),...n]},defineProperty(r,o,n){return o in t&&delete t[o],Reflect.defineProperty(e,o,n),!0},getOwnPropertyDescriptor(r,o){return o in t?Reflect.getOwnPropertyDescriptor(t,o):Reflect.getOwnPropertyDescriptor(e,o)},has(r,o){return o in t||o in e}})}var qt=["debug","info","warning","error","fatal"];function Vt(e,t){let r=qt.indexOf(e);if(r<0)throw new TypeError(Invalid log level: ${JSON.stringify(e)}.);let o=qt.indexOf(t);if(o<0)throw new TypeError(Invalid log level: ${JSON.stringify(t)}.);return r-o}function ue(e=[]){return Zt.getLogger(e)}var Je=Symbol.for("logtape.rootLogger"),Zt=class ${static getLogger(t=[]){let r=Je in _e?_e[Je]??null:null;return r==null&&(r=new $(null,[]),_e[Je]=r),typeof t=="string"?r.getChild(t):t.length===0?r:r.getChild(t)}constructor(t,r){Object.defineProperty(this,"parent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"children",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"category",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sinks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parentSinks",{enumerable:!0,configurable:!0,writable:!0,value:"inherit"}),Object.defineProperty(this,"filters",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lowestLevel",{enumerable:!0,configurable:!0,writable:!0,value:"debug"}),Object.defineProperty(this,"contextLocalStorage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.parent=t,this.children={},this.category=r,this.sinks=[],this.filters=[]}getChild(t){let r=typeof t=="string"?t:t[0],o=this.children[r],n=o instanceof $?o:o?.deref();return n==null&&(n=new $(this,[...this.category,r]),this.children[r]="WeakRef"in _e?new WeakRef(n):n),typeof t=="string"||t.length===1?n:n.getChild(t.slice(1))}reset(){for(;this.sinks.length>0;)this.sinks.shift();for(this.parentSinks="inherit";this.filters.length>0;)this.filters.shift();this.lowestLevel="debug"}resetDescendants(){for(let t of Object.values(this.children))(t instanceof $?t:t.deref())?.resetDescendants();this.reset()}with(t){return new an(this,{...t})}filter(t){for(let r of this.filters)if(!r(t))return!1;return this.filters.length<1?this.parent?.filter(t)??!0:!0}*getSinks(t){if(!(this.lowestLevel===null||Vt(t,this.lowestLevel)<0)){if(this.parent!=null&&this.parentSinks==="inherit")for(let r of this.parent.getSinks(t))yield r;for(let r of this.sinks)yield r}}emit(t,r){if(!(this.lowestLevel===null||Vt(t.level,this.lowestLevel)<0||!this.filter(t))){for(let o of this.getSinks(t.level))if(!r?.has(o))try{o(t)}catch(n){let i=new Set(r);i.add(o),ln.log("fatal","Failed to emit a log record to sink {sink}: {error}",{sink:o,error:n,record:t},i)}}}log(t,r,o,n){let i=$.getLogger().contextLocalStorage?.getStore()??{},s,l=typeof o=="function"?{category:this.category,level:t,timestamp:Date.now(),get message(){return Ht(r,this.properties)},rawMessage:r,get properties(){return s==null&&(s={...i,...o()}),s}}:{category:this.category,level:t,timestamp:Date.now(),message:Ht(r,{...i,...o}),rawMessage:r,properties:{...i,...o}};this.emit(l,n)}logLazily(t,r,o={}){let n=$.getLogger().contextLocalStorage?.getStore()??{},i,s;function l(){if((s==null||i==null)&&(s=r((a,...c)=>(i=a,zt(a,c))),i==null))throw new TypeError("No log record was made.");return[s,i]}this.emit({category:this.category,level:t,get message(){return l()[0]},get rawMessage(){return l()[1]},timestamp:Date.now(),properties:{...n,...o}})}logTemplate(t,r,o,n={}){let i=$.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:t,message:zt(r,o),rawMessage:r,timestamp:Date.now(),properties:{...i,...n}})}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},an=class er{constructor(t,r){Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.logger=t,this.properties=r}get category(){return this.logger.category}get parent(){return this.logger.parent}getChild(t){return this.logger.getChild(t).with(this.properties)}with(t){return new er(this.logger,{...this.properties,...t})}log(t,r,o,n){this.logger.log(t,r,typeof o=="function"?()=>({...this.properties,...o()}):{...this.properties,...o},n)}logLazily(t,r){this.logger.logLazily(t,r,this.properties)}logTemplate(t,r,o){this.logger.logTemplate(t,r,o,this.properties)}debug(t,...r){typeof t=="string"?this.log("debug",t,r[0]??{}):typeof t=="function"?this.logLazily("debug",t):this.logTemplate("debug",t,r)}info(t,...r){typeof t=="string"?this.log("info",t,r[0]??{}):typeof t=="function"?this.logLazily("info",t):this.logTemplate("info",t,r)}warn(t,...r){typeof t=="string"?this.log("warning",t,r[0]??{}):typeof t=="function"?this.logLazily("warning",t):this.logTemplate("warning",t,r)}error(t,...r){typeof t=="string"?this.log("error",t,r[0]??{}):typeof t=="function"?this.logLazily("error",t):this.logTemplate("error",t,r)}fatal(t,...r){typeof t=="string"?this.log("fatal",t,r[0]??{}):typeof t=="function"?this.logLazily("fatal",t):this.logTemplate("fatal",t,r)}},ln=Zt.getLogger(["logtape","meta"]);function Ht(e,t){let r=[],o="";for(let n=0;n<e.length;n++){let i=e.charAt(n),s=e.charAt(n+1);if(i==="{"&&s==="{")o=o+i,n++;else if(i==="}"&&s==="}")o=o+i,n++;else if(i==="{")r.push(o),o="";else if(i==="}"){let l;o.match(/^\s|\s$/)?l=o in t?t[o]:t[o.trim()]:l=t[o],r.push(l),o=""}else o=o+i}return r.push(o),r}function zt(e,t){let r=[];for(let o=0;o<e.length;o++)r.push(e[o]),o<t.length&&r.push(t[o]);return r}var cn=Xt(rn()),Te=cn.default,Yt={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},tr="Deno"in globalThis&&"inspect"in globalThis.Deno&&typeof globalThis.Deno.inspect=="function"?(e,t)=>globalThis.Deno.inspect(e,{strAbbreviateSize:1/0,iterableLimit:1/0,...t}):Te!=null&&"inspect"in Te&&typeof Te.inspect=="function"?(e,t)=>Te.inspect(e,{maxArrayLength:1/0,maxStringLength:1/0,...t}):e=>JSON.stringify(e);function rr(e={}){let t=e.timestamp==null||e.timestamp==="date-time-timezone"?s=>new Date(s).toISOString().replace("T"," ").replace("Z"," +00:00"):e.timestamp==="date-time-tz"?s=>new Date(s).toISOString().replace("T"," ").replace("Z"," +00"):e.timestamp==="date-time"?s=>new Date(s).toISOString().replace("T"," ").replace("Z",""):e.timestamp==="time-timezone"?s=>new Date(s).toISOString().replace(/.*T/,"").replace("Z"," +00:00"):e.timestamp==="time-tz"?s=>new Date(s).toISOString().replace(/.*T/,"").replace("Z"," +00"):e.timestamp==="time"?s=>new Date(s).toISOString().replace(/.*T/,"").replace("Z",""):e.timestamp==="date"?s=>new Date(s).toISOString().replace(/T.*/,""):e.timestamp==="rfc3339"?s=>new Date(s).toISOString():e.timestamp,r=e.category??"·",o=e.value??tr,n=e.level==null||e.level==="ABBR"?s=>Yt[s]:e.level==="abbr"?s=>Yt[s].toLowerCase():e.level==="FULL"?s=>s.toUpperCase():e.level==="full"?s=>s:e.level==="L"?s=>s.charAt(0).toUpperCase():e.level==="l"?s=>s.charAt(0):e.level,i=e.format??(({timestamp:s,level:l,category:a,message:c})=>${s} ${l} ${a}: ${c});return s=>{let l="";for(let u=0;u<s.message.length;u++)u%2===0?l+=s.message[u]:l+=o(s.message[u]);let a=t(s.timestamp),c=n(s.level),p=typeof r=="function"?r(s.category):s.category.join(r);return${i({timestamp:a,level:c,category:p,message:l,record:s})}
}}var Da=rr(),Xe="\x1B[0m",Ze={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},et={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},un={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function pn(e={}){let t=e.format,r=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=${r==null?"":etr}${o==null?"":Zeo},i=r==null&&o==null?"":Xe,s=typeof e.levelStyle>"u"?"bold":e.levelStyle,l=e.levelColors??un,a=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,c=e.categoryColor??null,p=${a==null?"":eta}${c==null?"":Zec},u=a==null&&c==null?"":Xe;return rr({timestamp:"date-time-tz",value(f){return tr(f,{colors:!0})},...e,format({timestamp:f,level:m,category:g,message:w,record:_}){let A=l[_.level];return f=${n}${f}${i},m=${s==null?"":ets}${A==null?"":ZeA}${m}${s==null&&A==null?"":Xe},t==null?${f} ${m} ${p}${g}:${u} ${w}:t({timestamp:f,level:m,category:${p}${g}${u},message:w,record:_})}})}var $a=pn();var fn=Xt(on()),mn=fn.default;function te(){throw new Error("File sink is not available in the browser.")}var dn={openSync:te,writeSync:te,flushSync:te,closeSync:te,statSync:te,renameSync:te},Y=mn,Ga=Y==null?dn:{openSync(e){return Y.openSync(e,"a")},writeSync:Y.writeSync,flushSync:Y.fsyncSync,closeSync:Y.closeSync,statSync:Y.statSync,renameSync:Y.renameSync};var or=" must not return ",gn="transformer",hn="recoverer",En="defaultValue",re=gn+or,j="called with ",oe=En+" must not be ",ne=hn+or;var yn="Ok",nr="Err",sr=j+nr,ir=j+yn,Rn="Carrying E in "+nr+" instead of throwing it directly. See .cause",tt="an instance of Error of the current realm.",Ka="The thrown value is not "+tt,Ja="The contained E should be "+tt,wn="This .cause is not "+tt;function R(e){return e.ok}function h(e){return{ok:!0,val:e,err:null}}function d(e){return!e.ok}function x(e){return{ok:!1,val:null,err:e}}function E(e){return ar(e,sr)}function se(e){return lr(e,ir)}function ar(e,t){if(d(e))throw new TypeError(t);return e.val}function lr(e,t){if(R(e))throw new TypeError(t);return e.err}function k(e){return e.val}function L(e){return e.err}async function O(e,t){if(d(e))return e;let r=k(e),o=await t(r);return h(o)}async function v(e,t){if(R(e))return e;let r=L(e),o=await t(r);return x(o)}var xe="null",uc=re+xe,Tn=j+xe,pc=oe+xe,fc=ne+xe;var Oe="undefined",Ec=re+Oe,xn=j+Oe,yc=oe+Oe,Rc=ne+Oe;var S=e=>e.ok?h(e):x({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var pr=async(e,t)=>{let r=new Request(e,t);try{return h(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return x({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return x({name:"NetworkError",message:o.message,request:r});throw o}};var b=e=>{let{fetch:t=pr,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var N=e=>connect.sid=${e};function ve(e,t={}){if(e===null)return"null";if(Array.isArray(e))return Nn(e,t);switch(typeof e){case"string":return JSON.stringify(e);case"bigint":return${e}n;case"object":return e.constructor?.name!=="Object"?e.constructor?.name:kn(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function Nn(e,t){let{threshold:r=20}=t,o=e.map(s=>ve(s,t)),n=o.join(", ");if(n.length<=r)return${n};let i=o.join(,
);return[
${fr(2,i)}
]}function kn(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(s=>${s.toString()}: ${ve(es,t)}),n=o.join(", ");if(n.length<=r)return{${n}};let i=o.join(,
);return{
${fr(2,i)}
}}function fr(e,t){let r=" ".repeat(e);return t.split(
).map(o=>${r}${o}).join(
)}function Se(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=${t}(${r.map(n=>ve(n)).join(", ")}),o)}})}function mr(e){return Array.isArray(e)}function dr(e){return Se(t=>mr(t)&&t.every(r=>e(r)),"isArrayOf",e)}function rt(e){let t=new Set(e);return Se(r=>t.has(r),"isLiteralOneOf",e)}function ot(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function Ne(e){return typeof e=="string"}var P=async(e,t)=>{let r=e.response.clone(),o=rt(t);try{let n=await r.json();if(!ot(n))return;if(r.status===422){if(!Ne(n.message))return;for(let i of["NoQueryError","InvalidURLError"])if(t.includes(i))return{name:i,message:n.message}}return!o(n.name)||!Ne(n.message)?void 0:n.name==="NotLoggedInError"?!ot(n.detals)||!Ne(n.detals.project)||!dr(Ln)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},Ln=rt(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var pe=e=>e.replaceAll(" ","_").toLowerCase(),gr=e=>e.replaceAll("_"," ");var ke="null or undefined",ie=re+ke,Pn=j+ke,nt=oe+ke,Le=ne+ke;var Er=(e,t)=>{let{sid:r,hostName:o}=b(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:N(r)}}:void 0)},yr=async e=>O(await v(S(e),async t=>await P(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),br=(()=>{let e=async(t,r)=>{let{fetch:o}=b(r??{}),n=Er(t,r),i=await o(n);return d(i)?i:yr(E(i))};return e.toRequest=Er,e.fromResponse=yr,e})(),Rr=(e,t)=>{let{sid:r,hostName:o}=b(t??{}),n=new URLSearchParams(e.map(i=>["ids",i]));return new Request(https://${o}/api/projects?${n},r?{headers:{Cookie:N(r)}}:void 0)},wr=async e=>O(await v(S(e),async t=>await P(t,["NotLoggedInError"])??t),t=>t.json()),_r=(()=>{let e=async(t,r)=>{let{fetch:o}=b(r??{}),n=await o(Rr(t,r));return d(n)?n:wr(E(n))};return e.toRequest=Rr,e.fromResponse=wr,e})();var Tr=(e,t)=>{let{sid:r,hostName:o,followingId:n}=b(t??{});return new Request(https://${o}/api/pages/${e}/search/titles${n??followingId=${n}:""},r?{headers:{Cookie:N(r)}}:void 0)},xr=async e=>O(await v(S(e),async t=>t.response.status===422?{name:"InvalidFollowingIdError",message:await t.response.text()}:await P(t,["NotFoundError","NotLoggedInError"])??t),t=>t.json().then(r=>({pages:r,followingId:t.headers.get("X-following-id")??""}))),In=(()=>{let e=async(t,r)=>{let o=await b(r??{}).fetch(Tr(t,r));return d(o)?o:xr(E(o))};return e.toRequest=Tr,e.fromResponse=xr,e})();async function*Or(e,t){let r;do{let o=await In(e,{followingId:r,...t});if(d(o)){yield o;return}let n=E(o);yield h(n.pages),r=n.followingId}while(r)}var Mn=new TextEncoder().encode("0123456789abcdef"),vr=new Uint8Array(128).fill(16);Mn.forEach((e,t)=>vr[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>vr[e]=t+10);var Un=new TextEncoder().encode("0123456789abcdef"),Sr=new Uint8Array(128).fill(16);Un.forEach((e,t)=>Sr[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>Sr[e]=t+10);async function*Nr(e){let t=[],r=[],o=new Map,n=[];for(let i of e)i.isValid&&(i.id?i.isMember||t.push(i.id):r.push(i.name),n.push(i.name),o.set(i.name,i.checked));for(let i=0;i<t.length;i+=50){let s=t.slice(i,i+50);if(s.length===0)break;s.length===1&&s.push(s[0]);let l=await _r(s);if(d(l)){r=n;break}for(let a of E(l).projects)o.has(a.name)&&(yield h({...a,checked:o.get(a.name)??0}))}for(let i of r){let s=await br(i);yield R(s)?h({...E(s),checked:o.get(i)??0}):x({...se(s),project:i})}}var at=(e,t)=>t.some(r=>e instanceof r),kr,Lr;function Cn(){return kr||(kr=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function jn(){return Lr||(Lr=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var lt=new WeakMap,st=new WeakMap,Ae=new WeakMap;function Bn(e){let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{r(W(e.result)),n()},s=()=>{o(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",s)});return Ae.set(t,e),t}function Dn(e){if(lt.has(e))return;let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{r(),n()},s=()=>{o(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)});lt.set(e,t)}var ct={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return lt.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return W(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function Ir(e){ct=e(ct)}function $n(e){return jn().includes(e)?function(...t){return e.apply(ut(this),t),W(this.request)}:function(...t){return W(e.apply(ut(this),t))}}function Gn(e){return typeof e=="function"?$n(e):(e instanceof IDBTransaction&&Dn(e),at(e,Cn())?new Proxy(e,ct):e)}function W(e){if(e instanceof IDBRequest)return Bn(e);if(st.has(e))return st.get(e);let t=Gn(e);return t!==e&&(st.set(e,t),Ae.set(t,e)),t}var ut=e=>Ae.get(e);function Mr(e,t,{blocked:r,upgrade:o,blocking:n,terminated:i}={}){let s=indexedDB.open(e,t),l=W(s);return o&&s.addEventListener("upgradeneeded",a=>{o(W(s.result),a.oldVersion,a.newVersion,W(s.transaction),a)}),r&&s.addEventListener("blocked",a=>r(a.oldVersion,a.newVersion,a)),l.then(a=>{i&&a.addEventListener("close",()=>i()),n&&a.addEventListener("versionchange",c=>n(c.oldVersion,c.newVersion,c))}).catch(()=>{}),l}function Ur(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",o=>t(o.oldVersion,o)),W(r).then(()=>{})}var Wn=["get","getKey","getAll","getAllKeys","count"],qn=["put","add","delete","clear"],it=new Map;function Pr(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(it.get(t))return it.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,n=qn.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(n||Wn.includes(r)))return;let i=async function(s,...l){let a=this.transaction(s,n?"readwrite":"readonly"),c=a.store;return o&&(c=c.index(l.shift())),(await Promise.all([c[r](...l),n&&a.done]))[0]};return it.set(t,i),i}Ir(e=>({...e,get:(t,r,o)=>Pr(t,r)||e.get(t,r,o),has:(t,r)=>!!Pr(t,r)||e.has(t,r)}));var Vn=["continue","continuePrimaryKey","advance"],Ar={},pt=new WeakMap,Cr=new WeakMap,Hn={get(e,t){if(!Vn.includes(t))return e[t];let r=Ar[t];return r||(r=Ar[t]=function(...o){pt.set(this,Cr.get(this)[t](...o))}),r}};async function*zn(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,Hn);for(Cr.set(r,t),Ae.set(r,ut(t));t;)yield r,t=await(pt.get(r)||t.continue()),pt.delete(r)}function Fr(e,t){return t===Symbol.asyncIterator&&at(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&at(e,[IDBIndex,IDBObjectStore])}Ir(e=>({...e,get(t,r,o){return Fr(t,r)?zn:e.get(t,r,o)},has(t,r){return Fr(t,r)||e.has(t,r)}}));var jr,ft=async()=>{let e=ue(["@takker/cosense-storage","open"]);return jr??=await Mr("scrapbox-storage",4,{upgrade(t,r,o){e.infostart updating DB: ${r} -> ${o};let n=Date.now();for(let l of t.objectStoreNames)t.deleteObjectStore(l);t.createObjectStore("titles",{keyPath:"id"}).createIndex("project","project");let s=t.createObjectStore("projects",{keyPath:"id"});s.createIndex("checked","checked"),s.createIndex("name","name"),e.infofinish updating DB: ${Date.now()-n}ms},blocked(t,r){let o=The database "@takker/cosense-storage"(v${r}) is blocked because the older one (v${t}) is opened in other tabs.
Please close the other tabs and reload this page.;e.error(o),alert(o)},blocking(t,r){let o=The database "@takker/cosense-storage"(v${t}) is blocking the newer one (v${r}) opened.
Please close this page.;e.error(o),alert(o)}}),jr};var Br=(e,t)=>(mt||(mt=new BroadcastChannel($r),mt.addEventListener("message",r=>Dr(r.data))),Fe.set(t,new Set(e).union(Fe.get(t)??new Set)),()=>Fe.delete(t)),dt=(e,t)=>{if((t.added?.size??0)+(t.updated?.size??0)+(t.deleted?.size??0)===0)return;let r={type:"links:changed",project:e,diff:t};Dr(r);let o=new BroadcastChannel($r);o.postMessage(r),o.close()},Dr=e=>{for(let[t,r]of Fe)r.has(e.project)&&t(e)},$r="scrapbox-storage-notify",mt,Fe=new Map;var Yn=Math.pow(10,8)*24*60*60*1e3,Vh=-Yn;var Qn=3600;var Gr=Qn*24,Hh=Gr*7,Kn=Gr*365.2425,Jn=Kn/12,zh=Jn*3,gt=Symbol.for("constructDateFrom");function Wr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&gt in e?e[gt](t):e instanceof Date?new e.constructor(t):new Date(t)}function qr(e,t){return Wr(t||e,e)}function ht(e){return Math.trunc(+qr(e)/1e3)}var Vr=async(e,t)=>{let r=await ft(),o=ue(["@takker/cosense-storage","check"]),n=new Map;try{{o.debugcheck updates of links...;let s=new Set,l=r.transaction("projects","readwrite"),a=ht(new Date),c=a-600;for await(let f of l.store.index("checked").iterate(IDBKeyRange.lowerBound(c,!0))){let m=f.value;if(m.isValid===!1){s.add(m.id);continue}s.add(m.name);let g=m.checked;if(g+t>a||m?.updating&&g>c)continue;let w=structuredClone(m);w.updating=!0,n.set(m.id,w),f.update(w)}let p=[],u=l.store.index("name");for(let f of e)s.has(f)||p.push(u.get(f).then(m=>{m?.updating&&(m?.checked??0)>c||n.set(f,m??Xn(f))}));if(await Promise.all(p),await l.done,n.size===0){o.debugchecked. No project needs upgrade.;return}o.debugchecked. ${n.size} projects maybe need upgrade.}let i=ht(new Date);for await(let s of Nr(n.values())){if(d(s)){let{project:g,name:w}=se(s);switch(w){default:continue;case"NotFoundError":o.warn("${g}" is not found.);break;case"NotMemberError":o.warn(You are not a member of "${g}".);break;case"NotLoggedInError":o.warn(You are not a member of "${g}" or You are not logged in yet.);break}n.set(g,{id:g,name:g,checked:i,updating:!1,isValid:!1,reason:w});continue}let{checked:l,...a}=E(s);if(a.updated<l){o.debugno updates in "${a.name}",n.set(a.name,{...a,isValid:!0,checked:i,updating:!1});continue}o.debugstart downloading and storing links of "${a.name}";let c=new Set(await r.getAllKeysFromIndex("titles","project",a.name)),p=0,u=0;for await(let g of Or(a.name)){if(d(g)){let{name:I,message:F}=se(g);o.errorFailed to get links of "${a.name}" with ${I}: ${F};break}let w=E(g),_={},A=r.transaction("titles","readwrite");await Promise.all(w.map(async I=>{let F={...I,project:a.name},C=await A.store.get(I.id);if(!C)return _.added?.set?.(I.id,F)??(_.added=new Map([[I.id,F]])),A.store.add(F);if(c.delete(I.id),!!Zn(F,C))return _.updated?.set?.(I.id,[C,F])??(_.updated=new Map([[I.id,[C,F]]])),A.store.put(F)})),await A.done,p+=_.added?.size??0,u+=_.updated?.size??0,o.debugUpdating "/${a.name}": +${p} pages, ~${u} pages,dt(a.name,_)}let f=r.transaction("titles","readwrite"),m=new Map((await Promise.all([...c].map(async g=>{let w=await f.store.get(g);if(!w)return[];let _=[[g,w]];return await f.store.delete(g),_}))).flat());await f.done,o.debugFinish downloading and storing links of "${a.name}",o.debugUpdate "/${a.name}": +${p} pages, ~${u} pages, -${m.size} pages,n.set(a.name,{...a,isValid:!0,checked:i,updating:!1}),dt(a.name,{deleted:m})}}finally{let i=r.transaction("projects","readwrite");await Promise.all([...n].map(([,s])=>(s.updating=!1,i.store.put({...s})))),await i.done}},Hr=async e=>{let t=[...new Set(e)];if(t.length===0)return[];let r=Date.now(),n=(await ft()).transaction("titles","readonly"),i=n.store.index("project"),s=(await Promise.all(t.map(a=>i.getAll(a)))).flat();return await n.done,ue(["@takker/cosense-storage","load"]).debugRead ${s.length} links from ${t.length} projects in ${Date.now()-r}ms,s},Xn=e=>({name:e,displayName:e,id:"",isValid:!0,publicVisible:!0,isMember:!0,loginStrategies:[],theme:"default",gyazoTeamsName:null,translation:!0,infobox:!0,checked:0,updated:0,created:0,updating:!0}),Zn=(e,t)=>e.updated>t.updated||e.links.sort().join()!==t.links.sort().join();globalThis.Deno||Ur("userscript-links").catch(e=>console.error(e));var zr=e=>{let t=new Map,r=[...e].reverse();{let s=1;for(let l of r){t.set(l,(t.get(l)??0)|s);let a=l.toLowerCase();t.set(a,(t.get(a)??0)|s);let c=l.toUpperCase();t.set(c,(t.get(c)??0)|s),s<<=1}}let o=r.length,n=~(-1<<o),i=1<<o-1;return s=>{let l=0,a=n,c=[...s].reverse(),p=[],u=c.length;p[u]=o;for(let f of c){let m=t.get(f)??0,g=m|l,w=(m&a)+a^a|m,_=l|~(w|a),A=a&w;p[u-1]=p[u]+(_&i?1:A&i?-1:0),a=A<<1|~(g|_<<1),l=_<<1&g,u--}return p}};var es=[0,0,0,1,1,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6],Yr=e=>{let t=gr(e.trim()).split(/\s+/).sort((r,o)=>o.length-r.length);if(!(t.length===0||t.every(r=>r==="")))return r=>t.reduce((o,n)=>ts(n,o),r)},ts=(e,t)=>{let r=[...e].length,o=es[r],n=zr(e);return t.flatMap(({title:i,dist:s,matches:l,...a})=>{l??=[],s??=0;let c=n(i).flatMap((u,f)=>u<=o&&l.every(([m,g])=>f+r<=m||g<f)?[[f,u]]:[]);if(c.length===0)return[];let p=c.reduce((u,[f,m])=>(u.dist<=m||(u.dist=m,u.start=f),u),{dist:r,start:0});return l.push([p.start,p.start+r-1]),[{title:i,dist:p.dist+s,matches:l,...a}]})};var Kr=e=>{let t=new Map;for(let r of e)Et(t,r);return t},Jr=(e,t)=>{let r=new Map(e);if(t.added)for(let[,o]of t.added)Et(r,o);if(t.updated)for(let[,[o,n]]of t.updated)Qr(r,o),Et(r,n);if(t.deleted)for(let[,o]of t.deleted)Qr(r,o);return r},Et=(e,t)=>{let r=pe(t.title),o=e.get(r);if((o?.updated??0)>t.updated)return;let n=o?.metadata??new Map;n.set(t.project,{image:t.image}),e.set(r,{title:t.title,titleLc:r,updated:t.updated,linked:o?.linked??0,metadata:n});for(let i of t.links){let s=pe(i),l=e.get(s),a=l?.metadata??new Map;a.set(t.project,a.get(t.project)??{image:t.image}),e.set(s,{title:l?.title??i,titleLc:s,updated:l?.updated??0,linked:(l?.linked??0)+1,metadata:a})}},Qr=(e,t)=>{let r=pe(t.title),o=e.get(r);if(!o||(o.updated??0)>t.updated)return;let n=o.metadata;n.delete(t.project),n.size<=0?e.delete(r):e.set(r,{title:o.title,titleLc:r,updated:t.updated,linked:o.linked,metadata:n});for(let i of t.links){let s=pe(i),l=e.get(s);if(!l)continue;let a=l.metadata;a.delete(t.project),a.size<=0?e.delete(s):e.set(s,{title:l.title,titleLc:s,updated:t.updated,linked:l.linked-1,metadata:a})}};var yt=Nt("scrapbox-select-suggestion:search.worker.ts"),Ie=[],Xr=[],Zr=()=>{},rs={async load(e){if(yt.debug("start loading source"),!Rt(Xr,e)){Xr=[...e],Zr();let r=await Hr(e),o=Kr(r);Ie=[...o.values()],await Vr(e,600),Zr=Br(e,({diff:n})=>{o=Jr(o,n),Ie=[...o.values()]})}return Ie.length},async search(e,t,r){if(yt.debug("start searching: ",e),!e.trim())return;let o=Yr(e);if(!o){r([],1);return}let n=[...Ie],i=Math.ceil(n.length/t);for(let s=0;s<i;s++){let l=(s+1)/i,a=[...o(n.values().drop(s*t).take(t))];if(yt.debug(${s}/${i} search result:`,a),await r(a,l))return;await wt(0)}}};self.addEventListener("connect",e=>Ee(rs,e.ports0));
/*! Bundled license information:
comlink/dist/esm/comlink.mjs:
(**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*)
*/
code:takker-project.css
@import"https://fonts.googleapis.com/css?family=M+PLUS+Rounded+1c";html,body,#editor,.grid li{font-family:helvetica,arial,"M PLUS Rounded 1c",Sawarabi Gothic,Noto Sans JP,sans-serif}body *:before{--code-number-color: var(--code-color, #342d9c)}.section-title{counter-reset:codeline}.code-block span.indent code.code-body{counter-increment:codeline;margin-left:-1.5em;padding-left:2.3em}.code-block span.indent code.code-body:before{content:counter(codeline);position:absolute;display:inline-block;z-index:10;margin-left:-2.4em;width:2em;padding-right:.2em;text-align:right;vertical-align:bottom;border-right:solid 1px #fff;color:var(--code-number-color)}.code-block span.indent code.code-body:before{opacity:.5}.cursor-line .code-block span.indent code.code-body:before{opacity:1;font-weight:bolder;background-color:var(--accent-color)}.navbar-form .dropdown.open .dropdown-menu{min-width:100%;max-height:calc(100vh - 130px)!important;overflow-y:auto}.page-list-item.pin+.page-list-item:not(.pin){grid-column-start:1}.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):not([href^="https://scrapbox.io"]):after{font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";font-weight:900;font-size:.8rem;content:" ";display:inline-block}.line .deco-\.{font-size:.8em;position:relative;top:-.5em}.line:not(.cursor-line) .deco-\. a:is(.page-link:not(.icon),.link) span:not(.empty-char-index)+span+span~span{display:inline-block;width:0;text-indent:-9999px}.line:not(.cursor-line) .deco-\. .page-link:not(.icon) span.empty-char-index~span.char-index{display:inherit;width:inherit;text-indent:inherit}.line:not(.cursor-line) .deco-\. a.page-link:not(.icon) span.empty-char-index+span:before{content:"#"}.line .deco-\. :is(.page-link:not(.icon),.link):before{display:inline-block;min-width:1.15em;padding-left:1px;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";text-align:center;vertical-align:middle;font-weight:900;content:""}.line .deco-\..deco-\/{font-style:initial}.line .deco-\..deco-\/ :is(.page-link:not(.icon),.link):before{font-weight:400;content:""}div.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):is(href$=".pdf",[href^="https://twitter.com"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):after{display:none}.line span:not(.deco-\.)>span>a.link:is(href$=".pdf",[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{display:inline-block;width:1em;height:1em;vertical-align:-1px;text-align:center;background-size:contain;background-repeat:no-repeat;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands"}.line a.link:not(.icon)href$=".pdf":before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"]):before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{content:"";font-weight:400;margin-right:3px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index{display:inline-block;width:0;text-indent:-9999px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index:nth-of-type(30)~span.char-index{display:inherit;width:inherit;text-indent:inherit}.deco-\"{border-radius:.2em;padding:0 .4em;background-color:#8080801a;font-size:95%;font-style:italic}.deco-\":before{color:#a0a0a0;font-size:85%;font-family:"Font Awesome 5 Free";content:"";font-weight:900;vertical-align:super}.line .indent-mark .dot{opacity:0}.line .indent-mark .c-0+.dot{opacity:1}.line .indent-mark .c-1+.dot{opacity:.8}.line .indent-mark .c-2+.dot{opacity:.6}.line .indent-mark .c-3+.dot{opacity:.4}.line .indent-mark .c-4+.dot{opacity:.2}.line strong:not(class){background:linear-gradient(transparent 60%,#abff4f99 60% 100%)}.time-range .lines{user-select:unset;-webkit-user-select:unset}.line:not(.cursor-line) .deco-\|{display:inline-flex}.line .deco-\| img.image{object-fit:contain;margin:0}.line class^=level .deco-\|{flex-wrap:wrap}.line .level-1 .deco-\|>span{width:100%}.line .level-2 .deco-\|>span{width:50%}.line .level-3 .deco-\|>span{width:calc(100%/3)}.line .level-4 .deco-\|>span{width:25%}.line .level-5 .deco-\|>span{width:20%}.line class^=level .deco-\| img.image{object-fit:cover;width:100%;height:100%}.line .deco-\|>span,.line class^=level .deco-\|>span{overflow:hidden}.line .deco-\| img.image,.line class^=level .deco-\| img.image{margin:.2em}.selections .popup-menu .button-container .button:empty{display:none}.strong-button>strong,.italic-button>i,.strike-button>strike{display:inline-block;width:0;text-indent:-9999px}.selections .popup-menu .button-container .button:is(.link-button,.new-page-button,.copy-plain-button){font-size:0}.selections .popup-menu .button-container .button{font-family:Open Sans,Helvetica,Arial,Hiragino Sans,sans-serif,"Font Awesome 5 Free","Font Awesome 5 Brands";font-size:11px;line-height:20px;font-weight:600;display:inline-block;text-align:center}.link-button:after{font-size:11px;content:""}.strong-button:after{content:""}.italic-button:after{content:""}.strike-button:after{content:""}.copy-plain-button:after{font-size:11px;content:""}.new-page-button:after{font-size:11px;content:""}.line a.iconhref$="/hr"{pointer-events:none}.page-column{grid-template-columns:var(--page-column-columns, 46px minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas, "spacer page menu")}@media (991px < width){.page-column:has(.page-sidebar){grid-template-columns:var(--page-column-columns-sidebar, minmax(200px, 3fr) minmax(170px, 1fr) min-content);grid-template-areas:var(--page-column-areas-sidebar, "page sidebar menu")}}@media (min-width: 768px) and (max-width: 991px){.page-column{grid-template-columns:var(--page-column-columns-768, minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas-768, "page menu")}}@media (max-width: 767px){.page-column{display:grid;grid-template-columns:var(--page-column-columns-767, 1fr);grid-template-areas:var(--page-column-areas-767, "page")}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: minmax(200px, 960px) min-content;--page-column-areas-sidebar: "page menu"}.page-sidebar:not(:has(.definition-term)){display:none}.deco-\#{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace}.grid li.page-list-item a .pin{background-color:transparent;background-image:none}.grid li.page-list-item a .pin:after{content:"";font-family:"Font Awesome 5 Free";font-weight:900;font-size:20px;color:#1f915e;bottom:0}.deco-\>{position:absolute;width:100%;text-align:right}li.page-list-item.grid-style-item div.title{-webkit-line-clamp:2}.line.number-list .dot{background-color:transparent!important;display:list-item}.line.number-list .dot:before{display:block;position:absolute;font-family:"Font Awesome 5 Free";top:-11px;content:"";font-weight:900;font-size:11px;color:#c9c9c9;opacity:0}.line.number-list .c-0+.dot:before{opacity:1}.line.number-list .c-1+.dot:before{opacity:.8}.line.number-list .c-2+.dot:before{opacity:.6}.line.number-list .c-3+.dot:before{opacity:.4}.line.number-list .c-4+.dot:before{opacity:.2}img[src^="https://i.kakeru.app"]{background-color:#fff}.brand-icon{display:none!important}.navbar-brand:before{content:"";font-family:"Font Awesome 5 Free";font-size:28px;font-weight:900;color:#bbb}body{--empty-page-link-color: #309b98;--empty-page-link-hover-color: #28807d}.project-home .title{font-size:2rem}.expandable-menu{max-width:calc(100% - 232px)}@media screen and (min-width: 768px) and (max-width: 991px){.expandable-menu{max-width:calc(100% - 247px)}}@media screen and (min-width: 992px) and (max-width: 1260px){.expandable-menu{max-width:calc(100% - 262px)}}.line .indent-mark .dot{top:11px;width:6px;height:3px;background-color:#c9c9c9}.dropdown-menu,.drawer .drawer-menu{background-color:var(--dropdown-menu-bg, #fff);border:var(--dropdown-menu-border, unset)}.dropdown-menu>li>a,.drawer .drawer-menu ul li a,.page-menu ul>li>div{color:var(--dropdown-menu-text-color, #333)}.dropdown-menu>li>a:active,.drawer-menu ul li a:active,data-hover-visible :is(.dropdown-menu,.drawer-menu)>li>:is(a:hover,a:focus){color:var(--dropdown-menu-text-hover-color, #262626);background-color:var(--dropdown-menu-text-hover-bg, #f5f5f5)}:is(.dropdown-menu,.drawer-menu) .divider{color:var(--dropdown-menu-divider-color, #e5e5e5)}@media (prefers-color-scheme: dark){body{--body-bg: #202228;--navbar-bg: rgba(55, 59, 68, .3);--navbar-icon-color: #fff;--navbar-icon-active-color: #338c46;--navbar-icon-hovered-color: #338c46;--search-form-bg: rgba(255, 255, 255, .13);--search-form-icon-color: #fff;--search-form-icon-focus-color: #4a4a4a;--card-title-color: #f0f0f0;--card-title-bg: #2b2e38;--card-bg: #373b44;--card-hover-bg: rgba(0, 0, 0, .1);--card-active-bg: rgba(229, 229, 229, .1);--card-backside: #545860;--card-description-color: #c4c4c4;--card-description-link-color: #80c9fe;--card-description-code-color: #ccc;--card-box-shadow-color: #000;--card-box-shadow: 0 2px 0 var(--card-box-shadow-color);--card-box-hover-shadow: 0 2px 0 rgba(0, 0, 0, .23);--card-title-bg-pinned: #2b2e38;--relation-label-bg: #2b2e38;--relation-label-text: #dddede;--relation-label-links-bg: #80c9fe;--relation-label-links-text: #202228;--relation-label-empty-bg: #fb7476;--relation-label-empty-text: #fff;--tool-color: #535863;--tool-light-color: #353b48;--tool-badge-bg: #2b2e38;--tool-bg: #2b2e38;--tool-text-color: #dddede;--new-button-vertical-color: #fff;--new-button-horizontal-color: #fff;--new-button-bg: #46af5d;--new-button-hover-bg: #338c46;--new-button-active-bg: #346447;--telomere-border: #545863;--telomere-unread: #56a066;--page-text-color: rgba(255, 255, 255, .87);--page-link-color: #80c9fe;--page-link-hover-color: #6a9ec6;--page-link-color-cursor-line: #a985e4;--page-bg: #373b44;--empty-page-link-color: #fb7476;--empty-page-link-hover-color: #b47576;--line-title-color: rgba(255, 255, 255, .87);--line-permalink-color: rgba(234, 218, 74, .35);--code-color: #ccc;--code-bg: rgba(0, 0, 0, .18);--quote-bg-color: rgba(0, 0, 0, .2);--cursor-color: #fff}body{--dark-theme-bg: #24292f;--dark-theme-border: solid 1px #888}body{--navbar-bg: rgba(2, 167, 137, .5)}body{--new-button-horizontal-color: #b44a29;--new-button-vertical-color: var(--new-button-horizontal-color);--new-button-bg: #f4835f;--new-button-hover-bg: #f2693e;--new-button-active-bg: #ef4c17}body{--tool-color: #535863;--tool-light-color: #353b48;--tool-badge-bg: #2b2e38;--tool-bg: #2b2e38;--tool-text-color: #dddede;--body-headings-color: var(--tool-color)}body{--code-line-number-color: #D181FF;--cursor-code-line-number-color: #FF00F0}body{--dropdown-menu-bg: #373b44;--dropdown-menu-border: 1px solid #8888882d;--dropdown-menu-text-color: var(--page-text-color);--dropdown-menu-divider-color: #e5e5e5;--dropdown-menu-text-hover-color: var(--page-text-color);--dropdown-menu-text-hover-bg: #373b44}body{--card-title-bg: var(--navbar-bg);--card-title-bg-pinned: var(--navbar-bg)}html:not(data-display-style^=presentation) .page{box-shadow:none;border:solid 1px #888}.table-block .cell{border-bottom:solid 1px #888}.line code.helpfeel{background-color:var(--code-bg)}.line span.code-block .code-block-start{border:solid 1px #66667F;background-color:#272822;padding:2px 5px;color:#7c9ff7}.line span.code-block .code-block-start a{color:#7c9ff7}.code-block{--code-bg: #2d2b57;--code-color: #e3dfff;font-weight:400}code.highlight .hljs-subst{color:#e3dfff}code.highlight .hljs-title{color:#fad000;font-weight:400}code.highlight .hljs-name{color:#a1feff}code.highlight .hljs-tag{color:#fff}code.highlight .hljs-attr{color:#f8d000;font-style:italic}code.highlight :is(.hljs-built_in,.hljs-selector-tag,.hljs-section){color:#fb9e00}code.highlight .hljs-keyword{color:#fb9e00}code.highlight :is(.hljs-string,.hljs-attribute,.hljs-symbol,.hljs-bullet,.hljs-addition,.hljs-code,.hljs-regexp,.hljs-selector-class,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-template-tag,.hljs-quote,.hljs-deletion){color:#4cd213}code.highlight :is(.hljs-meta,.hljs-meta .hljs-string){color:#fb9e00}code.highlight .hljs-comment{color:#ac65ff}code.highlight :is(.hljs-keyword,.hljs-selector-tag,.hljs-literal,.hljs-name){font-weight:400}code.highlight :is(.hljs-literal,.hljs-number){color:#fa658d}code.highlight .hljs-emphasis{font-style:italic}code.highlight .hljs-strong{font-weight:700}code.highlight :is(.hljs-selector-pseudo,.hljs-deletion){color:#e06c75}::selection{color:unset;background:#0073e680}.selection{background-color:#fff7}.line .indent-mark .dot{background-color:gray}.line.number-list .dot:before{color:gray}}.page-linkhref*=".@":before{content:"✅"}.page-linkhref*="@20":not(href*=".@"):before{content:"⬜"}html:not(data-display-style^=presentation) body{background-image:url(https://i.gyazo.com/8d65198f72652e8887d2c941f39805b4.png)}.grid li.page-list-item a .description .formula{display:inline}.page-link:is(href^="/tosuke-notes",href^="/blu3mo/",href^="/masuilab/",href^="/takker-memex",href^="/takker-books",href^="/takker-CEPM",href^="/takker-MBRC",href^="/takker-CVBH",href^="/takker-CVST",href^="/takker-PS",href^="/takker-SM",href^="/takker-SoM",href^="/takker-private"):before{content:"🔒"}
code:takker-user.css
@media screen and (min-width: 400px){html:is(data-os*=android,data-os*=ios) .popup-menu .button-container .button,.popup-menu .button-container .button:is(data-os*=android,data-os*=ios){min-width:3em}}:not(data-display-style^=presentation) .page-column{--page-column-columns: 100px minmax(200px, 960px) min-content 1fr;--page-column-areas: "spacer page menu spacer2";--page-column-columns-sidebar: 100px minmax(200px, 3fr) minmax(170px, 1fr) min-content;--page-column-areas-sidebar: "spacer page sidebar menu";--page-column-columns-768: var(--page-column-columns);--page-column-areas-768: var(--page-column-areas);--page-column-columns-767: minmax(60px, calc(100% / 767 * 100)) 1fr;--page-column-areas-767: "spacer page"}@container (width > 1236px){:not(data-display-style^=presentation) .page-column{--page-column-columns: minmax(200px, 960px) min-content;--page-column-areas: "page menu"}}data-display-style^=presentation data-userscript-name="takker-scheduler/timeline-wedget"{display:none}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: var(--page-column-columns);--page-column-areas-sidebar: var(--page-column-areas)}.page-sidebar:not(:has(.definition-term)){display:none}.search-form .form-group input:focus{color:var(--page-text-color);background-color:var(--search-form-bg, rgba(255,255,255,.15))}.line span.code-block .code-block-start title=css a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=html a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=javascript a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=typescript a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=cpp a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=c a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=cs a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=python a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=toml a:before,.line span.code-block .code-block-start title=json a:before,.line span.code-block .code-block-start title=yaml a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=xml a:before{content:"謹";display:inline-block}.line span.code-block .code-block-start title=gitignore a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=markdown a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=txt a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=csv a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=fish a:before,.line span.code-block .code-block-start title=bash a:before,.line span.code-block .code-block-start title=zsh a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=dos a:before{content:"";display:inline-block}.line code,.line span.code-block{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace;font-size:105%}data-os=android{.page-column{div.page-menu{position:fixed;display:flex;flex-direction:row-reverse;right:0;.dropdown-menu-top,.dropdown-menu-right{top:46px}}}}
code:takker-memex.css
body *:before{--code-number-color: var(--code-color, #342d9c)}.section-title{counter-reset:codeline}.code-block span.indent code.code-body{counter-increment:codeline;margin-left:-1.5em;padding-left:2.3em}.code-block span.indent code.code-body:before{content:counter(codeline);position:absolute;display:inline-block;z-index:10;margin-left:-2.4em;width:2em;padding-right:.2em;text-align:right;vertical-align:bottom;border-right:solid 1px #fff;color:var(--code-number-color)}.code-block span.indent code.code-body:before{opacity:.5}.cursor-line .code-block span.indent code.code-body:before{opacity:1;font-weight:bolder;background-color:var(--accent-color)}.navbar-form .dropdown.open .dropdown-menu{min-width:100%;max-height:calc(100vh - 130px)!important;overflow-y:auto}.page-list-item.pin+.page-list-item:not(.pin){grid-column-start:1}.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):not([href^="https://scrapbox.io"]):after{font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";font-weight:900;font-size:.8rem;content:" ";display:inline-block}.line .deco-\.{font-size:.8em;position:relative;top:-.5em}.line:not(.cursor-line) .deco-\. a:is(.page-link:not(.icon),.link) span:not(.empty-char-index)+span+span~span{display:inline-block;width:0;text-indent:-9999px}.line:not(.cursor-line) .deco-\. .page-link:not(.icon) span.empty-char-index~span.char-index{display:inherit;width:inherit;text-indent:inherit}.line:not(.cursor-line) .deco-\. a.page-link:not(.icon) span.empty-char-index+span:before{content:"#"}.line .deco-\. :is(.page-link:not(.icon),.link):before{display:inline-block;min-width:1.15em;padding-left:1px;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";text-align:center;vertical-align:middle;font-weight:900;content:""}.line .deco-\..deco-\/{font-style:initial}.line .deco-\..deco-\/ :is(.page-link:not(.icon),.link):before{font-weight:400;content:""}div.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):is(href$=".pdf",[href^="https://twitter.com"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):after{display:none}.line span:not(.deco-\.)>span>a.link:is(href$=".pdf",[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{display:inline-block;width:1em;height:1em;vertical-align:-1px;text-align:center;background-size:contain;background-repeat:no-repeat;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands"}.line a.link:not(.icon)href$=".pdf":before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"]):before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{content:"";font-weight:400;margin-right:3px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index{display:inline-block;width:0;text-indent:-9999px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index:nth-of-type(30)~span.char-index{display:inherit;width:inherit;text-indent:inherit}.deco-\"{border-radius:.2em;padding:0 .4em;background-color:#8080801a;font-size:95%;font-style:italic}.deco-\":before{color:#a0a0a0;font-size:85%;font-family:"Font Awesome 5 Free";content:"";font-weight:900;vertical-align:super}.line .indent-mark .dot{opacity:0}.line .indent-mark .c-0+.dot{opacity:1}.line .indent-mark .c-1+.dot{opacity:.8}.line .indent-mark .c-2+.dot{opacity:.6}.line .indent-mark .c-3+.dot{opacity:.4}.line .indent-mark .c-4+.dot{opacity:.2}.line strong:not(class){background:linear-gradient(transparent 60%,#abff4f99 60% 100%)}.time-range .lines{user-select:unset;-webkit-user-select:unset}.line:not(.cursor-line) .deco-\|{display:inline-flex}.line .deco-\| img.image{object-fit:contain;margin:0}.line class^=level .deco-\|{flex-wrap:wrap}.line .level-1 .deco-\|>span{width:100%}.line .level-2 .deco-\|>span{width:50%}.line .level-3 .deco-\|>span{width:calc(100%/3)}.line .level-4 .deco-\|>span{width:25%}.line .level-5 .deco-\|>span{width:20%}.line class^=level .deco-\| img.image{object-fit:cover;width:100%;height:100%}.line .deco-\|>span,.line class^=level .deco-\|>span{overflow:hidden}.line .deco-\| img.image,.line class^=level .deco-\| img.image{margin:.2em}.selections .popup-menu .button-container .button:empty{display:none}.strong-button>strong,.italic-button>i,.strike-button>strike{display:inline-block;width:0;text-indent:-9999px}.selections .popup-menu .button-container .button:is(.link-button,.new-page-button,.copy-plain-button){font-size:0}.selections .popup-menu .button-container .button{font-family:Open Sans,Helvetica,Arial,Hiragino Sans,sans-serif,"Font Awesome 5 Free","Font Awesome 5 Brands";font-size:11px;line-height:20px;font-weight:600;display:inline-block;text-align:center}.link-button:after{font-size:11px;content:""}.strong-button:after{content:""}.italic-button:after{content:""}.strike-button:after{content:""}.copy-plain-button:after{font-size:11px;content:""}.new-page-button:after{font-size:11px;content:""}.line a.iconhref$="/hr"{pointer-events:none}.page-column{grid-template-columns:var(--page-column-columns, 46px minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas, "spacer page menu")}@media (991px < width){.page-column:has(.page-sidebar){grid-template-columns:var(--page-column-columns-sidebar, minmax(200px, 3fr) minmax(170px, 1fr) min-content);grid-template-areas:var(--page-column-areas-sidebar, "page sidebar menu")}}@media (min-width: 768px) and (max-width: 991px){.page-column{grid-template-columns:var(--page-column-columns-768, minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas-768, "page menu")}}@media (max-width: 767px){.page-column{display:grid;grid-template-columns:var(--page-column-columns-767, 1fr);grid-template-areas:var(--page-column-areas-767, "page")}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: minmax(200px, 960px) min-content;--page-column-areas-sidebar: "page menu"}.deco-\#{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace}.grid li.page-list-item a .pin{background-color:transparent;background-image:none}.grid li.page-list-item a .pin:after{content:"";font-family:"Font Awesome 5 Free";font-weight:900;font-size:20px;color:#1f915e;bottom:0}@media screen and (min-width: 400px){html:is(data-os*=android,data-os*=ios) .popup-menu .button-container .button,.popup-menu .button-container .button:is(data-os*=android,data-os*=ios){min-width:3em}}:not(data-display-style^=presentation) .page-column{--page-column-columns: 100px minmax(200px, 960px) min-content 1fr;--page-column-areas: "spacer page menu spacer2";--page-column-columns-sidebar: 100px minmax(200px, 3fr) minmax(170px, 1fr) min-content;--page-column-areas-sidebar: "spacer page sidebar menu";--page-column-columns-768: var(--page-column-columns);--page-column-areas-768: var(--page-column-areas);--page-column-columns-767: minmax(60px, calc(100% / 767 * 100)) 1fr;--page-column-areas-767: "spacer page"}@container (width > 1236px){:not(data-display-style^=presentation) .page-column{--page-column-columns: minmax(200px, 960px) min-content;--page-column-areas: "page menu"}}data-display-style^=presentation data-userscript-name="takker-scheduler/timeline-wedget"{display:none}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: var(--page-column-columns);--page-column-areas-sidebar: var(--page-column-areas)}.page-sidebar:not(:has(.definition-term)){display:none}.deco-\>{position:absolute;width:100%;text-align:right}.search-form .form-group input:focus{color:var(--page-text-color);background-color:var(--search-form-bg, rgba(255,255,255,.15))}.line span.code-block .code-block-start title=css a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=html a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=javascript a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=typescript a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=cpp a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=c a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=cs a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=python a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=toml a:before,.line span.code-block .code-block-start title=json a:before,.line span.code-block .code-block-start title=yaml a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=xml a:before{content:"謹";display:inline-block}.line span.code-block .code-block-start title=gitignore a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=markdown a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=txt a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=csv a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=fish a:before,.line span.code-block .code-block-start title=bash a:before,.line span.code-block .code-block-start title=zsh a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=dos a:before{content:"";display:inline-block}.line code,.line span.code-block{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace;font-size:105%}.table-block .cell{border:solid 1px var(--telomere-border, #808b8c)}li.page-list-item.grid-style-item div.title{-webkit-line-clamp:2}.line.number-list .dot{background-color:transparent!important;display:list-item}.line.number-list .dot:before{display:block;position:absolute;font-family:"Font Awesome 5 Free";top:-11px;content:"";font-weight:900;font-size:11px;color:#c9c9c9;opacity:0}.line.number-list .c-0+.dot:before{opacity:1}.line.number-list .c-1+.dot:before{opacity:.8}.line.number-list .c-2+.dot:before{opacity:.6}.line.number-list .c-3+.dot:before{opacity:.4}.line.number-list .c-4+.dot:before{opacity:.2}img[src^="https://i.kakeru.app"]{background-color:#fff}@media screen{.quick-launch .left-box{position:fixed;top:-2px;left:40px;z-index:1000}}@media screen and (min-width: 768px) and (max-width: 991px){.quick-launch .left-box{left:55px}}@media screen and (min-width: 992px) and (max-width: 1260px){.quick-launch .left-box{left:70px}}@media screen and (min-width: 1261px){.quick-launch .left-box{left:calc((100% - 1280px)/2 + 80px)}}.expandable-menu{max-width:calc(100% - 291px)}@media screen and (min-width: 768px) and (max-width: 991px){.expandable-menu{max-width:calc(100% - 306px)}}@media screen and (min-width: 992px) and (max-width: 1260px){.expandable-menu{max-width:calc(100% - 321px)}}.deco-\* img.image{max-height:600px}.page-linkhref*=".@":before{content:"✅"}.page-linkhref*="@20":not(href*=".@"):before{content:"⬜"}data-os=android{.page-column{div.page-menu{position:fixed;display:flex;flex-direction:row-reverse;right:0;.dropdown-menu-top,.dropdown-menu-right{top:46px}}}}.dropdown-menu,.drawer .drawer-menu{background-color:var(--dropdown-menu-bg, #fff);border:var(--dropdown-menu-border, unset)}.dropdown-menu>li>a,.drawer .drawer-menu ul li a,.page-menu ul>li>div{color:var(--dropdown-menu-text-color, #333)}.dropdown-menu>li>a:active,.drawer-menu ul li a:active,data-hover-visible :is(.dropdown-menu,.drawer-menu)>li>:is(a:hover,a:focus){color:var(--dropdown-menu-text-hover-color, #262626);background-color:var(--dropdown-menu-text-hover-bg, #f5f5f5)}:is(.dropdown-menu,.drawer-menu) .divider{color:var(--dropdown-menu-divider-color, #e5e5e5)}body{--dropdown-menu-bg: #373b44;--dropdown-menu-border: 1px solid #8888882d;--dropdown-menu-text-color: var(--page-text-color);--dropdown-menu-text-hover-color: var(--page-text-color);--dropdown-menu-text-hover-bg: #373b44}.line:not(.cursor-line) .deco-\'{position:absolute;width:100%;text-align:center}.navbar-brand:before{content:"";width:44px;height:44px;position:absolute;background-color:#252a30;background-image:url(https://daiiz-apps.appspot.com/today/jp.svg);background-size:cover;background-position:center;border-radius:6px}.line:not(.cursor-line) class="deco-( deco-)":not(:has(img.icon)){border-radius:50%;border:.05em solid var(--page-text-color, #4a4a4a);line-height:1;color:var(--page-text-color, #4a4a4a);font-weight:600;padding:5px;a{color:var(--page-text-color, #4a4a4a)}}
code:takker-private.css
body *:before{--code-number-color: var(--code-color, #342d9c)}.section-title{counter-reset:codeline}.code-block span.indent code.code-body{counter-increment:codeline;margin-left:-1.5em;padding-left:2.3em}.code-block span.indent code.code-body:before{content:counter(codeline);position:absolute;display:inline-block;z-index:10;margin-left:-2.4em;width:2em;padding-right:.2em;text-align:right;vertical-align:bottom;border-right:solid 1px #fff;color:var(--code-number-color)}.code-block span.indent code.code-body:before{opacity:.5}.cursor-line .code-block span.indent code.code-body:before{opacity:1;font-weight:bolder;background-color:var(--accent-color)}.navbar-form .dropdown.open .dropdown-menu{min-width:100%;max-height:calc(100vh - 130px)!important;overflow-y:auto}.page-list-item.pin+.page-list-item:not(.pin){grid-column-start:1}.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):not([href^="https://scrapbox.io"]):after{font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";font-weight:900;font-size:.8rem;content:" ";display:inline-block}.line .deco-\.{font-size:.8em;position:relative;top:-.5em}.line:not(.cursor-line) .deco-\. a:is(.page-link:not(.icon),.link) span:not(.empty-char-index)+span+span~span{display:inline-block;width:0;text-indent:-9999px}.line:not(.cursor-line) .deco-\. .page-link:not(.icon) span.empty-char-index~span.char-index{display:inherit;width:inherit;text-indent:inherit}.line:not(.cursor-line) .deco-\. a.page-link:not(.icon) span.empty-char-index+span:before{content:"#"}.line .deco-\. :is(.page-link:not(.icon),.link):before{display:inline-block;min-width:1.15em;padding-left:1px;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands";text-align:center;vertical-align:middle;font-weight:900;content:""}.line .deco-\..deco-\/{font-style:initial}.line .deco-\..deco-\/ :is(.page-link:not(.icon),.link):before{font-weight:400;content:""}div.line span:not(.modal-image):not(.pointing-device-map)>a.link:not(.icon):is(href$=".pdf",[href^="https://twitter.com"],[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):after{display:none}.line span:not(.deco-\.)>span>a.link:is(href$=".pdf",[href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"],[href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{display:inline-block;width:1em;height:1em;vertical-align:-1px;text-align:center;background-size:contain;background-repeat:no-repeat;font-family:"Font Awesome 5 Free","Font Awesome 5 Brands"}.line a.link:not(.icon)href$=".pdf":before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://github.com"],[href^="https://raw.githubusercontent.com"],[href^="https://gist.github.com"]):before{content:"";font-weight:400;margin-right:1px}:is(.line,.line .deco) a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]):before{content:"";font-weight:400;margin-right:3px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index{display:inline-block;width:0;text-indent:-9999px}.line .deco-\. a.link:is([href^="https://ja.wikipedia.org"],[href^="https://en.wikipedia.org"]) span.char-index:nth-of-type(30)~span.char-index{display:inherit;width:inherit;text-indent:inherit}.deco-\"{border-radius:.2em;padding:0 .4em;background-color:#8080801a;font-size:95%;font-style:italic}.deco-\":before{color:#a0a0a0;font-size:85%;font-family:"Font Awesome 5 Free";content:"";font-weight:900;vertical-align:super}.line .indent-mark .dot{opacity:0}.line .indent-mark .c-0+.dot{opacity:1}.line .indent-mark .c-1+.dot{opacity:.8}.line .indent-mark .c-2+.dot{opacity:.6}.line .indent-mark .c-3+.dot{opacity:.4}.line .indent-mark .c-4+.dot{opacity:.2}.line strong:not(class){background:linear-gradient(transparent 60%,#abff4f99 60% 100%)}.time-range .lines{user-select:unset;-webkit-user-select:unset}.line:not(.cursor-line) .deco-\|{display:inline-flex}.line .deco-\| img.image{object-fit:contain;margin:0}.line class^=level .deco-\|{flex-wrap:wrap}.line .level-1 .deco-\|>span{width:100%}.line .level-2 .deco-\|>span{width:50%}.line .level-3 .deco-\|>span{width:calc(100%/3)}.line .level-4 .deco-\|>span{width:25%}.line .level-5 .deco-\|>span{width:20%}.line class^=level .deco-\| img.image{object-fit:cover;width:100%;height:100%}.line .deco-\|>span,.line class^=level .deco-\|>span{overflow:hidden}.line .deco-\| img.image,.line class^=level .deco-\| img.image{margin:.2em}.selections .popup-menu .button-container .button:empty{display:none}.strong-button>strong,.italic-button>i,.strike-button>strike{display:inline-block;width:0;text-indent:-9999px}.selections .popup-menu .button-container .button:is(.link-button,.new-page-button,.copy-plain-button){font-size:0}.selections .popup-menu .button-container .button{font-family:Open Sans,Helvetica,Arial,Hiragino Sans,sans-serif,"Font Awesome 5 Free","Font Awesome 5 Brands";font-size:11px;line-height:20px;font-weight:600;display:inline-block;text-align:center}.link-button:after{font-size:11px;content:""}.strong-button:after{content:""}.italic-button:after{content:""}.strike-button:after{content:""}.copy-plain-button:after{font-size:11px;content:""}.new-page-button:after{font-size:11px;content:""}.line a.iconhref$="/hr"{pointer-events:none}.page-column{grid-template-columns:var(--page-column-columns, 46px minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas, "spacer page menu")}@media (991px < width){.page-column:has(.page-sidebar){grid-template-columns:var(--page-column-columns-sidebar, minmax(200px, 3fr) minmax(170px, 1fr) min-content);grid-template-areas:var(--page-column-areas-sidebar, "page sidebar menu")}}@media (min-width: 768px) and (max-width: 991px){.page-column{grid-template-columns:var(--page-column-columns-768, minmax(200px, 960px) min-content);grid-template-areas:var(--page-column-areas-768, "page menu")}}@media (max-width: 767px){.page-column{display:grid;grid-template-columns:var(--page-column-columns-767, 1fr);grid-template-areas:var(--page-column-areas-767, "page")}}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: minmax(200px, 960px) min-content;--page-column-areas-sidebar: "page menu"}.deco-\#{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace}.grid li.page-list-item a .pin{background-color:transparent;background-image:none}.grid li.page-list-item a .pin:after{content:"";font-family:"Font Awesome 5 Free";font-weight:900;font-size:20px;color:#1f915e;bottom:0}@media screen and (min-width: 400px){html:is(data-os*=android,data-os*=ios) .popup-menu .button-container .button,.popup-menu .button-container .button:is(data-os*=android,data-os*=ios){min-width:3em}}:not(data-display-style^=presentation) .page-column{--page-column-columns: 100px minmax(200px, 960px) min-content 1fr;--page-column-areas: "spacer page menu spacer2";--page-column-columns-sidebar: 100px minmax(200px, 3fr) minmax(170px, 1fr) min-content;--page-column-areas-sidebar: "spacer page sidebar menu";--page-column-columns-768: var(--page-column-columns);--page-column-areas-768: var(--page-column-areas);--page-column-columns-767: minmax(60px, calc(100% / 767 * 100)) 1fr;--page-column-areas-767: "spacer page"}@container (width > 1236px){:not(data-display-style^=presentation) .page-column{--page-column-columns: minmax(200px, 960px) min-content;--page-column-areas: "page menu"}}data-display-style^=presentation data-userscript-name="takker-scheduler/timeline-wedget"{display:none}.page-column:not(:has(.definition-term)){--page-column-columns-sidebar: var(--page-column-columns);--page-column-areas-sidebar: var(--page-column-areas)}.page-sidebar:not(:has(.definition-term)){display:none}.deco-\>{position:absolute;width:100%;text-align:right}.search-form .form-group input:focus{color:var(--page-text-color);background-color:var(--search-form-bg, rgba(255,255,255,.15))}.line span.code-block .code-block-start title=css a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=html a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=javascript a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=typescript a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=cpp a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=c a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=cs a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=python a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=toml a:before,.line span.code-block .code-block-start title=json a:before,.line span.code-block .code-block-start title=yaml a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=xml a:before{content:"謹";display:inline-block}.line span.code-block .code-block-start title=gitignore a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=markdown a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=txt a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=csv a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=fish a:before,.line span.code-block .code-block-start title=bash a:before,.line span.code-block .code-block-start title=zsh a:before{content:"";display:inline-block}.line span.code-block .code-block-start title=dos a:before{content:"";display:inline-block}.line code,.line span.code-block{font-family:Cica,Menlo,Monaco,Consolas,Courier New,monospace;font-size:105%}.table-block .cell{border:solid 1px var(--telomere-border, #808b8c)}.line.number-list .dot{background-color:transparent!important;display:list-item}.line.number-list .dot:before{display:block;position:absolute;font-family:"Font Awesome 5 Free";top:-11px;content:"";font-weight:900;font-size:11px;color:#c9c9c9;opacity:0}.line.number-list .c-0+.dot:before{opacity:1}.line.number-list .c-1+.dot:before{opacity:.8}.line.number-list .c-2+.dot:before{opacity:.6}.line.number-list .c-3+.dot:before{opacity:.4}.line.number-list .c-4+.dot:before{opacity:.2}img[src^="https://i.kakeru.app"]{background-color:#fff}[data-os=android]{.page-column{div.page-menu{position:fixed;display:flex;flex-direction:row-reverse;right:0;.dropdown-menu-top,.dropdown-menu-right{top:46px}}}}.dropdown-menu,.drawer .drawer-menu{background-color:var(--dropdown-menu-bg, #fff);border:var(--dropdown-menu-border, unset)}.dropdown-menu>li>a,.drawer .drawer-menu ul li a,.page-menu ul>li>div{color:var(--dropdown-menu-text-color, #333)}.dropdown-menu>li>a:active,.drawer-menu ul li a:active,data-hover-visible :is(.dropdown-menu,.drawer-menu)>li>:is(a:hover,a:focus){color:var(--dropdown-menu-text-hover-color, #262626);background-color:var(--dropdown-menu-text-hover-bg, #f5f5f5)}:is(.dropdown-menu,.drawer-menu) .divider{color:var(--dropdown-menu-divider-color, #e5e5e5)}body{--dropdown-menu-bg: #373b44;--dropdown-menu-border: 1px solid #8888882d;--dropdown-menu-text-color: var(--page-text-color);--dropdown-menu-text-hover-color: var(--page-text-color);--dropdown-menu-text-hover-bg: #373b44}html,body,#editor,.grid li{font-family:ヒラギノ角ゴ Pro W3,Hiragino Kaku Gothic Pro,メイリオ,Meiryo,MS Pゴシック,-apple-system,BlinkMacSystemFont,sans-serif}