for-any-project-min
for-any-projectをこのURLでbundleしたもの
code:script.js
var mT=Object.defineProperty;var So=(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 Ni=(e,t)=>{for(var r in t)mT(e,r,{get:tr,enumerable:!0})};function Oe(e){if(e)return fT(e)}function fT(e){for(var t in Oe.prototype)et=Oe.prototypet;return e}Oe.prototype.on=Oe.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks"$"+e=this._callbacks"$"+e||[]).push(t),this};Oe.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};Oe.prototype.off=Oe.prototype.removeListener=Oe.prototype.removeAllListeners=Oe.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};Oe.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};Oe.prototype.emitReserved=Oe.prototype.emit;Oe.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks"$"+e||[]};Oe.prototype.hasListeners=function(e){return!!this.listeners(e).length};var vr=Object.create(null);vr.open="0";vr.close="1";vr.ping="2";vr.pong="3";vr.message="4";vr.upgrade="5";vr.noop="6";var Mi=Object.create(null);Object.keys(vr).forEach(e=>{Mi[vre]=e});var jl={type:"error",data:"parser error"},vf=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="object BlobConstructor",Rf=typeof ArrayBuffer=="function",Tf=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Ai=({type:e,data:t},r,o)=>vf&&t instanceof Blob?r?o(t):wf(t,o):Rf&&(t instanceof ArrayBuffer||Tf(t))?r?o(t):wf(new Blob(t),o):o(vre+(t||"")),wf=(e,t)=>{let r=new FileReader;return r.onload=function(){let o=r.result.split(",")1;t("b"+(o||""))},r.readAsDataURL(e)};function Ef(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var Ul;function dT(e,t){if(vf&&e.data instanceof Blob)return e.data.arrayBuffer().then(Ef).then(t);if(Rf&&(e.data instanceof ArrayBuffer||Tf(e.data)))return t(Ef(e.data));Ai(e,!1,r=>{Ul||(Ul=new TextEncoder),t(Ul.encode(r))})}var kf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bs=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<kf.length;e++)bskf.charCodeAt(e)=e;var hT=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=bse.charCodeAt(o),i=bse.charCodeAt(o+1),a=bse.charCodeAt(o+2),c=bse.charCodeAt(o+3),un++=s<<2|i>>4,un++=(i&15)<<4|a>>2,un++=(a&3)<<6|c&63;return l},gT=typeof ArrayBuffer=="function",Ii=(e,t)=>{if(typeof e!="string")return{type:"message",data:_f(e,t)};let r=e.charAt(0);return r==="b"?{type:"message",data:yT(e.substring(1),t)}:Mir?e.length>1?{type:Mir,data:e.substring(1)}:{type:Mir}:jl},yT=(e,t)=>{if(gT){let r=hT(e);return _f(r,t)}else return{base64:!0,data:e}},_f=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob(e);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Pf="",Of=(e,t)=>{let r=e.length,o=new Array(r),n=0;e.forEach((s,i)=>{Ai(s,!1,a=>{oi=a,++n===r&&t(o.join(Pf))})})},Sf=(e,t)=>{let r=e.split(Pf),o=[];for(let n=0;n<r.length;n++){let s=Ii(rn,t);if(o.push(s),s.type==="error")break}return o};function Nf(){return new TransformStream({transform(e,t){dT(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 $l;function Li(e){return e.reduce((t,r)=>t+r.length,0)}function Ci(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 Lf(e,t){$l||($l=new TextDecoder);let r=[],o=0,n=-1,s=!1;return new TransformStream({transform(i,a){for(r.push(i);;){if(o===0){if(Li(r)<1)break;let c=Ci(r,1);s=(c0&128)===128,n=c0&127,n<126?o=3:n===126?o=1:o=2}else if(o===1){if(Li(r)<2)break;let c=Ci(r,2);n=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),o=3}else if(o===2){if(Li(r)<8)break;let c=Ci(r,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(jl);break}n=u*Math.pow(2,32)+l.getUint32(4),o=3}else{if(Li(r)<n)break;let c=Ci(r,n);a.enqueue(Ii(s?c:$l.decode(c),t)),o=0}if(n===0||n>e){a.enqueue(jl);break}}}})}var Bl=4;var ws=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),xT="arraybuffer";function Mf(e,...t){return t.reduce((r,o)=>(e.hasOwnProperty(o)&&(ro=eo),r),{})}var bT=Qt.setTimeout,wT=Qt.clearTimeout;function Es(e,t){t.useNativeTimers?(e.setTimeoutFn=bT.bind(Qt),e.clearTimeoutFn=wT.bind(Qt)):(e.setTimeoutFn=Qt.setTimeout.bind(Qt),e.clearTimeoutFn=Qt.clearTimeout.bind(Qt))}var ET=1.33;function kT(e){return typeof e=="string"?vT(e):Math.ceil((e.byteLength||e.size)*ET)}function vT(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 Af(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function RT(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(er));return t}function TT(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 _T=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},Gl=class extends Oe{constructor(e){super(),this.writable=!1,Es(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 _T(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=Ii(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&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=RT(e);return t.length?"?"+t:""}},PT=class extends Gl{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)};Sf(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,Of(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=Af()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},If=!1;try{If=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var OT=If;function ST(){}var NT=class extends PT{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}},wn=class Fi extends Oe{constructor(t,r,o){super(),this.createRequest=t,Es(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=Mf(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=Fi.requestsCount++,Fi.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=ST,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Fi.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()}};wn.requestsCount=0;wn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Cf);else if(typeof addEventListener=="function"){let e="onpagehide"in Qt?"pagehide":"unload";addEventListener(e,Cf,!1)}}function Cf(){for(let e in wn.requests)wn.requests.hasOwnProperty(e)&&wn.requestse.abort()}var LT=function(){let e=Ff({xdomain:!1});return e&&e.responseType!==null}(),ql=class extends NT{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=LT&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new wn(Ff,this.uri(),e)}};function Ff(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||OT))return new XMLHttpRequest}catch{}if(!t)try{return new Qt["Active".concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Df=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",CT=class extends Gl{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Df?{}:Mf(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;Ai(r,this.supportsBinary,n=>{try{this.doWrite(r,n)}catch{}o&&ws(()=>{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=Af()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Hl=Qt.WebSocket||Qt.MozWebSocket,zl=class extends CT{createSocket(e,t,r){return Df?new Hl(e,t,r):t?new Hl(e,t):new Hl(e)}doWrite(e,t){this.ws.send(t)}},Uf=class extends Gl{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=Lf(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),o=Nf();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&&ws(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}},MT={websocket:zl,webtransport:Uf,polling:ql},AT=/^(?:(?!^:@\/?#+:^:@\/*@)(http|https|ws|wss):\/\/)?((?:((^:@\/?#*)(?::(^:@\/?#*))?)?@)?((?:a-f0-9{0,4}:){2,7}a-f0-9{0,4}|^:\/?#*)(?::(\d*))?)(((\/(?:^?#(?!^?#\/*\.^?#\/.+(?:?#|$)))*\/?)?(^?#\/*))(?:\?(^#*))?(?:#(.*))?)/,IT="source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor";function ji(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=AT.exec(e||""),s={},i=14;for(;i--;)s[ITi]=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=FT(s,s.path),s.queryKey=DT(s,s.query),s}function FT(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 DT(e,t){let r={};return t.replace(/(?:^|&)(^&=*)=?(^&*)/g,function(o,n,s){n&&(rn=s)}),r}var Wl=typeof addEventListener=="function"&&typeof removeEventListener=="function",Di=[];Wl&&addEventListener("offline",()=>{Di.forEach(e=>e())},!1);var Ui=class $i extends Oe{constructor(t,r){if(super(),this.binaryType=xT,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=ji(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=ji(r.host).host);Es(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=TT(this.opts.query)),Wl&&(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"})},Di.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){let r=Object.assign({},this.opts.query);r.EIO=Bl,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&&$i.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",$i.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+=kT(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,ws(()=>{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($i.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(),Wl&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let o=Di.indexOf(this._offlineEventListener);o!==-1&&Di.splice(o,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};Ui.protocol=Bl;var UT=class extends Ui{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;Ui.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;Ui.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}},Vl=class extends UT{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=>MTo).filter(o=>!!o)),super(e,r)}};var v$=Vl.protocol;var Jl={};Ni(Jl,{Decoder:()=>VT,Encoder:()=>zT,PacketType:()=>ie,protocol:()=>Bf});var $T=typeof ArrayBuffer=="function",jT=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,jf=Object.prototype.toString,BT=typeof Blob=="function"||typeof Blob<"u"&&jf.call(Blob)==="object BlobConstructor",HT=typeof File=="function"||typeof File<"u"&&jf.call(File)==="object FileConstructor";function Xl(e){return $T&&(e instanceof ArrayBuffer||jT(e))||BT&&e instanceof Blob||HT&&e instanceof File}function Bi(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,o=e.length;r<o;r++)if(Bi(er))return!0;return!1}if(Xl(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Bi(e.toJSON(),!0);for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Bi(er))return!0;return!1}function WT(e){let t=[],r=e.data,o=e;return o.data=Kl(r,t),o.attachments=t.length,{packet:o,buffers:t}}function Kl(e,t){if(!e)return e;if(Xl(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=Kl(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=Kl(eo,t));return r}return e}function GT(e,t){return e.data=Yl(e.data,t),delete e.attachments,e}function Yl(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=Yl(er,t);else if(typeof e=="object")for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(er=Yl(er,t));return e}var qT="connect","connect_error","disconnect","disconnecting","newListener","removeListener",Bf=5,ie;(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"})(ie||(ie={}));var zT=class{constructor(e){this.replacer=e}encode(e){return(e.type===ie.EVENT||e.type===ie.ACK)&&Bi(e)?this.encodeAsBinary({type:e.type===ie.EVENT?ie.BINARY_EVENT:ie.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):this.encodeAsString(e)}encodeAsString(e){let t=""+e.type;return(e.type===ie.BINARY_EVENT||e.type===ie.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=WT(e),r=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(r),o}};function $f(e){return Object.prototype.toString.call(e)==="object Object"}var VT=class Hf extends Oe{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===ie.BINARY_EVENT;o||r.type===ie.BINARY_ACK?(r.type=o?ie.EVENT:ie.ACK,this.reconstructor=new KT(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(Xl(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(ieo.type===void 0)throw new Error("unknown packet type "+o.type);if(o.type===ie.BINARY_EVENT||o.type===ie.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(Hf.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 ie.CONNECT:return $f(r);case ie.DISCONNECT:return r===void 0;case ie.CONNECT_ERROR:return typeof r=="string"||$f(r);case ie.EVENT:case ie.BINARY_EVENT:return Array.isArray(r)&&(typeof r0=="number"||typeof r0=="string"&&qT.indexOf(r0)===-1);case ie.ACK:case ie.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},KT=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=GT(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function YT(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=ji(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 lr(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var XT=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Wf=class extends Oe{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=lr(e,"open",this.onopen.bind(this)),lr(e,"packet",this.onpacket.bind(this)),lr(e,"error",this.onerror.bind(this)),lr(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(XT.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:ie.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)=>r!==this._queue0?void 0:(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:ie.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 ie.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 ie.EVENT:case ie.BINARY_EVENT:this.onevent(e);break;case ie.ACK:case ie.BINARY_ACK:this.onack(e);break;case ie.DISCONNECT:this.ondisconnect();break;case ie.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:ie.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.emitReserved("connect"),this._drainQueue(!0)}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:ie.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 kn(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}kn.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};kn.prototype.reset=function(){this.attempts=0};kn.prototype.setMin=function(e){this.ms=e};kn.prototype.setMax=function(e){this.max=e};kn.prototype.setJitter=function(e){this.jitter=e};var Ql=class extends Oe{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,Es(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 kn({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||Jl;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 Vl(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let o=lr(t,"open",function(){r.onopen(),e&&e()}),n=i=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",i),e?e(i):this.maybeReconnectOnOpen()},s=lr(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(lr(e,"ping",this.onping.bind(this)),lr(e,"data",this.ondata.bind(this)),lr(e,"error",this.onerror.bind(this)),lr(e,"close",this.onclose.bind(this)),lr(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){ws(()=>{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 Wf(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)}},ks={};function En(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};let r=YT(e,t.path||"/socket.io"),o=r.source,n=r.id,s=r.path,i=ksn&&s in ksn.nsps,a=t.forceNew||t"force new connection"||t.multiplex===!1||i,c;return a?c=new Ql(o,t):(ksn||(ksn=new Ql(o,t)),c=ksn),r.query&&!t.query&&(t.query=r.queryKey),c.socket(r.path,t)}Object.assign(En,{Manager:Ql,Socket:Wf,io:En,connect:En});function pt(e){return e.val}function bt(e){return e.err}var Gf=" must not return ",JT="transformer",QT="recoverer",ZT="defaultValue",vn=JT+Gf,$r="called with ",Rn=ZT+" must not be ",Tn=QT+Gf;var e0="Ok",qf="Err",zf=$r+qf,Vf=$r+e0,t0="Carrying E in "+qf+" instead of throwing it directly. See .cause",Zl="an instance of Error of the current realm.",uj="The thrown value is not "+Zl,mj="The contained E should be "+Zl,r0="This .cause is not "+Zl;function Ie(e){return e.ok}function oe(e){return{ok:!0,val:e,err:null}}function W(e){return!e.ok}function xe(e){return{ok:!1,val:null,err:e}}function J(e){return Kf(e,zf)}function _n(e){return Yf(e,Vf)}function Kf(e,t){if(W(e))throw new TypeError(t);return e.val}function Yf(e,t){if(Ie(e))throw new TypeError(t);return e.err}async function ep(e,t){if(W(e))return e;let r=pt(e);return await t(r)}function No(e,t){if(W(e))return e;let r=pt(e),o=t(r);return oe(o)}async function Re(e,t){if(W(e))return e;let r=pt(e),o=await t(r);return oe(o)}async function Pe(e,t){if(Ie(e))return e;let r=bt(e),o=await t(r);return xe(o)}async function Hi(e,t){if(Ie(e))return e;let r=bt(e);return await t(r)}var Wi="null",RB=vn+Wi,s0=$r+Wi,TB=Rn+Wi,_B=Tn+Wi;var Gi="undefined",LB=vn+Gi,i0=$r+Gi,CB=Rn+Gi,MB=Tn+Gi;var Te=e=>e.ok?oe(e):xe({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var Jf=async(e,t)=>{let r=new Request(e,t);try{return oe(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return xe({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return xe({name:"NetworkError",message:o.message,request:r});throw o}};var me=e=>{let{fetch:t=Jf,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var Qf=e=>{let{sid:t,hostName:r}=me(e??{});return new Request(https://${r}/api/users/me,t?{headers:{Cookie:be(t)}}:void 0)},Zf=e=>Re(Te(e),async t=>await t.json()),qi=(()=>{let e=async t=>{let{fetch:r,...o}=me(t??{}),n=await r(Qf(o));return W(n)?n:Zf(J(n))};return e.toRequest=Qf,e.fromResponse=Zf,e})();var be=e=>connect.sid=${e},Rr=async e=>{let t=e?.csrf??globalThis._csrf;return t?oe(t):No(await qi(e),r=>r.csrfToken)};var wt=(e,t)=>{if(e?.connected)return Promise.resolve(oe(e));e??=En("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"],...t?{rejectUnauthorized:!1,extraHeaders:{Cookie:be(t),Host:"scrapbox.io",Referer:"https://scrapbox.io/"}}:{}});let r=new Promise(o=>{let n=s=>o(xe(s));e.once("connect",()=>{e.off("disconnect",n),o(oe(e))}),e.once("disconnect",n)});return e.connect(),r},Et=e=>{if(e.disconnected)return Promise.resolve(oe(void 0));let t=new Promise(r=>{let o=n=>{if(n!=="io client disconnect"){r(xe(n));return}r(oe(void 0)),e.off("disconnect",o)};e.on("disconnect",o)});return e.disconnect(),t};var ed=e=>c0.includes(e.name),c0="SocketIOError","DuplicateTitleError","NotFastForwardError";var td=(e,t,r,o)=>{if(t==="cursor")return e.emit(t,r),Promise.resolve(oe(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(xe({name:"SocketIOError"}));return}};e.on("disconnect",c);let l=o?.timeout??9e4,u=setTimeout(()=>{a(),n(xe({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(xe(ed(f.error)?f.error:{name:"UnexpectedRequestError",...f}));return}n(oe(f.data))}),s};function zi(e,t={}){if(e===null)return"null";if(Array.isArray(e))return l0(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:p0(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function l0(e,t){let{threshold:r=20}=t,o=e.map(i=>zi(i,t)),n=o.join(", ");if(n.length<=r)return[${n}];let s=o.join(`,
);return[
${rd(2,s)}
]}function p0(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(i=>${i.toString()}: ${zi(ei,t)}),n=o.join(", ");if(n.length<=r)return{${n}};let s=o.join(,
);return{
${rd(2,s)}
}}function rd(e,t){let r=" ".repeat(e);return t.split(
).map(o=>${r}${o}).join(
)}function et(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=${t}(${r.map(n=>zi(n)).join(", ")}),o)}})}function pr(e){return Array.isArray(e)}function tp(e){return et(t=>pr(t)&&t.every(r=>e(r)),"isArrayOf",e)}function Vi(e){let t=new Set(e);return et(r=>t.has(r),"isLiteralOneOf",e)}function vs(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function Ce(e){return typeof e=="string"}var He=async(e,t)=>{let r=e.response.clone(),o=Vi(t);try{let n=await r.json();if(!vs(n))return;if(r.status===422){if(!Ce(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!Ce(n.message)?void 0:n.name==="NotLoggedInError"?!vs(n.detals)||!Ce(n.detals.project)||!tp(u0)(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}},u0=Vi(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var se=e=>e.replaceAll(" ","_").toLowerCase();var ge=e=>[...e].map((t,r)=>t===" "?"_":!m0.includes(t)||r===e.length-1&&f0.includes(t)?encodeURIComponent(t):t).join(""),m0='@$&+=:;",',f0=':;",';var Ki="null or undefined",Pn=vn+Ki,d0=$r+Ki,Yi=Rn+Ki,Xi=Tn+Ki;function Zt(e){return e!=null}function Tr(e){return e==null}function ur(e,t){if(Zt(e))return e;throw new TypeError(t)}function Ji(e){return Tr(e)?xe(void 0):oe(e)}function rp(e,t){return Zt(e)?e:ur(t,Yi)}var od=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=me(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(https://${n}/api/pages/${e}/${ge(t)}?${a},o?{headers:{Cookie:be(o)}}:void 0)},nd=async e=>Pe(await Re(Te(e),t=>t.json()),async t=>t.response.status===414?{name:"TooLongURIError",message:"project ids may be too much."}:rp(await He(t,["NotFoundError","NotLoggedInError","NotMemberError"]),t)),er=(()=>{let e=async(t,r,o)=>ep(await me(o??{}).fetch(od(t,r,o)),n=>nd(n));return e.toRequest=od,e.fromResponse=nd,e})();var sd=(e,t)=>{let{sid:r,hostName:o}=me(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:be(r)}}:void 0)},id=async e=>Re(await Pe(Te(e),async t=>await He(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),jr=(()=>{let e=async(t,r)=>{let{fetch:o}=me(r??{}),n=sd(t,r),s=await o(n);return W(s)?s:id(J(s))};return e.toRequest=sd,e.fromResponse=id,e})(),ad=(e,t)=>{let{sid:r,hostName:o}=me(t??{}),n=new URLSearchParams(e.map(s=>["ids",s]));return new Request(https://${o}/api/projects?${n},r?{headers:{Cookie:be(r)}}:void 0)},cd=async e=>Re(await Pe(Te(e),async t=>await He(t,["NotLoggedInError"])??t),t=>t.json()),Qi=(()=>{let e=async(t,r)=>{let{fetch:o}=me(r??{}),n=await o(ad(t,r));return W(n)?n:cd(J(n))};return e.toRequest=ad,e.fromResponse=cd,e})();var np=async(e,t,r)=>{let[o,n,s]=await Promise.all([er(e,t,r),h0(r),g0(e,r)]);return W(o)?o:W(n)?n:W(s)?s:oe({...J(o),projectId:J(s),userId:J(n)})},op,h0=async e=>{if(op)return oe(op);let t=await qi(e);if(W(t))return t;let r=J(t);return"id"in r?(op=r.id,oe(r.id)):xe({name:"NotLoggedInError",message:"This script cannot be used without login"})},ld=new Map,g0=async(e,t)=>{let r=ld.get(e);return r?oe(r):No(await jr(e,t),({id:o})=>(ld.set(e,o),o))};function De(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=y0(()=>{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 l;console.error("persistent option is only available in Deno")}})}var pd=2**31-1;function y0(e,t){let r=t=Math.trunc(Math.max(t,0)||0),o=Date.now(),n,s=()=>{r=t-(Date.now()-o),n=r>pd?setTimeout(s,pd):setTimeout(e,r)};return s(),{valueOf:()=>n}}var Lo=async(e,t,r,o)=>{let n=await wt(o?.socket,o?.sid);if(W(n))return xe({name:"UnexpectedRequestError",error:_n(n)});let s=J(n),i=await np(e,t,o);if(W(i))return i;let a=J(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 oe(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 td(s,"commit",f);if(Ie(m))return a.commitId=J(m).commitId,oe(a.commitId);let h=_n(m),g=h.name;if(g==="SocketIOServerDisconnectError"||g==="UnexpectedRequestError")return xe(h);if(g==="TimeoutError"||g==="SocketIOError"){await De(3e3);continue}if(g==="NotFastForwardError"){await De(1e3);let y=await np(e,t,o);if(W(y))return y;a=J(y)}u=g;break}}return xe({name:"RetryError",attempts:c,message:Retrying exceeded the maxAttempts (${c}).})}finally{o?.socket||await Et(s)}};var sp=(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 E=Math.max(y,x),v=E-g;for(;v<o.length&&E<n.length&&o[v]===n[E];)++v,++E;return a[g+s]=c.length,c.push([{x:v,y:E},a[g+(y>x?-1:1)+s]]),E}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:E}of x0(m))for(;g<x||y<E;)E-x>y-g?(yield{value:n[y],type:r?"deleted":"added"},++y):E-x<y-g?(yield{value:o[g],type:r?"added":"deleted"},++g):(yield{value:o[g],type:"common"},++g,++y)}}};function*ip(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield ud(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 ud(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 ud=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*x0(e){for(let t=e.length-1;t>=0;t--)yield e[t]}var md=e=>e.padStart(8,"0"),ap=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${md(t).slice(-8)}${e.slice(-6)}0000${md(r)}};function*cp(e,t,{userId:r}){let{buildSES:o}=sp(e.map(({text:i})=>i),t),n=0,s=e[0].id;for(let i of ip(o())){switch(i.type){case"added":yield{_insert:s,lines:{id:ap(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 b0=(e,t)=>(e.type==="codeBlock"||e.type==="table")&&t.indent>(e.rows[0]?.indent??0),fd=(e,t)=>{let r=e[e.length-1];return r!==void 0&&b0(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},dd=(e,t)=>{if(t.hasTitle??!0){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(fd,[])]}return e.reduce(fd,[])};var hd=e=>e.split(
).map(t=>({indent:/^\s+/.exec(t)?.[0]?.length??0,text:t}));var gd=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(i=>i.text.substring(o+1)).join(
)}};var ae=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested)return i?.()??[];if(!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??0)),p=e(c[0]??"",s);return[...St(l,s),...p,...St(u,s)]}return i?.()??[]};var de=e=>[{type:"plain",raw:e,text:e}],yd=ae(de,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]});var w0=/\[\s+\]/,E0=(e,t)=>t.context==="table"?de(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],xd=ae(E0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[w0]});var k0=/.*?/,v0=(e,t)=>t.context==="table"?de(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],bd=ae(v0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[k0]});var R0=/^[$%] .+$/,T0=(e,t)=>{if(t.context==="table")return de(e,t);let r=e[0]??"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},wd=ae(T0,{parseOnNested:!1,parseOnQuoted:!1,patterns:[R0]});var _0=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,P0=(e,t)=>{if(t.context==="table")return de(e,t);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:St(n,{...t,nested:!0})}]},Ed=ae(P0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[_0]});var O0=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,S0=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,N0=/\[https?:\/\/[^\s\]]+\]/,L0=/https?:\/\/[^\s]+/,C0=(e,t)=>{if(t.context==="table")return de(e,t);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?.[0]===void 0)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()}]},kd=ae(C0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[O0,S0,N0,L0]});var M0=/\[\$ .+? \]/,A0=/\[\$ [^\]]+\]/,I0=(e,t)=>t.context==="table"?de(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],vd=ae(I0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[M0,A0]});var Rd=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Td=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,F0=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}},D0=(e,t)=>{if(t.context==="table")return de(e,t);let r=e.match(Rd)??e.match(Td);if(r===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,n="",s=""]=o?r:[r[0],r[2],r[1]],{latitude:i,longitude:a,zoom:c}=F0(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:e,latitude:i,longitude:a,zoom:c,place:s,url:l}]},_d=ae(D0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Rd,Td]});var U0=/(?:^|\s)#\S+/,$0=(e,t)=>{if(t.context==="table")return de(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...de(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},Pd=ae($0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[U0]});var j0=/^\? .+$/,B0=(e,t)=>t.context==="table"?de(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],Od=ae(B0,{parseOnNested:!1,parseOnQuoted:!1,patterns:[j0]});var H0=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,W0=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}))},Sd=ae(W0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[H0]});var G0=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,q0=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,z0=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,V0=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,K0=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||Y0(e),Y0=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),X0=(e,t)=>{if(t.context==="table")return de(e,t);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]=K0(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}]},Nd=ae(X0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[G0,q0,z0,V0]});var J0=/\[\/?[^[\]]+\]/,Q0=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},Ld=ae(Q0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[J0]});var Z0=/^[0-9]+\. .*$/,e_=(e,t)=>{if(t.context==="table")return de(e,t);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:St(s,{...t,nested:!1})}]},Cd=ae(e_,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Z0]});var t_=/^>.*$/,r_=(e,t)=>t.context==="table"?de(e,t):[{type:"quote",raw:e,nodes:St(e.substring(1),{...t,quoted:!0})}],Md=ae(r_,{parseOnNested:!1,parseOnQuoted:!1,patterns:[t_]});var o_=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,n_=(e,t)=>{if(t.context==="table")return de(e,t);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}))},Ad=ae(n_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[o_]});var s_=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,i_=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,a_=(e,t)=>{if(t.context==="table")return de(e,t);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}]},Id=ae(a_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[s_,i_]});var c_=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,l_=(e,t)=>t.context==="table"?de(e,t):[{type:"strong",raw:e,nodes:St(e.substring(2,e.length-2),{...t,nested:!0})}],Fd=ae(l_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[c_]});var p_=(e,t,r)=>e===""?[]:r?.()??[],u_=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>yd(t,r))(),St=u_(p_,Md,Od,Cd,bd,wd,vd,xd,Ed,Id,Ad,Fd,Nd,kd,Sd,_d,Ld,Pd);var Dd=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:St(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var Ud=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(i=>i.text.substring(o+1)).map(i=>i.split(" ").map(a=>St(a,{nested:!1,quoted:!1,context:"table"})))}};var $d=e=>({type:"title",text:e.rows[0].text});var jd=e=>{switch(e.type){case"title":return $d(e);case"codeBlock":return gd(e);case"table":return Ud(e);case"line":return Dd(e)}};var kt=(e,t)=>{let r=hd(e);return dd(r,{hasTitle:t?.hasTitle??!0}).map(jd)},Bd=e=>/^\s*\S.*$/m.exec(e)?.[0]?.trim()??"Untitled";var m_=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,f_=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,d_=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,h_=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,Zi=e=>{if(m_.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(f_);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(d_);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match(h_);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};var Gd=e=>{let t=kt(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(se(x.href)))return;o.set(se(x.href),!1),n.push(x.href);return;case"link":switch(x.pathType){case"relative":{let E=Wd(x.href);if(o.get(se(E)))return;o.set(se(E),!0),n.push(E);return}case"root":{let E=Wd(x.href);if(/^\/[\w\d-]+\/?$/.test(E)||s.has(se(E)))return;s.add(se(E)),i.push(E);return}case"absolute":{if(x.content)return;let E=Zi(x.href);if(E&&E.pathType!=="list"){l??=https://i.ytimg.com/vi/${E.videoId}/mqdefault.jpg;return}let v=x.href.match(m)?.[1];v&&p.add(v);return}default:return}case"icon":case"strongIcon":{if(x.pathType==="root"||a.has(se(x.path)))return;a.add(se(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 E=x.src.match(m)?.[1];E&&p.add(E)}if(x.type==="image"){let E=x.link.match(m)?.[1];E&&p.add(E)}return}case"helpfeel":f.add(x.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let E of x.nodes)h(E);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"?Hd(x.nodes[0].raw):x.nodes.map(E=>E.raw).join("").trim().slice(0,200));for(let E of x.nodes)h(E);continue;case"codeBlock":u.length<5&&u.push(Hd(x.content));continue;case"table":{for(let E of x.cells)for(let v of E)for(let b of v)h(b);if(!["infobox","cosense"].includes(x.fileName))continue;g.push(...x.cells.map(E=>E.map(v=>v.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,E)=>x+[...E].length,0)]},Hd=e=>\${e.trim().replaceAll("","\\").slice(0,198)}\`,Wd=e=>e.replace(/#a-f\d{24,32}$/,"");var so=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));var qd=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?t.trimStart().slice(2):[]);function*zd(e,t,r){let o=t.flatMap(g=>(Ce(g)?g:g.text).split(`
));for(let g of cp(e.lines,o,{userId:r}))yield g;let[n,s,i,a,c,l,u,p,f,m,h]=Gd(o.join(
));(e.title!==n||!e.persistent)&&(yield{title:n}),so(e.links,s)||(yield{links:s}),so(e.projectLinks,i)||(yield{projectLinks:i}),so(e.icons,a)||(yield{icons:a}),e.image!==c&&(yield{image:c}),so(e.descriptions,l)||(yield{descriptions:l}),so(e.files,u)||(yield{files:u}),so(qd(e.lines),p)||(yield{helpfeels:p}),so(e.infoboxDefinition,f)||(yield{infoboxDefinition:f}),yield{linesCount:m},yield{charsCount:h}}var Vd=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,o=t?.[2]?parseInt(t[2])+1:2;return${r}_${o}};var Kd=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);var Me=(e,t,r,o)=>Lo(e,t,async(n,s,i,a)=>{if(a==="DuplicateTitleError"){let m=Vd(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?[]:[...zd(n,u,n.userId)];return p!==void 0&&(p&&n.pin===0||!p&&n.pin>0)&&f.push({pin:p?Kd():0}),f},o);var Yd=(e,t,r)=>Lo(e,t,o=>o.persistent?[{deleted:!0}]:[],r);var ea=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i}=me(o??{}),a=await Rr(o);if(W(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":J(a),...n?{Cookie:be(n)}:{}},body:JSON.stringify({from:t,to:r})}),l=await i(c);return W(l)?l:Re(await Pe(Te(J(l)),async u=>await He(u,["NotFoundError","NotLoggedInError","NotMemberError"])??u),async u=>{let{message:p}=await u.json();return parseInt(p.match(/\d+/)?.[0]??"0")})};var Xd=(e,t)=>{let{sid:r,hostName:o,followingId:n}=me(t??{});return new Request(https://${o}/api/pages/${e}/search/titles${n??followingId=${n}:""},r?{headers:{Cookie:be(r)}}:void 0)},Jd=async e=>Re(await Pe(Te(e),async t=>t.response.status===422?{name:"InvalidFollowingIdError",message:await t.response.text()}:await He(t,["NotFoundError","NotLoggedInError"])??t),t=>t.json().then(r=>({pages:r,followingId:t.headers.get("X-following-id")??""}))),x_=(()=>{let e=async(t,r)=>{let o=await me(r??{}).fetch(Xd(t,r));return W(o)?o:Jd(J(o))};return e.toRequest=Xd,e.fromResponse=Jd,e})();async function*Qd(e,t){let r;do{let o=await x_(e,{followingId:r,...t});if(W(o)){yield o;return}let n=J(o);yield oe(n.pages),r=n.followingId}while(r)}var Zd=async(e,t,r)=>{let{sid:o,hostName:n,fetch:s}=me(r??{}),i=new Request(https://${n}/api/pages/${t}/search/query?q=${encodeURIComponent(e)},o?{headers:{Cookie:be(o)}}:void 0),a=await s(i);return W(a)?a:Re(await Pe(Te(J(a)),async c=>await He(c,["NotFoundError","NotLoggedInError","NotMemberError","NoQueryError"])??c),c=>c.json())};var eh=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=me(t??{}),s=await Rr(t);if(W(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":J(s),...r?{Cookie:be(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return W(a)?a:Re(await Pe(Te(J(a)),async c=>await He(c,["SessionError","BadRequestError","InvalidURLError"])??c),async c=>{let{title:l}=await c.json();return l})};var th=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=me(t??{}),s=await Rr(t);if(W(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":J(s),...r?{Cookie:be(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return W(a)?a:Pe(await Re(Te(J(a)),c=>c.json()),async c=>c.response.status===422?{name:"InvalidURLError",message:(await c.response.json()).message}:await He(c,["SessionError","BadRequestError"])??c)};var rh=async e=>{let{fetch:t,sid:r,hostName:o,gyazoTeamsName:n}=me(e??{}),s=new Request(https://${o}/api/login/gyazo/oauth-upload/token${n??gyazoTeamsName=${n}:""},r?{headers:{Cookie:be(r)}}:void 0),i=await t(s);return W(i)?i:Re(await Pe(Te(J(i)),async a=>await He(a,["NotLoggedInError"])??a),a=>a.json().then(c=>c.token))};var oh=(e,t,r,o)=>{let{sid:n,hostName:s}=me(o??{});return new Request(https://${s}/api/code/${e}/${ge(t)}/${ge(r)},n?{headers:{Cookie:be(n)}}:void 0)},nh=async e=>Re(await Pe(Te(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 He(t,["NotLoggedInError","NotMemberError"])??t),t=>t.text()),ta=(()=>{let e=async(t,r,o,n)=>{let s=oh(t,r,o,n),i=await me(n??{}).fetch(s);return W(i)?i:nh(J(i))};return e.toRequest=oh,e.fromResponse=nh,e})();var ah=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(lp),n=0,s=0,i=0;[r,o,n,s,i]=ih(r,o,n,s,i,t);let a=lp-n;a<9&&(a+=lp);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]=ih(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},lp=64,H=(e,t)=>e<<t|e>>>32-t,vt=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,sh=(e,t)=>{let[r,o,n,s]=e,i=vt(t,0),a=vt(t,4),c=vt(t,8),l=vt(t,12),u=vt(t,16),p=vt(t,20),f=vt(t,24),m=vt(t,28),h=vt(t,32),g=vt(t,36),y=vt(t,40),x=vt(t,44),E=vt(t,48),v=vt(t,52),b=vt(t,56),T=vt(t,60);return r=o+H(((n^s)&o^s)+r+i+3614090360,7),s=r+H(((o^n)&r^n)+s+a+3905402710,12),n=s+H(((r^o)&s^o)+n+c+606105819,17),o=n+H(((s^r)&n^r)+o+l+3250441966,22),r=o+H(((n^s)&o^s)+r+u+4118548399,7),s=r+H(((o^n)&r^n)+s+p+1200080426,12),n=s+H(((r^o)&s^o)+n+f+2821735955,17),o=n+H(((s^r)&n^r)+o+m+4249261313,22),r=o+H(((n^s)&o^s)+r+h+1770035416,7),s=r+H(((o^n)&r^n)+s+g+2336552879,12),n=s+H(((r^o)&s^o)+n+y+4294925233,17),o=n+H(((s^r)&n^r)+o+x+2304563134,22),r=o+H(((n^s)&o^s)+r+E+1804603682,7),s=r+H(((o^n)&r^n)+s+v+4254626195,12),n=s+H(((r^o)&s^o)+n+b+2792965006,17),o=n+H(((s^r)&n^r)+o+T+1236535329,22),r=o+H(((o^n)&s^n)+r+a+4129170786,5),s=r+H(((r^o)&n^o)+s+f+3225465664,9),n=s+H(((s^r)&o^r)+n+x+643717713,14),o=n+H(((n^s)&r^s)+o+i+3921069994,20),r=o+H(((o^n)&s^n)+r+p+3593408605,5),s=r+H(((r^o)&n^o)+s+y+38016083,9),n=s+H(((s^r)&o^r)+n+T+3634488961,14),o=n+H(((n^s)&r^s)+o+u+3889429448,20),r=o+H(((o^n)&s^n)+r+g+568446438,5),s=r+H(((r^o)&n^o)+s+b+3275163606,9),n=s+H(((s^r)&o^r)+n+l+4107603335,14),o=n+H(((n^s)&r^s)+o+h+1163531501,20),r=o+H(((o^n)&s^n)+r+v+2850285829,5),s=r+H(((r^o)&n^o)+s+c+4243563512,9),n=s+H(((s^r)&o^r)+n+m+1735328473,14),o=n+H(((n^s)&r^s)+o+E+2368359562,20),r=o+H((o^n^s)+r+p+4294588738,4),s=r+H((r^o^n)+s+h+2272392833,11),n=s+H((s^r^o)+n+x+1839030562,16),o=n+H((n^s^r)+o+b+4259657740,23),r=o+H((o^n^s)+r+a+2763975236,4),s=r+H((r^o^n)+s+u+1272893353,11),n=s+H((s^r^o)+n+m+4139469664,16),o=n+H((n^s^r)+o+y+3200236656,23),r=o+H((o^n^s)+r+v+681279174,4),s=r+H((r^o^n)+s+i+3936430074,11),n=s+H((s^r^o)+n+l+3572445317,16),o=n+H((n^s^r)+o+f+76029189,23),r=o+H((o^n^s)+r+g+3654602809,4),s=r+H((r^o^n)+s+E+3873151461,11),n=s+H((s^r^o)+n+T+530742520,16),o=n+H((n^s^r)+o+c+3299628645,23),r=o+H((n^(o|~s))+r+i+4096336452,6),s=r+H((o^(r|~n))+s+m+1126891415,10),n=s+H((r^(s|~o))+n+b+2878612391,15),o=n+H((s^(n|~r))+o+p+4237533241,21),r=o+H((n^(o|~s))+r+E+1700485571,6),s=r+H((o^(r|~n))+s+l+2399980690,10),n=s+H((r^(s|~o))+n+y+4293915773,15),o=n+H((s^(n|~r))+o+a+2240044497,21),r=o+H((n^(o|~s))+r+h+1873313359,6),s=r+H((o^(r|~n))+s+T+4264355552,10),n=s+H((r^(s|~o))+n+f+2734768916,15),o=n+H((s^(n|~r))+o+v+1309151649,21),r=o+H((n^(o|~s))+r+u+4149444226,6),s=r+H((o^(r|~n))+s+x+3174756917,10),n=s+H((r^(s|~o))+n+c+718787259,15),o=n+H((s^(n|~r))+o+g+3951481745,21),[e[0]+r>>>0,e[1]+o>>>0,e[2]+n>>>0,e[3]+s>>>0]},ih=(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=sh(e,t);let a=i;for(;a+64<=s.length;)e=sh(e,s.slice(a,a+64)),a+=64;t.fill(0).set(s.slice(a),0),r=s.length-a}return[o,n]=b_(o,n,s.length),[e,t,r,o,n]},b_=(e,t,r)=>(e+=r,e>4294967295&&(t+=1),[e>>>0,t]);var w_=new TextEncoder().encode("0123456789abcdef"),ch=new Uint8Array(128).fill(16);w_.forEach((e,t)=>ch[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>ch[e]=t+10);function lh(e){return e*2}function ph(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 uh(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 mh=new TextEncoder().encode("0123456789abcdef"),fh=new Uint8Array(128).fill(16);mh.forEach((e,t)=>fh[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>fh[e]=t+10);function dh(e){typeof e=="string"?e=new TextEncoder().encode(e):e instanceof ArrayBuffer?e=new Uint8Array(e).slice():e=e.slice();let[t,r]=uh(e,lh(e.length));return ph(t,r,0,mh),new TextDecoder().decode(t)}var hh=async(e,t,r)=>{let o=${dh(ah(await e.arrayBuffer()))},n=await E_(e,t,o,r);if(W(n))return n;let s=J(n);if("embedUrl"in s)return oe(s);let i=await k_(s.signedUrl,e,r);return W(i)?i:v_(t,s.fileId,o,r)},E_=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=me(o??{}),c={md5:r,size:e.size,contentType:e.type,name:e.name},l=await Hi(Ji(a),()=>Rr(o));if(W(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":J(l),...n?{Cookie:be(n)}:{}}}),p=await i(u);return W(p)?p:Re(await Pe(Te(J(p)),async f=>f.response.status===402?{name:"FileCapacityError",message:(await f.response.json()).message}:f),f=>f.json())},k_=async(e,t,r)=>{let{sid:o,fetch:n}=me(r??{}),s=await n(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...o?{Cookie:be(o)}:{}}});return W(s)?s:No(await Pe(Te(J(s)),async i=>i.response.headers.get("Content-Type")?.includes?.("/xml")?{name:"GCSError",message:await i.response.text()}:i),()=>{})},v_=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=me(o??{}),c=await Hi(Ji(a),()=>Rr(o));if(W(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":J(c),...n?{Cookie:be(n)}:{}}}),u=await i(l);return W(u)?u:Re(await Pe(Te(J(u)),async p=>p.response.status===404?{name:"NotFoundError",message:(await p.response.json()).message}:p),p=>p.json())};function Rt(e){return e.val}function Dt(e){return e.err}var gh=" must not return ",R_="transformer",T_="recoverer",__="defaultValue",ra=R_+gh,Co="called with ",oa=__+" must not be ",na=T_+gh;var P_="Ok",yh="Err",xh=Co+yh,bh=Co+P_,O_="Carrying E in "+yh+" instead of throwing it directly. See .cause",pp="an instance of Error of the current realm.",a5="The thrown value is not "+pp,c5="The contained E should be "+pp,S_="This .cause is not "+pp;function We(e){return e.ok}function le(e){return{ok:!0,val:e,err:null}}function G(e){return!e.ok}function ee(e){return{ok:!1,val:null,err:e}}function z(e){return wh(e,xh)}function ne(e){return Eh(e,bh)}function wh(e,t){if(G(e))throw new TypeError(t);return e.val}function Eh(e,t){if(We(e))throw new TypeError(t);return e.err}async function Gt(e,t){if(G(e))return e;let r=Rt(e),o=await t(r);return le(o)}function up(e,t,r){if(We(e)){let n=Rt(e);return r(n)}let o=Dt(e);return t(o)}var sa="null",d8=ra+sa,C_=Co+sa,h8=oa+sa,g8=na+sa;var ia="undefined",E8=ra+ia,M_=Co+ia,k8=oa+ia,v8=na+ia;var vh=async e=>{let t=e.title??".watchlistrc",r="projectsLastAccessed.json",o=await ta(e.project,t,r),n=G(o)?{}:JSON.parse(z(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 Me(e.project,t,()=>[t,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","",code:${r}, ${c},""])};var qt=!1,aa=e=>{qt=typeof e=="boolean"?e:new Set(e)},On=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},mp,...o)];case"log":case"info":case"debug":return[t,(...o)=>{qt!==!0&&(!qt||!qt.has(e))||r(%c${e},mp,...o)}];case"assert":return[t,(o,...n)=>{qt!==!0&&(!qt||!qt.has(e))||r(o,%c${e},mp,...n)}];case"time":case"timeEnd":return[t,o=>{qt!==!0&&(!qt||!qt.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(qt!==!0&&(!qt||!qt.has(e))))return r(...o)}]}})),mp="color: gray";var Br=globalThis.scrapbox;var ca=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}};var Rh=e=>{let{accessToken:t,fetch:r,page:o,per:n}=ca(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 Sn="Gyazo Viewer",Th=e=>{let t=Promise.resolve(),r=globalThis.GM_fetch;Br.PageMenu.addMenu({title:r?Sn:"Open Gyazo",icon:"kamon kamon-gyazo",onClick:r?()=>{t=t.then(()=>I_({per:e.maxCount??10,accessToken:e.accessToken,fetch:r,onClick:e.onClick}))}:()=>globalThis.open("https://gyazo.com/captures")})},I_=async e=>{let t;try{let r=Rh({page:0,...e});t=setTimeout(()=>{Br.PageMenu(Sn).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),Br.PageMenu(Sn).removeAllItems();for(let s of n)s.image_id&&Br.PageMenu(Sn).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),Br.PageMenu(Sn).removeAllItems(),Br.PageMenu(Sn).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 s$}from"https://scrapbox.io/api/code/takker-memex/GYAZO_ACCESS_TOKEN/auth.js";var ma,te,Sh,F_,Mo,_h,Nh,Lh,Ch,yp,fp,dp,Mh,Rs={},Ah=[],D_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ts=Array.isArray;function Hr(e,t){for(var r in t)e[r]=t[r];return e}function xp(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Wr(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?ma.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 pa(e,i,o,n,null)}function pa(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??++Sh,__i:-1,__u:0};return n==null&&te.vnode!=null&&te.vnode(s),s}function Q(e){return e.children}function mr(e,t){this.props=e,this.context=t}function Nn(e,t){if(t==null)return e.__?Nn(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"?Nn(e):null}function Ih(e){var t,r;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null){e.__e=e.__c.base=r.__e;break}return Ih(e)}}function hp(e){(!e.__d&&(e.__d=!0)&&Mo.push(e)&&!ua.__r++||_h!=te.debounceRendering)&&((_h=te.debounceRendering)||Nh)(ua)}function ua(){for(var e,t,r,o,n,s,i,a=1;Mo.length;)Mo.length>a&&Mo.sort(Lh),e=Mo.shift(),a=Mo.length,e.__d&&(r=void 0,n=(o=(t=e).__v).__e,s=[],i=[],t.__P&&((r=Hr({},o)).__v=o.__v+1,te.vnode&&te.vnode(r),bp(t.__P,r,o,t.__n,t.__P.namespaceURI,32&o.__u?[n]:null,s,n??Nn(o),!!(32&o.__u),i),r.__v=o.__v,r.__.__k[r.__i]=r,Uh(s,r,i),r.__e!=n&&Ih(r)));ua.__r=0}function Fh(e,t,r,o,n,s,i,a,c,l,u){var p,f,m,h,g,y,x,E=o&&o.__k||Ah,v=t.length;for(c=U_(r,t,E,c,v),p=0;p<v;p++)(m=r.__k[p])!=null&&(f=m.__i==-1?Rs:E[m.__i]||Rs,m.__i=p,y=bp(e,m,f,n,s,i,a,c,l,u),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&wp(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=Dh(m,c,e,x):typeof m.type=="function"&&y!==void 0?c=y:h&&(c=h.nextSibling),m.__u&=-7);return r.__e=g,c}function U_(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"?(c=s+f,(i=e.__k[s]=typeof i=="string"||typeof i=="number"||typeof i=="bigint"||i.constructor==String?pa(null,i,null,null,null):Ts(i)?pa(Q,{children:i},null,null,null):i.constructor==null&&i.__b>0?pa(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i).__=e,i.__b=e.__b+1,a=null,(l=i.__i=$_(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=Nn(a)),jh(a,a));return o}function Dh(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=Dh(n[s],t,r,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=Nn(e)),r.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function io(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ts(e)?e.some(function(r){io(r,t)}):t.push(e)),t}function $_(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&&e.key==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 Ph(e,t,r){t[0]=="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||D_.test(t)?r:r+"px"}function la(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||Ph(e.style,t,"");if(r)for(t in r)o&&r[t]==o[t]||Ph(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(Ch,"$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.u=o.u:(r.u=yp,e.addEventListener(t,s?dp:fp,s)):e.removeEventListener(t,s?dp:fp,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 Oh(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t.t==null)t.t=yp++;else if(t.t<r.u)return;return r(te.event?te.event(t):t)}}}function bp(e,t,r,o,n,s,i,a,c,l){var u,p,f,m,h,g,y,x,E,v,b,T,R,L,C,M,O,_=t.type;if(t.constructor!=null)return null;128&r.__u&&(c=!!(32&r.__u),s=[a=t.__e=r.__e]),(u=te.__b)&&u(t);e:if(typeof _=="function")try{if(x=t.props,E="prototype"in _&&_.prototype.render,v=(u=_.contextType)&&o[u.__c],b=u?v?v.props.value:u.__:o,r.__c?y=(p=t.__c=r.__c).__=p.__E:(E?t.__c=p=new _(x,b):(t.__c=p=new mr(x,b),p.constructor=_,p.render=B_),v&&v.sub(p),p.props=x,p.state||(p.state={}),p.context=b,p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),E&&p.__s==null&&(p.__s=p.state),E&&_.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Hr({},p.__s)),Hr(p.__s,_.getDerivedStateFromProps(x,p.__s))),m=p.props,h=p.state,p.__v=t,f)E&&_.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),E&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(E&&_.getDerivedStateFromProps==null&&x!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,b),!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,b)===!1||t.__v==r.__v){for(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(P){P&&(P.__=t)}),T=0;T<p._sb.length;T++)p.__h.push(p._sb[T]);p._sb=[],p.__h.length&&i.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,b),E&&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,R=te.__r,L=0,E){for(p.state=p.__s,p.__d=!1,R&&R(t),u=p.render(p.props,p.state,p.context),C=0;C<p._sb.length;C++)p.__h.push(p._sb[C]);p._sb=[]}else do p.__d=!1,R&&R(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++L<25);p.state=p.__s,p.getChildContext!=null&&(o=Hr(Hr({},o),p.getChildContext())),E&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),M=u,u!=null&&u.type===Q&&u.key==null&&(M=$h(u.props.children)),a=Fh(e,Ts(M)?M:[M],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(P){if(t.__v=null,c||s!=null)if(P.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(O=s.length;O--;)xp(s[O]);gp(t)}else t.__e=r.__e,t.__k=r.__k,P.then||gp(t);te.__e(P,t,r)}else s==null&&t.__v==r.__v?(t.__k=r.__k,t.__e=r.__e):a=t.__e=j_(r.__e,t,r,o,n,s,i,c,l);return(u=te.diffed)&&u(t),128&t.__u?void 0:a}function gp(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(gp)}function Uh(e,t,r){for(var o=0;o<r.length;o++)wp(r[o],r[++o],r[++o]);te.__c&&te.__c(t,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(s){s.call(n)})}catch(s){te.__e(s,n.__v)}})}function $h(e){return typeof e!="object"||e==null||e.__b&&e.__b>0?e:Ts(e)?e.map($h):Hr({},e)}function j_(e,t,r,o,n,s,i,a,c){var l,u,p,f,m,h,g,y=r.props,x=t.props,E=t.type;if(E=="svg"?n="http://www.w3.org/2000/svg":E=="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==!!E&&(E?m.localName==E:m.nodeType==3)){e=m,s[l]=null;break}}if(e==null){if(E==null)return document.createTextNode(x);e=document.createElementNS(n,E,x.is&&x),a&&(te.__m&&te.__m(t,s),a=!1),s=null}if(E==null)y===x||a&&e.data==x||(e.data=x);else{if(s=s&&ma.call(e.childNodes),y=r.props||Rs,!a&&s!=null)for(y={},l=0;l<e.attributes.length;l++)y[(m=e.attributes[l]).name]=m.value;for(l in y)if(m=y[l],l!="children"){if(l=="dangerouslySetInnerHTML")p=m;else if(!(l in x)){if(l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x)continue;la(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||la(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=""),Fh(t.type=="template"?e.content:e,Ts(f)?f:[f],t,r,o,E=="foreignObject"?"http://www.w3.org/1999/xhtml":n,s,i,s?s[0]:r.__k&&Nn(r,0),a,c),s!=null)for(l=s.length;l--;)xp(s[l]);a||(l="value",E=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[l]||E=="progress"&&!h||E=="option"&&h!=y[l])&&la(e,l,h,y[l],n),l="checked",g!=null&&g!=e[l]&&la(e,l,g,y[l],n))}return e}function wp(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){te.__e(n,r)}}function jh(e,t,r){var o,n;if(te.unmount&&te.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||wp(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){te.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(n=0;n<o.length;n++)o[n]&&jh(o[n],t,r||typeof e.type!="function");r||xp(e.__e),e.__c=e.__=e.__e=void 0}function B_(e,t,r){return this.constructor(e,r)}function ut(e,t,r){var o,n,s,i;t==document&&(t=document.documentElement),te.__&&te.__(e,t),n=(o=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],bp(t,e=(!o&&r||t).__k=Wr(Q,null,[e]),n||Rs,Rs,t.namespaceURI,!o&&r?[r]:n?null:t.firstChild?ma.call(t.childNodes):null,s,!o&&r?r:n?n.__e:t.firstChild,o,i),Uh(s,e,i)}function _s(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,hp(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"+Mh++,t.__=e,t.Provider=t.__l=(t.Consumer=function(r,o){return r.children(o)}).contextType=t,t}ma=Ah.slice,te={__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}},Sh=0,F_=function(e){return e!=null&&e.constructor==null},mr.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Hr({},this.state),typeof e=="function"&&(e=e(Hr({},r),this.props)),e&&Hr(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),hp(this))},mr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),hp(this))},mr.prototype.render=Q,Mo=[],Nh=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Lh=function(e,t){return e.__v.__b-t.__v.__b},ua.__r=0,Ch=/(PointerCapture)$|Capture$/i,yp=0,fp=Oh(!1),dp=Oh(!0),Mh=0;var Ao,Fe,Ep,Bh,Ps=0,Yh=[],ze=te,Hh=ze.__b,Wh=ze.__r,Gh=ze.diffed,qh=ze.__c,zh=ze.unmount,Vh=ze.__;function Os(e,t){ze.__h&&ze.__h(Fe,e,Ps||t),Ps=0;var r=Fe.__H||(Fe.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function X(e){return Ps=1,ao(Xh,e)}function ao(e,t,r){var o=Os(Ao++,2);if(o.t=e,!o.__c&&(o.__=[r?r(t):Xh(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=Fe,!Fe.__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.forEach(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};Fe.__f=!0;var s=Fe.shouldComponentUpdate,i=Fe.componentWillUpdate;Fe.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)},Fe.shouldComponentUpdate=n}return o.__N||o.__}function Z(e,t){var r=Os(Ao++,3);!ze.__s&&vp(r.__H,t)&&(r.__=e,r.u=t,Fe.__H.__h.push(r))}function da(e,t){var r=Os(Ao++,4);!ze.__s&&vp(r.__H,t)&&(r.__=e,r.u=t,Fe.__h.push(r))}function tt(e){return Ps=5,U(function(){return{current:e}},[])}function U(e,t){var r=Os(Ao++,7);return vp(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function A(e,t){return Ps=8,U(function(){return e},t)}function Gr(e){var t=Fe.context[e.__c],r=Os(Ao++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(Fe)),t.props.value):e.__}function H_(){for(var e;e=Yh.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(fa),e.__H.__h.forEach(kp),e.__H.__h=[]}catch(t){e.__H.__h=[],ze.__e(t,e.__v)}}ze.__b=function(e){Fe=null,Hh&&Hh(e)},ze.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Vh&&Vh(e,t)},ze.__r=function(e){Wh&&Wh(e),Ao=0;var t=(Fe=e.__c).__H;t&&(Ep===Fe?(t.__h=[],Fe.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})):(t.__h.forEach(fa),t.__h.forEach(kp),t.__h=[],Ao=0)),Ep=Fe},ze.diffed=function(e){Gh&&Gh(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Yh.push(t)!==1&&Bh===ze.requestAnimationFrame||((Bh=ze.requestAnimationFrame)||W_)(H_)),t.__H.__.forEach(function(r){r.u&&(r.__H=r.u),r.u=void 0})),Ep=Fe=null},ze.__c=function(e,t){t.some(function(r){try{r.__h.forEach(fa),r.__h=r.__h.filter(function(o){return!o.__||kp(o)})}catch(o){t.some(function(n){n.__h&&(n.__h=[])}),t=[],ze.__e(o,r.__v)}}),qh&&qh(e,t)},ze.unmount=function(e){zh&&zh(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(o){try{fa(o)}catch(n){t=n}}),r.__H=void 0,t&&ze.__e(t,r.__v))};var Kh=typeof requestAnimationFrame=="function";function W_(e){var t,r=function(){clearTimeout(o),Kh&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(r,35);Kh&&(t=requestAnimationFrame(r))}function fa(e){var t=Fe,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),Fe=t}function kp(e){var t=Fe;e.__c=e.__(),Fe=t}function vp(e,t){return!e||e.length!==t.length||t.some(function(r,o){return r!==e[o]})}function Xh(e,t){return typeof t=="function"?t(e):t}function Ue(e){return typeof e=="number"}var G_=(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}},q_=G_,Rp=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name=this.constructor.name}};function Jh(e,t,r={}){if(!t(e))throw new Rp(r.message??q_(e,t,r.name))}function Tp(e,t,r={}){return Jh(e,t,r),e}function mt(e){return typeof e>"u"}var ha=!1,Qh=null,Zh=()=>{scrapbox.addListener("lines:changed",()=>ha=!1),scrapbox.addListener("layout:changed",()=>ha=!1),Zh=void 0},eg=()=>(Zh?.(),ha||(Qh=scrapbox.Page.lines,ha=!0),Qh);var tg=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var rg=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var og=()=>ga(document.getElementById("editor"),"div#editor"),Ss=()=>ga(document.getElementsByClassName("lines").item(0),"div.lines");var rt=()=>{let e=document.getElementById("text-input");if(e)return rg(e,"textarea#text-input"),e};var ng=()=>ga(document.getElementsByClassName("popup-menu")?.[0],"div.popup-menu");var sg=()=>ga(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),ga=(e,t)=>{if(e)return tg(e,t),e};var Ut=()=>{let e=Ss();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 qr=e=>e.match(/^(\s*)/)?.[1]?.length??0,Io=(e,t)=>{let r=qr(ig(e,t)),o=0;for(;e+o+1<t.length&&qr(ig(e+o+1,t))>r;)o++;return o},ig=(e,t)=>{let r=t[e];return Ce(r)?r:r.text};var _p=e=>{if(mt(e))return;if(Ue(e))return ya(e)?.id;if(Ce(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)},ag=e=>{if(mt(e))return;if(Ue(e))return e;let t=_p(e);return t?Ut().findIndex(r=>r.id===t):-1};var ya=e=>{if(mt(e))return;if(Ue(e))return Ut()[e];let t=_p(e);return t?Ut().find(r=>r.id===t):void 0},Fo=e=>{if(cg(e))return e;let t=_p(e);if(mt(t))return t;let r=document.getElementById(L${t});if(!mt(r))return r},cg=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var co=()=>Tp(eg(),pr),ft=e=>{if(mt(e))return;if(Ue(e)||Ce(e))return ya(e)?.text;if(!(e instanceof HTMLElement))return;if(cg(e))return ya(e)?.text;if(e.classList.contains("char-index"))return e.textContent??void 0;if(e.classList.contains("line")||e.getElementsByClassName("lines")?.[0])return Ut().map(({text:o})=>o).join(
);let t=[],r=ya(e);if(!mt(r)){for(let o of V_(e))t.push(K_(o));return r.text.slice(Math.min(...t),Math.max(...t)+1)}};var lg=()=>{let e=Ss()?.firstElementChild;if(!mt(e))return e},pg=()=>{let e=Ss()?.lastElementChild;if(!mt(e))return e};var Pp=e=>{let t=ag(e);if(!mt(t))return Io(t,co())};function*V_(e){let t=e.getElementsByClassName("char-index");for(let r=0;r<t.length;r++)yield t[0]}var Op=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index"),K_=e=>{if(!Op(e))throw Error("A char DOM is required.");let t=e.className.match(/c-(\d+)/)?.[1];if(mt(t))throw Error('.char-index must have ".c-{\\d}"');return parseInt(t)},ug=e=>{let t=e?.getElementsByClassName?.("c-0")?.[0];return Op(t)?t:void 0};var Ns=(e,t)=>{let r=Fo(e)?.getElementsByClassName?.(c-${t})?.[0];return Op(r)?r:void 0};var dt=(e,t)=>{let{noModifiedKeys:r=!1,...o}=t??{},n={bubbles:!0,cancelable:!0,keyCode:Y_[e],...r?{}:{...o}},s=rt();if(!s)throw Error("#text-input must exist.");s.dispatchEvent(new KeyboardEvent("keydown",n)),s.dispatchEvent(new KeyboardEvent("keyup",n))},Y_={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 Sp=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 De(10)};var ot=()=>{let e=rt();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 Np=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=globalThis.innerHeight};function Tt(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 mg=()=>{dt("Home"),dt("Home")};var fg=async()=>{let e=lg();if(!e)throw Error(".line:first-of-type can't be found.");Np(e)||e.scrollIntoView({block:"center"});let t=ug(e);if(!t)throw Error(".line:first-of-type .c-0 can't be found.");let{left:r,top:o}=t.getBoundingClientRect();await Sp(e,{X:r,Y:o})},dg=async()=>{await gg(pg())},hg=async e=>{await gg(Fo(e))},gg=async e=>{if(!e)throw Error("The target line DOM is failed to find.");Np(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:o}=e.getElementsByClassName("text")0.getBoundingClientRect();await Sp(e,{X:t+1,Y:r+o/2})};var yg=(e=1)=>{for(let t of Tt(1,e))dt("z",{ctrlKey:!0})},xg=(e=1)=>{for(let t of Tt(1,e))dt("z",{shiftKey:!0,ctrlKey:!0})};var bg=async(e,t,r)=>{await hg(e),mg();for(let o of Tt(e,t))dt("ArrowDown",{shiftKey:!0});dt("End",{shiftKey:!0}),await Xe(r)};var xa=(e=1)=>{for(let t of Tt(1,e))dt("ArrowRight",{ctrlKey:!0})},ba=(e=1)=>{for(let t of Tt(1,e))dt("ArrowLeft",{ctrlKey:!0})};var wa=(e=1)=>{for(let t of Tt(1,e))dt("ArrowUp",{ctrlKey:!0})},Ea=(e=1)=>{for(let t of Tt(1,e))dt("ArrowDown",{ctrlKey:!0})},ka=(e=1)=>{for(let t of Tt(1,e))dt("ArrowRight",{altKey:!0})},va=(e=1)=>{for(let t of Tt(1,e))dt("ArrowLeft",{altKey:!0})};var Ra=(e=1)=>{for(let t of Tt(1,e))dt("ArrowUp",{altKey:!0})},Ta=(e=1)=>{for(let t of Tt(1,e))dt("ArrowDown",{altKey:!0})},Xe=e=>{let t=rt();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 $e=()=>{let e=sg();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=wg(...r);o&&t.append(o)},dispose:()=>t.remove(),Symbol.dispose:()=>t.remove()}},wg=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":returnJ_();case"check-circle":returnQ_();case"exclamation-triangle":returnZ_();case"text":return_a(o.text);case"group":{let n=wg(...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},_a=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},J_=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),_a(e)},Q_=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),_a(e)},Z_=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),_a(e)};var Ln=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_${se(e.to.title)}]=r,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var eP=(e,t,r)=>{let o=new URL(/${e}/${ge(t)},location.href);if(r?.body&&(o.search=?body=${encodeURIComponent(r.body)}),r?.id&&(o.hash=#${r.id}),r?.context&&Ln({...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()},Lp=(e,t,r)=>eP(e,t,{newTab:!1,reload:!1,body:r});var Cn=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}},Pa=async(e,t)=>{let r=t.clone();return await(await caches.open(tP(new Date))).put(e,r)},tP=e=>api-${e.getFullYear()}-${${e.getMonth()+1}.padStart(2,"0")}-${${e.getDate()}.padStart(2,"0")};var Nt=()=>{let e=rt();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 lo=()=>Nt().cursor;var Oa=()=>Nt().selection;var Ls=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),Eg=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 Sa=new Map,Cp=new Map,Mp=()=>{scrapbox.on("layout:changed",()=>{let e=rt();if(e)for(lett,rof Sa)for(leto,nof r)for(let s of n)e.addEventListener(t,o,Eg(s))}),Mp=void 0},kg=(e,t,r)=>{Mp?.();let o=Sa.get(e)??new Map,n=o.get(t)??new Set;if(n.has(Ls(r)))return;if(n.add(Ls(r)),o.set(t,n),Sa.set(e,o),typeof r=="object"&&r?.once){let i=Cp.get(t)??new Map,a=Ls(r),c=function(u){return Ap(e,t,r),i.delete(a),t.call(this,u)};i.set(a,c),Cp.set(t,i);let l=rt();if(!l)return;l.addEventListener(e,c,r)}let s=rt();s&&s.addEventListener(e,t,r)},Ap=(e,t,r)=>{Mp?.();let o=Sa.get(e);if(!o)return;let n=o.get(t);if(!n)return;let s=Ls(r);if(n.delete(s),typeof r=="object"&&r?.once){let a=Cp.get(t);if(!a)return;let c=a.get(s);if(!c)return;let l=rt();if(!l)return;l.removeEventListener(e,c,r),a.delete(s);return}let i=rt();i&&i.removeEventListener(e,t,r)};var vg={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\[","]":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},rP=new RegExp(${Object.values(vg).join("")},"gu");function Rg(e){return e.replaceAll(rP,t=>vg[t]).replace(/^[0-9a-zA-Z]/,t=>\\x${t.codePointAt(0).toString(16)})}var oP=0,L7=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:--oP,__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 te.vnode&&te.vnode(l),l}var Tg=({project:e,title:t,words:r,lines:o,query:n,close:s})=>{let i=A(c=>{Ln({type:"search",query:n,to:{project:e,title:t}}),!(c.metaKey||c.ctrlKey||c.altKey||c.shiftKey)&&s()},[e,t,n,s]),a=U(()=>{let c=new RegExp((${r.map(l=>Rg(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}/${ge(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 _g=e=>{let[t,r]=X(e),o=A(()=>r(!0),[]),n=A(()=>r(!1),[]),s=A(()=>r(i=>!i),[]);return[t,{open:o,close:n,toggle:s}]};var Pg=(e,t)=>{let[r,o]=X(),[n,s]=X(!1),i=tt(Promise.resolve());return Z(()=>{if(t===""){o(void 0);return}let a=!1;return i.current=(async()=>{if(await i.current,!a){s(!0);try{let c=await Zd(t,e);if(a)return;o(Ie(c)?J(c):void 0)}finally{s(!1)}}})(),()=>a=!0},[t,e]),{loading:n,result:r}};var Og=()=>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 nP=()=>d("i",{className:"spinner"}),Sg=({exportOps:e})=>{let[t,r]=X(""),o=scrapbox.Project.name,{loading:n,result:s}=Pg(o,t),i=A(m=>{r(m.currentTarget.value)},[]),[a,{open:c,close:l,toggle:u}]=_g(!1),p=tt({open:c,close:l,toggle:u});Z(()=>{Object.assign(p.current,{open:c,close:l,toggle:u})},[]),Z(()=>e(p.current),[e]);let f=A(m=>{m.target instanceof HTMLElement&&m.target.id==="background"&&l()},[]);return d(Q,{children:[d(Og,{}),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(nP,{}),${s?.pages?.length??0} pages]})]}),s?.pages&&s.pages.length>0&&d("ul",{className:"result",children:s.pages.map(m=>d("li",{children:d(Tg,{...m,project:o,query:t,close:l})},m.title))})]})]})};var Ng=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>{ut(d(Sg,{exportOps:r}),t)})};var Na=(e,t)=>Object.hasOwn(e,t),Lg={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:">"},Ig=e=>{let t=e.toLowerCase();return Na(Lg,t)?Lg[t]:e},Cg={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:"/","?"},sP=(e,t)=>{if(e.startsWith("Key")){let r=e.slice(3);return t||(r=r.toLowerCase()),r}return Na(Cg,e)?Cget?1:0:e},Mg={"<":"lt",">":"gt"},iP=/^($|Unidentified$|Process$|Dead$|Alt|Control|Hyper|Meta|Shift|Super|OS)/,Ip=e=>{let t=e.shiftKey,r=e.key||"Unidentified";if(r==="Unidentified"?r=sP(e.code||"",t):(r=Ig(r),r===" "&&(r="Space")),iP.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-"),Na(Mg,r)&&(r=Mgr),o||r.length>1?<${o}${r}>:r},Ag={a:"altKey",c:"ctrlKey",m:"metaKey",s:"shiftKey"},aP=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:Ig(o)};for(let s of r.split("-").slice(0,-1)){let i=s.toLowerCase();if(!Na(Ag,i))return{ok:!1,value:{name:"UnknownModifierError",modifier:s,context:e,message:${e}: Unknown modifier: ${s}}};let a=Agi;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}},Fg=e=>{let t=aP(e);return t.ok?{ok:!0,value:Ip(t.value)}:t},Dg=e=>e.match(/<^<>\s+>|\s\S|^$/g);var tr=!1;var Ug=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)=>{tr!==!0&&(!tr||!tr.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{tr!==!0&&(!tr||!tr.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{tr!==!0&&(!tr||!tr.has(e))||r(${e} ${o})}];default:returnt,(...o)=>{if(!(tr!==!0&&(!tr||!tr.has(e))))return r(...o)}}}));var Do=Ug("ScrapBindings:mod.ts"),La=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=$g(s);if(!a.ok){for(let l of a.value)Do.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 Do.debug("Binded the following commands:",n),this.emitChange(),o}unbind(...t){for(let r of t){let o=$g(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()),Do.debug("reset the sequence")};handleKeydown=t=>{if(!t.isTrusted)return;let r=Ip(t);if(!r)return;if(clearTimeout(this.timer),t.isComposing){this.backToInitial();return}this.currentSequence+=r,Do.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=()=>{Do.debug(run ${s});try{i(t)}catch(a){Do.error(a)}finally{this.backToInitial()}}}let n=this.filtered.size;if(Do.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)}},cP={name:"InvalidSequenceError",message:"cannot parse the sequence"},$g=e=>{let t=Dg(e);if(!t)return{ok:!1,value:cP};let r="",o=[];for(let n of t){let s=Fg(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 jg=()=>{if(scrapbox.Layout!=="page")return{selectionRange:{start:{line:0,char:0},end:{line:0,char:0}},selectedText:""};let{selectionRange:e,selectedText:t,position:r}=ot();if(!t){let u=Pp(r.line)??0,p={start:{line:r.line,char:0},end:{line:r.line+u,char:ft(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 Fp=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=n.replaceAll("[","").replaceAll("]","").trim(),a=Math.min(...[n,...s].map(l=>qr(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}]}};Fp.hookName="default-hook";var zr=e=>{let{project:t=scrapbox.Project.name,mode:r="newtab"}=e??{},o=[...e?.hooks??[],Fp],{selectionRange:{start:n,end:s},selectedText:i}=jg();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:Ut().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}=$e();try{if(p.pages.length>0){let y=p.pages.length;m({type:"spinner"},{type:"text",text:Create new ${y} pages...});let x=await wt(e?.socket);if(G(x))throw ne(x);f=z(x);let E=0;await Promise.all(p.pages.map(async v=>{let b=Array.isArray(v.lines)?T=>[...T.map(R=>R.text),...v.lines]:v.lines;await Me(v.project,v.title,b,{socket:f}),m({type:"spinner"},{type:"text",text:Create ${y-++E} pages...})}))}m({type:"spinner"},{type:"text",text:${p.pages.length>0?"Created. ":""}Removing cut text...});let g=p.text;if(i===g)return;await Me(scrapbox.Project.name,scrapbox.Page.title,y=>{let x=y.map(E=>E.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?Lp(y.project,y.title):globalThis.open(https://scrapbox.io/${y.project}/${ge(y.title)},"_self");break;case"newtab":globalThis.open(https://scrapbox.io/${y.project}/${ge(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=De(1e3);f&&await Et(f),await g,h()}};return u.hookName=c,u};var lP=Math.pow(10,8)*24*60*60*1e3,cQ=-lP,Uo=6048e5,Dp=864e5,_r=6e4,po=36e5,Ca=1e3;var Ma=3600;var Up=Ma*24,pP=Up*7,Bg=Up*365.2425,Hg=Bg/12,uP=Hg*3,$p=Symbol.for("constructDateFrom");function S(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&$p in e?e[$p](t):e instanceof Date?new e.constructor(t):new Date(t)}function w(e,t){return S(t||e,e)}var mP={};function fr(){return mP}function Ae(e,t){let r=fr(),o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=w(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 dr(e,t){let r=w(e,t?.in);return r.setHours(0,0,0,0),r}function Je(e,...t){let r=S.bind(null,e||t.find(o=>typeof o=="object"));return t.map(r)}function uo(e,t){let[r,o]=Je(e,t.start,t.end);return{start:r,end:o}}function Cs(e,t){let{start:r,end:o}=uo(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(S(r,i)),i.setDate(i.getDate()+a),i.setHours(0,0,0,0);return n?c.reverse():c}function nt(e,t,r){let[o,n]=Je(r?.in,e,t);return+dr(o)==+dr(n)}function hr(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var jp={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return hr(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):hr(r+1,2)},d(e,t){return hr(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 hr(e.getHours()%12||12,t.length)},H(e,t){return hr(e.getHours(),t.length)},m(e,t){return hr(e.getMinutes(),t.length)},s(e,t){return hr(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return hr(n,t.length)}};function Wg(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function $t(e){return!(!Wg(e)&&typeof e!="number"||isNaN(+w(e)))}var fP=/(\w)\1*|''|'(''|[^'])+('|$)|./g,dP=/^'([^]*?)'?$/,hP=/''/g,gP=/[a-zA-Z]/;function pe(e,t){let r=w(e);if(!$t(r))throw new RangeError("Invalid time value");let o=t.match(fP);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return yP(n);let i=jp[s];if(i)return i(r,n);if(s.match(gP))throw new RangeError("Format string contains an unescaped latin alphabet character "+s+"");return n}).join(""):""}function yP(e){let t=e.match(dP);return t?t[1].replace(hP,"'"):e}function _e(e,t,r){let o=w(e,r?.in);return isNaN(t)?S(r?.in||e,NaN):(t&&o.setDate(o.getDate()+t),o)}function jt(e,t,r){return _e(e,-t,r)}function Ms(e,t,r){return S(r?.in||e,+w(e)+t)}function As(e,t,r){return Ms(e,t*1e3,r)}function $o(e,t,r){return _e(e,t*7,r)}function Is(e,t){return w(e,t?.in).getDate()}function jo(e,t){let r=w(e,t?.in),o=r.getFullYear(),n=fr(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=S(t?.in||e,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=Ae(i,t),c=S(t?.in||e,0);c.setFullYear(o,0,s),c.setHours(0,0,0,0);let l=Ae(c,t);return+r>=+a?o+1:+r>=+l?o:o-1}var xP={};function bP(){return xP}function Bp(e,t){let r=bP(),o=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=jo(e,t),s=S(t?.in||e,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),Ae(s,t)}function mo(e,t){let r=w(e,t?.in),o=+Ae(r,t)-+Bp(r,t);return Math.round(o/Uo)+1}function qg(e,t){return w(e,t?.in).getMonth()}function Bo(e,t){return w(e,t?.in).getFullYear()}var zg=e=>{let t=new Map;for(let r of e){let o=${Bo(r)}-${qg(r)}-${Is(r)},n=t.get(o);n&&n.getTime()>r.getTime()||t.set(o,r)}return[...t.values()]};function Fs(e,t,r){let o=w(e,r?.in);if(isNaN(t))return S(r?.in||e,NaN);if(!t)return o;let n=o.getDate(),s=S(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 Hp(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=w(e,r?.in),p=n||o?Fs(u,n+o*12):u,f=i||s?_e(p,i+s*7):p,m=c+a*60,h=(l+m*60)*1e3;return S(r?.in||e,+f+h)}function Vg(e,t){let r=w(e,t?.in),o=r.getFullYear(),n=r.getMonth(),s=S(r,0);return s.setFullYear(o,n+1,0),s.setHours(0,0,0,0),s.getDate()}function Wp(e,t,r){let o=w(e,r?.in),n=o.getFullYear(),s=o.getDate(),i=S(r?.in||e,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);let a=Vg(i);return o.setMonth(t,Math.min(s,a)),o}function Kg(e,t,r){let o=w(e,r?.in);return isNaN(+o)?S(r?.in||e,NaN):(t.year!=null&&o.setFullYear(t.year),t.month!=null&&(o=Wp(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 Yg(e,t){return w(e,t?.in).getMinutes()}function Pr(e,t,r){let o=w(e,r?.in);return o.setTime(o.getTime()+t*_r),o}function Ho(e){return t=>{let r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function Aa(e,t){return+w(e)-+w(t)}function fo(e,t,r){let o=Aa(e,t)/_r;return Ho(r?.roundingMethod)(o)}function Xg(e,t){return w(e,t?.in).getHours()}function Gp(e,t,r){return Ms(e,t*po,r)}function Ia(e,t){let r=w(e,t?.in);return r.setHours(23,59,59,999),r}function Vr(e){let t=w(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 Kr(e,t,r){let[o,n]=Je(r?.in,e,t),s=dr(o),i=dr(n),a=+s-Vr(s),c=+i-Vr(i);return Math.round((a-c)/Dp)}function Jg(e,t,r){return $o(e,-t,r)}function Fa(e,t,r){let o=w(e,r?.in),n=mo(o,r)-t;return o.setDate(o.getDate()-n*7),w(o,r?.in)}function Qg(e,t){let{start:r,end:o}=uo(t?.in,e),n=+r>+o,s=n?Ae(o,t):Ae(r,t),i=n?Ae(r,t):Ae(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(S(r,c)),c=$o(c,l),c.setHours(15);return n?u.reverse():u}function Da(e,t,r){let[o,n]=Je(r?.in,e,t),s=o.getFullYear()-n.getFullYear(),i=o.getMonth()-n.getMonth();return s*12+i}function Wo(e,t){let r=+w(e)-+w(t);return r<0?-1:r>0?1:r}function Go(e,t){return+w(e)>+w(t)}var Zg=e=>e==null,ho=e=>typeof e=="string";async function*ey(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 ht=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&&Go(g.record.start,y)&&y.setDate(y.getDate()+1),g.record.end=y}return g};var Mn=e=>e.record?.start??e.plan?.start??e.base,ty=e=>e.record?.end??(Zg(e.plan?.duration)?e.base:As(Mn(e),e.plan.duration));var Se=({title:e,base:t,plan:r,record:o})=>["",pe(t,"yyyy-MM-dd")," ",r?.start?pe(r.start,"HH:mm"):" ".repeat(5)," ",r?.duration?${r.duration/60}.padStart(4,"0"):" ".repeat(4)," ",o?.start?pe(o?.start,"HH:mm:ss"):" ".repeat(8)," ",o?.end?pe(o?.end,"HH:mm:ss"):" ".repeat(8),"",e].join("");function*ry(e){for(let t of qo(e))ho(t)||(yield t)}function*qo(e){for(let t=0;t<e.length;t++){let r=e[t],o=ho(r)?r:r.text,n=Io(t,e),s=ht(o);if(!s){yield o;continue}yield{...s,lines:e.slice(t+1,t+1+n).map(i=>ho(i)?i:i.text)},t+=n}}var wP=5*60,qp=async()=>{let e=ot().position.line,t=ht(ft(e)??""),r=t?.base??new Date,o={start:t?.plan?.start?As(t.plan.start,wP+(t.plan.duration??0)):void 0,duration:t?.plan?.duration};scrapbox.Page.insertLine(Se({title:"",base:r,plan:o,record:{}}),e+1),await scrapbox.Page.waitForSave()};var Ua=async()=>{let e=ot().position.line,t=ht(ft(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;o||(scrapbox.Page.updateLine(Se({record:{start:r?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var An=async()=>{let e=ot().position.line,t=ht(ft(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;r&&(scrapbox.Page.updateLine(Se({record:{start:r,end:o?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var zp=async()=>{let e=ot().position.line,t=ht(ft(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(r){if(o)return;await An();return}if(o)return;let s;for(let{text:a}of co().slice(0,(e??0)+1).reverse()){let{record:c}=ht(a)??{};if(c?.end){s=c.end;break}}let i=new Date;scrapbox.Page.updateLine(Se({record:{start:s??i,end:i},...n}),e),await scrapbox.Page.waitForSave()};var zo=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=ot();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var Vp=(e,t=7)=>new Date((e+2592e3*((t+1)**1.5-1)/5221.154823442138)*1e3);var Kp=(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 EP){let l=n.match(a);if(!l)continue;let u=c(l),p=u.isDuration?Hp(t,u):Kg(t,u);return s==="s"?{name:o.trimEnd(),start:p,...r!==void 0?{duration:parseInt(r)*60}:{}}:{name:o.trimEnd(),start:Vp(t.getTime()/1e3,(p.getTime()-t.getTime())/(24*60*60*1e3)),...r!==void 0?{duration:parseInt(r)*60}:{}}}},EP=[{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 Ds=async()=>{let e=new Date,[t,r]=zo(),o=co().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}=Kp(i,e)??{};return!a||!c&&!l?s:[Se({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 $a=async(e,t,r)=>{let o=[];for(let n=e;n<=t;n++){let s=ft(n)??"",i=ht(s);if(!i){o.push(s);continue}o.push(Se(r(i,n)))}for(let n=e;n<=t;n++)scrapbox.Page.updateLine(o[n-e],n);await scrapbox.Page.waitForSave()};var Yp=async(e=1)=>{let[t,r]=zo();await $a(t,r,o=>(o.base=_e(o.base,e),o))};var Xp=async()=>{let[e,t]=zo(),r=new Date;await $a(e,t,o=>(nt(o.base,r)||(o.base=r),o))};var kP="日刊記録sheet",vP=/日刊記録sheet (\d{4})-(\d{2})-(\d{2})/,Us=["[** 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 Jp=e=>{let t=e.match(vP);if(!t)return;let[,r,o,n]=t,s=new Date(parseInt(r),parseInt(o)-1,parseInt(n));return $t(s)?s:void 0},gr=e=>pe(e,'${kP}' yyyy-MM-dd),Vo=e=>{let t=Jp(e[0]);if(!t)return e;let r=RP(t),o=[],n=[];for(let a of qo(e.slice(1))){if(typeof a=="string"){if(Us.includes(a)||r!==""&&r===a)continue;n.push(a);continue}o.push(a)}let s=o.sort((a,c)=>Wo(Mn(a),Mn(c)));if(s.length===0)return[e[0],r,...Us,...n];let i=[0,0,0,0,0,0,0,0];for(let a=1;a<Us.length;a++){let c=Gp(new Date(t.getFullYear(),t.getMonth(),t.getDate()),3*a),l=s.findIndex(m=>Go(Mn(m),c));if(l<0){i[a]=-1;continue}if(l===0)continue;let u=s[l-1],p=Mn(u),f=ty(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?[Us[u]]:[]),Se(a),...a.lines]),...i.flatMap((a,c)=>a===-1?[Us[c]]:[]),...n]},RP=e=>yesterday: ${gr(jt(e,1))};var Qp=async(e,t)=>{let r=()=>{},o=setTimeout(()=>{let{render:n,dispose:s}=$e();r=s,n({type:"spinner"},{type:"text",text:"formatting..."})},500);await Me(e,t,n=>Vo(n.map(s=>s.text))),clearTimeout(o),r()};async function*Zp(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++)nt(o[c].base,i)&&(a.push(...o.splice(c,1)),c--);n.push((async()=>(await Me(e,gr(i),c=>Vo([...c.map(l=>l.text),...a.flatMap(l=>[Se(l),...l.lines??[]])]),r),{date:i,size:a.length}))())}yield*ey(n)}var $s=async({from:{project:e,title:t},to:r})=>{let o=await er(e,t);if(G(o))throw ne(o);let n=Jp(t),{lines:s}=z(o),i=[];for(let p of ry(s))n&&nt(p.base,n)||i.push(p);let{render:a,dispose:c}=$e();a({type:"spinner"},{type:"text",text:copying ${i.length} tasks...});let l=await wt();if(G(l))throw ne(l);let u=z(l);try{let p=0,f=!1;for await(let m of Zp(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 Me(e,t,m=>{let h=[];for(let g of qo(m)){if(ho(g)){h.push(g);continue}n&&nt(g.base,n)&&h.push(Se(g),...g.lines)}return h},{socket:u}),a({type:"check-circle"},{type:"text",text:"Moved"})}finally{await Et(u),await De(1e3),c()}};var ja=e=>e.match(/^(\s*)/)?.[1]?.length??0;var yr=e=>${e}.padStart(2,"0");var Ko=e=>"hours"in e,rr=(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,Or=e=>${${e.year}.padStart(4,"0")}-${yr(e.month)}-${yr(e.date)}${"hours"in e?T${yr(e.hours)}:${yr(e.minutes)}:""},we=e=>{let t=Or(e);return new Date(t.includes("T")?t:${t}T00:00)},Lt=e=>({year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes()});var ny=e=>{switch(e.toLowerCase()){case"y":return"yearly";case"m":return"monthly";case"w":return"weekly";case"d":return"daily";default:return}};var sy=e=>{switch(e){case"+":return"todo";case"-":return"note";case"!":return"deadline";case".":return"done";case"~":return"up-down";default:return}},iy=e=>{switch(e){case"todo":return"+";case"note":return"-";case"deadline":return"!";case"done":return".";case"up-down":return"~"}};var Sr=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,E,v,b,T,R,L,C,M,O,_,P,N,I,F,j,D,V]=t,B=${e.slice(0,t.index).trim()}${e.slice((t.index??0)+r.length).trim()},K=ay(s,i,a,c,l);if(!$t(we(K)))return ee({name:"InvalidDateError",message:The reference point of the task "${Or(K)}" is an invalid date.});let Y=cy(K,f,m,h,u||g,p||y,x);if(Y!==void 0){if(Ue(Y)&&isNaN(Y)||!Ue(Y)&&!$t(we(Y)))return ee({name:"InvalidDateError",message:The estimated end of the task${Ue(Y)?"": "${Or(Y)}"} is an invalid date.});if(Ue(Y)&&Y<0||!Ue(Y)&&rr(Y,K))return ee({name:"TaskRangeError",message:The reference point of an task cannot be after its estimated end.
reference point:${Or(K)}
estimated end:${Or(Ue(Y)?Lt(Pr(we(K),Y)):Y)}})}let ue=/^[\uFE00-\uFE0F]*[✅❌]/.test(e)?"done":sy(o),re=ue?{status:ue,refDate:K}:void 0;re&&n&&(re.speed=parseInt(n));let lt=ay(R||s,L||i,C||a,b||M||c,T||O||l);if(!$t(we(lt)))return ee({name:"InvalidDateError",message:The start of the task/event "${Or(lt)}" is an invalid date.});let Le=cy(lt,N||f,I||m,F||h,_||j||u||g,P||D||p||y,V||x),$=Ko(lt)&&Ue(Le)?{start:lt,duration:Le}:void 0;if($){let xt={name:B,executed:$,generated:!1,raw:e};return re&&(xt.freshness=re),(E||v)&&(xt.recurrence={frequency:ny(E??"D")??"daily",count:v?parseInt(v):1}),le(xt)}if(!re)return ee({name:"InvalidDateError",message:"Task requires freshness to be spec"});let ve={name:B,freshness:re,generated:!1,raw:e};return Y&&(ve.estimated=Y),le($?{...ve,executed:$}:ve)},Nr=e=>!("executed"in e),go=e=>"recurrence"in e,ly=e=>!("executed"in e||"freshness"in e&&Ko(e.freshness.refDate)&&e.estimated&&(Ue(e.estimated)||Ko(e.estimated))),Bs=e=>"executed"in e?e.executed.duration:Ue(e.estimated)?e.estimated:void 0,Lr=e=>Nr(e)?e.freshness.refDate:e.executed.start,py=e=>{if(!Nr(e)){let r=we(e.executed.start);return Lt(Pr(r,e.executed.duration))}if(Ue(e.estimated)&&Ko(e.freshness.refDate)){let r=we(e.freshness.refDate);return Lt(Pr(r,e.estimated))}let t=we(Ue(e.estimated)?e.freshness.refDate:e.estimated??e.freshness.refDate);return t.setHours(0),t.setMinutes(0),Lt(_e(t,1))},NP=e=>{let t=e.freshness?${iy(e.freshness.status)}${e.freshness.speed??""}:"",r=${Or(Lr(e))},o=Bs(e);return${t}@${r}${o===void 0?"":D${o}}${e.name}},Ba=(e,t)=>{let r=Lt(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(Da(we(r),we(n.start))%(o.count??1)!==0)return;break}case"weekly":case"daily":{let a=o.frequency==="weekly"?7:1;if(Kr(we(r),we(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},Ha=e=>e.freshness?e.generated?NP(e):e.raw:e.generated?void 0:e.raw,ay=(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}},cy=(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!Ko(e)||!Ko(f)?f:Math.round((we(f).getTime()-we(e).getTime())/(60*1e3))};var Hs=(e,t)=>{if(!e.generated&&go(e)){let s=Ba(e,t);return s?Hs(s,t):void 0}let r=we(Nr(e)?e.freshness.refDate:e.executed.start),o=Bs(e),n=Ha(e);return{title:n!==void 0?${n}:e.name,base:r,plan:{start:ly(e)?void 0:r,duration:o!==void 0?o*60:void 0},record:{}}};var eu={あさごはん:"#log-breakfast",ひるごはん:"#log-lunch",よるごはん:"#log-dinner"},Yo=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=ht(n);if(!i)return;if(s.length===0)return{text:e,pages:[]};let{title:a,base:c,record:l,...u}=i,p=LP(a,c,l),f=Se({title:${p},base:c,record:l,...u}),m=Math.min(...s.map(g=>ja(g))),h=[.../[\[\]]/.test(a)&&a!==${p}?[a]:[],...t in eu?[...s.map(g=>g.slice(m)),"",eu[t],"#log-eatenfood"]:[...s.map(g=> ${g.slice(m)}),""]];return{text:f,pages:[{project:r,title:p,lines:uy(t,h,[l.start??c]),mode:o}]}};Yo.hookName="task-hook";var LP=(e,t,r)=>{let o=pe(r.start??t,"yyyy-MM-dd");if(e in eu)return${o} ${e};if(Sr(e.slice(1,-1)))return e.slice(1,-1);let n=e.replace(/[\[\]]/g,"").trim();return${n}${n.endsWith(o)?"": ${o}}},Xo=(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=>ja(p))),l=r.startsWith("takker")?zg([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(ja(s))}${a},pages:[{project:r,title:a,lines:uy(t,u,l),mode:o}]}};Xo.hookName="new-page-hook";var Jo=(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=>se(a[1])),i=n.replaceAll("[","").replaceAll("]","");return{text:${o}${i},pages:[{project:t,title:i,lines:(a,{links:c})=>{let l=c.map(u=>se(u));if(!s.every(u=>l.includes(u)))return[...a.map(u=>u.text),n]},mode:r}]}};Jo.hookName="splitted-link-hook";var uy=(e,t,r)=>(o,{links:n})=>{let s=n.map(p=>se(p)),i=s.includes(se(e))?[]:[from ${e}],a=r.flatMap(p=>{let f=pe(p,"yyyy-MM-dd");if(s.includes(f))return[];let m=pe(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 my=e=>e.preventDefault(),fy=e=>e.stopPropagation(),dy={"<A-a><A-t>":async e=>{my(e),fy(e);let[t,r]=CP(),o=co().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=Sr(i);if(!a||W(a))return s;let c=J(a);if(c.freshness?.status==="done")return s;let l=Hs(c,new Date);return l?(l.title=${i},Se(l)):s}).join(
);await bg(t,r,o),await Ds()},"<A-a><A-m>":e=>{scrapbox.Layout==="page"&&(my(e),fy(e),$s({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"}))}},CP=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=ot();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var Qo=e=>e.preventDefault(),Zo=e=>e.stopPropagation(),tu={"<A-a><A-a>":e=>{Qo(e),Zo(e),qp()},"<A-a><A-s>":e=>{Qo(e),Zo(e),Ua()},"<A-a><A-e>":e=>{Qo(e),Zo(e),An()},"<A-a><A-0>":e=>{Qo(e),Zo(e),zp()},"<A-a><A-1>":e=>{Qo(e),Zo(e),Yp(1)},"<A-a><A-t>":e=>{Qo(e),Zo(e),Xp()},"<A-a><A-S>":e=>{scrapbox.Layout==="page"&&(Qo(e),Zo(e),Qp(scrapbox.Project.name,scrapbox.Page.title))}};var st=e=>e.preventDefault(),it=e=>e.stopPropagation(),en=(e,t)=>{let r=ng()?.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&&(st(e),it(e),o.click())},MP={"-":e=>en(e,""),"]":e=>en(e,""),c:e=>en(e,"Copy plain"),$:e=>en(e,""),"{":e=>en(e,/{{c\d+}}/),"}":e=>en(e,"reset cloze"),n:e=>en(e,"make note")},AP={"<C-]>":e=>{let{position:{line:t,char:r}}=ot(),o=Ns(t,r)?.closest("a.page-link")??Fo(t)?.querySelector?.("a.page-link");o instanceof HTMLAnchorElement&&(st(e),it(e),o.click())},"<C-o>":e=>{st(e),it(e),history.back()}},IP={"<C-home>":e=>{st(e),it(e),fg()},"<C-end>":e=>{st(e),it(e),dg()}},hy=[Yo,Xo,Jo],FP={"<C-X>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(st(e),it(e),zr({project:t,mode:"self",hooks:hy})?.())},"<C-D>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(st(e),it(e),zr({project:t,mode:"noopen",hooks:hy})?.())},"<C-h>":e=>{st(e),it(e),ba()},"<C-j>":e=>{st(e),it(e),Ea()},"<C-k>":e=>{st(e),it(e),wa()},"<C-l>":e=>{st(e),it(e),xa()},"<A-h>":e=>{st(e),it(e),va()},"<A-j>":e=>{st(e),it(e),Ta()},"<A-k>":e=>{st(e),it(e),Ra()},"<A-l>":e=>{st(e),it(e),ka()}};scrapbox.TimeStamp.removeAllFormats();var DP={"<A-t><A-t>":e=>{st(e),it(e),Xe(pe(new Date,"#yyyy-MM-dd HH:mm:ss "))},"<A-t><A-j>":e=>{st(e),it(e),Xe(pe(new Date,"yyyy-MM-dd HH:mm:ss "))},"<A-t><A-k>":e=>{st(e),it(e),Xe(pe(new Date,"HH:mm:ss "))},"<A-t><A-l>":e=>{st(e),it(e),Xe(pe(new Date,"yyyy-MM-dd"))}},gy={...MP,...AP,...IP,...FP,...DP,...dy};var{render:UP}=$e(),ru,$P=e=>{ru!==void 0&&cancelAnimationFrame(ru),ru=requestAnimationFrame(()=>UP({type:"text",text:e}))},ou=new La({addEventListener:kg,removeEventListener:Ap},{onSequenceUpdate:$P}),yy=ou.bind({...gy,...scrapbox.Project.name==="takker-memex"?tu:{}});yy.size>0&&alert([...yy.entries()].map(([e,t])=>${e}:
${t.map(r=>- ${r}).join(`
)}).join(`
));var jP=/https?:\/\/vimeo\.com\/([0-9]+)/i,xy=e=>{let t=e.match(jP);if(t)return t[1]};var BP=/https?:\/\/open\.spotify\.com\/(track|artist|playlist|album|episode|show)\/([a-zA-Z\d_-]+)(?:\?[^\s]{0,100}|)/,by=e=>{let t=e.match(BP);if(!t)return;let[,r,o]=t;return{videoId:o,pathType:r}};var HP=/https?:\/\/anchor\.fm\/[a-zA-Z\d_-]+\/episodes\/([a-zA-Z\d_-]+(?:\/[a-zA-Z\d_-]+)?)(?:\?[^\s]{0,100}|)/,wy=e=>{let t=e.match(HP);if(!t)return;let[,r]=t;return r};var Ey=e=>{let{type:t,pathType:r,content:o,href:n,...s}=e;if(o===""){let i=Zi(n);if(i)return{type:"youtube",href:n,...i,...s};let a=xy(n);if(a)return{type:"vimeo",videoId:a,href:n,...s};let c=by(n);if(c)return{type:"spotify",href:n,...c,...s};let l=wy(n);if(l)return{type:"anchor-fm",videoId:l,href:n,...s};if(GP(n))return{type:"video",href:n,...s}}return WP(n)?{type:"audio",content:o,href:n,...s}:{type:"absoluteLink",content:o,href:n,...s}},WP=e=>/\.(?:mp3|ogg|wav|aac)$/.test(e),GP=e=>/\.(?:mp4|webm)$/.test(e);var ky=" must not return ",qP="transformer",zP="recoverer",VP="defaultValue",afe=qP+ky,vy="called with ",cfe=VP+" must not be ",lfe=zP+ky,KP="Ok",Ry="Err",YP=vy+Ry,pfe=vy+KP,ufe="Carrying E in "+Ry+" instead of throwing it directly. See .cause",nu="an instance of Error of the current realm.",mfe="The thrown value is not "+nu,ffe="The contained E should be "+nu,dfe="This .cause is not "+nu;function Qe(e){return e.ok}function Ct(e){return!e.ok}function yo(e){return Ty(e,YP)}function Ty(e,t){if(Ct(e))throw new TypeError(t);return e.val}var Py=" must not return ",JP="transformer",QP="recoverer",ZP="defaultValue",eO=JP+Py,tO="called with ",rO=ZP+" must not be ",oO=QP+Py,Wa="null",nde=eO+Wa,sde=tO+Wa,ide=rO+Wa,ade=oO+Wa;var Oy=" must not return ",nO="transformer",sO="recoverer",iO="defaultValue",aO=nO+Oy,cO="called with ",lO=iO+" must not be ",pO=sO+Oy,Ga="undefined",lde=aO+Ga,pde=cO+Ga,ude=lO+Ga,mde=pO+Ga;var Sy=" must not return ",uO="transformer",mO="recoverer",fO="defaultValue",wde=uO+Sy,Ny="called with ",Ede=fO+" must not be ",kde=mO+Sy;var dO="Ok",Ly="Err",vde=Ny+Ly,Rde=Ny+dO,Tde="Carrying E in "+Ly+" instead of throwing it directly. See .cause",su="an instance of Error of the current realm.",_de="The thrown value is not "+su,Pde="The contained E should be "+su,Ode="This .cause is not "+su;var Cy=" must not return ",hO="transformer",gO="recoverer",yO="defaultValue",Lde=hO+Cy,My="called with ",Cde=yO+" must not be ",Mde=gO+Cy;var xO="Ok",Ay="Err",Ade=My+Ay,Ide=My+xO,Fde="Carrying E in "+Ay+" instead of throwing it directly. See .cause",iu="an instance of Error of the current realm.",Dde="The thrown value is not "+iu,Ude="The contained E should be "+iu,$de="This .cause is not "+iu;var Iy=" must not return ",bO="transformer",wO="recoverer",EO="defaultValue",zde=bO+Iy,Fy="called with ",Vde=EO+" must not be ",Kde=wO+Iy,kO="Ok",Dy="Err",Yde=Fy+Dy,Xde=Fy+kO,Jde="Carrying E in "+Dy+" instead of throwing it directly. See .cause",au="an instance of Error of the current realm.",Qde="The thrown value is not "+au,Zde="The contained E should be "+au,ehe="This .cause is not "+au;var Uy=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 Qi([]);if(Ct(o))return r;let n=yo(o).projects.map(s=>s.id);return r.filter(s=>!n.includes(s))}catch(t){if(!(t instanceof SyntaxError))throw t;return[]}};var TO;(e=>{})(TO||={});var qa="0.16.9",cu,lu,$y=e=>{let t=https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${e}/katex.min.js;if(lu)throw lu;if(!document.querySelector(scriptsrc="${t}")){let r=document.createElement("script");r.src=t,cu=new Promise((o,n)=>{r.onload=()=>o(window.katex),r.onerror=s=>{lu=s,n(s)},document.head.append(r)})}return cu||new Promise(r=>{let o=setInterval(()=>{window.katex&&(clearInterval(o),r(window.katex))},500)})};var za=(e,t)=>{let[r,o]=X("");return{ref:A(s=>{s&&$y(qa).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 jy=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(i=>i.text.substring(o+1)).join(
)}};var ce=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested)return i?.()??[];if(!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??0)),p=e(c[0]??"",s);return[...Mt(l,s),...p,...Mt(u,s)]}return i?.()??[]};var he=e=>[{type:"plain",raw:e,text:e}],By=ce(he,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]});var _O=/\[\s+\]/,PO=(e,t)=>t.context==="table"?he(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Hy=ce(PO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[_O]});var OO=/.*?/,SO=(e,t)=>t.context==="table"?he(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Wy=ce(SO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[OO]});var NO=/^[$%] .+$/,LO=(e,t)=>{if(t.context==="table")return he(e,t);let r=e[0]??"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},Gy=ce(LO,{parseOnNested:!1,parseOnQuoted:!1,patterns:[NO]});var CO=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,MO=(e,t)=>{if(t.context==="table")return he(e,t);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:Mt(n,{...t,nested:!0})}]},qy=ce(MO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[CO]});var AO=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,IO=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,FO=/\[https?:\/\/[^\s\]]+\]/,DO=/https?:\/\/[^\s]+/,UO=(e,t)=>{if(t.context==="table")return he(e,t);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?.[0]===void 0)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()}]},zy=ce(UO,{parseOnNested:!0,parseOnQuoted:!0,patterns:[AO,IO,FO,DO]});var $O=/\[\$ .+? \]/,jO=/\[\$ [^\]]+\]/,BO=(e,t)=>t.context==="table"?he(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],Vy=ce(BO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[$O,jO]});var Ky=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Yy=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,HO=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}},WO=(e,t)=>{if(t.context==="table")return he(e,t);let r=e.match(Ky)??e.match(Yy);if(r===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,n="",s=""]=o?r:[r[0],r[2],r[1]],{latitude:i,longitude:a,zoom:c}=HO(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:e,latitude:i,longitude:a,zoom:c,place:s,url:l}]},Xy=ce(WO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Ky,Yy]});var GO=/(?:^|\s)#\S+/,qO=(e,t)=>{if(t.context==="table")return he(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...he(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},Jy=ce(qO,{parseOnNested:!0,parseOnQuoted:!0,patterns:[GO]});var zO=/^\? .+$/,VO=(e,t)=>t.context==="table"?he(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],Qy=ce(VO,{parseOnNested:!1,parseOnQuoted:!1,patterns:[zO]});var KO=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,YO=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}))},Zy=ce(YO,{parseOnNested:!0,parseOnQuoted:!0,patterns:[KO]});var XO=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,JO=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,QO=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,ZO=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,eS=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||tS(e),tS=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),rS=(e,t)=>{if(t.context==="table")return he(e,t);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]=eS(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}]},ex=ce(rS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[XO,JO,QO,ZO]});var oS=/\[\/?[^[\]]+\]/,nS=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},tx=ce(nS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[oS]});var sS=/^[0-9]+\. .*$/,iS=(e,t)=>{if(t.context==="table")return he(e,t);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:Mt(s,{...t,nested:!1})}]},rx=ce(iS,{parseOnNested:!1,parseOnQuoted:!1,patterns:[sS]});var aS=/^>.*$/,cS=(e,t)=>t.context==="table"?he(e,t):[{type:"quote",raw:e,nodes:Mt(e.substring(1),{...t,quoted:!0})}],ox=ce(cS,{parseOnNested:!1,parseOnQuoted:!1,patterns:[aS]});var lS=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,pS=(e,t)=>{if(t.context==="table")return he(e,t);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}))},nx=ce(pS,{parseOnNested:!1,parseOnQuoted:!0,patterns:[lS]});var uS=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,mS=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,fS=(e,t)=>{if(t.context==="table")return he(e,t);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}]},sx=ce(fS,{parseOnNested:!1,parseOnQuoted:!0,patterns:[uS,mS]});var dS=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,hS=(e,t)=>t.context==="table"?he(e,t):[{type:"strong",raw:e,nodes:Mt(e.substring(2,e.length-2),{...t,nested:!0})}],ix=ce(hS,{parseOnNested:!1,parseOnQuoted:!0,patterns:[dS]});var gS=(e,t,r)=>e===""?[]:r?.()??[],yS=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>By(t,r))(),Mt=yS(gS,ox,Qy,rx,Wy,Gy,Hy,qy,Vy,sx,nx,ix,ex,zy,Zy,Xy,tx,Jy);var ax=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:Mt(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var cx=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(i=>i.text.substring(o+1)).map(i=>i.split(" ").map(a=>Mt(a,{nested:!1,quoted:!1,context:"table"})))}};var lx=e=>({type:"title",text:e.rows[0].text});var px=e=>{switch(e.type){case"title":return lx(e);case"codeBlock":return jy(e);case"table":return cx(e);case"line":return ax(e)}};var xS=(e,t)=>(e.type==="codeBlock"||e.type==="table")&&t.indent>(e.rows[0]?.indent??0),ux=(e,t)=>{let r=e[e.length-1];return r!==void 0&&xS(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},mx=(e,t)=>{if(t.hasTitle??!0){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(ux,[])]}return e.reduce(ux,[])};var fx=e=>e.split(
).map(t=>({indent:/^\s+/.exec(t)?.[0]?.length??0,text:t}));var Ws=(e,t)=>{let r=fx(e);return mx(r,{hasTitle:t?.hasTitle??!0}).map(px)};var dx=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 bS="0.6.5",yx=ScrapBubble-${bS},hx=await globalThis.caches.open(yx);(async()=>{for(let e of await globalThis.caches.keys())e.startsWith("ScrapBubble-")&&e!==yx&&(await globalThis.caches.delete(e),console.log(ScrapBubble deleted old cache :"${e}"))})();var gx=dx(3);async function*Va(e,t){let r=((t?.saveFailedResponse?hx.match(e):void 0)??Cn(e,t)).then(i=>["cache",i]);{let i=De(1e3).then(()=>"timeout"),a=await Promise.race([r,i]);if(a!=="timeout"){a[1]&&(yield["cache",a[1]]);let c=await gx(()=>fetch(e));!c.ok&&t?.saveFailedResponse&&await hx.put(e,c.clone()),yield["network",c]}}let o=gx(()=>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 xx=(e,t)=>new Date(e.headers.get("Date")??0).getTime()/1e3+t<new Date().getTime()/1e3;var Ka=()=>{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 zt=!1,bx=e=>{zt=typeof e=="boolean"?e:new Set(e)},xo=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)=>{zt!==!0&&(!zt||!zt.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{zt!==!0&&(!zt||!zt.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{zt!==!0&&(!zt||!zt.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(zt!==!0&&(!zt||!zt.has(e))))return r(...o)}]}}));var pu=Ka(),Ya=new Map,wS=xo("ScrapBubble:useProject.ts"),wx=e=>{let[t,r]=X();return Z(()=>{pu.on(e,r);let o=Ya.get(e);return o?r(o.loading?void 0:o.value):(Ya.set(e,{loading:!0}),r(void 0),(async()=>{try{let n=jr.toRequest(e);for await(let[,s]of Va(n)){let i=await jr.fromResponse(s);Ya.set(e,{loading:!1,value:i}),pu.dispatch(e,i);break}}catch(n){wS.error(n),Ya.delete(e)}})()),()=>pu.off(e,r)},[e]),t};var ES=["default-light","default-dark","default-minimal"],kS=["paper-light","paper-dark-dark","paper-dark"],Ex=["blue","purple","green","orange","red"],vS=["hacker1","hacker2"],kx=["winter","spring","summer","automn"],vx=["tropical"],Rx=["kyoto","newyork","paris"],Tx=["mred","lgreen"],nbe=["default-light","default-minimal","paper-light",...Ex,...kx,...vx,...Rx,...Tx];var RS=[...ES,...kS,...Ex,...vS,...kx,...vx,...Rx,...Tx];function _x(e){return RS.includes(e)}var Px="default-light",rn=e=>{let t=wx(e);return U(()=>{if(!t||Ct(t))return Px;let r=yo(t).theme;return _x(r)?r:Px},[t])};var In=(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 Fn=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 Ox=({project:e,title:t,descriptions:r,thumbnail:o,linkTo:n,bubble:s,delay:i,prefetch:a})=>{let c=U(()=>o?[]:Ws(r.join(
),{hasTitle:!1}),[o,r]),l=rn(e),u=A(async({currentTarget:f})=>{a(e,t),await In(f,i)&&s({project:e,title:t,linkTo:n,type:"link",position:Fn(f)})},[e,t,i,n?.project,n?.titleLc]),p=U(()=>n?()=>{Ln({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}/${ge(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(Sx,{node:h,project:e}))},m)]:[])})]})]})},Sx=({node:e,project:t})=>{switch(e.type){case"code":return d("code",{children:e.text});case"formula":return d(TS,{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(Q,{children:e.nodes.map(r=>d(Sx,{node:r,project:t}))});case"icon":case"strongIcon":return d(_S,{node:e,project:t});case"hashTag":return d(PS,{node:e});case"link":return d(OS,{node:e});case"plain":case"blank":return d(Q,{children:e.text});default:return}},TS=({node:{formula:e}})=>{let{ref:t,error:r}=za(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},_S=({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}/${ge(n)}/icon})},PS=({node:{href:e}})=>d("span",{class:"page-link",children:["#",e]}),OS=({node:{pathType:e,href:t,content:r}})=>e!=="absolute"?d("span",{class:"page-link",children:t}):d("span",{class:"link",children:r||t});var ke=(e,t)=>/${e.toLowerCase()}/${se(t)},Xa=e=>{let t=e.match("/([^/]+)/(.+)");if(!t)throw SyntaxError("${e}" cannnot match "/(^/+)/(.+)");return{project:t[1],titleLc:t[2]}};var Ix=Symbol.for("immer-nothing"),Nx=Symbol.for("immer-draftable"),Ee=Symbol.for("immer-state");function or(e,...t){throw new Error(Immer minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf)}var Dn=Object.getPrototypeOf;function Un(e){return!!e&&!!e[Ee]}function Jr(e){return e?Fx(e)||Array.isArray(e)||!!e[Nx]||!!e.constructor?.[Nx]||tc(e)||rc(e):!1}var SS=Object.prototype.constructor.toString();function Fx(e){if(!e||typeof e!="object")return!1;let t=Dn(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===SS}function Gs(e,t){ec(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,o)=>t(o,r,e))}function ec(e){let t=e[Ee];return t?t.type_:Array.isArray(e)?1:tc(e)?2:rc(e)?3:0}function fu(e,t){return ec(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Dx(e,t,r){let o=ec(e);o===2?e.set(t,r):o===3?e.add(r):e[t]=r}function NS(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function tc(e){return e instanceof Map}function rc(e){return e instanceof Set}function gt(e){return e.copy_||e.base_}function du(e,t){if(tc(e))return new Map(e);if(rc(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Fx(e);if(t===!0||t==="class_only"&&!r){let o=Object.getOwnPropertyDescriptors(e);delete o[Ee];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(Dn(e),o)}else{let o=Dn(e);if(o!==null&&r)return{...e};let n=Object.create(o);return Object.assign(n,e)}}function xu(e,t=!1){return oc(e)||Un(e)||!Jr(e)||(ec(e)>1&&(e.set=e.add=e.clear=e.delete=LS),Object.freeze(e),t&&Object.entries(e).forEach(([r,o])=>xu(o,!0))),e}function LS(){or(2)}function oc(e){return Object.isFrozen(e)}var hu={};function on(e){let t=hu[e];return t||or(0,e),t}function CS(e,t){hu[e]||(hu[e]=t)}var qs;function Ja(){return qs}function MS(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Lx(e,t){t&&(on("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function gu(e){yu(e),e.drafts_.forEach(AS),e.drafts_=null}function yu(e){e===qs&&(qs=e.parent_)}function Cx(e){return qs=MS(qs,e)}function AS(e){let t=e[Ee];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Mx(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[Ee].modified_&&(gu(t),or(4)),Jr(e)&&(e=Qa(t,e),t.parent_||Za(t,e)),t.patches_&&on("Patches").generateReplacementPatches_(r[Ee].base_,e,t.patches_,t.inversePatches_)):e=Qa(t,r,[]),gu(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ix?e:void 0}function Qa(e,t,r){if(oc(t))return t;let o=t[Ee];if(!o)return Gs(t,(n,s)=>Ax(e,o,t,n,s,r)),t;if(o.scope_!==e)return t;if(!o.modified_)return Za(e,o.base_,!0),o.base_;if(!o.finalized_){o.finalized_=!0,o.scope_.unfinalizedDrafts_--;let n=o.copy_,s=n,i=!1;o.type_===3&&(s=new Set(n),n.clear(),i=!0),Gs(s,(a,c)=>Ax(e,o,n,a,c,r,i)),Za(e,n,!1),r&&e.patches_&&on("Patches").generatePatches_(o,r,e.patches_,e.inversePatches_)}return o.copy_}function Ax(e,t,r,o,n,s,i){if(Un(n)){let a=s&&t&&t.type_!==3&&!fu(t.assigned_,o)?s.concat(o):void 0,c=Qa(e,n,a);if(Dx(r,o,c),Un(c))e.canAutoFreeze_=!1;else return}else i&&r.add(n);if(Jr(n)&&!oc(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Qa(e,n),(!t||!t.scope_.parent_)&&typeof o!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,o)&&Za(e,n)}}function Za(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&xu(t,r)}function IS(e,t){let r=Array.isArray(e),o={type_:r?1:0,scope_:t?t.scope_:Ja(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=o,s=bu;r&&(n=[o],s=zs);let{revoke:i,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=i,a}var bu={get(e,t){if(t===Ee)return e;let r=gt(e);if(!fu(r,t))return FS(e,r,t);let o=r[t];return e.finalized_||!Jr(o)?o:o===uu(e.base_,t)?(mu(e),e.copy_[t]=Vs(o,e)):o},has(e,t){return t in gt(e)},ownKeys(e){return Reflect.ownKeys(gt(e))},set(e,t,r){let o=Ux(gt(e),t);if(o?.set)return o.set.call(e.draft_,r),!0;if(!e.modified_){let n=uu(gt(e),t),s=n?.[Ee];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(NS(r,n)&&(r!==void 0||fu(e.base_,t)))return!0;mu(e),Xr(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 uu(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,mu(e),Xr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=gt(e),o=Reflect.getOwnPropertyDescriptor(r,t);return o&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:o.enumerable,value:r[t]}},defineProperty(){or(11)},getPrototypeOf(e){return Dn(e.base_)},setPrototypeOf(){or(12)}},zs={};Gs(bu,(e,t)=>{zs[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});zs.deleteProperty=function(e,t){return zs.set.call(this,e,t,void 0)};zs.set=function(e,t,r){return bu.set.call(this,e[0],t,r,e[0])};function uu(e,t){let r=e[Ee];return(r?gt(r):e)[t]}function FS(e,t,r){let o=Ux(t,r);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}function Ux(e,t){if(!(t in e))return;let r=Dn(e);for(;r;){let o=Object.getOwnPropertyDescriptor(r,t);if(o)return o;r=Dn(r)}}function Xr(e){e.modified_||(e.modified_=!0,e.parent_&&Xr(e.parent_))}function mu(e){e.copy_||(e.copy_=du(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var DS=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,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"&&or(6),o!==void 0&&typeof o!="function"&&or(7);let n;if(Jr(t)){let s=Cx(this),i=Vs(t,void 0),a=!0;try{n=r(i),a=!1}finally{a?gu(s):yu(s)}return Lx(s,o),Mx(n,s)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===Ix&&(n=void 0),this.autoFreeze_&&xu(n,!0),o){let s=[],i=[];on("Patches").generateReplacementPatches_(t,n,s,i),o(s,i)}return n}else or(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)}createDraft(e){Jr(e)||or(8),Un(e)&&(e=US(e));let t=Cx(this),r=Vs(e,void 0);return r[Ee].isManual_=!0,yu(t),r}finishDraft(e,t){let r=e&&e[Ee];(!r||!r.isManual_)&&or(9);let{scope_:o}=r;return Lx(o,t),Mx(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}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=on("Patches").applyPatches_;return Un(e)?o(e,t):this.produce(e,n=>o(n,t))}};function Vs(e,t){let r=tc(e)?on("MapSet").proxyMap_(e,t):rc(e)?on("MapSet").proxySet_(e,t):IS(e,t);return(t?t.scope_:Ja()).drafts_.push(r),r}function US(e){return Un(e)||or(10,e),$x(e)}function $x(e){if(!Jr(e)||oc(e))return e;let t=e[Ee],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=du(e,t.scope_.immer_.useStrictShallowCopy_)}else r=du(e,!0);return Gs(r,(o,n)=>{Dx(r,o,$x(n))}),t&&(t.finalized_=!1),r}function jx(){class e extends Map{constructor(c,l){super(),this[Ee]={type_:2,parent_:l,scope_:l?l.scope_:Ja(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return gt(this[Ee]).size}has(c){return gt(this[Ee]).has(c)}set(c,l){let u=this[Ee];return i(u),(!gt(u).has(c)||gt(u).get(c)!==l)&&(r(u),Xr(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[Ee];return i(l),r(l),Xr(l),l.base_.has(c)?l.assigned_.set(c,!1):l.assigned_.delete(c),l.copy_.delete(c),!0}clear(){let c=this[Ee];i(c),gt(c).size&&(r(c),Xr(c),c.assigned_=new Map,Gs(c.base_,l=>{c.assigned_.set(l,!1)}),c.copy_.clear())}forEach(c,l){let u=this[Ee];gt(u).forEach((p,f,m)=>{c.call(l,this.get(f),f,this)})}get(c){let l=this[Ee];i(l);let u=gt(l).get(c);if(l.finalized_||!Jr(u)||u!==l.base_.get(c))return u;let p=Vs(u,l);return r(l),l.copy_.set(c,p),p}keys(){return gt(this[Ee]).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[Ee]={type_:3,parent_:l,scope_:l?l.scope_:Ja(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return gt(this[Ee]).size}has(c){let l=this[Ee];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[Ee];return i(l),this.has(c)||(s(l),Xr(l),l.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let l=this[Ee];return i(l),s(l),Xr(l),l.copy_.delete(c)||(l.drafts_.has(c)?l.copy_.delete(l.drafts_.get(c)):!1)}clear(){let c=this[Ee];i(c),gt(c).size&&(s(c),Xr(c),c.copy_.clear())}values(){let c=this[Ee];return i(c),s(c),c.copy_.values()}entries(){let c=this[Ee];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(Jr(c)){let l=Vs(c,a);a.drafts_.set(c,l),a.copy_.add(l)}else a.copy_.add(c)}))}function i(a){a.revoked_&&or(3,JSON.stringify(gt(a)))}CS("MapSet",{proxyMap_:t,proxySet_:n})}var Vt=new DS,nc=Vt.produce,Pbe=Vt.produceWithPatches.bind(Vt),Obe=Vt.setAutoFreeze.bind(Vt),Sbe=Vt.setUseStrictShallowCopy.bind(Vt),Nbe=Vt.applyPatches.bind(Vt),Lbe=Vt.createDraft.bind(Vt),Cbe=Vt.finishDraft.bind(Vt);jx();var Bx=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},Hx=(e,t)=>nc(e,r=>{if(!r)return t;if(r.updated<t.updated){let{lines:o,linked:n,projectLinked:s,...i}=t;Object.assign(r,i),wu(t)||(r.lines=o),n&&(r.linked??=n),s&&(r.projectLinked??=s);return}wu(r)&&!wu(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)}),wu=e=>e.lines[0].id==="dummy";var Wx=(e,t)=>{let r=new Map,o=se(t.title);for(let c of t.links){let l=Eu(e,c);l.linked=[o],r.set(ke(e,c),l)}let n=ke(e,o),s=t.projectLinks.map(c=>{let l=Xa(c);return ke(l.project,l.titleLc)}),i={...sc(e,t),linked:[],projectLinked:[]};r.set(n,i);let a=t.links.map(c=>se(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=ke(e,f),h=r.get(m)??Eu(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=ke(e,c.titleLc),u=sc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}for(let c of t.relatedPages.projectLinks1hop){let l=ke(c.projectName,c.titleLc);s.includes(l)||i.projectLinked.push(l);let u=sc(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=ke(e,f),h=r.get(m)??Eu(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=ke(e,c.titleLc),u=sc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}return r},sc=(e,t)=>({project:e,titleLc:"titleLc"in t?t.titleLc:se(t.title),exists:"persistent"in t?t.persistent:!0,descriptions: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}),Eu=(e,t)=>({project:e,titleLc:se(t),exists:!1,descriptions:[],image:null,lines:[{text:t,id:"dummy",userId:"dummy",updated:0,created:0}],updated:0,isLinkedCorrect:!1});var ic=xo("ScrapBubble:bubble.ts"),ku=new Map,ac=new Set,vu=Ka();function*qx(e){for(let t of e)yield ku.get(t)}var zx=(e,t)=>vu.on(e,t),Vx=(e,t)=>vu.off(e,t),Kx=async(e,t,r,o)=>{let n=[];for(let s of[...t].reverse()){let i=ke(s,e);ac.has(i)||n.push($S(s,e,r,o))}await Promise.all(n)},Gx=0,$S=async(e,t,r,o)=>{let n=ke(e,t);if(ac.has(n))return;ac.add(n);let s=Gx++,i=${s} Check update ${n};ic.time(i);try{let a=er.toRequest(e,t,{followRename:!0,projects:[...r]});for await(let[c,l]of Va(a,{ignoreSearch:!0,saveFailedResponse:!0})){ic.debug(${s}${c} ${n});let u=await er.fromResponse(l);if(Qe(u)){let p=Wx(e,yo(u));for(let[f,m]of p){let h=ku.get(f),g=Hx(h,m);g&&h!==g&&(ku.set(f,g),vu.dispatch(f,m))}}if(o?.ignoreFetch===!0||c==="cache"&&!xx(l,o?.maxAge??60))break}}catch(a){ic.error(a)}finally{ac.delete(n),ic.timeEnd(i),Gx--}};var Yx=xo("ScrapBubble:useBubbleData.ts"),$n=e=>{let[t,r]=X(Ru(e));return Z(()=>{r(Ru(e));let o,n=()=>{clearTimeout(o),o=setTimeout(()=>{Yx.debug(Update ${e.length} pages),r(Ru(e))},10)};return e.forEach(s=>zx(s,n)),()=>e.forEach(s=>Vx(s,n))},e),t},Ru=e=>{let t=[...qx(e)].flatMap(r=>r?[r]:[]);return Yx.debug(Required: ${e.length} pages, ${t.length} found,t),t};var Xx=({source:e,linked:t,externalLinked:r,projectsForSort:o,...n})=>{let s=U(()=>[...t.keys(),...r.keys()],[t,r]),i=$n(s),a=U(()=>[...o],[o]),c=U(()=>{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=U(()=>({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=ke(u,p),y=t.get(g)??r.get(g);return d("li",{children:d(Ox,{project:u,title:f,linkTo:y,descriptions:m,thumbnail:h??"",...n})},g)})})};var jn=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 Tu=(e,t)=>t.some(r=>{let o=!e.project;switch(r.type){case"hashTag":return o&&se(r.href)===e.titleLc;case"link":{if(r.pathType=="absolute"||r.pathType==="relative"!==o)return!1;let{project:n,title:s=""}=jn({pathType:r.pathType,href:r.href});return o?!n&&se(s)===e.titleLc:n===e.project&&se(s)===e.titleLc}case"quote":case"strong":case"decoration":return Tu(e,r.nodes)}});var bo=_s({title:"",project:"",whiteList:new Set,bubble:()=>{},hide:()=>{},delay:0,prefetch:()=>{}}),Qx=({lines:e,project:t,title:r,whiteList:o,noIndent:n,hash:s,linkTo:i,...a})=>{let c=U(()=>e.flatMap(m=>typeof m=="string"?[]:[m.id]),[e]),l=U(()=>{let m=0;return Ws(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=U(()=>{if(s&&c.includes(s))return s;if(i)return l.find(m=>m.type!=="line"?!1:Tu(i,m.nodes))?.id},[l,c,s,i?.project,i?.titleLc]),p=tt(null);Z(()=>{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=rn(t);return d("div",{className:"lines","data-theme":f,ref:p,children:d(bo.Provider,{value:{project:t,title:r,whiteList:o,...a},children:l.map(m=>{switch(m.type){case"title":return d(Q,{children:[d(Hn,{index:m.id,indent:0,noIndent:n,permalink:m.id===u,children:d("a",{className:"page-link",type:"link",href:/${t}/${ge(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(jS,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"table":return d(BS,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"line":return d(Hn,{index:m.id,indent:m.indent,noIndent:n,permalink:m.id===u,children:m.nodes.length>0?m.nodes.map(h=>d(Bn,{node:h},h.raw)):d("br",{})},m.id)}})})})},Hn=({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}),jS=({block:{fileName:e,content:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=Gr(bo),[a,c]=X(""),l=A(async u=>{u.preventDefault(),u.stopPropagation();try{await navigator.clipboard.writeText(t),c("Copied"),await De(1e3),c("")}catch(p){alert(Failed to copy the code block
Error: ${p})}},[t]);return d(Q,{children:[d(Hn,{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}/${ge(i)}/${e},target:"_blank",children:e})}),d("span",{className:"copy",title:"Copy",onClick:l,children:a})]})}),d(Q,{children:t.split(
).map((u,p)=>d(Hn,{index:o[p+1],indent:r,permalink:o[p+1]===n,children:d("code",{className:"code-block",children:u})}))})]})},BS=({block:{fileName:e,cells:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=Gr(bo);return d(Q,{children:[d(Hn,{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}/${ge(i)}/${e}.csv,target:"_blank",children:e})})})}),d(Q,{children:t.map((a,c)=>d(Hn,{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(Bn,{node:p},p.raw))}))})}))})]})},Bn=({node:e})=>{switch(e.type){case"code":return d("code",{className:"code",children:e.text});case"formula":return d(HS,{node:e});case"commandLine":return d(GS,{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(Bn,{node:t},t.raw))});case"strong":return d("strong",{children:e.nodes.map(t=>d(Bn,{node:t},t.raw))});case"decoration":return d(WS,{node:e});case"plain":case"blank":return d(Q,{children:e.text});case"hashTag":return d(VS,{node:e});case"link":return d(KS,{node:e});case"googleMap":return d(qS,{node:e});case"icon":return d(Jx,{node:e});case"strongIcon":return d(Jx,{node:e,strong:!0});case"image":return d(zS,{node:e});case"strongImage":return d("img",{className:"image strong-image",src:e.src});case"numberList":return d(Q,{children:[${e.number}. ,e.nodes.map(t=>d(Bn,{node:t},t.raw))]})}},HS=({node:{formula:e}})=>{let{ref:t,error:r}=za(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},WS=({node:{decos:e,nodes:t}})=>d("span",{className:e.map(r=>deco-${r}).join(" "),children:t.map(r=>d(Bn,{node:r},r.raw))}),GS=({node:e})=>{let[t,r]=X(""),o=A(async n=>{n.preventDefault(),n.stopPropagation();try{await navigator.clipboard.writeText(e.text),r("Copied"),await De(1e3),r("")}catch(s){alert(Failed to copy the code block
Error: ${s})}},[e.text]);return d(Q,{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})})]})},qS=({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}})})}),Jx=({node:{pathType:e,path:t},strong:r})=>{let{project:o}=Gr(bo),[n,s]=e==="relative"?[o,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[o,t],i=ge(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})})},zS=({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})})},VS=({node:{href:e}})=>{let{project:t}=Gr(bo),r=Zx(t,e),o=eb(t,e,"hashtag");return d("a",{href:/${t}/${ge(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]})},KS=({node:{pathType:e,...t}})=>{switch(e){case"relative":case"root":return d(YS,{pathType:e,href:t.href});case"absolute":{let r=Ey({pathType:e,...t});switch(r.type){case"youtube":return d(XS,{...r});case"vimeo":return d(JS,{...r});case"spotify":return d(QS,{...r});case"anchor-fm":return d(ZS,{...r});case"audio":return d(eN,{...r});case"video":return d(rN,{...r});case"absoluteLink":return d("a",{className:"link",href:r.href,rel:"noopener noreferrer",target:"_blank",children:r.content||r.href})}}}},YS=({pathType:e,href:t})=>{let{project:r}=Gr(bo),{project:o=r,title:n,hash:s=""}=jn({pathType:e,href:t}),i=eb(o,n,"link",s),a=Zx(o,n??"");return d("a",{className:page-link${n!==void 0&&a?" empty-page-link":""},type:"link",href:/${o}${n===void 0?"":/${ge(n)}${s===""?"":#${s}}},rel:o===scrapbox.Project.name?"route":"noopener noreferrer",target:o===scrapbox.Project.name?"":"_blank",onPointerEnter:i,children:t})},XS=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})})},JS=({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})}),ZS=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:"anchor-fm",src:e.href.replace("/episodes/","/embed/episodes/"),allowFullScreen:!0})}),eN=e=>e.content===""?d("audio",{className:"audio-player",preload:"none",controls:!0,src:e.href}):d(tN,{...e}),tN=({href:e,content:t})=>{let r=tt(null),o=A(()=>{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})]})},rN=({href:e})=>d("div",{className:"video-player",children:d("video",{class:"video",style:{display:"inline-block"},controls:!0,loop:!0,src:e})}),Zx=(e,t)=>{let{whiteList:r}=Gr(bo),o=U(()=>(r.has(e)?[...r]:[e,...r]).map(s=>ke(s,t)),[r,e]),n=$n(o);return U(()=>Bx(n),n)},eb=(e,t,r,o)=>{let{delay:n,bubble:s,prefetch:i}=Gr(bo);return A(async({currentTarget:a})=>{t&&(i(e,t),await In(a,n)&&s({project:e,title:t,hash:o,type:r,position:Fn(a)}))},[e,t,o,r,n,i,s])};var tb=({pages:e,onClick:t,source:r,whiteList:o,...n})=>{let[s,i]=X(ke(e[0].project,e[0].titleLc)),a=U(()=>({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(oN,{project:c.project,titleLc:c.titleLc,selected:s===ke(c.project,c.titleLc),tabSelector:i},ke(c.project,c.titleLc)))}),e.map(c=>d(nN,{selected:s===ke(c.project,c.titleLc),...c,title:c.lines[0].text,hash:r.hash,linkTo:r.linkTo,whiteList:o,...n},ke(c.project,c.titleLc)))]})},oN=({project:e,titleLc:t,tabSelector:r,selected:o})=>{let n=A(()=>r(ke(e,t)),[e,t]),s=rn(e);return d("button",{type:"button",role:"tab","aria-selected":o,"data-theme":s,tabIndex:-1,onClick:n,children:e})},nN=({selected:e,...t})=>{let r=rn(t.project);return d("div",{role:"tabpanel","data-theme":r,hidden:!e,children:d(Qx,{...t})})};var rb=xo("ScrapBubble:Bubble.tsx"),ob=({source:e,parentTitles:t,whiteList:r,...o})=>{let n=U(()=>r.has(e.project)?new Set([e.project,...r]):new Set([e.project]),[r,e.project]),[s,i,a]=iN(e,n,r,t);return d(Q,{children:[sN(a)&&d(tb,{pages:a,source:e,whiteList:r,onClick:o.hide,...o}),d(Xx,{linked:s,externalLinked:i,onClick:o.hide,source:e,projectsForSort:n,...o})]})},sN=e=>e.length>0,iN=(e,t,r,o)=>{let[[n,s,i],a]=X([new Map,new Map,[]]),c=U(()=>{let p=[...t].map(f=>ke(f,e.title));return rb.debug("projects",p),p},[t,e.title]),l=$n(c),u=U(()=>o.map(p=>se(p)),[o]);return da(()=>{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:E,titleLc:v}=Xa(x);u.includes(v)&&r.has(E)||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 E=ke(h.project,x);p.has(E)||p.set(E,y)}u.includes(h.titleLc)||h.exists&&m.push(h)}a(nc(h=>{rb.debug(depth: ${u.length}, bubbled from ${ke(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 nb=(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 sb=e=>{let t=U(()=>nb(e.style,import.meta.url),[e.style]);return d(Q,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var ib=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 ab=e=>e instanceof HTMLSpanElement&&e.matches(".line-title .text"),cc=e=>e instanceof HTMLAnchorElement&&e.classList.contains("page-link");var cb=()=>{let[e,t]=X([{bubble:o=>r(0,o),hide:()=>r(0)}]),r=A((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 _u=(e,t,r,o,n)=>{Z(()=>(e.addEventListener(t,r,o),()=>e.removeEventListener(t,r,o)),[e,t,o,...n??[]])};var Pu="scrap-bubble",lb=({delay:e,whiteList:t,watchList:r,style:o})=>{let[{bubble:n,hide:s},...i]=cb(),a=A((c,l)=>Kx(l,t.has(c)?t:new Set([c]),r),[t,r]);return _u(document,"pointerenter",async c=>{let l=c.target;if(!cc(l)&&!ab(l))return;let{project:u=scrapbox.Project.name,title:p,hash:f=""}=cc(l)?jn({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 In(l,e)&&n({project:u,title:m,hash:f,position:Fn(l),type:aN(l)})},{capture:!0},[e,t,r]),_u(document,"click",c=>{c.target.dataset.userscriptName!==Pu&&s()},{capture:!0},[s]),Z(()=>(scrapbox.addListener("page:changed",s),()=>scrapbox.removeListener("page:changed",s)),[s]),d(Q,{children:[d("link",{rel:"stylesheet",href:https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${qa}/katex.min.css}),d("style",{children:ib}),d(sb,{style:o}),i.map(c=>d(ob,{...c,whiteList:t,delay:e,prefetch:a},ke(c.source.project,c.source.title)))]})},aN=e=>cc(e)?e.type==="link"?"link":"hashtag":"title";var pb=async e=>{let{delay:t=500,whiteList:r=[],watchList:o=(await Uy()).slice(0,100),style:n="",debug:s=!1}=e??{};bx(s);let i=document.createElement("div");i.dataset.userscriptName=Pu,document.body.append(i);let a=i.attachShadow({mode:"open"});ut(d(lb,{delay:t,whiteList:new Set([scrapbox.Project.name,...r]),watchList:new Set(o),style:n}),a)};var cN=["takker-memex","takker-private","takker","takker-books","villagepump"],nn=[];switch(scrapbox.Project.name){case"hub":case"villagepump":case"verbalizing-community":nn.push("villagepump","hub","verbalizing-community");break;case"programming-notes":case"customize":case"scrapboxlab":nn.push("programming-notes","customize","scrapboxlab");break;case"sta":nn.push("sta-taskmanagement");break;case"sta-taskmanagement":case"taskmanagement":nn.push("sta-taskmanagement","taskmanagement");break;case"plurality-japanese":nn.push("nishio","tkgshn");case"takker-books":nn.push("work4ai");break}pb({delay:/mobile/i.test(navigator.userAgent)?300:500,whiteList:[...cN,...nn],style:@import "/api/code/takker/kakeruの背景を白にするUserCSS/style.css";
@import "/api/code/takker/アイコン記法を画像記法っぽくするUserCSS/style2.css";});var ub=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 mb=(e,t,r)=>{if(r.length===0)return[];let o=r.map(a=>a.text).join(
),n=kt(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}=ub(a.fileName),u=s.get(c);s.set(c,{path:u?.path??https://scrapbox.io/api/code/${e}/${ge(t)}/${ge(c)},lang:u?.lang??l,startIds:[...u?.startIds??[],r[i].id]}),i+=a.content.split(
).length+1;break}}return s.values()};function Su(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(xr(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(xr(s)),t(o[s])}},r=new lc;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),Ou(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function fb(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return Wn(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[Wn(r.read())]=t();return a}default:throw new Error("Invalid packet")}},r=new lc(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 lc=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);Ou(this.buf,t,r)}write(t){let r=this._write(4+t.length);Ou(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 Nu(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}},xr,Wn,db;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;xr=r=>e.encode(r),Wn=r=>t.decode(r),db='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(xr("")instanceof Uint8Array))throw new Error(Invariant violation: "${db} 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 Nu(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function Ou(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var Ks="0.24.0";var Ze=JSON.stringify,hb="warning",gb="silent";function yb(e){if(yt(e,"target"),e.indexOf(",")>=0)throw new Error(Invalid target: ${e});return e}var mc=()=>null,je=e=>typeof e=="boolean"?null:"a boolean",q=e=>typeof e=="string"?null:"a string",fc=e=>e instanceof RegExp?null:"a RegExp object",an=e=>typeof e=="number"&&e===(e|0)?null:"an integer",wb=e=>typeof e=="function"?null:"a function",Ge=e=>Array.isArray(e)?null:"an array",nr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",pN=e=>typeof e=="object"&&e!==null?null:"an array or an object";var xb=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",Eb=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",uN=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",mN=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",kb=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(${Ze(r)} must be ${s});return n}function at(e,t,r){for(let o in e)if(!(o in t))throw new Error(Invalid option ${r}: ${Ze(o)})}function vb(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 ${Ze(r)} in mangle cache to map to either a string or false)}}return t}function dc(e,t,r,o,n){let s=k(t,r,"color",je),i=k(t,r,"logLevel",q),a=k(t,r,"logLimit",an);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 yt(e,t,r){if(typeof e!="string")throw new Error(Expected value for ${t}${r!==void 0?" "+Ze(r):""} to be a string, got ${typeof e} instead);return e}function Rb(e,t,r){let o=k(t,r,"legalComments",q),n=k(t,r,"sourceRoot",q),s=k(t,r,"sourcesContent",je),i=k(t,r,"target",mN),a=k(t,r,"format",q),c=k(t,r,"globalName",q),l=k(t,r,"mangleProps",fc),u=k(t,r,"reserveProps",fc),p=k(t,r,"mangleQuoted",je),f=k(t,r,"minify",je),m=k(t,r,"minifySyntax",je),h=k(t,r,"minifyWhitespace",je),g=k(t,r,"minifyIdentifiers",je),y=k(t,r,"lineLimit",an),x=k(t,r,"drop",Ge),E=k(t,r,"dropLabels",Ge),v=k(t,r,"charset",q),b=k(t,r,"treeShaking",je),T=k(t,r,"ignoreAnnotations",je),R=k(t,r,"jsx",q),L=k(t,r,"jsxFactory",q),C=k(t,r,"jsxFragment",q),M=k(t,r,"jsxImportSource",q),O=k(t,r,"jsxDev",je),_=k(t,r,"jsxSideEffects",je),P=k(t,r,"define",nr),N=k(t,r,"logOverride",nr),I=k(t,r,"supported",nr),F=k(t,r,"pure",Ge),j=k(t,r,"keepNames",je),D=k(t,r,"platform",q),V=k(t,r,"tsconfigRaw",uN);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(yb).join(",")}):e.push(--target=${yb(i)})),a&&e.push(--format=${a}),c&&e.push(--global-name=${c}),D&&e.push(--platform=${D}),V&&e.push(--tsconfig-raw=${typeof V=="string"?V:JSON.stringify(V)}),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}),v&&e.push(--charset=${v}),b!==void 0&&e.push(--tree-shaking=${b}),T&&e.push("--ignore-annotations"),x)for(let B of x)e.push(--drop:${yt(B,"drop")});if(E&&e.push(--drop-labels=${Array.from(E).map(B=>yt(B,"dropLabels")).join(",")}),l&&e.push(--mangle-props=${l.source}),u&&e.push(--reserve-props=${u.source}),p!==void 0&&e.push(--mangle-quoted=${p}),R&&e.push(--jsx=${R}),L&&e.push(--jsx-factory=${L}),C&&e.push(--jsx-fragment=${C}),M&&e.push(--jsx-import-source=${M}),O&&e.push("--jsx-dev"),_&&e.push("--jsx-side-effects"),P)for(let B in P){if(B.indexOf("=")>=0)throw new Error(Invalid define: ${B});e.push(--define:${B}=${yt(PB,"define",B)})}if(N)for(let B in N){if(B.indexOf("=")>=0)throw new Error(Invalid log override: ${B});e.push(--log-override:${B}=${yt(NB,"log override",B)})}if(I)for(let B in I){if(B.indexOf("=")>=0)throw new Error(Invalid supported: ${B});let K=I[B];if(typeof K!="boolean")throw new Error(Expected value for supported ${Ze(B)} to be a boolean, got ${typeof K} instead);e.push(--supported:${B}=${K})}if(F)for(let B of F)e.push(--pure:${yt(B,"pure")});j&&e.push("--keep-names")}function fN(e,t,r,o,n){let s=[],i=[],a=Object.create(null),c=null,l=null;dc(s,t,a,r,o),Rb(s,t,a);let u=k(t,a,"sourcemap",Eb),p=k(t,a,"bundle",je),f=k(t,a,"splitting",je),m=k(t,a,"preserveSymlinks",je),h=k(t,a,"metafile",je),g=k(t,a,"outfile",q),y=k(t,a,"outdir",q),x=k(t,a,"outbase",q),E=k(t,a,"tsconfig",q),v=k(t,a,"resolveExtensions",Ge),b=k(t,a,"nodePaths",Ge),T=k(t,a,"mainFields",Ge),R=k(t,a,"conditions",Ge),L=k(t,a,"external",Ge),C=k(t,a,"packages",q),M=k(t,a,"alias",nr),O=k(t,a,"loader",nr),_=k(t,a,"outExtension",nr),P=k(t,a,"publicPath",q),N=k(t,a,"entryNames",q),I=k(t,a,"chunkNames",q),F=k(t,a,"assetNames",q),j=k(t,a,"inject",Ge),D=k(t,a,"banner",nr),V=k(t,a,"footer",nr),B=k(t,a,"entryPoints",pN),K=k(t,a,"absWorkingDir",q),Y=k(t,a,"stdin",nr),ue=k(t,a,"write",je)??n,re=k(t,a,"allowOverwrite",je),lt=k(t,a,"mangleCache",nr);if(a.plugins=!0,at(t,a,in ${e}() call),u&&s.push(--sourcemap${u===!0?"":=${u}}),p&&s.push("--bundle"),re&&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}),E&&s.push(--tsconfig=${E}),C&&s.push(--packages=${C}),v){let $=[];for(let ve of v){if(yt(ve,"resolve extension"),ve.indexOf(",")>=0)throw new Error(Invalid resolve extension: ${ve});$.push(ve)}s.push(--resolve-extensions=${$.join(",")})}if(P&&s.push(--public-path=${P}),N&&s.push(--entry-names=${N}),I&&s.push(--chunk-names=${I}),F&&s.push(--asset-names=${F}),T){let $=[];for(let ve of T){if(yt(ve,"main field"),ve.indexOf(",")>=0)throw new Error(Invalid main field: ${ve});$.push(ve)}s.push(--main-fields=${$.join(",")})}if(R){let $=[];for(let ve of R){if(yt(ve,"condition"),ve.indexOf(",")>=0)throw new Error(Invalid condition: ${ve});$.push(ve)}s.push(--conditions=${$.join(",")})}if(L)for(let $ of L)s.push(--external:${yt($,"external")});if(M)for(let $ in M){if($.indexOf("=")>=0)throw new Error(Invalid package name in alias: ${$});s.push(--alias:${$}=${yt(M$,"alias",$)})}if(D)for(let $ in D){if($.indexOf("=")>=0)throw new Error(Invalid banner file type: ${$});s.push(--banner:${$}=${yt(D$,"banner",$)})}if(V)for(let $ in V){if($.indexOf("=")>=0)throw new Error(Invalid footer file type: ${$});s.push(--footer:${$}=${yt(V$,"footer",$)})}if(j)for(let $ of j)s.push(--inject:${yt($,"inject")});if(O)for(let $ in O){if($.indexOf("=")>=0)throw new Error(Invalid loader extension: ${$});s.push(--loader:${$}=${yt(O$,"loader",$)})}if(_)for(let $ in _){if($.indexOf("=")>=0)throw new Error(Invalid out extension: ${$});s.push(--out-extension:${$}=${yt(_$,"out extension",$)})}if(B)if(Array.isArray(B))for(let $=0,ve=B.length;$<ve;$++){let xt=B[$];if(typeof xt=="object"&&xt!==null){let Dr=Object.create(null),Ur=k(xt,Dr,"in",q),kr=k(xt,Dr,"out",q);if(at(xt,Dr,"in entry point at index "+$),Ur===void 0)throw new Error('Missing property "in" for entry point at index '+$);if(kr===void 0)throw new Error('Missing property "out" for entry point at index '+$);i.push([kr,Ur])}else i.push(["",yt(xt,"entry point at index "+$)])}else for(let $ in B)i.push([$,yt(B[$],"entry point",$)]);if(Y){let $=Object.create(null),ve=k(Y,$,"contents",kb),xt=k(Y,$,"resolveDir",q),Dr=k(Y,$,"sourcefile",q),Ur=k(Y,$,"loader",q);at(Y,$,'in "stdin" object'),Dr&&s.push(--sourcefile=${Dr}),Ur&&s.push(--loader=${Ur}),xt&&(l=xt),typeof ve=="string"?c=xr(ve):ve instanceof Uint8Array&&(c=ve)}let Le=[];if(b)for(let $ of b)$+="",Le.push($);return{entries:i,flags:s,write:ue,stdinContents:c,stdinResolveDir:l,absWorkingDir:K,nodePaths:Le,mangleCache:vb(lt)}}function dN(e,t,r,o){let n=[],s=Object.create(null);dc(n,t,s,r,o),Rb(n,t,s);let i=k(t,s,"sourcemap",Eb),a=k(t,s,"sourcefile",q),c=k(t,s,"loader",q),l=k(t,s,"banner",q),u=k(t,s,"footer",q),p=k(t,s,"mangleCache",nr);return at(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:vb(p)}}function Tb(e){let t={},r={didClose:!1,reason:""},o={},n=0,s=0,i=new Uint8Array(16*1024),a=0,c=v=>{let b=a+v.length;if(b>i.length){let R=new Uint8Array(b*2);R.set(i),i=R}i.set(v,a),a+=v.length;let T=0;for(;T+4<=a;){let R=Nu(i,T);if(T+4+R>a)break;T+=4,h(i.subarray(T,T+R)),T+=R}T>0&&(i.copyWithin(0,T,a),a-=T)},l=v=>{r.didClose=!0,v&&(r.reason=": "+(v.message||v));let b="The service was stopped"+r.reason;for(let T in o)o[T](b,null);o={}},u=(v,b,T)=>{if(r.didClose)return T("The service is no longer running"+r.reason,null);let R=n++;o[R]=(L,C)=>{try{T(L,C)}finally{v&&v.unref()}},v&&v.ref(),e.writeToStdin(Su({id:R,isRequest:!0,value:b}))},p=(v,b)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(Su({id:v,isRequest:!1,value:b}))},f=async(v,b)=>{try{if(b.command==="ping"){p(v,{});return}if(typeof b.key=="number"){let T=t[b.key];if(!T)return;let R=T[b.command];if(R){await R(v,b);return}}throw new Error("Invalid command: "+b.command)}catch(T){let R=[sn(T,e,null,void 0,"")];try{p(v,{errors:R})}catch{}}},m=!0,h=v=>{if(m){m=!1;let T=String.fromCharCode(...v);if(T!==Ks)throw new Error(Cannot start service: Host version "${Ks}" does not match binary version ${Ze(T)});return}let b=fb(v);if(b.isRequest)f(b.id,b.value);else{let T=o[b.id];delete o[b.id],b.value.error?T(b.value.error,{}):T(null,b.value)}};return{readFromStdout:c,afterClose:l,service:{buildOrContext:({callName:v,refs:b,options:T,isTTY:R,defaultWD:L,callback:C})=>{let M=0,O=s++,_={},P={ref(){++M===1&&b&&b.ref()},unref(){--M===0&&(delete t[O],b&&b.unref())}};t[O]=_,P.ref(),hN(v,O,u,p,P,e,_,T,R,L,(N,I)=>{try{C(N,I)}finally{P.unref()}})},transform:({callName:v,refs:b,input:T,options:R,isTTY:L,fs:C,callback:M})=>{let O=_b(),_=P=>{try{if(typeof T!="string"&&!(T instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:N,mangleCache:I}=dN(v,R,L,gb),F={command:"transform",flags:N,inputFS:P!==null,input:P!==null?xr(P):typeof T=="string"?xr(T):T};I&&(F.mangleCache=I),u(b,F,(j,D)=>{if(j)return M(new Error(j),null);let V=Gn(D.errors,O),B=Gn(D.warnings,O),K=1,Y=()=>{if(--K===0){let ue={warnings:B,code:D.code,map:D.map,mangleCache:void 0,legalComments:void 0};"legalComments"in D&&(ue.legalComments=D?.legalComments),D.mangleCache&&(ue.mangleCache=D?.mangleCache),M(null,ue)}};if(V.length>0)return M(Ys("Transform failed",V,B),null);D.codeFS&&(K++,C.readFile(D.code,(ue,re)=>{ue!==null?M(ue,null):(D.code=re,Y())})),D.mapFS&&(K++,C.readFile(D.map,(ue,re)=>{ue!==null?M(ue,null):(D.map=re,Y())})),Y()})}catch(N){let I=[];try{dc(I,R,{},L,gb)}catch{}let F=sn(N,e,O,void 0,"");u(b,{command:"error",flags:I,error:F},()=>{F.detail=O.load(F.detail),M(Ys("Transform failed",[F],[]),null)})}};if((typeof T=="string"||T instanceof Uint8Array)&&T.length>1024*1024){let P=_;_=()=>C.writeFile(T,P)}_(null)},formatMessages:({callName:v,refs:b,messages:T,options:R,callback:L})=>{if(!R)throw new Error(Missing second argument in ${v}() call);let C={},M=k(R,C,"kind",q),O=k(R,C,"color",je),_=k(R,C,"terminalWidth",an);if(at(R,C,in ${v}() call),M===void 0)throw new Error(Missing "kind" in ${v}() call);if(M!=="error"&&M!=="warning")throw new Error(Expected "kind" to be "error" or "warning" in ${v}() call);let P={command:"format-msgs",messages:Qr(T,"messages",null,"",_),isWarning:M==="warning"};O!==void 0&&(P.color=O),_!==void 0&&(P.terminalWidth=_),u(b,P,(N,I)=>{if(N)return L(new Error(N),null);L(null,I.messages)})},analyzeMetafile:({callName:v,refs:b,metafile:T,options:R,callback:L})=>{R===void 0&&(R={});let C={},M=k(R,C,"color",je),O=k(R,C,"verbose",je);at(R,C,in ${v}() call);let _={command:"analyze-metafile",metafile:T};M!==void 0&&(_.color=M),O!==void 0&&(_.verbose=O),u(b,_,(P,N)=>{if(P)return L(new Error(P),null);L(null,N.result)})}}}}function hN(e,t,r,o,n,s,i,a,c,l,u){let p=_b(),f=e==="context",m=(y,x)=>{let E=[];try{dc(E,a,{},c,hb)}catch{}let v=sn(y,s,p,void 0,x);r(n,{command:"error",flags:E,error:v},()=>{v.detail=p.load(v.detail),u(Ys(f?"Context failed":"Build failed",[v],[]),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"),"");gN(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,E){let v=s.hasFS,{entries:b,flags:T,write:R,stdinContents:L,stdinResolveDir:C,absWorkingDir:M,nodePaths:O,mangleCache:_}=fN(e,a,c,hb,v);if(R&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let P={command:"build",key:t,entries:b,flags:T,write:R,stdinContents:L,stdinResolveDir:C,absWorkingDir:M||l,nodePaths:O,context:f};y&&(P.plugins=y),_&&(P.mangleCache=_);let N=(j,D)=>{let V={errors:Gn(j.errors,p),warnings:Gn(j.warnings,p),outputFiles:void 0,metafile:void 0,mangleCache:void 0},B=V.errors.slice(),K=V.warnings.slice();j.outputFiles&&(V.outputFiles=j.outputFiles.map(xN)),j.metafile&&(V.metafile=JSON.parse(j.metafile)),j.mangleCache&&(V.mangleCache=j.mangleCache),j.writeToStdout!==void 0&&console.log(Wn(j.writeToStdout).replace(/\n$/,"")),x(V,(Y,ue)=>{if(B.length>0||Y.length>0){let re=Ys("Build failed",B.concat(Y),K.concat(ue));return D(re,null,Y,ue)}D(null,V,Y,ue)})},I,F;f&&(i["on-end"]=(j,D)=>new Promise(V=>{N(D,(B,K,Y,ue)=>{let re={errors:Y,warnings:ue};F&&F(B,K),I=void 0,F=void 0,o(j,re),V()})})),r(n,P,(j,D)=>{if(j)return u(new Error(j),null);if(!f)return N(D,(K,Y)=>(E(),u(K,Y)));if(D.errors.length>0)return u(Ys("Context failed",D.errors,D.warnings),null);let V=!1,B={rebuild:()=>(I||(I=new Promise((K,Y)=>{let ue;F=(lt,Le)=>{ue||(ue=()=>lt?Y(lt):K(Le))};let re=()=>{r(n,{command:"rebuild",key:t},(Le,$)=>{Le?Y(new Error(Le)):ue?ue():re()})};re()})),I),watch:(K={})=>new Promise((Y,ue)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');at(K,{},"in watch() call"),r(n,{command:"watch",key:t},Le=>{Le?ue(new Error(Le)):Y(void 0)})}),serve:(K={})=>new Promise((Y,ue)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let re={},lt=k(K,re,"port",an),Le=k(K,re,"host",q),$=k(K,re,"servedir",q),ve=k(K,re,"keyfile",q),xt=k(K,re,"certfile",q),Dr=k(K,re,"fallback",q),Ur=k(K,re,"onRequest",wb);at(K,re,"in serve() call");let kr={command:"serve",key:t,onRequest:!!Ur};lt!==void 0&&(kr.port=lt),Le!==void 0&&(kr.host=Le),$!==void 0&&(kr.servedir=$),ve!==void 0&&(kr.keyfile=ve),xt!==void 0&&(kr.certfile=xt),Dr!==void 0&&(kr.fallback=Dr),r(n,kr,(bf,lT)=>{if(bf)return ue(new Error(bf));Ur&&(i["serve-request"]=(pT,uT)=>{Ur(uT.args),o(pT,{})}),Y(lT)})}),cancel:()=>new Promise(K=>{if(V)return K();r(n,{command:"cancel",key:t},()=>{K()})}),dispose:()=>new Promise(K=>{if(V)return K();V=!0,r(n,{command:"dispose",key:t},()=>{K(),E(),n.unref()})})};n.ref(),u(null,B)})}}var gN=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 T={};if(typeof b!="object")throw new Error(Plugin at index ${g} must be an object);let R=k(b,T,"name",q);if(typeof R!="string"||R==="")throw new Error(Plugin at index ${g} is missing a name);try{let L=k(b,T,"setup",wb);if(typeof L!="function")throw new Error("Plugin is missing a setup function");at(b,T,on plugin ${Ze(R)});let C={name:R,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};g++;let O=L({initialOptions:i,resolve:(_,P={})=>{if(!x)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof _!="string")throw new Error("The path to resolve must be a string");let N=Object.create(null),I=k(P,N,"pluginName",q),F=k(P,N,"importer",q),j=k(P,N,"namespace",q),D=k(P,N,"resolveDir",q),V=k(P,N,"kind",q),B=k(P,N,"pluginData",mc),K=k(P,N,"with",nr);return at(P,N,"in resolve() call"),new Promise((Y,ue)=>{let re={command:"resolve",path:_,key:e,pluginName:R};if(I!=null&&(re.pluginName=I),F!=null&&(re.importer=F),j!=null&&(re.namespace=j),D!=null&&(re.resolveDir=D),V!=null)re.kind=V;else throw new Error('Must specify "kind" when calling "resolve"');B!=null&&(re.pluginData=c.store(B)),K!=null&&(re.with=yN(K,"with")),t(o,re,(lt,Le)=>{lt!==null?ue(new Error(lt)):Y({errors:Gn(Le.errors,c),warnings:Gn(Le.warnings,c),path:Le.path,external:Le.external,sideEffects:Le.sideEffects,namespace:Le.namespace,suffix:Le.suffix,pluginData:c.load(Le.pluginData)})})})},onStart(_){let P='This error came from the "onStart" callback registered here:',N=pc(new Error(P),n,"onStart");l.push({name:R,callback:_,note:N}),C.onStart=!0},onEnd(_){let P='This error came from the "onEnd" callback registered here:',N=pc(new Error(P),n,"onEnd");u.push({name:R,callback:_,note:N}),C.onEnd=!0},onResolve(_,P){let N='This error came from the "onResolve" callback registered here:',I=pc(new Error(N),n,"onResolve"),F={},j=k(_,F,"filter",fc),D=k(_,F,"namespace",q);if(at(_,F,in onResolve() call for plugin ${Ze(R)}),j==null)throw new Error("onResolve() call is missing a filter");let V=h++;p[V]={name:R,callback:P,note:I},C.onResolve.push({id:V,filter:j.source,namespace:D||""})},onLoad(_,P){let N='This error came from the "onLoad" callback registered here:',I=pc(new Error(N),n,"onLoad"),F={},j=k(_,F,"filter",fc),D=k(_,F,"namespace",q);if(at(_,F,in onLoad() call for plugin ${Ze(R)}),j==null)throw new Error("onLoad() call is missing a filter");let V=h++;f[V]={name:R,callback:P,note:I},C.onLoad.push({id:V,filter:j.source,namespace:D||""})},onDispose(_){m.push(_)},esbuild:n.esbuild});O&&await O,y.push(C)}catch(L){return{ok:!1,error:L,pluginName:R}}}s["on-start"]=async(b,T)=>{c.clear();let R={errors:[],warnings:[]};await Promise.all(l.map(async({name:L,callback:C,note:M})=>{try{let O=await C();if(O!=null){if(typeof O!="object")throw new Error(Expected onStart() callback in plugin ${Ze(L)} to return an object);let _={},P=k(O,_,"errors",Ge),N=k(O,_,"warnings",Ge);at(O,_,from onStart() callback in plugin ${Ze(L)}),P!=null&&R.errors.push(...Qr(P,"errors",c,L,void 0)),N!=null&&R.warnings.push(...Qr(N,"warnings",c,L,void 0))}}catch(O){R.errors.push(sn(O,n,c,M&&M(),L))}})),r(b,R)},s["on-resolve"]=async(b,T)=>{let R={},L="",C,M;for(let O of T.ids)try{({name:L,callback:C,note:M}=p[O]);let _=await C({path:T.path,importer:T.importer,namespace:T.namespace,resolveDir:T.resolveDir,kind:T.kind,pluginData:c.load(T.pluginData),with:T.with});if(_!=null){if(typeof _!="object")throw new Error(Expected onResolve() callback in plugin ${Ze(L)} to return an object);let P={},N=k(_,P,"pluginName",q),I=k(_,P,"path",q),F=k(_,P,"namespace",q),j=k(_,P,"suffix",q),D=k(_,P,"external",je),V=k(_,P,"sideEffects",je),B=k(_,P,"pluginData",mc),K=k(_,P,"errors",Ge),Y=k(_,P,"warnings",Ge),ue=k(_,P,"watchFiles",Ge),re=k(_,P,"watchDirs",Ge);at(_,P,from onResolve() callback in plugin ${Ze(L)}),R.id=O,N!=null&&(R.pluginName=N),I!=null&&(R.path=I),F!=null&&(R.namespace=F),j!=null&&(R.suffix=j),D!=null&&(R.external=D),V!=null&&(R.sideEffects=V),B!=null&&(R.pluginData=c.store(B)),K!=null&&(R.errors=Qr(K,"errors",c,L,void 0)),Y!=null&&(R.warnings=Qr(Y,"warnings",c,L,void 0)),ue!=null&&(R.watchFiles=uc(ue,"watchFiles")),re!=null&&(R.watchDirs=uc(re,"watchDirs"));break}}catch(_){R={id:O,errors:[sn(_,n,c,M&&M(),L)]};break}r(b,R)},s["on-load"]=async(b,T)=>{let R={},L="",C,M;for(let O of T.ids)try{({name:L,callback:C,note:M}=f[O]);let _=await C({path:T.path,namespace:T.namespace,suffix:T.suffix,pluginData:c.load(T.pluginData),with:T.with});if(_!=null){if(typeof _!="object")throw new Error(Expected onLoad() callback in plugin ${Ze(L)} to return an object);let P={},N=k(_,P,"pluginName",q),I=k(_,P,"contents",kb),F=k(_,P,"resolveDir",q),j=k(_,P,"pluginData",mc),D=k(_,P,"loader",q),V=k(_,P,"errors",Ge),B=k(_,P,"warnings",Ge),K=k(_,P,"watchFiles",Ge),Y=k(_,P,"watchDirs",Ge);at(_,P,from onLoad() callback in plugin ${Ze(L)}),R.id=O,N!=null&&(R.pluginName=N),I instanceof Uint8Array?R.contents=I:I!=null&&(R.contents=xr(I)),F!=null&&(R.resolveDir=F),j!=null&&(R.pluginData=c.store(j)),D!=null&&(R.loader=D),V!=null&&(R.errors=Qr(V,"errors",c,L,void 0)),B!=null&&(R.warnings=Qr(B,"warnings",c,L,void 0)),K!=null&&(R.watchFiles=uc(K,"watchFiles")),Y!=null&&(R.watchDirs=uc(Y,"watchDirs"));break}}catch(_){R={id:O,errors:[sn(_,n,c,M&&M(),L)]};break}r(b,R)};let E=(b,T)=>T([],[]);u.length>0&&(E=(b,T)=>{(async()=>{let R=[],L=[];for(let{name:C,callback:M,note:O}of u){let _,P;try{let N=await M(b);if(N!=null){if(typeof N!="object")throw new Error(Expected onEnd() callback in plugin ${Ze(C)} to return an object);let I={},F=k(N,I,"errors",Ge),j=k(N,I,"warnings",Ge);at(N,I,from onEnd() callback in plugin ${Ze(C)}),F!=null&&(_=Qr(F,"errors",c,C,void 0)),j!=null&&(P=Qr(j,"warnings",c,C,void 0))}}catch(N){_=[sn(N,n,c,O&&O(),C)]}if(_){R.push(..._);try{b.errors.push(..._)}catch{}}if(P){L.push(...P);try{b.warnings.push(...P)}catch{}}}T(R,L)})()});let v=()=>{for(let b of m)setTimeout(()=>b(),0)};return x=!0,{ok:!0,requestPlugins:y,runOnEndCallbacks:E,scheduleOnDisposeCallbacks:v}};function _b(){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 pc(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=Pb(t,s,r);if(i)return o={text:e.message,location:i},o}catch{}}}function sn(e,t,r,o,n){let s="Internal error",i=null;try{s=(e&&e.message||e)+""}catch{}try{i=Pb(t,(e.stack+"").split(
),"")}catch{}return{id:"",pluginName:n,text:s,location:i,notes:o?[o]:[],detail:r?r.store(e):-1}}function Pb(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:xr(c.slice(0,l)).length,length:xr(c.slice(l,l+u)).length,lineText:c+
+t.slice(1).join(
),suggestion:""}}break}}return null}function Ys(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 Gn(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function bb(e,t,r){if(e==null)return null;let o={},n=k(e,o,"file",q),s=k(e,o,"namespace",q),i=k(e,o,"line",an),a=k(e,o,"column",an),c=k(e,o,"length",an),l=k(e,o,"lineText",q),u=k(e,o,"suggestion",q);if(at(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 Qr(e,t,r,o,n){let s=[],i=0;for(let a of e){let c={},l=k(a,c,"id",q),u=k(a,c,"pluginName",q),p=k(a,c,"text",q),f=k(a,c,"location",xb),m=k(a,c,"notes",Ge),h=k(a,c,"detail",mc),g=in element ${i} of "${t}";at(a,c,g);let y=[];if(m)for(let x of m){let E={},v=k(x,E,"text",q),b=k(x,E,"location",xb);at(x,E,g),y.push({text:v||"",location:bb(b,g,n)})}s.push({id:l||"",pluginName:u||o,text:p||"",location:bb(f,g,n),notes:y,detail:r?r.store(h):-1}),i++}return s}function uc(e,t){let r=[];for(let o of e){if(typeof o!="string")throw new Error(${Ze(t)} must be an array of strings);r.push(o)}return r}function yN(e,t){let r=Object.create(null);for(let o in e){let n=e[o];if(typeof n!="string")throw new Error(key ${Ze(o)} in object ${Ze(t)} must be a string);r[o]=n}return r}function xN({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=Wn(n)),o}}}var Sb=Ks,gc=e=>yc().build(e),Nb=(e,t)=>yc().transform(e,t),Lb=(e,t)=>yc().formatMessages(e,t),Cb=(e,t)=>yc().analyzeMetafile(e,t);var cn,Ob,hc,yc=()=>{if(hc)return hc;throw cn?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')},xc=e=>{let t=e.wasm,r=e.worker;if(cn)throw new Error('Cannot call "initialize" more than once');return cn=bN(t,r),cn.catch(()=>{cn=void 0}),cn},bN=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}=Tb({writeToStdin(c){r.postMessage(c)},isSync:!1,hasFS:!1,esbuild:{build:gc,transform:Nb,formatMessages:Lb,analyzeMetafile:Cb,version:Sb,initialize:xc}});await s,Ob=()=>{r.terminate(),cn=void 0,Ob=void 0,hc=void 0},hc={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 Pt(e){if(typeof e!="string")throw new TypeError(Path must be a string. Received ${JSON.stringify(e)})}function Cr(e){return e===47||e===92}function Zr(e){return e>=97&&e<=122||e>=65&&e<=90}function Ec(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError("Must be a file URL.");return e}function Mb(e){e=Ec(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}function Cu(e){Pt(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return Cr(r)?!0:!!(Zr(r)&&t>2&&e.charCodeAt(1)===58&&Cr(e.charCodeAt(2)))}var kc=class extends Error{constructor(t){super(t),this.name="AssertionError"}};function vc(e,t=""){if(!e)throw new kc(t)}var CN={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function Rc(e){return e.replaceAll(/[\s]/g,t=>CN[t]??t)}function Fb(e){if(!Cu(e))throw new TypeError("Must be an absolute path.");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=Rc(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError("Invalid hostname.");return o}function eo(e){return e===47}function Ub(e){return e=Ec(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function Au(e){return Pt(e),e.length>0&&eo(e.charCodeAt(0))}function jb(e){if(!Au(e))throw new TypeError("Must be an absolute path.");let t=new URL("file:///");return t.pathname=Rc(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}var GN=(()=>{let{Deno:e}=globalThis;if(typeof e?.build?.os=="string")return e.build.os;let{navigator:t}=globalThis;return t?.appVersion?.includes?.("Win")?"windows":"linux"})(),Ve=GN==="windows";var qn=Ve?"\\":"/";function Tc(e){return Ve?Mb(e):Ub(e)}function Js(e){return Ve?Fb(e):jb(e)}function _c(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function Pc(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 Bb(e){return _c(e)&&(e.imports!==void 0?Iu(e.imports):!0)&&(e.scopes!==void 0?Fu(e.scopes):!0)}function Iu(e){return _c(e)}function Fu(e){return _c(e)&&Object.values(e).every(t=>Du(t))}function Du(e){return _c(e)}function Oc(e){try{return new URL(e),!0}catch{return!1}}function Wb(e,t){let r={};for(let[o,n]of Object.entries(e)){let s=zN(o,t);if(s===null)continue;if(typeof n!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let i=Uu(n,t);if(i===null){console.warn("the address was invalid."),r[s]=null;continue}if(o.endsWith("/")&&!Mr(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]=Mr(i)}return Pc(r)}function Mr(e){return e.href}function qN(e,t){let r={};for(let[n,s]of Object.entries(e)){if(!Du(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=Mr(i);r[a]=Wb(s,t)}let o={};for(let n of Object.keys(r))o[n]=Pc(r[n]);return Pc(o)}function zN(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=Uu(e,t);return r!==null?Mr(r):e}function Uu(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 VN=["ftp","file","http","https","ws","wss"];function KN(e){return VN.some(t=>Mr(e).startsWith(t))}function Hb(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(!Oc(n))throw new TypeError("resolutionResult must be an URL.");return n}else if(o.endsWith("/")&&e.startsWith(o)&&(t===null||KN(t))){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Oc(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(!Oc(i))throw new TypeError("url must be an URL.");if(!Mr(i).startsWith(n))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return Mr(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 $u(e,t){let r={};if(!Bb(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(!Iu(o))throw new TypeError('"imports" top-level key needs to be an object.');r=Wb(o,t)}let s={};if(n!==void 0){if(!Fu(n))throw new TypeError('"scopes" top-level key needs to be an object.');s=qN(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 Gb(e,{imports:t={},scopes:r={}},o){let n=Mr(o),s=Uu(e,o),i=s!==null?Mr(s):e;for(let[c,l]of Object.entries(r))if(c===n||c.endsWith("/")&&n.startsWith(c)){let u=Hb(i,s,l);if(u!==null)return u}let a=Hb(i,s,t);if(a!==null)return a;if(s!==null)return Mr(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}function zb(e,{allowTrailingComma:t=!0}={}){if(new.target)throw new TypeError("parse is not a constructor");return new ju(e,{allowTrailingComma:t}).parse()}var qb=globalThis.JSON.parse,ju=class{#i=new Set( \r
);#o=new Set([..."[]{}:,/",...this.#i]);#t;#e;#s;#a;constructor(t,r){this.#t=${t},this.#e=this.#t.length,this.#s=this.#m(),this.#a=r}parse(){let t=this.#n(),r=this.#p(t),{done:o,value:n}=this.#s.next();if(!o)throw new SyntaxError(Eo(n));return r}#n(){let{done:t,value:r}=this.#s.next();if(t)throw new SyntaxError("Unexpected end of JSONC input");return r}*#m(){for(let t=0;t<this.#e;t++)if(!this.#i.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.#o.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.#r();case"NullOrTrueOrFalseOrNumber":return this.#g(t);case"String":return this.#h(t);default:throw new SyntaxError(Eo(t))}}#f(){let t={};for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndObject")return t;if(o.type!=="String")throw new SyntaxError(Eo(o));let n=this.#h(o),s=this.#n();if(s.type!=="NameSeparator")throw new SyntaxError(Eo(s));let i=this.#n();Object.defineProperty(t,n,{value:this.#p(i),writable:!0,enumerable:!0,configurable:!0});let a=this.#n();if(a.type==="EndObject")return t;if(a.type!=="ValueSeparator")throw new SyntaxError(Eo(a))}}#r(){let t=[];for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndArray")return t;t.push(this.#p(o));let n=this.#n();if(n.type==="EndArray")return t;if(n.type!=="ValueSeparator")throw new SyntaxError(Eo(n))}}#h(t){let r;try{r=qb(t.sourceText)}catch{throw new SyntaxError(Eo(t))}return vc(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=qb(t.sourceText)}catch{throw new SyntaxError(Eo(t))}return vc(typeof r=="number"),r}};function Eo({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 Nc(e){if(e.protocol==="file:")return{path:Tc(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}}async function Bu(e){let t=await Deno.readTextFile(e),r=zb(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 Vb(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 XN=${qn}node_modules${qn},JN=${qn}node_modules;function Sc(e){return e.includes(XN)||e.endsWith(JN)}function Hu(e){return(e.namespace===""||e.namespace==="file")&&(Sc(e.resolveDir)||Sc(e.path)||Sc(e.importer))}function Wu(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 Bu(e.configPath);if(i.imports!==void 0||i.scopes!==void 0){let a={imports:i.imports,scopes:i.scopes};Vb(a),r=$u(a,Js(e.configPath))}else i.importMap!==void 0&&(s=new URL(i.importMap,Js(e.configPath)).href)}else e.importMapURL!==void 0&&(s=e.importMapURL);if(s){let i=await fetch(s),a=await i.json();r=$u(a,new URL(i.url))}}),t.onResolve({filter:/.*/},async function(s){if(Hu(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(${Js(s.resolveDir).href}/);else return;let a;if(r!==null){let p=Gb(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}=Nc(a);return await t.resolve(c,{namespace:l,kind:s.kind})})}}}var vPe=new TextEncoder;var QN=[],ZN=[],Gu="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";for(let e=0,t=Gu.length;e<t;++e)QN[e]=Gu[e],ZN[Gu.charCodeAt(e)]=e;var GPe=Deno.env.get("DENO_REGISTRY_URL")??"https://jsr.io";var aL=await Deno.permissions.query({name:"run"}).then(e=>e.state!=="granted")?"portable":"native";var Kb=Wu;var Yb=" must not return ",cL="transformer",lL="recoverer",pL="defaultValue",zn=cL+Yb,to="called with ",Vn=pL+" must not be ",Kn=lL+Yb;var Lc="null or undefined",Yn=zn+Lc,uL=to+Lc,qu=Vn+Lc,Cc=Kn+Lc;function br(e){return e!=null}var mL="Ok",Xb="Err",Jb=to+Xb,Qb=to+mL,fL="Carrying E in "+Xb+" instead of throwing it directly. See .cause",zu="an instance of Error of the current realm.",$Oe="The thrown value is not "+zu,jOe="The contained E should be "+zu,dL="This .cause is not "+zu;function ct(e){return e.ok}function At(e){return{ok:!0,val:e,err:null}}function Bt(e){return!e.ok}function Kt(e){return{ok:!1,val:null,err:e}}function ln(e){return Zb(e,Jb)}function Xn(e){return ew(e,Qb)}function Zb(e,t){if(Bt(e))throw new TypeError(t);return e.val}function ew(e,t){if(ct(e))throw new TypeError(t);return e.err}function Vu(e,t){if(br(e))return At(e);let r=t();return Kt(r)}var tw=e=>!!(hL.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),hL=["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"];function vo(e){if(typeof e!="string")throw new TypeError(Path must be a string, received "${JSON.stringify(e)}")}function pn(e){return e===47}function Mc(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 Jn(e){return e=Mc(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function rw(e){e instanceof URL&&(e=Jn(e)),vo(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(pn(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 ow(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 nw(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 sw(e,t){if(vo(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(Suffix must be a string, received "${JSON.stringify(t)}")}function iw(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 aw(e,t=""){e instanceof URL&&(e=Jn(e)),sw(e,t);let r=nw(e,pn),o=iw(r,pn);return t?ow(o,t):o}function cw(){let e=globalThis,t=e.Deno?.build?.os;return typeof t=="string"?t==="windows":e.navigator?.platform?.startsWith("Win")??e.process?.platform?.startsWith("win")??!1}var Ac=cw();function lw(e){e=Mc(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}function pw(e){return Ac?lw(e):Jn(e)}var yL={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function Ic(e){return e.replaceAll(/[\s]/g,t=>yL[t]??t)}function uw(e){return vo(e),e.length>0&&pn(e.charCodeAt(0))}function mw(e){if(!uw(e))throw new TypeError(Path must be absolute: received "${e}");let t=new URL("file:///");return t.pathname=Ic(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}function Yu(e){return e===47||e===92}function fw(e){return e>=97&&e<=122||e>=65&&e<=90}function dw(e){vo(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return Yu(r)?!0:!!(fw(r)&&t>2&&e.charCodeAt(1)===58&&Yu(e.charCodeAt(2)))}function hw(e){if(!dw(e))throw new TypeError(Path must be absolute: received "${e}");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=Ic(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError(Invalid hostname: "${o.hostname}");return o}function gw(e){return Ac?hw(e):mw(e)}var yw=e=>{if(e.protocol==="file:")return{path:pw(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},Xu=e=>e.namespace==="file"?gw(e.path):new URL(${e.namespace}:${e.path});var xw=(e,t)=>{let r=Vu(RL(e),()=>({name:"NotFoundError",message:"Source map URL is not found"}));if(G(r))return r;let{url:o,start:n,end:s}=z(r);return URL.canParse(o,t)?le({url:new URL(o,t),start:n,end:s}):ee({name:"InvalidURLError",message:Invalid URL: ${o}})},RL=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 TL=["base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx"],bw=e=>TL.includes(e),ww=e=>/^js|^ts|css$/.test(e),Ew=e=>{let t=e.url,r=aw(t);if(bw(r))return r;if(r==="mjs")return"js";let o=new URL(t);o.search="",o.hash="";let n=rw(o.href).slice(1);if(bw(n))return n;if(n==="mjs")return"js";let i=(e.headers.get("Content-Type")??"text/plain").split(";")[0]?.trim?.()??"text/plain";return _L(i)},_L=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 Fc(e,t){if(isNaN(e)||isNaN(t))throw new Error("Cannot compare against non-numbers");return e===t?0:e<t?-1:1}function Rw(e=[],t=[]){return e.length&&!t.length?-1:!e.length&&t.length?1:0}function Qu(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 Qn="0|[1-9]\\d*",PL="\\d*[a-zA-Z-][a-zA-Z0-9-]*",OL=(?<major>${Qn})\\.(?<minor>${Qn})\\.(?<patch>${Qn}),kw=(?:${Qn}|${PL}),Tw=(?:-(?<prerelease>${kw}(?:\\.${kw})*)),vw="[0-9A-Za-z-]+",_w=(?:\\+(?<buildmetadata>${vw}(?:\\.${vw})*)),Pw=v?${OL}${Tw}?${_w}?,Ow=new RegExp(^${Pw}$),Sw="(?:<|>)?=?",SL="x|X|\\*",Ju=${Qn}|${SL},Dc=v=\\s*(?<major>${Ju})(?:\\.(?<minor>${Ju})(?:\\.(?<patch>${Ju})${Tw}?${_w}?)?)?,Nw=new RegExp(^(?<operator>~>?|\\^|${Sw})\\s*${Dc}$),Lw=new RegExp(^(?<operator>${Sw})\\s*(${Pw})$|^$);function Zu(e){return typeof e=="number"&&!Number.isNaN(e)&&(!Number.isFinite(e)||0<=e&&e<=Number.MAX_SAFE_INTEGER)}var em=256;var NL=new RegExp(^${Qn}$);function Yt(e){return e.split(".").filter(Boolean).map(t=>{if(NL.test(t)){let r=Number(t);if(Zu(r))return r}return t})}function Ar(e){return e.split(".").filter(Boolean)}function Ro(e,t){let r=Number(e);if(!Zu(r))throw new TypeError(t);return r}function un(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 sr(e,t){return e===t?0:Fc(e.major,t.major)||Fc(e.minor,t.minor)||Fc(e.patch,t.patch)||Rw(e.prerelease,t.prerelease)||Qu(e.prerelease,t.prerelease)}function tm(e){return e.toFixed(0)}function mn(e){let t=tm(e.major),r=tm(e.minor),o=tm(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 LL(e,t){if(un(t))return!0;let r=sr(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 Uc(e,t){for(let r of t)if(!LL(e,r))return!1;if(e.prerelease&&e.prerelease.length>0){for(let r of t){if(un(r))continue;let{major:o,minor:n,patch:s,prerelease:i}=r;if(i&&i.length>0&&e.major===o&&e.minor===n&&e.patch===s)return!0}return!1}return!0}function $c(e,t){return t.some(r=>Uc(e,r))}var jc={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},Zn={operator:void 0,...jc};function Cw(e,t){return sr(e,t)>0}function Qs(e,t){let r;for(let o of e)$c(o,t)&&(r=r&&Cw(r,o)?r:o);return r}function CL(e){let r=e.match(Lw)?.groups;if(!r)return null;let{operator:o,prerelease:n,buildmetadata:s}=r,i=r.major?{major:Ro(r.major,Cannot parse comparator ${e}: invalid major version),minor:Ro(r.minor,Cannot parse comparator ${e}: invalid minor version),patch:Ro(r.patch,Cannot parse comparator ${e}: invalid patch version),prerelease:n?Yt(n):[],build:s?Ar(s):[]}:jc;return{operator:o||void 0,...i}}function Ne(e){return!e||e.toLowerCase()==="x"||e==="*"}function ML(e){if(!Ne(e.major))return Ne(e.minor)?{operator:">=",major:+e.major,minor:0,patch:0,prerelease:[],build:[]}:Ne(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?Yt(e.prerelease):[],build:[]}}function AL(e){if(!Ne(e.major))return Ne(e.minor)?{operator:"<",major:+e.major+1,minor:0,patch:0,prerelease:[],build:[]}:Ne(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:Yt(e.prerelease),build:[]}:{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:[],build:[]}}function IL(e){let t=e.match(new RegExp(^${Dc})),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(^${Dc}\\s*$))?.groups;if(!a)return null;let c=ML(r),l=AL(a);return[c,l].filter(Boolean)}function FL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Zn];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=Yt(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 DL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Zn];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=Yt(e.prerelease??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]}function UL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(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=Yt(e.prerelease??""),c=Ar(e.build??"");return[{operator:"<",major:n,minor:s,patch:i,prerelease:a,build:c}]}function $L(e){let t=Ne(e.minor),r=Ne(e.patch),o=+e.major,n=+e.minor,s=+e.patch;if(t)return r?[{operator:"<",major:o+1,minor:0,patch:0}]:[{operator:"<",major:o,minor:n+1,patch:0}];if(r)return[{operator:"<",major:o,minor:n+1,patch:0}];let i=Yt(e.prerelease??""),a=Ar(e.build??"");return[{operator:"<=",major:o,minor:n,patch:s,prerelease:i,build:a}]}function jL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(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=Yt(e.prerelease??""),c=Ar(e.build??"");return[{operator:">",major:n,minor:s,patch:i,prerelease:a,build:c}]}function BL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Zn];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=Yt(e.prerelease??""),c=Ar(e.build??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a,build:c}]}function HL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[Zn];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=Yt(e.prerelease??""),c=Ar(e.build??"");return[{operator:void 0,major:n,minor:s,patch:i,prerelease:a,build:c}]}function WL(e){let t=e.match(Nw)?.groups;if(!t)return CL(e);switch(t.operator){case"^":return FL(t);case"~":case"~>":return DL(t);case"<":return UL(t);case"<=":return $L(t);case">":return jL(t);case">=":return BL(t);case"=":case"":return HL(t);default:throw new Error(Cannot parse version range: '${t.operator}' is not a valid operator)}}function GL(e){return e.split(/\s+/).flatMap(WL)}function Mw(e){let t=e.replaceAll(/(?<=<|>|=|~|\^)(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>IL(r)||GL(r));if(t.some(r=>r.includes(null)))throw new TypeError(Cannot parse version range: range "${e}" is invalid);return t}function rm(e){if(typeof e!="string")throw new TypeError(Cannot parse version as version must be a string: received ${typeof e});if(e.length>em)throw new TypeError(Cannot parse version as version length is too long: length is ${e.length}, max length is ${em});e=e.trim();let t=e.match(Ow)?.groups;if(!t)throw new TypeError(Cannot parse version: ${e});let r=Ro(t.major,Cannot parse version ${e}: invalid major version),o=Ro(t.minor,Cannot parse version ${e}: invalid minor version),n=Ro(t.patch,Cannot parse version ${e}: invalid patch version),s=t.prerelease?Yt(t.prerelease):[],i=t.buildmetadata?Ar(t.buildmetadata):[];return{major:r,minor:o,patch:n,prerelease:s,build:i}}function om(e){try{return Mw(e)}catch{return}}function nm(e){try{return rm(e)}catch{return}}var Zs={operator:void 0,major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]};var To=async e=>{try{let t=await fetch(e);return t.ok?le([t,!1]):ee({name:"HTTPError",message:${t.status} ${t.statusText},response:t})}catch(t){if(t instanceof TypeError)return ee({name:"NetworkError",message:t.message,request:e});if(t instanceof DOMException)return ee({name:"AbortError",message:t.message,request:e});throw t}};var sm="https://jsr.io",Aw=async(e,t)=>{let r=await(t?.fetch??To)(new Request(${t?.endpoint??sm}/${e}/meta.json),t?.cacheFirst);return Gt(r,([o])=>o.json())};var Iw=async(e,t,r)=>{let o=await(r?.fetch??To)(new Request(${r?.endpoint??sm}/${e}/${t}_meta.json),r?.cacheFirst);return Gt(o,([n])=>n.json())};var Fw=async(e,t)=>{let r=await(t?.fetch??To)(new Request(${t?.endpoint??"https://registry.npmjs.org"}/${e}),t?.cacheFirst);return Gt(r,([o])=>o.json())};var $w=(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}),Bc=(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}),jw=async(e,t)=>{if(t?.resolvedVersions){let c=new Map(t.resolvedVersions.get(e.name)??[]),l=Qs([...c.keys()],e.range);if(l){let u=c.get(l)??ei,p=u[e.entryPoint];return typeof p!="string"&&console.log(p),p?le(Dw(e.name,mn(l),p)):ee(Bc(e,Object.keys(u)))}}let r=await Fw(e.name,t);if(G(r))return r;let o=z(r),n=new Map(Object.entries(o.versions).flatMap(([c,{exports:l}])=>{let u=nm(c);return u?[[u,l??ei]]:[]})),s=Qs([...n.keys()],e.range);if(!s)return ee($w(e,Object.keys(o.versions)));let i={...ei};for(let c of Object.keys(n.get(s)??ei))i[c]=c;let a=i[e.entryPoint];return a?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[s,i]]),le(Dw(e.name,mn(s),a))):ee(Bc(e,Object.keys(i)))},Dw=(e,t,r)=>new URL(r,https://esm.sh/${e}@${t}/),Bw=async(e,t)=>{if(t?.resolvedVersions){let a=new Map(t.resolvedVersions.get(e.name)??[]),c=Qs([...a.keys()],e.range);if(c){let l=a.get(c)??ei,u=l[e.entryPoint];return u?le(Uw(e.name,mn(c),u)):ee(Bc(e,Object.keys(l)))}}let r=await qL(e,t);if(G(r))return r;let o=z(r),n=await Iw(e.name,mn(o),t);if(G(n))return n;let s=z(n).exports,i=s[e.entryPoint];return i?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[o,s]]),le(Uw(e.name,mn(o),i))):ee(Bc(e,Object.keys(z(n).exports)))},Uw=(e,t,r)=>new URL(r,https://jsr.io/${e}/${t}/),qL=async(e,t)=>{let r=await Aw(e.name,t);if(G(r))return r;let o=z(r),n=Object.keys(o.versions).flatMap(i=>{let a=nm(i);return a?[a]:[]}),s=Qs(n,e.range);return s?le(s):ee($w(e,Object.keys(o.versions)))},ei={".":"./"};var zL=e=>({name:"OnlyScopeProvidedError",specifier:e}),Hw=e=>({name:"PackageNotFoundError",specifier:e}),Ww=e=>{if(e.protocol!=="npm:")return ee({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 ee(zL(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 ee(Hw(e));let s=t.slice(r,n),i=decodeURIComponent(t.slice(n+1,o)),a=i?om(i)??[[Zs]]:[[Zs]],c=t.slice(o+1),l=c?./${c}:".",u={name:s,range:a,entryPoint:l};return i&&(u.tag=i),le(u)},Gw=e=>{if(e.protocol!=="jsr:")return ee({name:"NotJsrProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0;if(t[r]!=="@")return ee({name:"ScopeNotFoundError",specifier:e});let o=t.indexOf("/",r);if(o===-1)return ee(Hw(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?om(a)??[[Zs]]:[[Zs]],l=t.slice(n+1),u=l?./${l}:".",p={name:i,range:c,entryPoint:u};return a&&(p.tag=a),le(p)};var qw=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 Kw=e=>{let t=new Map,r=async o=>{let n=o.namespace==="npm",s=(n?Ww:Gw)(Xu(o));if(G(s)){let a=ne(s);return{errors:[{text:a.name,detail:a}]}}let i=await(n?jw:Bw)(z(s),{resolvedVersions:t,...e});if(G(i)){let a=ne(i);return{errors:[{text:${a.name} ${a.message},detail:a}]}}return yw(z(i))};return{name:"remote-loader",setup({onLoad:o,onResolve:n,initialOptions:s}){for(let i of[...zw,...Vw])n({filter:/.*/,namespace:i.slice(0,-1)},VL);n({filter:/.*/,namespace:"npm"},r),n({filter:/.*/,namespace:"jsr"},r);for(let i of zw)o({filter:/.*/,namespace:i.slice(0,-1)},a=>KL(Xu(a),{...e,sourcemap:s.sourcemap!==!1&&s.sourcemap!==void 0}));for(let i of Vw)o({filter:/.*/,namespace:i.slice(0,-1)},()=>{throw new Error(${i} import is not supported yet.)})}}},VL=e=>({path:e.path,namespace:e.namespace}),zw=["http:","https:","data:"],Vw=["node:"],KL=async(e,t)=>{let r=t.reload?t.reload===!0?!1:!t.reload.some(l=>l.test(e)):!0,o=t.fetch??To,n=await o(new Request(e),r);if(G(n))return{errors:[{text:${ne(n).message} Failed to fetch ${e},detail:ne(n)}]};let[s,i]=z(n),a=Ew(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&&ww(a)){let l=await c.text(),u=xw(l,e);if(We(u)){let{url:p,start:f,end:m}=z(u);if(p.protocol!=="data:"){let h=await o(new Request(p),r);if(G(h))return{contents:l,loader:a,warnings:[{text:${ne(h).message} Failed to fetch the source map URL,notes:[{text:Source map URL: ${p}},{text:Original URL: ${e}}],detail:ne(h)}]};let g=await z(h)[0].blob().then(qw);return{contents:l.slice(0,f)+g+l.slice(m),loader:a}}}}return{contents:new Uint8Array(await c.arrayBuffer()),loader:a}};var oi=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"}},YL=/[$_\p{ID_Start}]/u,XL=/[$_\u200C\u200D\p{ID_Continue}]/u,am=".*";function JL(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function Jw(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&&YL.test(c)||a!==o+1&&XL.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(!JL(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 Qw(e,t={}){let r=Jw(e);t.delimiter??="/#?",t.prefixes??="./";let o=^${ir(t.delimiter)}+?,n=[],s=0,i=0,a="",c=new Set,l=v=>{if(i<r.length&&r[i].type===v)return r[i++].value},u=()=>l("OTHER_MODIFIER")??l("ASTERISK"),p=v=>{let b=l(v);if(b!==void 0)return b;let{type:T,index:R}=r[i];throw new TypeError(Unexpected ${T} at ${R}, expected ${v})},f=()=>{let v="",b;for(;b=l("CHAR")??l("ESCAPED_CHAR");)v+=b;return v},m=v=>v,h=t.encodePart||m,g="",y=v=>{g+=v},x=()=>{g.length&&(n.push(new oi(3,"","",h(g),"",3)),g="")},E=(v,b,T,R,L)=>{let C=3;switch(L){case"?":C=1;break;case"*":C=0;break;case"+":C=2;break}if(!b&&!T&&C===3){y(v);return}if(x(),!b&&!T){if(!v)return;n.push(new oi(3,"","",h(v),"",C));return}let M;T?T==="*"?M=am:M=T:M=o;let O=2;M===o?(O=1,M=""):M===am&&(O=0,M="");let _;if(b?_=b:T&&(_=s++),c.has(_))throw new TypeError(Duplicate name '${_}'.);c.add(_),n.push(new oi(O,_,h(v),M,h(R),C))};for(;i<r.length;){let v=l("CHAR"),b=l("NAME"),T=l("REGEX");if(!b&&!T&&(T=l("ASTERISK")),b||T){let L=v??"";t.prefixes.indexOf(L)===-1&&(y(L),L=""),x();let C=u();E(L,b,T,"",C);continue}let R=v??l("ESCAPED_CHAR");if(R){y(R);continue}if(l("OPEN")){let L=f(),C=l("NAME"),M=l("REGEX");!C&&!M&&(M=l("ASTERISK"));let O=f();p("CLOSE");let _=u();E(L,C,M,O,_);continue}x(),p("END")}return n}function ir(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Yw(e){return e&&e.ignoreCase?"ui":"u"}function QL(e,t,r){return Zw(Qw(e,r),t,r)}function es(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function Zw(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+=ir(a.value):o+=(?:${ir(a.value)})${es(a.modifier)};continue}t&&t.push(a.name);let c=^${ir(r.delimiter)}+?,l=a.value;if(a.type===1?l=c:a.type===0&&(l=am),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?o+=(${l})${es(a.modifier)}:o+=((?:${l})${es(a.modifier)});continue}if(a.modifier===3||a.modifier===1){o+=(?:${ir(a.prefix)}(${l})${ir(a.suffix)}),o+=es(a.modifier);continue}o+=(?:${ir(a.prefix)},o+=((?:${l})(?:,o+=ir(a.suffix),o+=ir(a.prefix),o+=(?:${l}))*)${ir(a.suffix)}),a.modifier===0&&(o+="?")}let n=${ir(r.endsWith)}|$,s=${ir(r.delimiter)};if(r.end)return r.strict||(o+=${s}?),r.endsWith.length?o+=(?=${n}):o+="$",new RegExp(o,Yw(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,Yw(r))}var Po={delimiter:"",prefixes:"",sensitive:!0,strict:!0},ZL={delimiter:".",prefixes:"",sensitive:!0,strict:!0},e1={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function t1(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function eE(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function r1(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function tE(e){return!e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var rE=["ftp","file","http","https","ws","wss"];function oE(e){if(!e)return!0;for(let t of rE)if(e.test(t))return!0;return!1}function o1(e,t){if(e=eE(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 n1(e,t){if(e=eE(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 s1(e,t){return t||e===""?e:tE(e)?iE(e):sE(e)}function i1(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function a1(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function c1(e,t,r){if(r||e==="")return e;if(t&&!rE.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 l1(e,t,r){return nE(t)===e&&(e=""),r||e===""?e:aE(e)}function p1(e,t){return e=r1(e,":"),t||e===""?e:cm(e)}function nE(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function cm(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(Invalid protocol '${e}'.)}function u1(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function m1(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function sE(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 iE(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(Invalid IPv6 hostname '${e}');return e.toLowerCase()}function aE(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(Invalid port '${e}'.)}function f1(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 d1(e){return e===""?e:new URL(data:${e}).pathname}function h1(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function g1(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var y1=class{#i;#o=[];#t={};#e=0;#s=1;#a=0;#n=0;#m=0;#p=0;#f=!1;constructor(e){this.#i=e}get result(){return this.#t}parse(){for(this.#o=Jw(this.#i,!0);this.#e<this.#o.length;this.#e+=this.#s){if(this.#s=1,this.#o[this.#e].type==="END"){if(this.#n===0){this.#g(),this.#u()?this.#r(9,1):this.#d()?this.#r(8,1):this.#r(7,0);continue}else if(this.#n===2){this.#y(5);continue}this.#r(10,0);break}if(this.#m>0)if(this.#_())this.#m-=1;else continue;if(this.#T()){this.#m+=1;continue}switch(this.#n){case 0:this.#E()&&this.#y(1);break;case 1:if(this.#E()){this.#S();let e=7,t=1;this.#k()?(e=2,t=3):this.#f&&(e=2),this.#r(e,t)}break;case 2:this.#b()?this.#y(3):(this.#w()||this.#d()||this.#u())&&this.#y(5);break;case 3:this.#v()?this.#r(4,1):this.#b()&&this.#r(5,1);break;case 4:this.#b()&&this.#r(5,1);break;case 5:this.#P()?this.#p+=1:this.#O()&&(this.#p-=1),this.#R()&&!this.#p?this.#r(6,1):this.#w()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 6:this.#w()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 7:this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 8:this.#u()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="")}#r(e,t){switch(this.#n){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.#n!==0&&e!==10&&([1,2,3,4].includes(this.#n)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#n)&&[8,9].includes(e)&&(this.#t.pathname??=this.#f?"/":""),[1,2,3,4,5,6,7].includes(this.#n)&&e===9&&(this.#t.search??="")),this.#h(e,t)}#h(e,t){this.#n=e,this.#a=this.#e+t,this.#e+=t,this.#s=0}#g(){this.#e=this.#a,this.#s=0}#y(e){this.#g(),this.#n=e}#x(e){return e<0&&(e=this.#o.length-e),e<this.#o.length?this.#o[e]:this.#o[this.#o.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")}#E(){return this.#c(this.#e,":")}#k(){return this.#c(this.#e+1,"/")&&this.#c(this.#e+2,"/")}#b(){return this.#c(this.#e,"@")}#v(){return this.#c(this.#e,":")}#R(){return this.#c(this.#e,":")}#w(){return this.#c(this.#e,"/")}#d(){if(this.#c(this.#e,"?"))return!0;if(this.#o[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.#o[this.#e].type=="OPEN"}#_(){return this.#o[this.#e].type=="CLOSE"}#P(){return this.#c(this.#e,"[")}#O(){return this.#c(this.#e,"]")}#l(){let e=this.#o[this.#e],t=this.#x(this.#a).index;return this.#i.substring(t,e.index)}#S(){let e={};Object.assign(e,Po),e.encodePart=cm;let t=QL(this.#l(),void 0,e);this.#f=oE(t)}},im=["protocol","username","password","hostname","port","pathname","search","hash"],_o="*";function Xw(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 oo(e,t){return t?ri(e):e}function ti(e,t,r){let o;if(typeof t.baseURL=="string")try{o=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=oo(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=oo(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=oo(o.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=oo(o.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=oo(o.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=oo(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=oo(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=oo(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(invalid baseURL '${t.baseURL}'.)}if(typeof t.protocol=="string"&&(e.protocol=p1(t.protocol,r)),typeof t.username=="string"&&(e.username=a1(t.username,r)),typeof t.password=="string"&&(e.password=i1(t.password,r)),typeof t.hostname=="string"&&(e.hostname=s1(t.hostname,r)),typeof t.port=="string"&&(e.port=l1(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,o&&!t1(e.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(e.pathname=oo(o.pathname.substring(0,n+1),r)+e.pathname)}e.pathname=c1(e.pathname,e.protocol,r)}return typeof t.search=="string"&&(e.search=n1(t.search,r)),typeof t.hash=="string"&&(e.hash=o1(t.hash,r)),e}function ri(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function x1(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function b1(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",o=^${x1(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+=ri(a.value);continue}s+={${ri(a.value)}}${es(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+=ri(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+=ri(a.suffix),l&&(s+="}"),a.modifier!==3&&(s+=es(a.modifier))}return s}var cE=class{#i;#o={};#t={};#e={};#s={};#a=!1;constructor(e={},t,r){try{let o;if(typeof t=="string"?o=t:r=t,typeof e=="string"){let a=new y1(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:_o,protocol:_o,username:_o,password:_o,hostname:_o,port:_o,search:_o,hash:_o};this.#i=ti(s,e,!0),nE(this.#i.protocol)===this.#i.port&&(this.#i.port="");let i;for(i of im){if(!(i in this.#i))continue;let a={},c=this.#i[i];switch(this.#t[i]=[],i){case"protocol":Object.assign(a,Po),a.encodePart=cm;break;case"username":Object.assign(a,Po),a.encodePart=u1;break;case"password":Object.assign(a,Po),a.encodePart=m1;break;case"hostname":Object.assign(a,ZL),tE(c)?a.encodePart=iE:a.encodePart=sE;break;case"port":Object.assign(a,Po),a.encodePart=aE;break;case"pathname":oE(this.#o.protocol)?(Object.assign(a,e1,n),a.encodePart=f1):(Object.assign(a,Po,n),a.encodePart=d1);break;case"search":Object.assign(a,Po,n),a.encodePart=h1;break;case"hash":Object.assign(a,Po,n),a.encodePart=g1;break}try{this.#s[i]=Qw(c,a),this.#o[i]=Zw(this.#s[i],this.#t[i],a),this.#e[i]=b1(this.#s[i],a),this.#a=this.#a||this.#s[i].some(l=>l.type===2)}catch{throw new TypeError(invalid ${i} pattern '${this.#ii}'.)}}}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=ti(r,e,!1):r=ti(r,Xw(e,t),!1)}catch{return!1}let o;for(o of im)if(!this.#o[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=ti(r,e,!1):r=ti(r,Xw(e,t),!1)}catch{return null}let o={};t?o.inputs=[e,t]:o.inputs=[e];let n;for(n of im){let s=this.#o[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 oi(3,"","","","",3),s=new oi(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.#s[e],[s]):!t.#e[e]&&r.#e[e]?i([s],r.#s[e]):i(t.#s[e],r.#s[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=cE);var lE,pE=async(e,t)=>(lE??=xc({wasm:e,worker:t}),await lE,async r=>{let{outputFiles:o}=await gc({entryPoints:[r],format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[Kb(),Kw({fetch:w1,reload:[new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"})]})],write:!1});return{contents:o[0].text}}),w1=async(e,t)=>{let r=tw(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let o=await lm(e);if(o)return o}try{let o=await r(e);return o.ok?(r===GM_fetch&&!e.url.startsWith("data:")&&await Pa(e,o),le([o,!1])):await lm(e)??ee({name:"HTTPError",message:${o.status} ${o.statusText},response:o})}catch(o){let n=await lm(e);if(n)return n;if(o instanceof TypeError)return ee({name:"NetworkError",message:o.message,request:e});if(o instanceof DOMException)return ee({name:"AbortError",message:o.message,request:e});throw o}},lm=async e=>{if(e.url.startsWith("data:"))return;let t=await Cn(e);if(t)return t.url||Object.defineProperty(t,"url",{value:e.url}),le([t,!0])};var uE=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e);var mE=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},fE=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},dE=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},hE=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var gE=()=>{let e;return{show:(o,{x:n,y:s})=>{e=E1(),e.append(k1(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?.()}}},E1=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},k1=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 yE=()=>{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}=gE();return{component:e,setStatus:async(s,i)=>{switch(e.textContent="",await o(),s){case"loading":e.append(dE());break;case"pass":e.append(mE());break;case"fail":e.append(fE());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 xE=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(hE()),t.addEventListener("click",e),t};var bE=e=>{let{component:t,setStatus:r}=yE(),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(xE(e),t),{menu:o,setStatus:r}};function wE(e){return new Promise(t=>setTimeout(t,e))}function EE(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 wE(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 kE,vE=async(e,t)=>{let r=[],n=EE(async()=>{r.forEach(({menu:i,setStatus:a})=>{a("none"),i.remove()});let s=mb(scrapbox.Project.name,scrapbox.Page.title??"",Ut());for(let i of s){let a=i.lang.toLowerCase();if(uE(a))for(let c of i.startIds){let l=document.getElementById(L${c}),{menu:u,setStatus:p}=bE(async()=>{await p("loading");try{kE??=await pE(e,t);let{contents:f}=await kE(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 R1(e,t){for(var r in t)e[r]=t[r];return e}function RE(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 Wc(e,t){var r=t(),o=X({t:{__:r,u:t}}),n=o[0].t,s=o[1];return da(function(){n.__=r,n.u=t,pm(n)&&s({t:n})},[e,r,t]),Z(function(){return pm(n)&&s({t:n}),e(function(){pm(n)&&s({t:n})})},[e]),r}function pm(e){var t,r,o=e.u,n=e.__;try{var s=o();return!((t=n)===(r=s)&&(t!==0||1/t==1/r)||t!=t&&r!=r)}catch{return!0}}function TE(e,t){this.props=e,this.context=t}(TE.prototype=new mr).isPureReactComponent=!0,TE.prototype.shouldComponentUpdate=function(e,t){return RE(this.props,e)||RE(this.state,t)};var _E=te.__b;te.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),_E&&_E(e)};var BAe=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;var T1=te.__e;te.__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)}T1(e,t,r,o)};var PE=te.unmount;function ME(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=R1({},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 ME(o,t,r)})),e}function AE(e,t,r){return e&&r&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(o){return AE(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 um(){this.__u=0,this.o=null,this.__b=null}function IE(e){var t=e.__.__c;return t&&t.__a&&t.__a(e)}function Hc(){this.i=null,this.l=null}te.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),PE&&PE(e)},(um.prototype=new mr).__c=function(e,t){var r=t.__c,o=this;o.o==null&&(o.o=[]),o.o.push(r);var n=IE(o.__v),s=!1,i=function(){s||(s=!0,r.__R=null,n?n(a):a())};r.__R=i;var a=function(){if(!--o.__u){if(o.state.__a){var c=o.state.__a;o.__v.__k[0]=AE(c,c.__c.__P,c.__c.__O)}var l;for(o.setState({__a:o.__b=null});l=o.o.pop();)l.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(i,i)},um.prototype.componentWillUnmount=function(){this.o=[]},um.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]=ME(this.__b,r,o.__O=o.__P)}this.__b=null}var n=t.__a&&Wr(Q,null,e.fallback);return n&&(n.__u&=-33),[Wr(Q,null,t.__a?null:e.children),n]};var OE=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]}};(Hc.prototype=new mr).__a=function(e){var t=this,r=IE(t.__v),o=t.l.get(e);return o[0]++,function(n){var s=function(){t.props.revealOrder?(o.push(n),OE(t,e,o)):n()};r?r(s):s()}},Hc.prototype.render=function(e){this.i=null,this.l=new Map;var t=io(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},Hc.prototype.componentDidUpdate=Hc.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,r){OE(e,r,t)})};var _1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,P1=/^(?: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]/,O1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,S1=/[A-Z0-9]/g,N1=typeof document<"u",L1=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};mr.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(mr.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var SE=te.event;function C1(){}function M1(){return this.cancelBubble}function A1(){return this.defaultPrevented}te.event=function(e){return SE&&(e=SE(e)),e.persist=C1,e.isPropagationStopped=M1,e.isDefaultPrevented=A1,e.nativeEvent=e};var FE,I1={enumerable:!1,configurable:!0,get:function(){return this.class}},NE=te.vnode;te.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||N1&&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"||L1(r.type)?c==="onfocus"?i="onfocusin":c==="onblur"?i="onfocusout":O1.test(i)&&(i=c):c=i="oninput":s&&P1.test(i)?i=i.replace(S1,"-$&").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=io(r.children).forEach(function(l){l.props.selected=n.value.indexOf(l.props.value)!=-1})),o=="select"&&n.defaultValue!=null&&(n.value=io(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",I1)):(r.className&&!r.class||r.class&&r.className)&&(n.class=n.className=r.className),t.props=n}(e),e.$$typeof=_1,NE&&NE(e)};var LE=te.__r;te.__r=function(e){LE&&LE(e),FE=e.__c};var CE=te.diffed;te.diffed=function(e){CE&&CE(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),FE=null};var Gc=e=>[...e].map((t,r)=>t===" "?"_":!F1.includes(t)||r===e.length-1&&D1.includes(t)?encodeURIComponent(t):t).join(""),F1='@$&+=:;",',D1=':;",';var DE=({title:e,projects:t,selected:r,confirm:o})=>d("div",{className:candidate${r?" selected":""},children:[d(U1,{title:e,confirm:o}),t.map(n=>d($1,{project:n.name,title:e,mark:n.mark,confirm:n.confirm}))]}),U1=({title:e,confirm:t})=>d("a",{className:"button",tabIndex:0,role:"menuitem",href:./${Gc(e)},onClick:UE(t),children:e}),$1=({project:e,title:t,mark:r,confirm:o})=>{let n=UE(o);return r===""?null:d("a",{className:"mark",tabIndex:0,href:../${e}/${Gc(t)},onClick:n,title:/${e}/${Gc(t)},children:r instanceof URL?d("img",{src:r.href}):${r}})},UE=e=>A(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var $E=(e,t)=>{let[r,o]=X(null),n=A(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=A(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=A(()=>o(e.length===0?null:t(e[0])),[e,t]),a=A(()=>o(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:n,prev:s,selectFirst:i,selectLast:a}};var jE=e=>{let[t,r]=X(null),o=U(()=>{let n=t?.getBoundingClientRect?.(),i=Ns(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 fm="enableProjectsOnSuggestion",BE=(e,t)=>{let[r,o]=X(qc([...e],t)),n=A((s,i)=>{j1(s,i,e,t),o(qc([...e],t))},[e,t.enableSelfProjectOnStart]);return Z(()=>{let s=i=>{i.key===fm&&o(qc([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:n}},mm=!0,qc=(e,t)=>{try{let r=localStorage.getItem(fm);if(r===null)return zc(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)?mm?o:o.filter(n=>n!==scrapbox.Project.name):mm?[...o,scrapbox.Project.name]:o:(zc(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return zc(e),e}},j1=(e,t,r,o)=>{let n=qc([...r],o);o.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(mm=t),zc(t?[...n,e]:n.filter(s=>s!==e))},zc=e=>localStorage.setItem(fm,JSON.stringify(e));var HE=()=>U(()=>document.documentElement.dataset.os??"",[]);var ni=(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 WE=({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 qE=({position:e,start:t,enableSelfProjectOnStart:r,projects:o,...n})=>{let{projects:s,set:i}=BE(o,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:c,left:l,right:u}=jE({line:e.line,char:t}),p=HE();return d(Q,{children:[d(H1,{itemCount:n.items.length,enableProjects:s,projects:o,top:c,right:u,set:i,os:p,...n}),d(B1,{updateStandardElement:a,start:t,enableProjects:s,projects:o,top:c,left:l,os:p,...n})]})},B1=({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=A((O,_,P)=>{let N=[${_?/${_}/${O}:O}${P?.icon?".icon":""}];r((I,{line:F})=>[${...I.slice(0,e).join("")}${N}${...I.slice(e+...n.length).join("")},{line:F,char:e+[...N].length}])},[e,n]),y=U(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),x=U(()=>{let O=[];for(let _ of a){if(O.length===f)break;_.projects.some(P=>s.includes(P))&&O.push({title:_.title,projects:_.projects.flatMap(P=>s.includes(P)?[{name:P,mark:y?ni(m[P]??"",import.meta.url)||P[0]:"",confirm:N=>g(_.title,P,N)}]:[]),confirm:P=>g(_.title,void 0,P)})}return O},[s,y,a,f,m,g]),{selectedId:E,next:v,prev:b,selectLast:T,selectFirst:R}=$E(x,GE),L=A(O=>E===null?!1:(x.find(_=>GE(_)===E)?.confirm?.(O),!0),[E,x]);Z(()=>p(x.length===0?void 0:{selectNext:O=>(v(O),!0),selectPrev:O=>(b(O),!0),selectFirst:()=>(R(),!0),selectLast:()=>(T(),!0),confirm:L,cancel:()=>(o(),!0)}),[p,x.length,v,b,R,T,L]);let C=U(()=>x.length>0&&c!=null&&l!=null?{top:c,left:l}:{display:"none"},[x.length,c,l]),M=A(O=>{if(!O){t(O);return}let _=O.parentNode;if(!(_ instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(_.host.parentElement)},[t]);return d("div",{ref:M,className:"container candidates","data-os":h,style:C,children:[x.map(O=>d(DE,{...O,selected:E===O.title},O.title)),a.length>f&&d("div",{className:"counter",children:${a.length-f} more links}),d(WE,{progress:u})]})},H1=({enableProjects:e,projects:t,projectScore:r,mark:o,itemCount:n,top:s,right:i,set:a,os:c,freezeUntil:l})=>{let u=U(()=>[...t].sort((f,m)=>(r.get(m)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:ni(o[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),rt().focus()})}]:[]),[t,r,e,o]),p=U(()=>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(W1,{...f},f.name))})},W1=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}}),GE=e=>e.title;var zE=e=>{let t=U(()=>ni(e.style,import.meta.url),[e.style]);return d(Q,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var VE=()=>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*KE(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 YE=(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(q1(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=G1(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"}},G1=(e,t)=>{for(let{whole:r,start:o}of KE(e))if(!(t<=o||o+[...r].length<=t))return{whole:r,start:o}},q1=(e,t)=>!(t.trim()===""||t.includes(
)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var XE=()=>{let e=tt(scrapbox.Page.lines),t=tt(!1);return Z(()=>{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)}},[]),A(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var z1=On("scrapbox-select-suggestion:useLifecycle.ts"),JE=()=>{let[e,t]=ao(YE,{type:"ready"}),r=XE(),o=U(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:c,selection:l}=Nt();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:c.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);Z(()=>{let i=()=>{o("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{o("selection:changed")},c=Oa();return c.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),c.removeChangeListener(a)}},[]),Z(()=>{if(e.context!=="input")return;let i=()=>{o("cursor:changed")},a=lo();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[n,s]=X(e);return n!==e&&(s(e),z1.debug("Detect changes",e)),{state:e,setEnable:A(i=>t({type:i?"enable":"disable"}),[]),cancel:A(()=>t({type:"cancel"}),[]),freezeUntil:A(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:A(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:c,selection:l}=Nt(),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 Xe(f),c.setPosition(m),c.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var QE=(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 ek=Symbol("Comlink.proxy"),V1=Symbol("Comlink.endpoint"),gm=Symbol("Comlink.releaseProxy"),dm=Symbol("Comlink.finalizer"),Kc=Symbol("Comlink.thrown"),tk=e=>typeof e=="object"&&e!==null||typeof e=="function",K1={canHandle:e=>tk(e)&&e[ek],serialize(e){let{port1:t,port2:r}=new MessageChannel;return ok(e,t),[r,[r]]},deserialize(e){return e.start(),ym(e)}},Y1={canHandle:e=>tk(e)&&Kc 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}},rk=new Map([["proxy",K1],["throw",Y1]]);function X1(e,t){for(let r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function ok(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(n){if(!n||!n.data)return;if(!X1(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(fn),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]]=fn(n.data.value),l=!0;break;case"APPLY":l=p.apply(u,c);break;case"CONSTRUCT":{let f=new p(...c);l=xm(f)}break;case"ENDPOINT":{let{port1:f,port2:m}=new MessageChannel;ok(e,m),l=tC(f,[f])}break;case"RELEASE":l=void 0;break;default:return}}catch(u){l={value:u,[Kc]:0}}Promise.resolve(l).catch(u=>({value:u,[Kc]:0})).then(u=>{let[p,f]=Jc(u);t.postMessage(Object.assign(Object.assign({},p),{id:s}),f),i==="RELEASE"&&(t.removeEventListener("message",o),nk(t),dm in e&&typeof e[dm]=="function"&&e[dm]())}).catch(u=>{let[p,f]=Jc({value:new TypeError("Unserializable return value"),[Kc]:0});t.postMessage(Object.assign(Object.assign({},p),{id:s}),f)})}),t.start&&t.start()}function J1(e){return e.constructor.name==="MessagePort"}function nk(e){J1(e)&&e.close()}function ym(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)}}),hm(e,r,[],t)}function Vc(e){if(e)throw new Error("Proxy has been released and is not useable")}function sk(e){return ts(e,new Map,{type:"RELEASE"}).then(()=>{nk(e)})}var Yc=new WeakMap,Xc="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(Yc.get(e)||0)-1;Yc.set(e,t),t===0&&sk(e)});function Q1(e,t){let r=(Yc.get(t)||0)+1;Yc.set(t,r),Xc&&Xc.register(e,t,e)}function Z1(e){Xc&&Xc.unregister(e)}function hm(e,t,r=[],o=function(){}){let n=!1,s=new Proxy(o,{get(i,a){if(Vc(n),a===gm)return()=>{Z1(s),sk(e),t.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>s};let c=ts(e,t,{type:"GET",path:r.map(l=>l.toString())}).then(fn);return c.then.bind(c)}return hm(e,t,[...r,a])},set(i,a,c){Vc(n);let[l,u]=Jc(c);return ts(e,t,{type:"SET",path:[...r,a].map(p=>p.toString()),value:l},u).then(fn)},apply(i,a,c){Vc(n);let l=r[r.length-1];if(l===V1)return ts(e,t,{type:"ENDPOINT"}).then(fn);if(l==="bind")return hm(e,t,r.slice(0,-1));let[u,p]=ZE(c);return ts(e,t,{type:"APPLY",path:r.map(f=>f.toString()),argumentList:u},p).then(fn)},construct(i,a){Vc(n);let[c,l]=ZE(a);return ts(e,t,{type:"CONSTRUCT",path:r.map(u=>u.toString()),argumentList:c},l).then(fn)}});return Q1(s,e),s}function eC(e){return Array.prototype.concat.apply([],e)}function ZE(e){let t=e.map(Jc);return[t.map(r=>r[0]),eC(t.map(r=>r[1]))]}var ik=new WeakMap;function tC(e,t){return ik.set(e,t),e}function xm(e){return Object.assign(e,{[ek]:!0})}function Jc(e){for(let[t,r]of rk)if(r.canHandle(e)){let[o,n]=r.serialize(e);return[{type:"HANDLER",name:t,value:o},n]}return[{type:"RAW",value:e},ik.get(e)||[]]}function fn(e){switch(e.type){case"HANDLER":return rk.get(e.name).deserialize(e.value);case"RAW":return e.value}}function ts(e,t,r,o){return new Promise(n=>{let s=rC();t.set(s,n),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),o)})}function rC(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var rs=On("scrapbox-select-suggestion:cancelableSearch.ts"),ak=e=>{let t=ym(e);return{load:async r=>{rs.debug("start loading source");let o=await t.load([...r]);return rs.debug(loaded ${o} candidates),o},search:(r,o)=>oC(r,o??5e3,t.search),[Symbol.dispose]:()=>{t[gm](),e instanceof MessagePort?e.close():e.terminate(),rs.debug("shared worker closed.")}}},oC=(e,t,r)=>{if(rs.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,xm((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();rs.debug(Comlink search completed for "${e}" in ${a}ms)}},cancel(){n=!0;let i=new Date().getTime()-o.getTime();rs.debug(Comlink search cancelled for "${e}" after ${i}ms)}})};var Qc=(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 si=e=>e.query!=="",ck=e=>(t,r)=>{if("query"in r){if(r.query===t.query)return t;let i=si(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:si(t)?t.candidates:[]}}if(!si(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 ii="SharedWorker"in globalThis;var iC=On("scrapbox-select-suggestion:useSearch.ts"),lk=(e,t)=>{let r=U(()=>ak(ii?new SharedWorker(t.workerUrl,{type:"module"}).port:new Worker(t.workerUrl,{type:"module"})),[t.workerUrl]);Z(()=>(r.load(t.projects),()=>{using i=r}),[r,t.projects]);let o=A(ck(i=>{let a=!1;return{run:async()=>{let c=Qc((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]=ao(o,{query:""});return Z(()=>s({query:e}),[e]),U(()=>{if(!si(n))return;let[i,a]=aC(n.candidates);return iC.debug("Detect changes",{progress:n.progress,items:a}),{progress:n.progress,projectScore:i,items:a}},[n])},aC=e=>{let t=new Map,r=[];for(let o of e.sort(QE)){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 pk=(e,t)=>{let r=tt({...t});Z(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),Z(()=>{e(r.current)},[e])};var cC={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},uk=e=>{let{state:t,setEnable:r,...o}=JE(),n=lk(t.type==="completion"?t.context==="input"?t.query.slice(1,-1):t.query:"",e),[s,i]=X(),{callback:a,style:c,...l}=e;return pk(a,{enable:A(()=>r(!0),[]),disable:A(()=>r(!1),[]),...t.type!=="completion"||!s?cC:s}),d(Q,{children:[d(VE,{}),d(zE,{style:c}),t.type==="completion"&&n&&d(qE,{callback:i,...n,...t,...o,...l})]})};var mk=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 aa(n),new Promise(u=>ut(d(uk,{limit:o,projects:l,mark:s,style:i,callback:u,enableSelfProjectOnStart:a,workerUrl:c}),r))};var Xt=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*fk(e,t){for(let[r,o]of t.entries()){let n=e.get(r);if(n&&Xt(n.blocks)===Xt(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 Zc={};Ni(Zc,{getTitle:()=>Bd,parse:()=>kt});var dk=e=>{let t=new Map;if(e.length===0)return t;let r=kt(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 hk=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 el=class{constructor(t,r){this._filename=t;this._preview=hk(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||Xt(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=Fo(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 gk=({previewers:e})=>{let t=new Map,r=()=>{let s=dk(Ut());for(let{changed:i,filename:a}of fk(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 el(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 ai=e=>{let t=new FileReader,r=new Promise(o=>t.onload=()=>o(t.result));return t.readAsDataURL(e),r};var yk=async e=>{if(!("after"in e))return;let t=Xt(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 ai(new Blob([t],{type:"image/svg+xml"})),s=document.createElement("img");s.src=n,e.render(s)};var bm={};Ni(bm,{default:()=>wk});var UC=Object.create,bk=Object.defineProperty,$C=Object.getOwnPropertyDescriptor,jC=Object.getOwnPropertyNames,BC=Object.getPrototypeOf,HC=Object.prototype.hasOwnProperty,WC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),GC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of jC(t))!HC.call(e,n)&&n!==r&&bk(e,n,{get:()=>t[n],enumerable:!(o=$C(t,n))||o.enumerable});return e},qC=(e,t,r)=>(r=e!=null?UC(BC(e)):{},GC(t||!e||!e.__esModule?bk(r,"default",{value:e,enumerable:!0}):r,e)),zC=WC((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)}}),xk=qC(zC()),wk=xk.default??xk;var wm={};Ni(wm,{default:()=>vk});var VC=Object.create,kk=Object.defineProperty,KC=Object.getOwnPropertyDescriptor,YC=Object.getOwnPropertyNames,XC=Object.getPrototypeOf,JC=Object.prototype.hasOwnProperty,QC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ZC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of YC(t))!JC.call(e,n)&&n!==r&&kk(e,n,{get:()=>t[n],enumerable:!(o=KC(t,n))||o.enumerable});return e},eM=(e,t,r)=>(r=e!=null?VC(XC(e)):{},ZC(t||!e||!e.__esModule?kk(r,"default",{value:e,enumerable:!0}):r,e)),tM=QC((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}}),Ek=eM(tM()),vk=Ek.default??Ek;var rM=(()=>{var e=globalThis;return{default:e}})(),oM=(()=>{var e=(...t)=>Object.assign({},...t);return{default:e}})(),os=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(rM);case"is-function":return t(bm);case"parse-headers":return t(wm);case"npm:xtend":return t(oM);default:return console.error('module "'+e+'" not found'),null}},nM=Object.create,Tk=Object.defineProperty,sM=Object.getOwnPropertyDescriptor,iM=Object.getOwnPropertyNames,aM=Object.getPrototypeOf,cM=Object.prototype.hasOwnProperty,tl=(e=>typeof os<"u"?os:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof os<"u"?os:t)[r]}):e)(function(e){if(typeof os<"u")return os.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),lM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),pM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of iM(t))!cM.call(e,n)&&n!==r&&Tk(e,n,{get:()=>t[n],enumerable:!(o=sM(t,n))||o.enumerable});return e},uM=(e,t,r)=>(r=e!=null?nM(aM(e)):{},pM(t||!e||!e.__esModule?Tk(r,"default",{value:e,enumerable:!0}):r,e)),mM=lM((e,t)=>{"use strict";var r=tl("npm:global/window"),o=tl("is-function"),n=tl("parse-headers"),s=tl("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(F,j,D){h||(h=!0,m.callback(F,j,D))};function y(){b.readyState===4&&setTimeout(v,0)}function x(){var F=void 0;if(b.response?F=b.response:F=b.responseText||p(b),P)try{F=JSON.parse(F)}catch{}return F}function E(F){return clearTimeout(N),F instanceof Error||(F=new Error(""+(F||"Unknown XMLHttpRequest Error"))),F.statusCode=0,g(F,I)}function v(){if(!R){var F;clearTimeout(N),m.useXDR&&b.status===void 0?F=200:F=b.status===1223?204:b.status;var j=I,D=null;return F!==0?(j={body:x(),statusCode:F,method:C,headers:{},url:L,rawRequest:b},b.getAllResponseHeaders&&(j.headers=n(b.getAllResponseHeaders()))):D=new Error("Internal XMLHttpRequest Error"),g(D,j,j.body)}}var b=m.xhr||null;b||(m.cors||m.useXDR?b=new l.XDomainRequest:b=new l.XMLHttpRequest);var T,R,L=b.url=m.uri||m.url,C=b.method=m.method||"GET",M=m.body||m.data,O=b.headers=m.headers||{},_=!!m.sync,P=!1,N,I={body:void 0,headers:{},statusCode:0,method:C,url:L,rawRequest:b};if("json"in m&&m.json!==!1&&(P=!0,O.accept||O.Accept||(O.Accept="application/json"),C!=="GET"&&C!=="HEAD"&&(O["content-type"]||O["Content-Type"]||(O["Content-Type"]="application/json"),M=JSON.stringify(m.json===!0?M:m.json))),b.onreadystatechange=y,b.onload=v,b.onerror=E,b.onprogress=function(){},b.onabort=function(){R=!0},b.ontimeout=E,b.open(C,L,!_,m.username,m.password),_||(b.withCredentials=!!m.withCredentials),!_&&m.timeout>0&&(N=setTimeout(function(){if(!R){R=!0,b.abort("timeout");var F=new Error("XMLHttpRequest timeout");F.code="ETIMEDOUT",E(F)}},m.timeout)),b.setRequestHeader)for(T in O)O.hasOwnProperty(T)&&b.setRequestHeader(T,O[T]);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(M||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(){}}),Rk=uM(mM()),rl=Rk.default??Rk;var ol=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},p$e=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)}}}(),Ok=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},Sk=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}}(),Em=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)},ci="";function fM(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 dM=
This page requires a browser that supports WebGL.<br/>
<a href="http://get.webgl.org">Click here to upgrade your browser.</a>
,hM=
It does not appear your computer can support WebGL.<br/>
<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>
,gM=1,yM=2;function xM(e,t,r){function o(i){var a=e.parentNode;a&&(a.innerHTML=fM(i))}function n(i,a){typeof r=="function"?r(i):o(a)}if(!window.WebGLRenderingContext)return n(gM,dM),null;var s=bM(e,t);return s?s.getExtension("OES_standard_derivatives"):n(yM,hM),s}function bM(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 ns(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:(ci=n.getShaderInfoLog(s),console.error("*** Error compiling shader "+s+":"+ci),e.trigger("error",{shader:s,source:t,type:r,error:ci,offset:o||0}),n.deleteShader(s),null)}function _k(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:(ci=n.getProgramInfoLog(s),console.log("Error in program linking:"+ci),n.deleteProgram(s),null)}function km(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(ol(n[0])==="object")for(s=0;s<n.length;s++)r.push.apply(r,Em(km(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":ol(n))==="object"&&r.push.apply(r,Em(km(n,o)))}return r}function wM(e){var t=e.getBoundingClientRect();return t.top+t.height>0&&t.top<(window.innerHeight||document.documentElement.clientHeight)}function Pk(e){return(e&e-1)===0}function EM(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function kM(e,t){return e&&t?e.toString()!==t.toString():!1}function vM(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(),t.status==200?t.responseText:""}function Nk(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,Em(n))}}catch(f){a=!0,c=f}finally{try{!i&&l.return&&l.return()}finally{if(a)throw c}}}})}var vm=function(){function e(t,r){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Ok(this,e),Nk(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 Sk(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)},EM()&&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=Pk(this.width)&&Pk(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}();vm.getMaxTextureSize=function(e){return e.getParameter(e.MAX_TEXTURE_SIZE)};vm.activeUnit=-1;var Lk=function(){function e(t,r,o){var n=this;Ok(this,e),Nk(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=xM(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");rl.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");rl.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 Sk(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 E=x.substring(15).replace(/\'|\"|\;|\s/g,"");if(E.endsWith("glsl")){if(o.deps[E]===void 0){var v="https://lygia.xyz"+E;o.deps[E]=vM(v)}o.fragmentString+=o.deps[E]+
#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=ns(this,this.vertexString,this.gl.VERTEX_SHADER),f=ns(this,this.fragmentString,this.gl.FRAGMENT_SHADER);f?this.isValid=!0:(f=ns(this,void main(){
gl_FragColor = vec4(1.0);
},this.gl.FRAGMENT_SHADER),this.isValid=!1);var m=_k(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":ol(r))==="object"&&r.data&&r.width&&r.height?(o.data=r.data,o.width=r.width,o.height=r.height):(typeof r>"u"?"undefined":ol(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 vm(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=km(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=kM(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=wM(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=ns(r,r.vertexString,o.VERTEX_SHADER);for(var s in t){var i=t[s],a=ns(r,i.fragment,o.FRAGMENT_SHADER,1);a?r.isValid=!0:(a=ns(r,void main(){
gl_FragColor = vec4(1.0);
},o.FRAGMENT_SHADER),r.isValid=!1);var c=_k(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 RM(){var e=document.getElementsByClassName("glslCanvas");if(e.length>0){window.glslCanvases=[];for(var t=0;t<e.length;t++){var r=new Lk(e[t]);r.isValid&&window.glslCanvases.push(r)}}}window.addEventListener("load",function(){RM()});var nl=Lk;var Ck=e=>{if(!("after"in e))return Promise.resolve(void 0);let t=document.createElement("canvas");return new nl(t).load(Xt(e.after)),e.render(t),Promise.resolve(void 0)};var Mk=e=>{let t="";for(let r=0;r<e.length;r+=3)r+2===e.length?t+=Rm(e[r],e[r+1],0):r+1===e.length?t+=Rm(e[r],0,0):t+=Rm(e[r],e[r+1],e[r+2]);return t},sl=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?"_":"?"))),Rm=(e,t,r)=>{let o=e>>2,n=(e&3)<<4|t>>4,s=(t&15)<<2|r>>6,i=r&63;return sl(o&63)+sl(n&63)+sl(s&63)+sl(i&63)};var Ak=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${Mk(o)}};var Ik=async e=>{if(!("after"in e))return;let t=document.createElement("img"),r=await Ak(Xt(e.after));t.src=r,e.render(t)};var Tm=Promise.resolve({log:new Uint8Array(0)}),il,Fk=(e,t,r,o)=>(Tm=(async()=>{await Tm,il??=await TM(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),il.removeEventListener("message",a))};il.addEventListener("message",a)}),s={type:"compile",input:e};return il.postMessage(s),n})(),Tm),TM=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 Dk=(e,t)=>async r=>{if(!("after"in r))return;let o=_M(),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 Fk(Xt(r.after),e,t,s);if(clearTimeout(a),!c){r.render(o.div),o.log(n);return}i.src=await ai(new Blob([c],{type:"image/svg+xml"})),r.render(i)},_M=()=>{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 Ht(e,t){return Ae(e,{...t,weekStartsOn:1})}function dn(e,t){let r=w(e,t?.in),o=r.getFullYear(),n=S(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=Ht(n),i=S(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=Ht(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function li(e,t){let r=dn(e,t),o=S(t?.in||e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Ht(o)}function _m(e,t){let r,o=t?.in;return e.forEach(n=>{!o&&typeof n=="object"&&(o=S.bind(null,n));let s=w(n,o);(!r||r<s||isNaN(+s))&&(r=s)}),S(o,r||NaN)}function pi(e,t,r){let o=Aa(e,t)/1e3;return Ho(r?.roundingMethod)(o)}function al(e){return(t={})=>{let r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}function ss(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 IM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},FM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},DM={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"]},UM={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"]},$M={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"}},jM={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"}},BM=(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"},HM={ordinalNumber:BM,era:ss({values:IM,defaultWidth:"wide"}),quarter:ss({values:FM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:ss({values:DM,defaultWidth:"wide"}),day:ss({values:UM,defaultWidth:"wide"}),dayPeriod:ss({values:$M,defaultWidth:"wide",formattingValues:jM,defaultFormattingWidth:"wide"})};function is(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)?GM(a,p=>p.test(i)):WM(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 WM(e,t){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function GM(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function Bk(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 qM=/^(\d+)(th|st|nd|rd)?/i,zM=/\d+/i,VM={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},KM={any:[/^b/i,/^(a|c)/i]},YM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},XM={any:[/1/i,/2/i,/3/i,/4/i]},JM={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},QM={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]},ZM={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},eA={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]},tA={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},rA={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}},oA={ordinalNumber:Bk({matchPattern:qM,parsePattern:zM,valueCallback:e=>parseInt(e,10)}),era:is({matchPatterns:VM,defaultMatchWidth:"wide",parsePatterns:KM,defaultParseWidth:"any"}),quarter:is({matchPatterns:YM,defaultMatchWidth:"wide",parsePatterns:XM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:is({matchPatterns:JM,defaultMatchWidth:"wide",parsePatterns:QM,defaultParseWidth:"any"}),day:is({matchPatterns:ZM,defaultMatchWidth:"wide",parsePatterns:eA,defaultParseWidth:"any"}),dayPeriod:is({matchPatterns:tA,defaultMatchWidth:"any",parsePatterns:rA,defaultParseWidth:"any"})};var nA={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},sA={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},iA={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},LHe={date:al({formats:nA,defaultWidth:"full"}),time:al({formats:sA,defaultWidth:"full"}),dateTime:al({formats:iA,defaultWidth:"full"})};function Pm(e,t){let r=w(e,t?.in),o=+Ht(r)-+li(r);return Math.round(o/Uo)+1}function Hk(e,t){let r=w(e,t?.in).getDay();return r===0?7:r}function Om(e){return Math.trunc(+w(e)/1e3)}function Gk(e,t,r){let o=w(e,r?.in),n=Pm(o,r)-t;return o.setDate(o.getDate()-n*7),o}function cs(e,t,r){let o=fr(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=w(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 _e(s,l,r)}function qk(e,t,r){let o=w(e,r?.in),n=Hk(o,r),s=t-n;return _e(o,s,r)}var gA=class{subPriority=0;validate(e,t){return!0}},yA=class extends gA{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 ye=class{run(e,t,r,o){let n=this.parse(e,t,r,o);return n?{setter:new yA(n.value,this.validate,this.set,this.priority,this.subPriority),rest:n.rest}:null}validate(e,t,r){return!0}},xA=class extends ye{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"});case"GGGG":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"]},Ke={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}/},Ir={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 Ye(e,t){return e&&{value:t(e.value),rest:e.rest}}function Be(e,t){let r=t.match(e);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function Fr(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*po+s*_r+i*Ca),rest:t.slice(r[0].length)}}function zk(e){return Be(Ke.anyDigitsSigned,e)}function qe(e,t){switch(e){case 1:return Be(Ke.singleDigit,t);case 2:return Be(Ke.twoDigits,t);case 3:return Be(Ke.threeDigits,t);case 4:return Be(Ke.fourDigits,t);default:return Be(new RegExp("^\\d{1,"+e+"}"),t)}}function cl(e,t){switch(e){case 1:return Be(Ke.singleDigitSigned,t);case 2:return Be(Ke.twoDigitsSigned,t);case 3:return Be(Ke.threeDigitsSigned,t);case 4:return Be(Ke.fourDigitsSigned,t);default:return Be(new RegExp("^-?\\d{1,"+e+"}"),t)}}function Sm(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function Vk(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 Kk(e){return e%400===0||e%4===0&&e%100!==0}var bA=class extends ye{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 Ye(qe(4,e),o);case"yo":return Ye(r.ordinalNumber(e,{unit:"year"}),o);default:return Ye(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=Vk(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}},wA=class extends ye{priority=130;parse(e,t,r){let o=n=>({year:n,isTwoDigitYear:t==="YY"});switch(t){case"Y":return Ye(qe(4,e),o);case"Yo":return Ye(r.ordinalNumber(e,{unit:"year"}),o);default:return Ye(qe(t.length,e),o)}}validate(e,t){return t.isTwoDigitYear||t.year>0}set(e,t,r,o){let n=jo(e,o);if(r.isTwoDigitYear){let i=Vk(r.year,n);return e.setFullYear(i,0,o.firstWeekContainsDate),e.setHours(0,0,0,0),Ae(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),Ae(e,o)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]},EA=class extends ye{priority=130;parse(e,t){return cl(t==="R"?4:t.length,e)}set(e,t,r){let o=S(e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Ht(o)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]},kA=class extends ye{priority=130;parse(e,t){return cl(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"]},vA=class extends ye{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"});case"QQQQ":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"]},RA=class extends ye{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"});case"qqqq":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"]},TA=class extends ye{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 Ye(Be(Ke.month,e),o);case"MM":return Ye(qe(2,e),o);case"Mo":return Ye(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"});case"MMMM":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}},_A=class extends ye{priority=110;parse(e,t,r){let o=n=>n-1;switch(t){case"L":return Ye(Be(Ke.month,e),o);case"LL":return Ye(qe(2,e),o);case"Lo":return Ye(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"});case"LLLL":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"]},PA=class extends ye{priority=100;parse(e,t,r){switch(t){case"w":return Be(Ke.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 Ae(Fa(e,r,o),o)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]},OA=class extends ye{priority=100;parse(e,t,r){switch(t){case"I":return Be(Ke.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 Ht(Gk(e,r))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]},SA=[31,28,31,30,31,30,31,31,30,31,30,31],NA=[31,29,31,30,31,30,31,31,30,31,30,31],LA=class extends ye{priority=90;subPriority=1;parse(e,t,r){switch(t){case"d":return Be(Ke.date,e);case"do":return r.ordinalNumber(e,{unit:"date"});default:return qe(t.length,e)}}validate(e,t){let r=e.getFullYear(),o=Kk(r),n=e.getMonth();return o?t>=1&&t<=NA[n]:t>=1&&t<=SA[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"]},CA=class extends ye{priority=90;subpriority=1;parse(e,t,r){switch(t){case"D":case"DD":return Be(Ke.dayOfYear,e);case"Do":return r.ordinalNumber(e,{unit:"date"});default:return qe(t.length,e)}}validate(e,t){let r=e.getFullYear();return Kk(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"]},MA=class extends ye{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"});case"EEEE":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=cs(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]},AA=class extends ye{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 Ye(qe(t.length,e),n);case"eo":return Ye(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"});case"eeee":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=cs(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"]},IA=class extends ye{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 Ye(qe(t.length,e),n);case"co":return Ye(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"});case"cccc":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=cs(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"]},FA=class extends ye{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 Ye(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 Ye(r.day(e,{width:"narrow",context:"formatting"}),o);case"iiiiii":return Ye(r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o);case"iiii":default:return Ye(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=qk(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"]},DA=class extends ye{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"});case"aaaa":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(Sm(r),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]},UA=class extends ye{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"});case"bbbb":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(Sm(r),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]},$A=class extends ye{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"});case"BBBB":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(Sm(r),0,0,0),e}incompatibleTokens=["a","b","t","T"]},jA=class extends ye{priority=70;parse(e,t,r){switch(t){case"h":return Be(Ke.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"]},BA=class extends ye{priority=70;parse(e,t,r){switch(t){case"H":return Be(Ke.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"]},HA=class extends ye{priority=70;parse(e,t,r){switch(t){case"K":return Be(Ke.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"]},WA=class extends ye{priority=70;parse(e,t,r){switch(t){case"k":return Be(Ke.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"]},GA=class extends ye{priority=60;parse(e,t,r){switch(t){case"m":return Be(Ke.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"]},qA=class extends ye{priority=50;parse(e,t,r){switch(t){case"s":return Be(Ke.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"]},zA=class extends ye{priority=30;parse(e,t){let r=o=>Math.trunc(o*Math.pow(10,-t.length+3));return Ye(qe(t.length,e),r)}set(e,t,r){return e.setMilliseconds(r),e}incompatibleTokens=["t","T"]},VA=class extends ye{priority=10;parse(e,t){switch(t){case"X":return Fr(Ir.basicOptionalMinutes,e);case"XX":return Fr(Ir.basic,e);case"XXXX":return Fr(Ir.basicOptionalSeconds,e);case"XXXXX":return Fr(Ir.extendedOptionalSeconds,e);case"XXX":default:return Fr(Ir.extended,e)}}set(e,t,r){return t.timestampIsSet?e:S(e,e.getTime()-Vr(e)-r)}incompatibleTokens=["t","T","x"]},KA=class extends ye{priority=10;parse(e,t){switch(t){case"x":return Fr(Ir.basicOptionalMinutes,e);case"xx":return Fr(Ir.basic,e);case"xxxx":return Fr(Ir.basicOptionalSeconds,e);case"xxxxx":return Fr(Ir.extendedOptionalSeconds,e);case"xxx":default:return Fr(Ir.extended,e)}}set(e,t,r){return t.timestampIsSet?e:S(e,e.getTime()-Vr(e)-r)}incompatibleTokens=["t","T","X"]},YA=class extends ye{priority=40;parse(e){return zk(e)}set(e,t,r){return[S(e,r*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"},XA=class extends ye{priority=20;parse(e){return zk(e)}set(e,t,r){return[S(e,r),{timestampIsSet:!0}]}incompatibleTokens="*"},wGe={G:new xA,y:new bA,Y:new wA,R:new EA,u:new kA,Q:new vA,q:new RA,M:new TA,L:new _A,w:new PA,I:new OA,d:new LA,D:new CA,E:new MA,e:new AA,c:new IA,i:new FA,a:new DA,b:new UA,B:new $A,h:new jA,H:new BA,K:new HA,k:new WA,m:new GA,s:new qA,S:new zA,X:new VA,x:new KA,t:new YA,T:new XA};var Yk=(e,t,r=0,o=[])=>{let[n,s]=X("uninitialized"),[i,a]=X({ok:!0,value:t}),c=A(e,o);return Z(()=>{(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 Xk=e=>{let t=e.flatMap(({changes:n,created:s,userId:i})=>n.flatMap(a=>{let c=rI(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}},rI=(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 Ot=e=>{let{fetch:t=(n,s)=>globalThis.fetch(n,s),baseURL:r="https://scrapbox.io/",...o}=e;return{fetch:t,baseURL:r,...o}};var It=e=>connect.sid=${e};var oI=(e,t,r)=>{let{sid:o,baseURL:n,head:s}=Ot(r??{});return new Request(${n}api/commits/${e}/${t}?head=${s??""},o?{headers:{Cookie:It(o)}}:void 0)},Jk=(e,t,r)=>Ot(r??{}).fetch(oI(e,t,r));var Qk="Cannot complete the mapping as an error was thrown from an item";function ll(e,t,r){let o=new TransformStream({async transform(n,s){try{let i=await n;s.enqueue(i)}catch(i){i instanceof AggregateError&&i.message===Qk&&s.error(i)}}});return(async()=>{let n=o.writable.getWriter(),s=[];try{for await(let i of t){let a=Promise.resolve().then(()=>r(i));n.write(a);let c=a.then(()=>s.splice(s.indexOf(c),1));s.push(c),s.length>=e&&await Promise.race(s)}await Promise.all(s),n.close()}catch{let i=[];for(let a of await Promise.allSettled(s))a.status==="rejected"&&i.push(a.reason);n.write(Promise.reject(new AggregateError(i,Qk))).catch(()=>{})}})(),Symbol.asyncIterator in o.readable&&typeof o.readable[Symbol.asyncIterator]=="function"?o.readable[Symbol.asyncIterator]():async function*(){let n=o.readable.getReader();for(;;){let{done:s,value:i}=await n.read();if(s)break;yield i}n.releaseLock()}()}var ui=e=>[...e].map((t,r)=>t===" "?"_":!iI.includes(t)||r===e.length-1&&aI.includes(t)?encodeURIComponent(t):t).join(""),iI='@$&+=:;",',aI=':;",';var cI=(e,t,r)=>{let{sid:o,baseURL:n,followRename:s,projects:i}=Ot(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(${n}api/pages/${e}/${ui(t)}?${a},o?{headers:{Cookie:It(o)}}:void 0)},Nm=(e,t,r)=>Ot(r??{}).fetch(cI(e,t,r));var Zk=async(e,t)=>{let r=await Jk(e,t);if(!r.ok)throw new Error(Failed to fetch commits for ${e}/${t}: ${r.statusText},{cause:r});return Xk((await r.json()).commits)};var ev=()=>{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=>ut(d(lI,{getController:o=>r(o)}),t))},lI=({getController:e})=>{let[t,r]=X(!0),o=A(()=>r(!1),[]),n=A(()=>r(!0),[]),s=A(()=>r(h=>!h),[]);Z(()=>e({open:o,close:n,toggle:s}),[e]);let i=A(h=>{h.target instanceof HTMLElement&&h.target.id==="background"&&n()},[]),{state:a,result:c}=Yk(async()=>{if(t||scrapbox.Layout!=="page")return;let h=await Zk(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 E=Math.max(...[...y.keys()].filter(b=>b<g));if(E===g)return[];let v=y.get(E)?.text;return v===void 0?[]:[v]})}},{range:[],getSnapshot:()=>[]},1e3,[t]),[l,u]=X(0),[p,f]=X(0);Z(()=>{if(a!=="resolved")return;let h=Math.max(0,c.range.length-1);u(h),f(h)},[c]);let m=A(h=>f(parseInt(h.currentTarget.value)),[]);return d(Q,{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(Q,{children:[d("input",{type:"range",max:l,min:"0",step:"1",value:p,title:pe(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),onInput:m}),d("time",{dateTime:pe(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),children:pe(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 hn=()=>/mobile/i.test(navigator.userAgent);async function*tv(e,t){if(e.length===0||e.every(({before:o,after:n})=>o===n))return;let r=J(await wt());try{let{readable:o,writable:n}=new TransformStream(void 0),s=n.getWriter(),i=ll(5,e,async l=>{let u=0,p=0;l.before===l.after&&(await s.ready,await s.write({link:l,projectCount:0,replaced:0,done:!0}));let f=ll(2,new Set(t),async m=>{let h=await pI(l,m,r);if(W(h))throw uI(_n(h));u++,p+=J(h),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!1})});await Array.fromAsync(f),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!0})}),a=Array.fromAsync(i).then(async()=>{await s.ready,await s.close()}),c=o.getReader();for(;;){let{done:l,value:u}=await c.read();if(l)return;yield u}await a}finally{await Et(r)}}var pI=async(e,t,r)=>{let[o]=await Promise.all([ea(t,e.before,e.after),Me(t,e.before,(n,{persistent:s})=>{if(s)return[e.after,...n.map(i=>i.text).slice(1)]},{socket:r})]);return o},no=e=>e.split(
).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),uI=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var rv=e=>kt(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return mI(r);case"table":return fI(r);case"line":return dI(r)}}).map(r=>r).join(
),mI=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},fI=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[${o}table:${e},...t.map(n=>${o} ${n.map(s=>s.map(i=>mi(i)).join("")).join(" ")})]},dI=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${mi(r)}).join("")}],mi=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>mi(t)).join("")};case"strong":return${e.nodes.map(t=>mi(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=>mi(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=>no(e).length>0?"":"",onClick:e=>{let t=rv(e);if(e!=t)return t}});var ov=e=>!e.includes(
)&&/\[[^\]]+\]/.test(e);scrapbox.PopupMenu.addButton({title:e=>ov(e)?"[][]":"",onClick:e=>{if(!ov(e))return;let t=e.replaceAll("[","").replaceAll("]","");return(async()=>{let{render:r,dispose:o}=$e();try{let n=scrapbox.Project.name;r({type:"spinner"},{type:"text",text:create /${n}/${t}}),await Me(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 De(2e3),o()}})(),${t}}});var sv=(e,t)=>{switch(e.type){case"title":return"";case"codeBlock":return[e.fileName,
\\`\`${EI(e.fileName)},e.content,"\n"].join(
);case"table":return hI(e);case"line":return yI(e,t)}},hI=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=>us(i)).join("")).join(" | ")} |),n===0&&t.push(|${" -- |".repeat(r)})}),t.join(
)},gI=" ",yI=(e,t)=>{let r=e.nodes.map(n=>us(n,{section:e.indent===t})).join("").trim();if(r==="")return"";if(e.indent===t)return r;let o=gI.repeat(e.indent-t-1);return/^\d+\. /.test(r)||(o+="- "),o+r},us=(e,t)=>{let{section:r=!1}=t??{};switch(e.type){case"quote":return> ${e.nodes.map(o=>us(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=>us(o)).join("")}**;case"formula":return$${e.formula}$;case"decoration":{let o=e.nodes.map(n=>us(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}/${nv(n.join("/"))})}case"relative":return[${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${nv(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=>us(o)).join("")};case"blank":case"plain":return e.text}},nv=e=>...e.map((t,r)=>t===" "?"_":!xI.includes(t)||r===e.length-1&&bI.includes(t)?encodeURIComponent(t):t).join(""),xI='@$&+=:;",',bI=':;",',wI=[{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"}],EI=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return wI.find(r=>r.extensions.includes(t))?.fileType??""};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{(async()=>{try{let t=Zc.parse(e,{hasTitle:!1}),r=Math.min(...t.map(o=>o.indent));await navigator.clipboard.writeText(t.map(o=>sv(o,r)).join(`
))}catch(t){alert(Failed to copy:
${JSON.stringify(t)})}})()}});var Lm=(e,...t)=>{let r=t.reduce((o,n)=>Ce(o)?o:o instanceof Promise?o.then(s=>Ce(s)?s:n(s)):n(o),e);return r instanceof Promise?r.then(o=>${o}):${e}};var ms=e=>e.ok?le(e):ee({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var iv=e=>window.GM_fetch?.(https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x)?.then?.(t=>Gt(ms(t),r=>r.json()));var pl=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}},av=e=>typeof e=="object"&&e!==null;var fi=class e extends Error{name="UnexpectedResponseError";status;statusText;body;path;constructor(t){super(${t.status} ${t.statusText} when fetching ${t.path.toString()}),this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.path=t.path,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};var ul=async e=>{let t=await e.text();if(e.ok)return le(t);if(e.status===400)return ee({name:"BadRequestError",message:t});try{let r=JSON.parse(t);if(!av(r)||typeof r.message!="string")throw new fi({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)});switch(e.status){case 401:return ee({name:"UnauthorizedError",message:r.message});case 403:return ee({name:"NotPrivilegeError",message:r.message});case 404:return ee({name:"NotFoundError",message:r.message});case 422:return ee({name:"InvalidParameterError",message:r.message});case 429:return ee({name:"RateLimitError",message:r.message});default:throw new fi({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)})}}catch(r){throw r instanceof SyntaxError?new fi({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)}):r}};var cv=async(e,t)=>{let{title:r,description:o,metadataIsPublic:n,collectionId:s,refererURL:i,accessToken:a,created:c,app:l,fetch:u}=pl(t),p=new FormData;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});let f=await u("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:p}),m=await ul(f);return G(m)?m:le(JSON.parse(z(m)))};var lv=(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 ml="",pv=!1,fl=new Map,uv=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 c=await GM_fetch(e);if(!c.ok)return;let l=c.headers.get("content-type")?.split?.(";")?.[0]??${e}.endsWith(".mp4")?"video/mp4":"video/webm",u=new File([await c.blob()],o||${t},{type:l});if(l==="video/mp4"){let m=await lv(u);if(m.ok){let h=new URL(await m.text());return fl.set(e.href,h),h}}let p=await hh(u,r);if(G(p))throw Error(ne(p).name);let f=new URL(z(p).embedUrl);return fl.set(e.href,f),f}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(pv){if(!ml)return}else{let c=await rh();if(pv=!0,G(c)){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(ml=z(c)||"",!ml){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let i=await cv(await s.blob(),{accessToken:ml,refererURL:t,description:o});if(G(i))throw Error(ne(i).name);let a=new URL(z(i).permalink_url);return fl.set(e.href,a),a};var dv=[["&","&amp;"],["<","&lt;"],[">","&gt;"],['"',"&quot;"],["'","&#39;"]],kI=Object.fromEntries([...dv.map(([e,t])=>[t,e]),["&apos;","'"],["&nbsp;"," "]]),vI=new Map(dv),qot=new RegExp([${...vI.keys().join("")}],"g");var RI={entityList:kI},TI=1114111,_I=/&#([0-9]+);/g,PI=/&#x(\p{AHex}+);/gu,mv=new WeakMap;function Cm(e,t={}){let{entityList:r}={...RI,...t},o=mv.get(r);return o||(o=new RegExp((${Object.keys(r).sort((n,s)=>s.length-n.length).join("|")}),"g"),mv.set(r,o)),e.replaceAll(o,n=>r[n]).replaceAll(_I,(n,s)=>fv(s,10)).replaceAll(PI,(n,s)=>fv(s,16))}function fv(e,t){let r=parseInt(e,t);return r>TI?"�":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:Cm(u)}),n.push(l),a=[...a].slice(c[1]-i).join(""),i=c[1]}a&&n.push({type:"plain",text:Cm(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 OI=["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"],hl=(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||OI.includes(o)?r:n?o===e?${decodeURIComponent(n)}:/${o}/${decodeURIComponent(n)}:/${o}};var hv=(e=SI)=>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(iv(r)??th(t.href));if(G(o))throw ne(o);let n=z(o);return e("images"in n?{...n,id:r}:n,t)})():t},SI=async e=>{if("images"in e)return di(e);let{quote:t,replyTo:r,...o}=dl(e);return[...r?[...(await di(r)).split(
).map(n=> > ${n}),...r.quote?(await di(r.quote)).split(
).map(n=> > ${n}):[]]:[],...(await di(o)).split(
).map(n=>> ${n}),...t?(await di(t)).split(
).map(n=>> > ${n}):[]].join(
)},di=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[> @${Am(e.screenName)} ${t.origin}${t.pathname},...e.description?.split?.(
)?.map?.(n=>> ${Am(n)})??["> [/ no description provided]"],...e.images.length>0?[> ${e.images.map(n=>[${n}])}]:[]].join(
);let r=e.content,o=e.author.screenName;return[@${Am(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 Mm(n.mediai-1,t)}] [${await Mm(n.mediai,t)}]);return i===n.media.length&&s.push([${await Mm(n.mediai-1,t)}]),
${s.join(`
`)}
}case"url":return${hl()(n.url)} }}))).join("").split(
)].join(
)},gl="",NI=async()=>{if(gl)return gl;let e=await jr(scrapbox.Project.name);if(G(e))throw new Error(ne(e).name);return gl=z(e).id,gl},Mm=async(e,t)=>await uv(e.url,t,await NI(),"")??e.url,Am=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]]\s*/g," ").trim();var gv=e=>window.GM_fetch?.(https://t.co/${e})?.then?.(t=>Gt(ms(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 yv=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=gv(e.pathname.slice(1));return r?r.then(o=>up(o,()=>e,n=>n??e)):e};var xv=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 bv=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 Im=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var wv=/charset=(^;+)/,Ev=e=>window.GM_fetch?.(${e})?.then?.(t=>Gt(ms(t),async r=>{let o=r.headers.get("content-type")?.match?.(wv)?.1??await LI(r.clone());return new TextDecoder(o).decode(await r.arrayBuffer())})),LI=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?.(wv)?.1??"utf-8"};var kv=(e=CI)=>async t=>e(await MI(t),t),CI=(e,t)=>{let r=(Ce(e)?e:e.title).replace(/\s/g," ").replaceAll("","[").replaceAll("","]");return r?[${t.hash?${decodeURIComponent(t.hash.slice(1))} | :""}${r} ${t}]:${t}},MI=async e=>{let t=Ev(e);if(!t){let o=await eh(e);if(G(o))throw ne(o);return z(o)}let r=await t;if(G(r))throw ne(r);return new DOMParser().parseFromString(z(r),"text/html")};var vv=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 Rv=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 Tv=(e,...t)=>{if(e instanceof URL)return Lm(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=Lm(new URL(u),...t);return Ce(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}=$e(),l=()=>a({type:"spinner"},{type:"text",text:URL: ${o}/${r} converted, ${n} failed});return l(),Promise.all(i.map(async u=>{if(Ce(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 _v=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 Pv=e=>kt(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return AI(r);case"table":return II(r);case"line":return FI(r)}}).map(r=>r).join(`
),AI=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},II=({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(" ")})]},FI=({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=Pv(e);if(e!==t)return t}});var Fm=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=>Fm(e)?"replace":"",onClick:e=>{let t=Fm(e);if(t!==void 0)return t}});var Ov=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 Sv=async(e,t)=>{let r=no(e),o=await Ov([...new Set(r)]);if(!o.convert||o.links.length===0)return;let n=new Map(o.links.map(s=>[s.before,$e()]));for await(let{link:s,projectCount:i,replaced:a,done:c}of tv(o.links,t)){let l=n.get(s.before);if(!l)return;if(c){l.render({type:"check-circle"},{type:"text",text:"${s.after}", ${a}l. ${i}p.}),setTimeout(()=>l.dispose(),1e3);return}l.render({type:"spinner"},{type:"text",text:"${s.after}", ${a}l. ${i}p.})}};var Nv=async(e,t)=>{let r=no(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}=$e(),i=z(await wt());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([ea(u,r,o),Me(u,r,(f,{persistent:m})=>{if(m)return[o,...f.map(h=>h.text).slice(1)]},{socket:i})]);if(G(p))throw n({type:"exclamation-triangle"},{type:"text",text:${ne(p).name} ${ne(p).message}}),DI(ne(p));return a++,n({type:"spinner"},{type:"text",text:Replacing links in ${t.length-a} projects...}),z(p)}))).reduce((u,p)=>u+p,0);n({type:"check-circle"},{type:"text",text:Successfully replaced ${l} links.})}finally{await Et(i),setTimeout(s,1e3)}},DI=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var Lv=e=>{let t=[scrapbox.Project.name,...e];scrapbox.PopupMenu.addButton({title:r=>{let o=no(r).length;return o>1?"update links":o===1?"update a link":""},onClick:r=>{let o=no(r).length;o>1?Sv(r,t):o===1&&Nv(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 Cv=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+=gi(${n!==r?"\\item":""}\\begin{itemize},n*2)+
;if(o.indent<r)for(let n=r;n>o.indent;n--)t+=gi("\\end{itemize}",(n-1)*2)+
;r=o.indent,t+=gi(${r>0?"\\item ":""}${UI(o)},r*2)+
}for(let o=r;o>0;o--)t+=gi("\\end{itemize}",(o-1)*2)+
;return t},UI=e=>{switch(e.type){case"codeBlock":return $I(e);case"table":return jI(e);case"line":return BI(e)}},$I=e=>\\begin{lstlisting}language=${Wt(WI(e.fileName))},caption=${Wt(e.fileName)},label=lang:${e.fileName},numbers=left
${e.content}
\\end{lstlisting},jI=e=>{let t=\\caption{${Wt(e.fileName)}}\\label{table:${Wt(e.fileName)}},r=Math.max(...e.cells.map(n=>n.length)),o=e.cells.map(n=> ${n.map(s=>s.map(i=>fs(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}},BI=e=>e.nodes.map(t=>fs(t)).join(""),fs=e=>{switch(e.type){case"quote":return\\begin{quote}
${gi(e.nodes.map(t=>fs(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{${Wt(e.path)}};case"strong":return\\textbf{${e.nodes.map(t=>fs(t)).join("")}};case"formula":return$${e.formula}$;case"decoration":{let t=e.nodes.map(r=>fs(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=>fs(t)).join("")};case"helpfeel":return\\lstinline!? ${Wt(e.text)}!;case"code":return\\lstinline!${Wt(e.text)}!;case"commandLine":return\\lstinline!${Wt(e.symbol)} ${Wt(e.text)}!;case"link":return e.pathType==="absolute"?e.content===""?\\url{${e.href}}:\\href{${e.href}}{${Wt(e.content)}}:Wt(e.href);case"googleMap":return\\href{${e.url}}{${Wt(e.place)}};case"hashTag":return Wt(#${e.href});case"blank":case"plain":return Wt(e.text)}},HI=[{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"}],WI=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return HI.find(r=>r.extensions.includes(t))?.fileType??""},Wt=e=>e.replaceAll("\\","\\textbackslash ").replaceAll("#","\\#").replaceAll("%","\\%").replaceAll("$","\\$").replaceAll("&","\\&").replaceAll("~","\\textasciitilde ").replaceAll("^","\\textasciicircum ").replaceAll("_","\\_").replaceAll("{","\\{").replaceAll("}","\\}").replaceAll("|","\\textbar ").replaceAll("<","\\textless ").replaceAll(">","\\textgreater "),gi=(e,t)=>e.split(
).map(r=>${" ".repeat(t)}${r}).join(
);scrapbox.PopupMenu.addButton({title:"TeX",onClick:e=>{navigator.clipboard.writeText(Cv(kt(e))).catch(t=>{console.error(t),alert(${t.name} ${t.message}
${t.stack})})}});var yl="https://keicho.herokuapp.com/api/";var Mv=async(e,t)=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let r=await window.GM_fetch(${yl}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 Av=()=>{let{popupMenu:e,render:t}=GI();og()?.append?.(e);let r=lo(),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)}}},GI=()=>{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 Iv=async(e="normal")=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let t=await window.GM_fetch(${yl}web/create/?mode=${e},{mode:"cors"});return t.ok?{ok:!0,value:await t.text()}:{ok:!1,value:{name:"ResponseError",res:t}}};var Fv=e=>https://keicho.netlify.app/#talk=${e};var Dv=e=>{let t=e.split(
),r=t[1]??t[0],o=e===t[0]?"":t[0];return o?[o.trim(),r].join(
):r};var xl=async(e,t,r)=>{let o=lo(),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 Oa().clear(),o.setPosition({line:n,char:[...s].length}),await Xe(
${e}),o.getPosition().line};var Uv=e=>kt(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=>bl(s))).join(" ")})].join(
).trimEnd();case"line":return${r}${t.nodes.map(o=>bl(o)).join("")}.trimEnd()}}).join(
),bl=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>bl(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=>bl(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 ds=e=>/^[((]/.test(e);var jv=async e=>{let t=scrapbox.Page.lines;if(!t)return;let{cursor:r,selection:o}=Nt(),n=e?.entire||o.hasSelectionAll(),s=n?t.map(P=>P.text).join(
):o.getSelectedText(),i=e?.botIcon??"[/nishio/nisbot.icon]",{render:a,visible:c,open:l,close:u,dispose:p}=Av();u();let f=new Set,m=()=>{p();for(let P of f)P()},h=P=>f.add(P),g={text:"Exit",onClick:m},y=e?.talkId||$v(s)||(n?"":$v(t.slice(0,1+r.getPosition().line).map(P=>P.text).join(
))),x=!y;if(!y){let P=Iv(e?.mode),N=setTimeout(()=>{a({text:"Start talking..."}),l();let F=0;N=setInterval(()=>{a({text:Start talking${".".repeat(F%3)}}),F++},1e3)},1e3),I=await P;if(clearTimeout(N),!I.ok){if(I.value.name==="GMFetchNotAvailableError"){alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc.");return}if(I.value.name==="ResponseError"){a({text:Error: ${I.value.res.status} ${I.value.res.statusText}},g),l(),console.error(Error: ${I.value.res.status} ${I.value.res.statusText},await I.value.res.text());return}return}y=I.value}let E=y,v=o.normalizeOrder(o.getRange()),b=n?t.length-1:v.end.line,T=t[b],R=n?"":" ".repeat(Math.min(...t.slice(v.start.line,v.end.line+1).map(P=>qr(P.text)))),L=async P=>{let N=await Mv(P,E);if(!N.ok)switch(N.value.name){case"ResponseError":return a({text:Error: ${N.value.res.status} ${N.value.res.statusText}},g),l(),console.error(Error: ${N.value.res.status} ${N.value.res.statusText},await N.value.res.text()),N;case"GMFetchNotAvailableError":return alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc."),N}return N},C="",M=async P=>{let N=Uv(P).split(
).map(D=>D.trim()).join(
).trim();N.startsWith(C)&&(N=N.slice(C.length));let I=N.split(
);if(I.length===0)return;if(I.every(D=>ds(D))&&(C=N),I.filter(D=>!ds(D)).length<2){let D,V;for(let B of I){if(V=await L(B),!V.ok)return V;ds(B)||(D=V)}return D??V}let j=0;{let D;for(;j<I.length&&ds(I[j]);j++)if(D=await L(I[j]),!D.ok)return D}{let D=await L("まず聞いて");if(!D.ok)return D}for(;j<I.length&&!ds(I[j]);j++){let D=await L(I[j]);if(!D.ok)return D}return await L("おしまい")},O=async P=>{if(scrapbox.Layout!=="page"||P==="")return;let N=M(P),I=setTimeout(()=>{a({text:"Asking..."}),l();let B=0;I=setInterval(()=>{a({text:Asking${".".repeat(B%3)}}),B++},1e3)},1e3),F=await N;if(clearTimeout(I),!F||!F.ok)return;let{text:j,buttons:D}=F.value,V=Dv(j);if(V.trim()){let B=${R}${i}${V.includes(`
)?
${V.split(`
).map(K=> ${R}${K}).join(
)}:V}
${R};b=await xl(B,T,b),T=t[b]}a({text:"Send",onClick:_},{text:"🙂",onClick:()=>Xe("🙂")},{text:"🙁",onClick:()=>Xe("🙁")},...D.map(B=>({text:B,onClick:async()=>{b=await xl(B,T,b),T=t[b],await O(B)}})),g),l()},_=async()=>{if(scrapbox.Layout!=="page")return;let P=scrapbox.Page.lines,N=r.getPosition().line,[I,F,j]=qI(P,N,i);I!==""&&(b=j,T=P[b],R=" ".repeat(Math.min(...P.slice(F,j+1).map(D=>qr(D.text)))),await O(I))};return x&&(b=await xl(Fv(E),T,b),T=t[b]),await O(s),{ask:_,open:l,close:u,visible:c,exit:m,onExit:h}},$v=e=>{for(let t of e.split(
).reverse()){let r=t.match(/https?:\/\/keicho\.netlify\.app\/#talk=(\w+)/)?.[1];if(r)return r}},qI=(e,t,r)=>{let o=Math.max(e.findLastIndex((s,i)=>i<t&&s.text.trim().startsWith(r)),1),n=o+Io(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 Bv=[Yo,Xo,Jo];scrapbox.PopupMenu.addButton({title:e=>{let t=zr({project:scrapbox.Project.name,mode:"noopen",hooks:Bv});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&&zr({project:e,mode:"noopen",hooks:Bv})?.()}});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 zI=[Im,yv,Im,bv,vv,hl(),Rv,hv(),xv,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,_v,kv()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=Tv(e,...zI);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return Xe(r)})}});Lv(["takker","takker-memex","takker-private","takker-books"]);if(!/mobile/i.test(navigator.userAgent)){let e=(t,r)=>{t.trim()!==""&&jv({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())};rt().addEventListener("keydown",a),i(()=>rt().removeEventListener("keydown",a))})};scrapbox.PopupMenu.addButton({title:()=>"🤖",onClick:t=>e(t)})}var yi=(e,t)=>t.map(r=>r.replace(/@yyyy-MM-dd HH:mm:ss@/g,pe(e,"yyyy-MM-dd HH:mm:ss")).replace(/@yyyy-MM-dd@/g,pe(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==="+"?_e(e,parseInt(s)*(i==="w"?7:1)):jt(e,parseInt(s)*(i==="w"?7:1)):e;return pe(a?_e(Ae(c),VI(a)):c,"yyyy-MM-dd")}).replace(/@yyyy-ww@/g,${Bo(e)}-w${${mo(e)}.padStart(2,"0")}).replace(/@yyyy-ww([+-])(\d+)(w?)@/g,(o,n,s,i)=>{let a=n==="+"?_e(e,parseInt(s)*(i==="w"?7:1)):jt(e,parseInt(s)*(i==="w"?7:1));return${Bo(a)}-w${${mo(a)}.padStart(2,"0")}}).replace(/@yyyy@/g,${Bo(e)}).replace(/@yyyy([+-])(\d+)y@/g,(o,n,s)=>{let i=parseInt(s);return${Bo(e)+(n==="+"?i:-i)}})),VI=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 Wv=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:_e(l,1)},{render:p,dispose:f}=$e(),m;try{let h=await Hv(t),g=await Hv(r),y=Cs(u).filter(b=>{let T=yi(b,h)[0],R=n.find(L=>L.title===T);return!R||!R.exists}),x=Qg(u).filter(b=>{let T=yi(b,g)[0],R=n.find(L=>L.title===T);return!R||!R.exists});if(y.length===0&&x.length===0)return;let E=y.length+x.length;p({type:"spinner"},{type:"text",text:create ${E} review pages...});let v=await wt();if(G(v))throw ne(v);m=z(v);for(let b of[...y.map(T=>yi(T,h)),...x.map(T=>yi(T,g))])await Me(e,b[0],(T,R)=>R.persistent?void 0:b,m?{socket:m}:{}),E--,p({type:"spinner"},{type:"text",text:create ${E} 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 Et(m),await De(1e3),f()}},i=s(),a=new Date,c=setInterval(()=>{let l=new Date;nt(a,l)||(a=l,i.then(()=>i=s()))},1e4);return()=>(clearTimeout(c),i)},Hv=async e=>{let t=await ta(e[0],e[1],e[2]);if(G(t)){let o=new Error;throw o.name=ne(t).name,o.message=${ne(t).message} at fetching /${e0}/${e1}/${e2},o}let r=z(t).split(
);if(r.length===0)throw new Error(template "/${e0}/${e1}/${e2}" is empty!);return r};var Gv=function(){};function bi(e,t={}){Gv.prototype.name=e;let r={};return new Proxy(Gv,{get(o,n){return n==="caller"?null:n==="__createMock__"?bi:n==="__unenv__"?!0:n in t?t[n]:r[n]=r[n]||bi(${e}.${n.toString()})},apply(o,n,s){return bi(${e}())},construct(o,n,s){return bi(${e})},enumerate(){return[]}})}var Dm=bi("mock");function KI(e){return new Error(unenv ${e} is not implemented yet!)}function fe(e){return Object.assign(()=>{throw KI(e)},{__unenv__:!0})}var YI=Object.freeze(Object.create(null,{__unenv__:{get:()=>!0}})),wl=Object.create(null),XI=globalThis.process?.env,xi=e=>XI||globalThis.__env__||(e?wl:globalThis),JI=new Proxy(wl,{get(e,t){return xi()[t]??wl[t]},has(e,t){let r=xi();return t in r||t in wl},set(e,t,r){let o=xi(!0);return o[t]=r,!0},deleteProperty(e,t){let r=xi(!0);return delete r[t],!0},ownKeys(){let e=xi();return Object.keys(e)}}),QI=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)}}),ZI=globalThis.queueMicrotask?(e,...t)=>{globalThis.queueMicrotask(e.bind(void 0,...t))}:eF();function eF(){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 tF="unenv",rF=[],oF="",nF={ares:"",http_parser:"",icu:"",modules:"",node:"",openssl:"",uv:"",v8:"",zlib:""};function wr(){return Um}var sF=wr,iF=wr,aF=wr,cF=wr,lF=wr,pF=wr,uF=function(e){return e==="message"||e==="multipleResolves"?Um:!1},mF=wr,fF=wr,dF=function(e){return[]},hF=()=>0,gF=function(e){throw new Error("[unenv] process.binding is not supported")},qv="/",yF=function(){return qv},xF=function(e){qv=e},bF=function(){return 0},wF=function(){return 1e3},EF=function(){return 1e3},kF=function(){return 1e3},vF=function(){return 1e3},RF=function(){return[]},TF=e=>{},_F=fe("process.abort"),PF=new Set,OF="",SF="",NF=YI,LF=!1,CF=()=>0,MF=()=>0,AF=fe("process.cpuUsage"),IF=0,FF=fe("process.dlopen"),DF=wr,UF=wr,$F=fe("process.eventNames"),jF=[],BF="",HF=fe("process.exit"),WF=Object.create({inspector:void 0,debug:void 0,uv:void 0,ipv6:void 0,tls_alpn:void 0,tls_sni:void 0,tls_ocsp:void 0,tls:void 0,cached_builtins:void 0}),GF=()=>[],qF=fe("process.getMaxListeners"),zF=fe("process.kill"),VF=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0}),KF=1e3,YF="",XF=1e3,JF=fe("process.rawListeners"),QF=Object.create({name:"",lts:"",sourceUrl:void 0,headersUrl:void 0}),ZF=Object.create({compact:void 0,directory:void 0,filename:void 0,getReport:fe("process.report.getReport"),reportOnFatalError:void 0,reportOnSignal:void 0,reportOnUncaughtException:void 0,signal:void 0,writeReport:fe("process.report.writeReport")}),eD=fe("process.resourceUsage"),tD=fe("process.setegid"),rD=fe("process.seteuid"),oD=fe("process.setgid"),nD=fe("process.setgroups"),sD=fe("process.setuid"),iD=fe("process.setMaxListeners"),aD=fe("process.setSourceMapsEnabled"),cD=Dm.__createMock__("process.stdout"),lD=Dm.__createMock__("process.stderr"),pD=Dm.__createMock__("process.stdin"),uD=!1,mD=()=>0,fD=0,dD=fe("process.setUncaughtExceptionCaptureCallback"),hD=()=>!1,gD=!1,yD=fe("process.loadEnvFile"),xD=void 0,bD={has:()=>!1},wD={ref(){},unref(){}},ED=!1,kD={register(){},unregister(){},registerBeforeExit(){}},vD=fe("process.assert"),RD=fe("process.openStdin"),TD=fe("process._debugEnd"),_D=fe("process._debugProcess"),PD=fe("process._fatalException"),OD=fe("process._getActiveHandles"),SD=fe("process._getActiveRequests"),ND=fe("process._kill"),LD=[],CD=fe("process._rawDebug"),MD=fe("process._startProfilerIdleNotifier"),AD=fe("process.__stopProfilerIdleNotifier"),ID=fe("process._tickCallback"),Oit=fe("process._linkedBinding"),FD=void 0,DD=fe("process.initgroups"),UD=[],$D=wr,jD=!1,BD=[],HD=0,WD=0,Um={_events:BD,_eventsCount:HD,_exiting:jD,_maxListeners:WD,_debugEnd:TD,_debugProcess:_D,_fatalException:PD,_getActiveHandles:OD,_getActiveRequests:SD,_kill:ND,_preload_modules:LD,_rawDebug:CD,_startProfilerIdleNotifier:MD,_stopProfilerIdleNotifier:AD,_tickCallback:ID,domain:FD,initgroups:DD,moduleLoadList:UD,reallyExit:$D,exitCode:fD,abort:_F,addListener:iF,allowedNodeEnvironmentFlags:PF,hasUncaughtExceptionCaptureCallback:hD,setUncaughtExceptionCaptureCallback:dD,loadEnvFile:yD,sourceMapsEnabled:gD,throwDeprecation:ED,mainModule:xD,permission:bD,channel:wD,arch:OF,argv:rF,argv0:SF,assert:vD,binding:gF,chdir:xF,config:NF,connected:LF,constrainedMemory:CF,availableMemory:MF,cpuUsage:AF,cwd:yF,debugPort:IF,dlopen:FF,disconnect:DF,emit:uF,emitWarning:UF,env:JI,eventNames:$F,execArgv:jF,execPath:BF,exit:HF,finalization:kD,features:WF,getBuiltinModule:TF,getegid:wF,geteuid:EF,getgid:kF,getgroups:RF,getuid:vF,getActiveResourcesInfo:GF,getMaxListeners:qF,hrtime:QI,kill:zF,listeners:dF,listenerCount:hF,memoryUsage:VF,nextTick:ZI,on:sF,off:cF,once:aF,openStdin:RD,pid:KF,platform:YF,ppid:XF,prependListener:mF,prependOnceListener:fF,rawListeners:JF,release:QF,removeAllListeners:pF,removeListener:lF,report:ZF,resourceUsage:eD,setegid:tD,seteuid:rD,setgid:oD,setgroups:nD,setuid:sD,setMaxListeners:iD,setSourceMapsEnabled:aD,stderr:lD,stdin:pD,stdout:cD,title:tF,traceDeprecation:uD,umask:bF,uptime:mD,version:oF,versions:nF},wi=Um;var GD=Object.create,Jv=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,zD=Object.getOwnPropertyNames,VD=Object.getPrototypeOf,KD=Object.prototype.hasOwnProperty,Qv=(e=>typeof So<"u"?So:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof So<"u"?So:t)[r]}):e)(function(e){if(typeof So<"u")return So.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Zv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),YD=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of zD(t))!KD.call(e,n)&&n!==r&&Jv(e,n,{get:()=>t[n],enumerable:!(o=qD(t,n))||o.enumerable});return e},eR=(e,t,r)=>(r=e!=null?GD(VD(e)):{},YD(t||!e||!e.__esModule?Jv(r,"default",{value:e,enumerable:!0}):r,e)),XD=Zv((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in wi&&"node"in wi.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Qv][0](${"node","util".join(":")})}catch{r=null}t.exports=r}),JD=Zv((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in wi&&"node"in wi.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[Qv][0](${"node","fs".join(":")})}catch{r=null}t.exports=r}),QD={},El=ZD(globalThis,QD);function ZD(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 zv=["debug","info","warning","error","fatal"];function Vv(e,t){let r=zv.indexOf(e);if(r<0)throw new TypeError(Invalid log level: ${JSON.stringify(e)}.);let o=zv.indexOf(t);if(o<0)throw new TypeError(Invalid log level: ${JSON.stringify(t)}.);return r-o}function Ei(e=[]){return tR.getLogger(e)}var $m=Symbol.for("logtape.rootLogger"),tR=class Oo{static getLogger(t=[]){let r=$m in El?El[$m]??null:null;return r==null&&(r=new Oo(null,[]),El[$m]=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 Oo?o:o?.deref();return n==null&&(n=new Oo(this,[...this.category,r]),this.children[r]="WeakRef"in El?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 Oo?t:t.deref())?.resetDescendants();this.reset()}with(t){return new eU(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||Vv(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||Vv(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),tU.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=Oo.getLogger().contextLocalStorage?.getStore()??{},i,a=typeof o=="function"?{category:this.category,level:t,timestamp:Date.now(),get message(){return Kv(r,this.properties)},rawMessage:r,get properties(){return i==null&&(i={...s,...o()}),i}}:{category:this.category,level:t,timestamp:Date.now(),message:Kv(r,{...s,...o}),rawMessage:r,properties:{...s,...o}};this.emit(a,n)}logLazily(t,r,o={}){let n=Oo.getLogger().contextLocalStorage?.getStore()??{},s,i;function a(){if((i==null||s==null)&&(i=r((c,...l)=>(s=c,Yv(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=Oo.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:t,message:Yv(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)}},eU=class rR{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 rR(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)}},tU=tR.getLogger(["logtape","meta"]);function Kv(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 Yv(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 rU=eR(XD()),kl=rU.default,Xv={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},oR="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}):kl!=null&&"inspect"in kl&&typeof kl.inspect=="function"?(e,t)=>kl.inspect(e,{maxArrayLength:1/0,maxStringLength:1/0,...t}):e=>JSON.stringify(e);function nR(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??oR,n=e.level==null||e.level==="ABBR"?i=>Xv[i]:e.level==="abbr"?i=>Xv[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 Lit=nR(),jm="\x1B[0m",Bm={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},Hm={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},oU={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function nU(e={}){let t=e.format,r=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=${r==null?"":Hmr}${o==null?"":Bmo},s=r==null&&o==null?"":jm,i=typeof e.levelStyle>"u"?"bold":e.levelStyle,a=e.levelColors??oU,c=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,l=e.categoryColor??null,u=${c==null?"":Hmc}${l==null?"":Bml},p=c==null&&l==null?"":jm;return nR({timestamp:"date-time-tz",value(f){return oR(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?"":Hmi}${x==null?"":Bmx}${m}${i==null&&x==null?"":jm},t==null?${f} ${m} ${u}${h}:${p} ${g}:t({timestamp:f,level:m,category:${u}${h}${p},message:g,record:y})}})}var Cit=nU();var sU=eR(JD()),iU=sU.default;function hs(){throw new Error("File sink is not available in the browser.")}var aU={openSync:hs,writeSync:hs,flushSync:hs,closeSync:hs,statSync:hs,renameSync:hs},gn=iU,Mit=gn==null?aU:{openSync(e){return gn.openSync(e,"a")},writeSync:gn.writeSync,flushSync:gn.fsyncSync,closeSync:gn.closeSync,statSync:gn.statSync,renameSync:gn.renameSync};var vl="null",Hat=zn+vl,pU=to+vl,Wat=Vn+vl,Gat=Kn+vl;var Rl="undefined",Yat=zn+Rl,uU=to+Rl,Xat=Vn+Rl,Jat=Kn+Rl;async function*iR(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 Qi(i);if(Bt(a)){r=n;break}for(let c of ln(a).projects)o.has(c.name)&&(yield At({...c,checked:o.get(c.name)??0}))}for(let s of r){let i=await jr(s);yield ct(i)?At({...ln(i),checked:o.get(s)??0}):Kt({...Xn(i),project:s})}}var qm=(e,t)=>t.some(r=>e instanceof r),aR,cR;function fU(){return aR||(aR=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function dU(){return cR||(cR=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var zm=new WeakMap,Wm=new WeakMap,Tl=new WeakMap;function hU(e){let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(yn(e.result)),n()},i=()=>{o(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)});return Tl.set(t,e),t}function gU(e){if(zm.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)});zm.set(e,t)}var Vm={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return zm.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return yn(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 mR(e){Vm=e(Vm)}function yU(e){return dU().includes(e)?function(...t){return e.apply(Km(this),t),yn(this.request)}:function(...t){return yn(e.apply(Km(this),t))}}function xU(e){return typeof e=="function"?yU(e):(e instanceof IDBTransaction&&gU(e),qm(e,fU())?new Proxy(e,Vm):e)}function yn(e){if(e instanceof IDBRequest)return hU(e);if(Wm.has(e))return Wm.get(e);let t=xU(e);return t!==e&&(Wm.set(e,t),Tl.set(t,e)),t}var Km=e=>Tl.get(e);function fR(e,t,{blocked:r,upgrade:o,blocking:n,terminated:s}={}){let i=indexedDB.open(e,t),a=yn(i);return o&&i.addEventListener("upgradeneeded",c=>{o(yn(i.result),c.oldVersion,c.newVersion,yn(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 bU=["get","getKey","getAll","getAllKeys","count"],wU=["put","add","delete","clear"],Gm=new Map;function lR(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Gm.get(t))return Gm.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,n=wU.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(n||bU.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 Gm.set(t,s),s}mR(e=>({...e,get:(t,r,o)=>lR(t,r)||e.get(t,r,o),has:(t,r)=>!!lR(t,r)||e.has(t,r)}));var EU=["continue","continuePrimaryKey","advance"],pR={},Ym=new WeakMap,dR=new WeakMap,kU={get(e,t){if(!EU.includes(t))return e[t];let r=pR[t];return r||(r=pR[t]=function(...o){Ym.set(this,dR.get(this)[t](...o))}),r}};async function*vU(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,kU);for(dR.set(r,t),Tl.set(r,Km(t));t;)yield r,t=await(Ym.get(r)||t.continue()),Ym.delete(r)}function uR(e,t){return t===Symbol.asyncIterator&&qm(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&qm(e,[IDBIndex,IDBObjectStore])}mR(e=>({...e,get(t,r,o){return uR(t,r)?vU:e.get(t,r,o)},has(t,r){return uR(t,r)||e.has(t,r)}}));var hR,Xm=async()=>{let e=Ei(["@takker/cosense-storage","open"]);return hR??=await fR("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)}}),hR};var gR=(e,t)=>(Jm||(Jm=new BroadcastChannel(xR),Jm.addEventListener("message",r=>yR(r.data))),_l.set(t,new Set(e).union(_l.get(t)??new Set)),()=>_l.delete(t)),Qm=(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};yR(r);let o=new BroadcastChannel(xR);o.postMessage(r),o.close()},yR=e=>{for(let[t,r]of _l)r.has(e.project)&&t(e)},xR="scrapbox-storage-notify",Jm,_l=new Map;var bR=async(e,t)=>{let r=await Xm(),o=Ei(["@takker/cosense-storage","check"]),n=new Map;try{{o.debugcheck updates of links...;let i=new Set,a=r.transaction("projects","readwrite"),c=Om(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??RU(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=Om(new Date);for await(let i of iR(n.values())){if(Bt(i)){let{project:h,name:g}=Xn(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}=ln(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 Qd(c.name)){if(Bt(h)){let{name:E,message:v}=Xn(h);o.errorFailed to get links of "${c.name}" with ${E}: ${v};break}let g=ln(h),y={},x=r.transaction("titles","readwrite");await Promise.all(g.map(async E=>{let v={...E,project:c.name},b=await x.store.get(E.id);if(!b)return y.added?.set?.(E.id,v)??(y.added=new Map([[E.id,v]])),x.store.add(v);if(l.delete(E.id),!!TU(v,b))return y.updated?.set?.(E.id,[b,v])??(y.updated=new Map([[E.id,[b,v]]])),x.store.put(v)})),await x.done,u+=y.added?.size??0,p+=y.updated?.size??0,o.debugUpdating "/${c.name}": +${u} pages, ~${p} pages,Qm(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}),Qm(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}},Pl=async e=>{let t=[...new Set(e)];if(t.length===0)return[];let r=Date.now(),n=(await Xm()).transaction("titles","readonly"),s=n.store.index("project"),i=(await Promise.all(t.map(c=>s.getAll(c)))).flat();return await n.done,Ei(["@takker/cosense-storage","load"]).debugRead ${i.length} links from ${t.length} projects in ${Date.now()-r}ms,i},RU=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}),TU=(e,t)=>e.updated>t.updated||e.links.sort().join()!==t.links.sort().join();var Ft=e=>${e.getFullYear()}-${yr(e.getMonth()+1)}-${yr(e.getDate())},ki=e=>{let[t,r,o]=e.split("-").map(n=>parseInt(n,10));return{year:t,month:r,date:o}},vi=e=>${jo(e)}-w${yr(mo(e))},Ol=e=>{let[t,r]=e.split("-w").map(o=>parseInt(o,10));return Ae(Fa(new Date(t,0,1),r))};var wR="takker-memex",ER=async(e=new Date(2023,0,24))=>{if(scrapbox.Project.name!==wR)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=Cs({start:e,end:i}).filter(f=>{let m=gr(f),h=t.find(g=>g.title===m);return!h||!h.exists});if(c.length===0)return;let{render:l,dispose:u}=$e(),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=>Ft(x));for(let{title:x,links:E,project:v}of await Pl(["takker","takker-memex"]))for(let b of[x,...E]){let T=Sr(b);if(!T)continue;if(G(T)){let{name:C,message:M}=ne(T);console.error(/${v}/${b}: ${C} ${M});continue}let R=se(b);if(m.has(R))continue;m.add(R);let L=z(T);if(L.freshness?.status!=="done")for(let C of c){let M=Hs(L,C);if(!M)continue;let O=Ft(M.base);h.includes(O)&&(f.set(O,[...f.get(O)??[],M]),go(L))}}let g=await wt();if(G(g))throw ne(g);p=z(g);let y=0;l({type:"spinner"},{type:"text",text:create 0/${c.length} diary pages...});for(let x of c){let E=gr(x),v=f.get(Ft(x))?.map?.(R=>Se(R))??[],b=#${pe(x,"yyyy-MM-dd")},T=#${pe(x,"yyyy-MM-dd HH:mm:ss")};await Me(wR,E,(R,{persistent:L})=>{if(L)return;let C=[...R.map(M=>M.text),...v];return C.some(M=>M.includes(b))?Vo(C):Vo([...C,T])},{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 Et(p),await De(1e3),u()}},o=r(),n=new Date,s=setInterval(()=>{let i=new Date;nt(n,i)||(n=i,o.then(()=>o=r()))},1e4);return()=>(clearTimeout(s),o)};ER(new Date(2024,11,24));var ef=(...e)=>{let t=e.flatMap(o=>{if(typeof o=="string")return[Sl(o)];if(Array.isArray(o.type))return[kR(o.type)];switch(o.type){case"text":return[Sl(o.text)];case"group":{let n=ef(...o.items);return n?[n]:[]}default:return[kR(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},Sl=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},kR=e=>{if(Array.isArray(e)){let t=document.createElement("span");t.classList.add("fa-stack");let r=Zm(e[0]);r.classList.add("fa-stack-1x");let o=Zm(e[1]);return o.classList.add("fa-stack-1x"),t.append(r,o),Sl(t)}return Sl(Zm(e))},Zm=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:tf,selection:rf}=Nt(),RR=e=>{let{className:t,display:r,onClick:o,context:n="page"}=e,s=document.createElement("div");t&&s.classList.add(t),vR(n)||(s.style.display="none");let i=(...l)=>{if(l.length===1&&l[0]===""){s.style.display="none";return}s.textContent="";let u=ef(...l);u&&s.append(u)},a=typeof r=="function"?r({cursor:tf,selection:rf}):r;return i(...Array.isArray(a)?a:[a]),s.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),o({cursor:tf,selection:rf,setDisplay:i})}),{status:s,context:n,update:()=>{if(vR(n)?s.removeAttribute("style"):s.style.display="none",typeof r=="function"){let l=r({cursor:tf,selection:rf});i(...Array.isArray(l)?l:[l])}}}},vR=e=>e!=="stream"?scrapbox.Layout===e:scrapbox.Layout==="list"&&location.pathname.startsWith("/stream");var TR=()=>{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 of=new Set,{cursor:_U,selection:PU}=Nt(),OU=TR();var cr=e=>{let t=RR(e);return of.add(t),OU.append(t.status),()=>{t.status.remove(),of.delete(t)}},nf=()=>{for(let{update:e}of of)e()};_U.addChangeListener(()=>nf());PU.addChangeListener(()=>nf());scrapbox.addListener("layout:changed",nf);var _R=async(e,t)=>{try{let r=t.getSelectedText()||ft(e.getPosition().line);if(!r)return;await navigator.clipboard.writeText(r)}catch(r){console.error(r),alert(Faild to copy:
${JSON.stringify(r)})}},PR=async(e,t)=>{try{let r=t.hasSelection(),o=r?t.getRange().start.line:e.getPosition().line,n=r?t.getSelectedText():ft(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(),dt("Delete")}catch(r){console.error(r),alert(Faild to cut:
${JSON.stringify(r)})}},OR=async e=>{try{let t=await navigator.clipboard.readText();if(!t)return;e.focus(),await Xe(t)}catch(t){console.error(t),alert(Faild to paste:
${JSON.stringify(t)})}},SR=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=lo();t.hasFocus||(e.preventDefault(),t.focus())});var sf=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")}},NR=new sf;var LR=e=>new Promise(t=>setTimeout(t,e));async function Er(e,{wait:t=1}={}){let r=NR.textInput;r.focus(),r.value=e;let o=document.createEvent("UIEvent");o.initEvent("input",!0,!1),r.dispatchEvent(o),await LR(t)}if(hn()){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:()=>Er(pe(new Date,"#yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD HH:mm:ss ",onClick:()=>Er(pe(new Date,"yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD",onClick:()=>Er(pe(new Date,"yyyy-MM-dd"))}),scrapbox.PageMenu(e).addItem({title:"HH:mm:ss ",onClick:()=>Er(pe(new Date,"HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"⬜",onClick:()=>Er("⬜")}),scrapbox.PageMenu(e).addItem({title:"🚧",onClick:()=>Er("🚧")}),scrapbox.PageMenu(e).addItem({title:"⌛",onClick:()=>Er("⌛")}),scrapbox.PageMenu(e).addItem({title:"📝",onClick:()=>Er("📝")}),scrapbox.PageMenu(e).addItem({title:"✅",onClick:()=>Er("✅")}),scrapbox.PageMenu(e).addItem({title:"❌",onClick:()=>Er("❌")})}scrapbox.PageMenu.addItem({title:"Open kakeru",image:"https://i.kakeru.app/15c3b1a40b6b3c2ebd68f33f4c86b3f6-opaque.png",onClick:()=>window.open("https://kakeru.app")});var CR=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var af=()=>AR(document.getElementsByClassName("lines").item(0),"div.lines");var MR=()=>AR(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),AR=(e,t)=>{if(e)return CR(e,t),e};var Ri=()=>{let e=af();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 IR=e=>{if(mt(e))return;if(Ue(e))return NU(e)?.id;if(Ce(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)};var NU=e=>{if(mt(e))return;if(Ue(e))return Ri()[e];let t=IR(e);return t?Ri().find(r=>r.id===t):void 0},cf=e=>{if(LU(e))return e;let t=IR(e);if(mt(t))return t;let r=document.getElementById(L${t});if(!mt(r))return r},LU=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var FR=()=>{let e=MR();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=DR(...r);o&&t.append(o)},dispose:()=>t.remove(),[Symbol.dispose]:()=>t.remove()}},DR=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[AU()];case"check-circle":return[IU()];case"exclamation-triangle":return[FU()];case"text":return[Ll(o.text)];case"group":{let n=DR(...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},Ll=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},AU=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Ll(e)},IU=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Ll(e)},FU=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Ll(e)};var UR=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}};var lf=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 UU=()=>{let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.right="0",e.style.textAlign="right",e},gs=new Map,Cl,pf=()=>{for(let r of gs.values())r.remove();gs.clear();let e=Qc(()=>$U(Ri()),{interval:1e3,maxQueued:0}),t=()=>{e.clear(),e()};if(scrapbox.Layout!=="page"){if(scrapbox.removeListener("lines:changed",t),!Cl)return;clearInterval(Cl),Cl=void 0;return}t(),scrapbox.addListener("lines:changed",t),Cl=setInterval(t,60*1e3)},$U=e=>{for(let t of e){let r=ht(t.text);if(!r?.record?.start){gs.get(t.id)?.remove?.(),gs.delete(t.id);continue}let o=gs.get(t.id)??UU();cf(t.id)?.append?.(o),gs.set(t.id,o),o.textContent=lf(fo(r.record.end??new Date,r.record.start))}};scrapbox.Project.name==="takker-memex"&&(pf(),scrapbox.addListener("page:changed",pf),scrapbox.addListener("lines:changed",pf));var jU=e=>{let[t,r]=e.reduce((o,{text:n})=>{let s=ht(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 _m(t)},BU=async(e,t)=>{let[r,o]=await Promise.all([Nm(e,gr(t),{fetch:$R}),Nm(e,gr(jt(t,1)),{fetch:$R})]),n=r.ok?(await r.json()).lines:[];return o.ok&&n.push(...(await o.json()).lines),n},$R=async(e,t)=>{let r=await UR(new Request(e,t));return!r||pi(new Date,new Date(${r.headers.get("Date")}))>=60?globalThis.fetch(e,t):r},{render:HU}=FR(),jR=async()=>{let e=jU(await BU("takker-memex",new Date))??dr(new Date);HU({type:"text",text:lf(fo(new Date,e))})};jR();setInterval(jR,60*1e3);async function BR(e,{from:t,to:r,merge:o}){if(t===r)return{success:!0,dup:!1};let n=await er(t,e);if(G(n))return{success:!1,at:"from",name:ne(n).name,message:ne(n).message};let s=z(n);if(!s.persistent)return{success:!1,at:"from",name:"EmptyPageError",message:"The request page is empty."};let i=await er(r,e);if(G(i))return{success:!1,at:"to",name:ne(i).name,message:ne(i).message};let a=z(n);return a.persistent&&!o?{success:!1,at:"to",name:"NoEmptyPageError",message:The same page already exists in "/${r}"}:(await Me(r,e,c=>[...c,...s.lines.slice(1)].map(l=>l.text)),await Yd(t,e),{success:!0,dup:a.persistent})}var uf=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}=$e();o({type:"spinner"},{type:"text",text:/${t}/${e} → /${r}/${e}});try{let s=await BR(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}/${ge(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 uf()}});scrapbox.PageMenu.addItem({title:"Transport and Open",onClick:async()=>{let e=await uf();e&&window.open(e)}});var WU="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)}/${WU},{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}))}});Br.PageMenu.addMenu({image:"https://img.icons8.com/ios/180/FFFFFF/inbox.png",title:"~task",onClick:()=>{let{cursor:e,selection:t}=Nt(),r=e.getPosition().line,o=t.getSelectedText(),n=o||e.lines[r].text,s=n.split(
).map(i=>i.replace(/^\s*(.+)$/g,$1~@${pe(new Date,"yyyy-MM-dd")})).join(
);o||t.setRange({start:{line:r,char:0},end:{line:r,char:n.length}}),Xe(s)}});var Ti=e=>Wc(...U(()=>{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 bR(e,60),t={...t,loading:!1},o()})(),r);let n=()=>{r=(async()=>{await r,t={...t,loading:!0},o();let[s,i]=GU(await Pl(e));t={...t,tasks:s,errors:i,loading:!1},o()})()};return n(),gR(e,n)},()=>t]},e)),GU=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=se(a);if(t.has(c))continue;t.add(c);let l=Sr(a);if(l){if(G(l)){o.push({project:i,title:a,...ne(l)});continue}r.push({project:i,title:a,...z(l)})}}return[r,o]};var Ml=()=>{let[e,t]=ao(qU,{isOpen:!1,prevOverflowY:""}),r=tt(null),o=A(()=>{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=A(()=>{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=U(()=>{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}},qU=(e,t)=>{let r=t(e);return e.isOpen===r.isOpen&&e.prevOverflowY===r.prevOverflowY?e:r.isOpen?r:{isOpen:!1}};var _i=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 ys=({text:e,title:t})=>{let[r,o]=X(""),n=A(async s=>{s.preventDefault(),s.stopPropagation();try{await navigator.clipboard.writeText(e),o("Copied"),await De(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 zU=60*60*24*1e3,HR=(e,t)=>{let r=we(e.refDate),o=(t.getTime()-r.getTime())/zU;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 GR=(e,t)=>{if(t.score!==e.score)return t.score-e.score;let r=WR(e.freshness),o=WR(t.freshness);return r!==o?o-r:rr(Lr(e),Lr(t))?-1:1},WR=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 Pi=({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 xs=()=>{let[e,t]=X(new Date);return Z(()=>{let r=setInterval(()=>t(new Date),6e4);return()=>{clearInterval(r)}},[]),e};var qR=e=>{switch(e){case"todo":return"ToDo";case"note":return"覚書";case"deadline":return"締切";case"up-down":return"浮遊";case"done":return"完了"}};var zR=(e,t)=>new URL(/${e.project}/${ge(e.title)},t??location.href);var Al=({children:e,project:t,title:r,className:o,...n})=>d("a",{...n,className:[o??"","page-link"].join(" "),type:"link",href:zR({project:t,title:r}).pathname,...t===scrapbox.Project.name?{rel:"route"}:{rel:"noopener noreferrer",target:"_blank"},children:e});var VR=({action:e,pActions:t})=>{let r=U(()=>qR(e.freshness.status),[e.freshness.status]),o=U(()=>Or(Lr(e)).slice(11)||" ",[Lr(e)]),n=U(()=>Bs(e),[e]),s=Math.floor(Math.round(e.score)/7),i=xs(),a=U(()=>e.executed!==void 0&&Go(Pr(we(e.executed.start),e.executed.duration),i),[e.executed?.start,e.executed?.duration,i]),c=U(()=>[...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:VU(e).toFixed(2)}}:{},children:[d(ys,{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(Al,{project:e.project,title:e.raw,children:e.name})]})},VU=e=>Math.max(.8*Math.exp(Math.log(8/7)/7*e.score),.05);var KR=(e=Ft(new Date))=>{let[t,r]=X(e),o=A(()=>{r(s=>{switch(s){case"errors":return"expired";case"expired":return Ft(new Date);default:{let i=we(ki(s));return i.setDate(i.getDate()+1),Ft(i)}}})},[]),n=A(()=>{r(s=>{let i=Ft(new Date);switch(s){case"errors":return"errors";case"expired":return"errors";case i:return"expired";default:{let a=we(ki(s));return a.setDate(a.getDate()-1),Ft(a)}}})},[]);return{pageNo:t,next:o,prev:n}};var Il=(e,t)=>Z(()=>(scrapbox.on(e,t),()=>scrapbox.off(e,t)),[]);var Oi=(e,t)=>{let r=tt({...t});Z(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),Z(()=>{e(r.current)},[e])};var YR=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=>ut(d(KU,{getController:o,projects:e}),r))},KU=({getController:e,projects:t})=>{let{tasks:r,errors:o,load:n,loading:s}=Ti(t),{pageNo:i,next:a,prev:c}=KR(),l=U(()=>{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=>!Nr(y)&&rr(py(y),Lt(g))&&y.freshness===void 0&&y.recurrence===void 0?[{...y,score:0,freshness:{refDate:y.executed.start,status:"todo"}}]:[]).sort((y,x)=>rr(Lr(y),Lr(x))?-1:0)}let h=we(ki(i));return r.flatMap(g=>{if(!g.freshness)return[];if(go(g))return[];let y=HR(g.freshness,h);return y>-999?[{...g,score:y}]:[]}).sort(GR)},[r,o,i]),{ref:u,open:p,close:f}=Ml();Oi(e,{open:p,close:f});let m=U(()=>[i,...l.map(h=> ${h.raw})].join(
),[l,i]);return Il("page:changed",f),d(Q,{children:[d("style",{children:_i}),d("dialog",{ref:u,children:[d("div",{className:"controller",children:[d(ys,{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(Pi,{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(VR,{action:h,pActions:l.slice(0,g)},h.raw))})]})]})};var Dl=(e,t)=>/${e}/${se(t)},Si=new Map,mf=new Map,XR=(e,t)=>{Si.set(e,t);for(let r of mf.get(e)??[])r(t)},Fl=()=>{xn!==void 0&&(clearInterval(xn),xn=void 0);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Dl(e,t);if(!Si.has(r))return;let o=Ut().map(n=>n.text);xn=setInterval(()=>{se(t)===se(o[0])&&(XR(r,o),xn!==void 0&&(clearInterval(xn),xn=void 0))},1e3)},xn;scrapbox.on("page:changed",()=>{scrapbox.off("lines:changed",Fl);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Dl(e,t);Si.has(r)&&scrapbox.on("lines:changed",Fl)});var YU=(e,t)=>{let r=Dl(e,t),o=Si.get(r);return o||(Si.set(r,[]),er(e,t).then(n=>{if(G(n))return[];let s=z(n).lines.map(i=>i.text);XR(r,s),t===scrapbox.Page.title&&!scrapbox.listeners("lines:changed").includes(Fl)&&scrapbox.on("lines:changed",Fl)})),o??[]},JR=(e,t)=>{let[r,o]=X(YU(e,t));return Z(()=>{let n=Dl(e,t),s=mf.get(n)??new Set;return s.add(o),mf.set(n,s),()=>{s.delete(o)}},[e,t]),r};var ff=e=>e.duration===void 0?void 0:Lt(Pr(we(e.start),e.duration)),df=(e,t)=>{let r=we(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:ff(s),duration:e.duration-n}]};var bn=e=>"title"in e,XU=e=>e.record?.duration!==void 0,QR=(e,t)=>bn(e)&&e.status==="done"?e.status:XU(e)?bn(e)&&e.executed?rr(Lt(t),e.executed.start)?"moved":"expired":"done":rr(ff(e.plan),Lt(t))?bn(e)?"expired":"done":"undone";var ZR=(e,t)=>{let r=Sr(e.title.slice(1,-1));if(!e.plan.start)return;let o={name:r&&We(r)?z(r).name:e.title,plan:{start:Lt(e.plan.start),duration:(e.plan.duration??0)/60}};if(e.record.start&&(o.record={start:Lt(e.record.start)},e.record.end&&(o.record.duration=fo(e.record.end,e.record.start))),!r||G(r))return o;let n=z(r),s={...o,title:n.raw,project:t};return n.freshness&&(s.status=n.freshness.status),Nr(n)||(s.executed=n.executed),s},hf=(e,t)=>{let r=Ha(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 eT=(e,t,r)=>{let o=[gf(e,jt(t,1),r),gf(e,t,r),gf(e,_e(t,1),r)],n=U(()=>o.flat(),o);return U(()=>{let s=dr(t),i=Ia(t);return n.flatMap(a=>{let[,c]=df(a.plan,s);if(!c)return[];let[l]=df(c,i);if(!l)return[];let{plan:u,...p}=a;return[{plan:l,...p}]}).sort((a,c)=>rr(a.plan.start,c.plan.start)?-1:0)},[n,t])},gf=(e,t,r)=>{let o=JR(e,gr(t)),n=U(()=>QU(o,e),[o,e]);return U(()=>n.length!==0?n:JU(t,r),[n,t,r])},JU=(e,t)=>t.flatMap(r=>{if(r.freshness?.status==="done")return[];if(Nr(r))return[];if(go(r)){let n=Ba(r,e);return n?[hf(n,r.project)]:[]}let o=we(r.executed.start);return nt(o,e)?[hf(r,r.project)]:[]}),QU=(e,t)=>{let r=[];for(let o of qo(e)){if(ho(o))continue;let n=ZR(o,t);n&&r.push(n)}return r};var tT=({event:e})=>{let t=U(()=>e.plan.start.hours+e.plan.start.minutes/60,[e.plan.start]),r=U(()=>--start: ${t}; --duration: ${e.plan.duration};,[t,e.plan.duration]),o=xs(),n=U(()=>QR(e,o),[e,o]);return bn(e)?d(Al,{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 rT=({project:e,date:t,tasks:r})=>{let o=eT(e,t,r),n=U(()=>o.flatMap(a=>bn(a)?[${a.title}]:[]).join(
),[o]),s=xs(),i=U(()=>nt(s,t)&&d("div",{className:"indicator",style:--start: ${Xg(s)+Yg(s)/60}}),[s,t]);return d("div",{className:"timeline",role:"gridcell",children:[o.map(a=>d(tT,{event:a},a.name)),i,d(ys,{text:n})]})};var yf=({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:Is(n)})},Ft(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":${yr(n)}:00},n))}),e.map(n=>d(rT,{project:r,date:n,tasks:t},Ft(n)))]})})]});var xf=(e,t,r)=>{let[o,n]=X(e),s=A(()=>n(t),[t]),i=A(()=>n(r),[t]),a=A(c=>n(c),[]);return{pageNo:o,next:s,prev:i,jump:a}};var oT=e=>{let t=tt(new Set),[r,o]=X(e),n=A(()=>{for(let l of t.current)l()},[]),s=A(()=>{o(!0),n()},[]),i=A(()=>o(!1),[]),a=A(()=>o(l=>(l||n(),!l)),[]),c=A(l=>(t.current.add(l),()=>t.current.delete(l)),[]);return{isOpen:r,open:s,close:i,toggle:a,onOpen:c}};var iT=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=>ut(d(ZU,{getController:o,projects:e,mainProject:e[0]}),r))},aT=(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=>ut(d(e$,{getController:n,projects:e,mainProject:e[0],open:t}),o))},nT=!1,ZU=({getController:e,projects:t,mainProject:r})=>{let{tasks:o,load:n,loading:s}=Ti(t),{pageNo:i,next:a,prev:c,jump:l}=xf(vi(new Date),t$,r$),u=U(()=>{let y=Ol(i);return[0,1,2,3,4,5,6].map(x=>_e(y,x))},[i]),{ref:p,open:f,close:m,isOpen:h}=Ml();nT||=h,Oi(e,{open:f,close:m,isOpen:h}),Il("page:changed",m);let g=A(()=>l(vi(new Date)),[l]);return d(Q,{children:[d("style",{children:_i}),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(Pi,{loading:s,onClick:n}),d("button",{type:"button",className:"close",onClick:m,children:""})]}),nT&&d("div",{ref:cT,className:"result scheduler","data-page-no":i,children:d(yf,{dateList:u,tasks:o,project:r})})]})]})},sT=!1,e$=({projects:e,mainProject:t,getController:r,open:o})=>{let{tasks:n,load:s,loading:i}=Ti(e),{pageNo:a,next:c,prev:l,jump:u}=xf(new Date,o$,n$),p=U(()=>[a],[a]),f=A(()=>u(new Date),[u]),{isOpen:m,open:h,close:g}=oT(o);return sT||=m,Oi(r,{open:h,close:g,isOpen:m}),d(Q,{children:[d("style",{children:_i}),sT&&d("div",{className:wedget${m?" open":""},ref:cT,children:[d("div",{className:"controller",children:[d("span",{children:Ft(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(Pi,{loading:i,onClick:s})]}),d(yf,{dateList:p,tasks:n,project:t,hasColumn:!1})]})]})},t$=e=>vi($o(Ol(e),1)),r$=e=>vi(Jg(Ol(e),1)),o$=e=>_e(e,1),n$=e=>jt(e,1),cT=e=>{let t=e?.getElementsByClassName?.("indicator")?.[0];if(!t)return;let r=globalThis.scrollY;t.scrollIntoView({block:"center"}),globalThis.scroll(0,r)};vh({project:"takker-dist"});aa(!0);Th({maxCount:10,accessToken:s$,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)}}});Ng().then(e=>{scrapbox.PageMenu.addItem({title:"Fulltext Search",onClick:()=>{e.toggle()}})});var i$="https://scrapbox.io/files/67344295032adf96d1e4c276.wasm",a$="/api/code/takker-dist/for-any-project-min/esbuild-worker.js";(async()=>{let e=new Request(i$),t=await Cn(e);t||(t=await fetch(e),await Pa(e,t)),await vE(await WebAssembly.compileStreaming(t),a$)})();(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 mk({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;ou.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)}})})();gk({previewers:[{when:/(?:^|\.)svg$/,preview:yk},{when:/(?:^|\.)glsl$/,preview:Ck},{when:/(?:^|\.)(?:plantuml|puml|pu)$/,preview:Ik},{when:/(?:^|\.)tikz\(tex\)$/,preview:Dk("/api/code/takker-dist/for-any-project-min/tex-worker.js","https://scrapbox.io/files/65d1645c19cd8e002433c3df")}]});(async()=>{let{toggle:e}=await ev();scrapbox.PageMenu.addItem({title:"履歴スライダー",image:"https://1.bp.blogspot.com/-UZtkSEX0wh4/U5l5_dNcEsI/AAAAAAAAhWs/UzJGVzyiX8Y/s800/kaichu_dokei.png",onClick:e})})();Wv("takker",["takker","振り返り(takker-workflow@0.0.1)のtemplate","txt"],["takker","1週間の振り返り(takker-workflow@0.0.1)のtemplate","txt"],new Date(2024,11,24));hn()&&(cr({display:{type:"caret-left"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?va():ba()}}),cr({display:{type:"caret-right"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?ka():xa()}}),cr({display:{type:"caret-up"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ra():wa()}}),cr({display:{type:"caret-down"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ta():Ea()}}),cr({display:{type:"copy"},onClick:async({cursor:e,selection:t})=>await _R(e,t)}),cr({display:{type:"cut"},onClick:async({cursor:e,selection:t})=>await PR(e,t)}),cr({display:{type:"clipboard"},onClick:async({cursor:e})=>await OR(e)}),cr({display:{type:"undo"},onClick:()=>yg()}),cr({display:{type:"redo"},onClick:()=>xg()}),cr({display:({cursor:e})=>e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?{type:["i-cursor","slash"]}:{type:"i-cursor"},onClick:({cursor:e})=>SR(e)}));if(hn()&&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:Ds}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>$s({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})})}if(hn()){let e="New Page",t=[Yo,Xo,Jo];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&&zr({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&&zr({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 YR(o);scrapbox.PageMenu.addMenu({title:e,image:"/assets/img/favicon/apple-touch-icon.png",onClick:n});let s=await iT(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 aT(o,ac),u=()=>{ac=!l.isOpen,l.isOpen?l.close():l.open?.(),localStorage.setItem(i,JSON.stringify(a))};hn()?cr({display:{type:"calendar"},onClick:u}):scrapbox.PageMenu.addItem({title:"toggle wedget",onClick:u})}})();export{cr as addButton,Xe as insertText,ou 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 xT=Object.defineProperty;var Lo=(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 Di=(e,t)=>{for(var r in t)xT(e,r,{get:tr,enumerable:!0})};function Se(e){if(e)return bT(e)}function bT(e){for(var t in Se.prototype)et=Se.prototypet;return e}Se.prototype.on=Se.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks"$"+e=this._callbacks"$"+e||[]).push(t),this};Se.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this};Se.prototype.off=Se.prototype.removeListener=Se.prototype.removeAllListeners=Se.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};Se.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};Se.prototype.emitReserved=Se.prototype.emit;Se.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks"$"+e||[]};Se.prototype.hasListeners=function(e){return!!this.listeners(e).length};var Rr=Object.create(null);Rr.open="0";Rr.close="1";Rr.ping="2";Rr.pong="3";Rr.message="4";Rr.upgrade="5";Rr.noop="6";var ji=Object.create(null);Object.keys(Rr).forEach(e=>{ji[Rre]=e});var Kl={type:"error",data:"parser error"},Pf=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="object BlobConstructor",Of=typeof ArrayBuffer=="function",Sf=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Bi=({type:e,data:t},r,o)=>Pf&&t instanceof Blob?r?o(t):Rf(t,o):Of&&(t instanceof ArrayBuffer||Sf(t))?r?o(t):Rf(new Blob(t),o):o(Rre+(t||"")),Rf=(e,t)=>{let r=new FileReader;return r.onload=function(){let o=r.result.split(",")1;t("b"+(o||""))},r.readAsDataURL(e)};function Tf(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}var zl;function wT(e,t){if(Pf&&e.data instanceof Blob)return e.data.arrayBuffer().then(Tf).then(t);if(Of&&(e.data instanceof ArrayBuffer||Sf(e.data)))return t(Tf(e.data));Bi(e,!1,r=>{zl||(zl=new TextEncoder),t(zl.encode(r))})}var _f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Rs=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<_f.length;e++)Rs_f.charCodeAt(e)=e;var ET=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=Rse.charCodeAt(o),i=Rse.charCodeAt(o+1),a=Rse.charCodeAt(o+2),c=Rse.charCodeAt(o+3),un++=s<<2|i>>4,un++=(i&15)<<4|a>>2,un++=(a&3)<<6|c&63;return l},kT=typeof ArrayBuffer=="function",Hi=(e,t)=>{if(typeof e!="string")return{type:"message",data:Nf(e,t)};let r=e.charAt(0);return r==="b"?{type:"message",data:vT(e.substring(1),t)}:jir?e.length>1?{type:jir,data:e.substring(1)}:{type:jir}:Kl},vT=(e,t)=>{if(kT){let r=ET(e);return Nf(r,t)}else return{base64:!0,data:e}},Nf=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob(e);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},Lf="",Cf=(e,t)=>{let r=e.length,o=new Array(r),n=0;e.forEach((s,i)=>{Bi(s,!1,a=>{oi=a,++n===r&&t(o.join(Lf))})})},Mf=(e,t)=>{let r=e.split(Lf),o=[];for(let n=0;n<r.length;n++){let s=Hi(rn,t);if(o.push(s),s.type==="error")break}return o};function Af(){return new TransformStream({transform(e,t){wT(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 Vl;function Ui(e){return e.reduce((t,r)=>t+r.length,0)}function $i(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 If(e,t){Vl||(Vl=new TextDecoder);let r=[],o=0,n=-1,s=!1;return new TransformStream({transform(i,a){for(r.push(i);;){if(o===0){if(Ui(r)<1)break;let c=$i(r,1);s=(c0&128)===128,n=c0&127,n<126?o=3:n===126?o=1:o=2}else if(o===1){if(Ui(r)<2)break;let c=$i(r,2);n=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),o=3}else if(o===2){if(Ui(r)<8)break;let c=$i(r,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(Kl);break}n=u*Math.pow(2,32)+l.getUint32(4),o=3}else{if(Ui(r)<n)break;let c=$i(r,n);a.enqueue(Hi(s?c:Vl.decode(c),t)),o=0}if(n===0||n>e){a.enqueue(Kl);break}}}})}var Yl=4;var Ts=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Qt=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),RT="arraybuffer";function Df(e,...t){return t.reduce((r,o)=>(e.hasOwnProperty(o)&&(ro=eo),r),{})}var TT=Qt.setTimeout,_T=Qt.clearTimeout;function _s(e,t){t.useNativeTimers?(e.setTimeoutFn=TT.bind(Qt),e.clearTimeoutFn=_T.bind(Qt)):(e.setTimeoutFn=Qt.setTimeout.bind(Qt),e.clearTimeoutFn=Qt.clearTimeout.bind(Qt))}var PT=1.33;function OT(e){return typeof e=="string"?ST(e):Math.ceil((e.byteLength||e.size)*PT)}function ST(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 Uf(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function NT(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(er));return t}function LT(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 CT=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},Ql=class extends Se{constructor(e){super(),this.writable=!1,_s(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 CT(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=Hi(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&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=NT(e);return t.length?"?"+t:""}},MT=class extends Ql{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)};Mf(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,Cf(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=Uf()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}},$f=!1;try{$f=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}var AT=$f;function IT(){}var FT=class extends MT{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}},Tn=class Wi extends Se{constructor(t,r,o){super(),this.createRequest=t,_s(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=Df(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=Wi.requestsCount++,Wi.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=IT,t)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Wi.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()}};Tn.requestsCount=0;Tn.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ff);else if(typeof addEventListener=="function"){let e="onpagehide"in Qt?"pagehide":"unload";addEventListener(e,Ff,!1)}}function Ff(){for(let e in Tn.requests)Tn.requests.hasOwnProperty(e)&&Tn.requestse.abort()}var DT=function(){let e=jf({xdomain:!1});return e&&e.responseType!==null}(),Zl=class extends FT{constructor(e){super(e);let t=e&&e.forceBase64;this.supportsBinary=DT&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Tn(jf,this.uri(),e)}};function jf(e){let t=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!t||AT))return new XMLHttpRequest}catch{}if(!t)try{return new Qt["Active".concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Bf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",UT=class extends Ql{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Bf?{}:Df(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;Bi(r,this.supportsBinary,n=>{try{this.doWrite(r,n)}catch{}o&&Ts(()=>{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=Uf()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Xl=Qt.WebSocket||Qt.MozWebSocket,ep=class extends UT{createSocket(e,t,r){return Bf?new Xl(e,t,r):t?new Xl(e,t):new Xl(e)}doWrite(e,t){this.ws.send(t)}},Hf=class extends Ql{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=If(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),o=Af();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&&Ts(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}},$T={websocket:ep,webtransport:Hf,polling:Zl},jT=/^(?:(?!^:@\/?#+:^:@\/*@)(http|https|ws|wss):\/\/)?((?:((^:@\/?#*)(?::(^:@\/?#*))?)?@)?((?:a-f0-9{0,4}:){2,7}a-f0-9{0,4}|^:\/?#*)(?::(\d*))?)(((\/(?:^?#(?!^?#\/*\.^?#\/.+(?:?#|$)))*\/?)?(^?#\/*))(?:\?(^#*))?(?:#(.*))?)/,BT="source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor";function Vi(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=jT.exec(e||""),s={},i=14;for(;i--;)s[BTi]=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=HT(s,s.path),s.queryKey=WT(s,s.query),s}function HT(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 WT(e,t){let r={};return t.replace(/(?:^|&)(^&=*)=?(^&*)/g,function(o,n,s){n&&(rn=s)}),r}var Jl=typeof addEventListener=="function"&&typeof removeEventListener=="function",Gi=[];Jl&&addEventListener("offline",()=>{Gi.forEach(e=>e())},!1);var qi=class zi extends Se{constructor(t,r){if(super(),this.binaryType=RT,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=Vi(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=Vi(r.host).host);_s(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=LT(this.opts.query)),Jl&&(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"})},Gi.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(t){let r=Object.assign({},this.opts.query);r.EIO=Yl,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&&zi.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",zi.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+=OT(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,Ts(()=>{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(zi.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(),Jl&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let o=Gi.indexOf(this._offlineEventListener);o!==-1&&Gi.splice(o,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,r),this.writeBuffer=[],this._prevBufferLen=0}}};qi.protocol=Yl;var GT=class extends qi{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;qi.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;qi.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}},tp=class extends GT{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=>$To).filter(o=>!!o)),super(e,r)}};var L$=tp.protocol;var sp={};Di(sp,{Decoder:()=>ZT,Encoder:()=>QT,PacketType:()=>ie,protocol:()=>qf});var qT=typeof ArrayBuffer=="function",zT=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,Gf=Object.prototype.toString,VT=typeof Blob=="function"||typeof Blob<"u"&&Gf.call(Blob)==="object BlobConstructor",KT=typeof File=="function"||typeof File<"u"&&Gf.call(File)==="object FileConstructor";function np(e){return qT&&(e instanceof ArrayBuffer||zT(e))||VT&&e instanceof Blob||KT&&e instanceof File}function Ki(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let r=0,o=e.length;r<o;r++)if(Ki(er))return!0;return!1}if(np(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return Ki(e.toJSON(),!0);for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Ki(er))return!0;return!1}function YT(e){let t=[],r=e.data,o=e;return o.data=rp(r,t),o.attachments=t.length,{packet:o,buffers:t}}function rp(e,t){if(!e)return e;if(np(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=rp(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=rp(eo,t));return r}return e}function XT(e,t){return e.data=op(e.data,t),delete e.attachments,e}function op(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=op(er,t);else if(typeof e=="object")for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(er=op(er,t));return e}var JT="connect","connect_error","disconnect","disconnecting","newListener","removeListener",qf=5,ie;(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"})(ie||(ie={}));var QT=class{constructor(e){this.replacer=e}encode(e){return(e.type===ie.EVENT||e.type===ie.ACK)&&Ki(e)?this.encodeAsBinary({type:e.type===ie.EVENT?ie.BINARY_EVENT:ie.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):this.encodeAsString(e)}encodeAsString(e){let t=""+e.type;return(e.type===ie.BINARY_EVENT||e.type===ie.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=YT(e),r=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(r),o}};function Wf(e){return Object.prototype.toString.call(e)==="object Object"}var ZT=class zf extends Se{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===ie.BINARY_EVENT;o||r.type===ie.BINARY_ACK?(r.type=o?ie.EVENT:ie.ACK,this.reconstructor=new e0(r),r.attachments===0&&super.emitReserved("decoded",r)):super.emitReserved("decoded",r)}else if(np(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(ieo.type===void 0)throw new Error("unknown packet type "+o.type);if(o.type===ie.BINARY_EVENT||o.type===ie.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(zf.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 ie.CONNECT:return Wf(r);case ie.DISCONNECT:return r===void 0;case ie.CONNECT_ERROR:return typeof r=="string"||Wf(r);case ie.EVENT:case ie.BINARY_EVENT:return Array.isArray(r)&&(typeof r0=="number"||typeof r0=="string"&&JT.indexOf(r0)===-1);case ie.ACK:case ie.BINARY_ACK:return Array.isArray(r)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},e0=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=XT(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};function t0(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=Vi(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 pr(e,t,r){return e.on(t,r),function(){e.off(t,r)}}var r0=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Vf=class extends Se{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=pr(e,"open",this.onopen.bind(this)),pr(e,"packet",this.onpacket.bind(this)),pr(e,"error",this.onerror.bind(this)),pr(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(r0.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:ie.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)=>r!==this._queue0?void 0:(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:ie.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 ie.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 ie.EVENT:case ie.BINARY_EVENT:this.onevent(e);break;case ie.ACK:case ie.BINARY_ACK:this.onack(e);break;case ie.DISCONNECT:this.ondisconnect();break;case ie.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:ie.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.emitReserved("connect"),this._drainQueue(!0)}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:ie.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 Pn(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}Pn.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};Pn.prototype.reset=function(){this.attempts=0};Pn.prototype.setMin=function(e){this.ms=e};Pn.prototype.setMax=function(e){this.max=e};Pn.prototype.setJitter=function(e){this.jitter=e};var ip=class extends Se{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,_s(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 Pn({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||sp;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 tp(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let o=pr(t,"open",function(){r.onopen(),e&&e()}),n=i=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",i),e?e(i):this.maybeReconnectOnOpen()},s=pr(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(pr(e,"ping",this.onping.bind(this)),pr(e,"data",this.ondata.bind(this)),pr(e,"error",this.onerror.bind(this)),pr(e,"close",this.onclose.bind(this)),pr(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){Ts(()=>{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 Vf(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)}},Ps={};function _n(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};let r=t0(e,t.path||"/socket.io"),o=r.source,n=r.id,s=r.path,i=Psn&&s in Psn.nsps,a=t.forceNew||t"force new connection"||t.multiplex===!1||i,c;return a?c=new ip(o,t):(Psn||(Psn=new ip(o,t)),c=Psn),r.query&&!t.query&&(t.query=r.queryKey),c.socket(r.path,t)}Object.assign(_n,{Manager:ip,Socket:Vf,io:_n,connect:_n});function mt(e){return e.val}function bt(e){return e.err}var Kf=" must not return ",o0="transformer",n0="recoverer",s0="defaultValue",On=o0+Kf,jr="called with ",Sn=s0+" must not be ",Nn=n0+Kf;var i0="Ok",Yf="Err",Xf=jr+Yf,Jf=jr+i0,a0="Carrying E in "+Yf+" instead of throwing it directly. See .cause",ap="an instance of Error of the current realm.",bj="The thrown value is not "+ap,wj="The contained E should be "+ap,c0="This .cause is not "+ap;function Ie(e){return e.ok}function oe(e){return{ok:!0,val:e,err:null}}function W(e){return!e.ok}function xe(e){return{ok:!1,val:null,err:e}}function J(e){return Qf(e,Xf)}function Ln(e){return Zf(e,Jf)}function Qf(e,t){if(W(e))throw new TypeError(t);return e.val}function Zf(e,t){if(Ie(e))throw new TypeError(t);return e.err}async function cp(e,t){if(W(e))return e;let r=mt(e);return await t(r)}function Co(e,t){if(W(e))return e;let r=mt(e),o=t(r);return oe(o)}async function Te(e,t){if(W(e))return e;let r=mt(e),o=await t(r);return oe(o)}async function Oe(e,t){if(Ie(e))return e;let r=bt(e),o=await t(r);return xe(o)}async function Yi(e,t){if(Ie(e))return e;let r=bt(e);return await t(r)}var Xi="null",CB=On+Xi,u0=jr+Xi,MB=Sn+Xi,AB=Nn+Xi;var Ji="undefined",$B=On+Ji,m0=jr+Ji,jB=Sn+Ji,BB=Nn+Ji;var _e=e=>e.ok?oe(e):xe({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var td=async(e,t)=>{let r=new Request(e,t);try{return oe(await globalThis.fetch(r))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return xe({name:"AbortError",message:o.message,request:r});if(o instanceof TypeError)return xe({name:"NetworkError",message:o.message,request:r});throw o}};var me=e=>{let{fetch:t=td,hostName:r="scrapbox.io",...o}=e;return{fetch:t,hostName:r,...o}};var rd=e=>{let{sid:t,hostName:r}=me(e??{});return new Request(https://${r}/api/users/me,t?{headers:{Cookie:be(t)}}:void 0)},od=e=>Te(_e(e),async t=>await t.json()),Qi=(()=>{let e=async t=>{let{fetch:r,...o}=me(t??{}),n=await r(rd(o));return W(n)?n:od(J(n))};return e.toRequest=rd,e.fromResponse=od,e})();var be=e=>connect.sid=${e},Tr=async e=>{let t=e?.csrf??globalThis._csrf;return t?oe(t):Co(await Qi(e),r=>r.csrfToken)};var wt=(e,t)=>{if(e?.connected)return Promise.resolve(oe(e));e??=_n("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"],...t?{rejectUnauthorized:!1,extraHeaders:{Cookie:be(t),Host:"scrapbox.io",Referer:"https://scrapbox.io/"}}:{}});let r=new Promise(o=>{let n=s=>o(xe(s));e.once("connect",()=>{e.off("disconnect",n),o(oe(e))}),e.once("disconnect",n)});return e.connect(),r},Et=e=>{if(e.disconnected)return Promise.resolve(oe(void 0));let t=new Promise(r=>{let o=n=>{if(n!=="io client disconnect"){r(xe(n));return}r(oe(void 0)),e.off("disconnect",o)};e.on("disconnect",o)});return e.disconnect(),t};var nd=e=>d0.includes(e.name),d0="SocketIOError","DuplicateTitleError","NotFastForwardError";var sd=(e,t,r,o)=>{if(t==="cursor")return e.emit(t,r),Promise.resolve(oe(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(xe({name:"SocketIOError"}));return}};e.on("disconnect",c);let l=o?.timeout??9e4,u=setTimeout(()=>{a(),n(xe({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(xe(nd(f.error)?f.error:{name:"UnexpectedRequestError",...f}));return}n(oe(f.data))}),s};function Zi(e,t={}){if(e===null)return"null";if(Array.isArray(e))return h0(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:g0(e,t);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function h0(e,t){let{threshold:r=20}=t,o=e.map(i=>Zi(i,t)),n=o.join(", ");if(n.length<=r)return[${n}];let s=o.join(`,
);return[
${id(2,s)}
]}function g0(e,t){let{threshold:r=20}=t,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(i=>${i.toString()}: ${Zi(ei,t)}),n=o.join(", ");if(n.length<=r)return{${n}};let s=o.join(,
);return{
${id(2,s)}
}}function id(e,t){let r=" ".repeat(e);return t.split(
).map(o=>${r}${o}).join(
)}function tt(e,t,...r){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=${t}(${r.map(n=>Zi(n)).join(", ")}),o)}})}function ur(e){return Array.isArray(e)}function lp(e){return tt(t=>ur(t)&&t.every(r=>e(r)),"isArrayOf",e)}function ea(e){let t=new Set(e);return tt(r=>t.has(r),"isLiteralOneOf",e)}function Os(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function Ce(e){return typeof e=="string"}var He=async(e,t)=>{let r=e.response.clone(),o=ea(t);try{let n=await r.json();if(!Os(n))return;if(r.status===422){if(!Ce(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(t.includes(s))return{name:s,message:n.message}}return!o(n.name)||!Ce(n.message)?void 0:n.name==="NotLoggedInError"?!Os(n.detals)||!Ce(n.detals.project)||!lp(y0)(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}},y0=ea(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var se=e=>e.replaceAll(" ","_").toLowerCase();var ge=e=>[...e].map((t,r)=>t===" "?"_":!x0.includes(t)||r===e.length-1&&b0.includes(t)?encodeURIComponent(t):t).join(""),x0='@$&+=:;",',b0=':;",';var ta="null or undefined",Cn=On+ta,w0=jr+ta,ra=Sn+ta,oa=Nn+ta;function Zt(e){return e!=null}function _r(e){return e==null}function mr(e,t){if(Zt(e))return e;throw new TypeError(t)}function na(e){return _r(e)?xe(void 0):oe(e)}function pp(e,t){return Zt(e)?e:mr(t,ra)}var ad=(e,t,r)=>{let{sid:o,hostName:n,followRename:s,projects:i}=me(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(https://${n}/api/pages/${e}/${ge(t)}?${a},o?{headers:{Cookie:be(o)}}:void 0)},cd=async e=>Oe(await Te(_e(e),t=>t.json()),async t=>t.response.status===414?{name:"TooLongURIError",message:"project ids may be too much."}:pp(await He(t,["NotFoundError","NotLoggedInError","NotMemberError"]),t)),er=(()=>{let e=async(t,r,o)=>cp(await me(o??{}).fetch(ad(t,r,o)),n=>cd(n));return e.toRequest=ad,e.fromResponse=cd,e})();var ld=(e,t)=>{let{sid:r,hostName:o}=me(t??{});return new Request(https://${o}/api/projects/${e},r?{headers:{Cookie:be(r)}}:void 0)},pd=async e=>Te(await Oe(_e(e),async t=>await He(t,["NotFoundError","NotLoggedInError","NotMemberError"])??t),t=>t.json()),Br=(()=>{let e=async(t,r)=>{let{fetch:o}=me(r??{}),n=ld(t,r),s=await o(n);return W(s)?s:pd(J(s))};return e.toRequest=ld,e.fromResponse=pd,e})(),ud=(e,t)=>{let{sid:r,hostName:o}=me(t??{}),n=new URLSearchParams(e.map(s=>["ids",s]));return new Request(https://${o}/api/projects?${n},r?{headers:{Cookie:be(r)}}:void 0)},md=async e=>Te(await Oe(_e(e),async t=>await He(t,["NotLoggedInError"])??t),t=>t.json()),sa=(()=>{let e=async(t,r)=>{let{fetch:o}=me(r??{}),n=await o(ud(t,r));return W(n)?n:md(J(n))};return e.toRequest=ud,e.fromResponse=md,e})();var mp=async(e,t,r)=>{let[o,n,s]=await Promise.all([er(e,t,r),E0(r),k0(e,r)]);return W(o)?o:W(n)?n:W(s)?s:oe({...J(o),projectId:J(s),userId:J(n)})},up,E0=async e=>{if(up)return oe(up);let t=await Qi(e);if(W(t))return t;let r=J(t);return"id"in r?(up=r.id,oe(r.id)):xe({name:"NotLoggedInError",message:"This script cannot be used without login"})},fd=new Map,k0=async(e,t)=>{let r=fd.get(e);return r?oe(r):Co(await Br(e,t),({id:o})=>(fd.set(e,o),o))};function De(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=v0(()=>{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 l;console.error("persistent option is only available in Deno")}})}var dd=2**31-1;function v0(e,t){let r=t=Math.trunc(Math.max(t,0)||0),o=Date.now(),n,s=()=>{r=t-(Date.now()-o),n=r>dd?setTimeout(s,dd):setTimeout(e,r)};return s(),{valueOf:()=>n}}var Mo=async(e,t,r,o)=>{let n=await wt(o?.socket,o?.sid);if(W(n))return xe({name:"UnexpectedRequestError",error:Ln(n)});let s=J(n),i=await mp(e,t,o);if(W(i))return i;let a=J(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 oe(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 sd(s,"commit",f);if(Ie(m))return a.commitId=J(m).commitId,oe(a.commitId);let h=Ln(m),g=h.name;if(g==="SocketIOServerDisconnectError"||g==="UnexpectedRequestError")return xe(h);if(g==="TimeoutError"||g==="SocketIOError"){await De(3e3);continue}if(g==="NotFastForwardError"){await De(1e3);let y=await mp(e,t,o);if(W(y))return y;a=J(y)}u=g;break}}return xe({name:"RetryError",attempts:c,message:Retrying exceeded the maxAttempts (${c}).})}finally{o?.socket||await Et(s)}};var fp=(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 E=Math.max(y,x),v=E-g;for(;v<o.length&&E<n.length&&o[v]===n[E];)++v,++E;return a[g+s]=c.length,c.push([{x:v,y:E},a[g+(y>x?-1:1)+s]]),E}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:E}of R0(m))for(;g<x||y<E;)E-x>y-g?(yield{value:n[y],type:r?"deleted":"added"},++y):E-x<y-g?(yield{value:o[g],type:r?"added":"deleted"},++g):(yield{value:o[g],type:"common"},++g,++y)}}};function*dp(e){let t=[],r=[];function*o(){if(t.length>r.length){for(let n=0;n<r.length;n++)yield hd(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 hd(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 hd=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*R0(e){for(let t=e.length-1;t>=0;t--)yield e[t]}var gd=e=>e.padStart(8,"0"),hp=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${gd(t).slice(-8)}${e.slice(-6)}0000${gd(r)}};function*gp(e,t,{userId:r}){let{buildSES:o}=fp(e.map(({text:i})=>i),t),n=0,s=e[0].id;for(let i of dp(o())){switch(i.type){case"added":yield{_insert:s,lines:{id:hp(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 T0=(e,t)=>(e.type==="codeBlock"||e.type==="table")&&t.indent>(e.rows[0]?.indent??0),yd=(e,t)=>{let r=e[e.length-1];return r!==void 0&&T0(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},xd=(e,t)=>{if(t.hasTitle??!0){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(yd,[])]}return e.reduce(yd,[])};var bd=e=>e.split(
).map(t=>({indent:/^\s+/.exec(t)?.[0]?.length??0,text:t}));var wd=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(i=>i.text.substring(o+1)).join(
)}};var ae=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested)return i?.()??[];if(!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??0)),p=e(c[0]??"",s);return[...St(l,s),...p,...St(u,s)]}return i?.()??[]};var de=e=>[{type:"plain",raw:e,text:e}],Ed=ae(de,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]});var _0=/\[\s+\]/,P0=(e,t)=>t.context==="table"?de(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],kd=ae(P0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[_0]});var O0=/.*?/,S0=(e,t)=>t.context==="table"?de(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],vd=ae(S0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[O0]});var N0=/^[$%] .+$/,L0=(e,t)=>{if(t.context==="table")return de(e,t);let r=e[0]??"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},Rd=ae(L0,{parseOnNested:!1,parseOnQuoted:!1,patterns:[N0]});var C0=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,M0=(e,t)=>{if(t.context==="table")return de(e,t);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:St(n,{...t,nested:!0})}]},Td=ae(M0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[C0]});var A0=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,I0=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,F0=/\[https?:\/\/[^\s\]]+\]/,D0=/https?:\/\/[^\s]+/,U0=(e,t)=>{if(t.context==="table")return de(e,t);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?.[0]===void 0)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()}]},_d=ae(U0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[A0,I0,F0,D0]});var $0=/\[\$ .+? \]/,j0=/\[\$ [^\]]+\]/,B0=(e,t)=>t.context==="table"?de(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],Pd=ae(B0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[$0,j0]});var Od=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Sd=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,H0=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}},W0=(e,t)=>{if(t.context==="table")return de(e,t);let r=e.match(Od)??e.match(Sd);if(r===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,n="",s=""]=o?r:[r[0],r[2],r[1]],{latitude:i,longitude:a,zoom:c}=H0(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:e,latitude:i,longitude:a,zoom:c,place:s,url:l}]},Nd=ae(W0,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Od,Sd]});var G0=/(?:^|\s)#\S+/,q0=(e,t)=>{if(t.context==="table")return de(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...de(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},Ld=ae(q0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[G0]});var z0=/^\? .+$/,V0=(e,t)=>t.context==="table"?de(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],Cd=ae(V0,{parseOnNested:!1,parseOnQuoted:!1,patterns:[z0]});var K0=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,Y0=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}))},Md=ae(Y0,{parseOnNested:!0,parseOnQuoted:!0,patterns:[K0]});var X0=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,J0=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,Q0=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,Z0=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,e_=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||t_(e),t_=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),r_=(e,t)=>{if(t.context==="table")return de(e,t);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]=e_(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}]},Ad=ae(r_,{parseOnNested:!0,parseOnQuoted:!0,patterns:[X0,J0,Q0,Z0]});var o_=/\[\/?[^[\]]+\]/,n_=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},Id=ae(n_,{parseOnNested:!0,parseOnQuoted:!0,patterns:[o_]});var s_=/^[0-9]+\. .*$/,i_=(e,t)=>{if(t.context==="table")return de(e,t);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:St(s,{...t,nested:!1})}]},Fd=ae(i_,{parseOnNested:!1,parseOnQuoted:!1,patterns:[s_]});var a_=/^>.*$/,c_=(e,t)=>t.context==="table"?de(e,t):[{type:"quote",raw:e,nodes:St(e.substring(1),{...t,quoted:!0})}],Dd=ae(c_,{parseOnNested:!1,parseOnQuoted:!1,patterns:[a_]});var l_=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,p_=(e,t)=>{if(t.context==="table")return de(e,t);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}))},Ud=ae(p_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[l_]});var u_=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,m_=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,f_=(e,t)=>{if(t.context==="table")return de(e,t);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}]},$d=ae(f_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[u_,m_]});var d_=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,h_=(e,t)=>t.context==="table"?de(e,t):[{type:"strong",raw:e,nodes:St(e.substring(2,e.length-2),{...t,nested:!0})}],jd=ae(h_,{parseOnNested:!1,parseOnQuoted:!0,patterns:[d_]});var g_=(e,t,r)=>e===""?[]:r?.()??[],y_=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>Ed(t,r))(),St=y_(g_,Dd,Cd,Fd,vd,Rd,Pd,kd,Td,$d,Ud,jd,Ad,_d,Md,Nd,Id,Ld);var Bd=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:St(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var Hd=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(i=>i.text.substring(o+1)).map(i=>i.split(" ").map(a=>St(a,{nested:!1,quoted:!1,context:"table"})))}};var Wd=e=>({type:"title",text:e.rows[0].text});var Gd=e=>{switch(e.type){case"title":return Wd(e);case"codeBlock":return wd(e);case"table":return Hd(e);case"line":return Bd(e)}};var kt=(e,t)=>{let r=bd(e);return xd(r,{hasTitle:t?.hasTitle??!0}).map(Gd)},qd=e=>/^\s*\S.*$/m.exec(e)?.[0]?.trim()??"Untitled";var x_=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,b_=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,w_=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,E_=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,ia=e=>{if(x_.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(b_);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"dotbe"}}}{let t=e.match(w_);if(t){let[,r,o]=t;return{videoId:r,params:new URLSearchParams(o),pathType:"short"}}}{let t=e.match(E_);if(t){let[,r,o]=t;return{listId:o,params:new URLSearchParams(r),pathType:"list"}}}};var Kd=e=>{let t=kt(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(se(x.href)))return;o.set(se(x.href),!1),n.push(x.href);return;case"link":switch(x.pathType){case"relative":{let E=Vd(x.href);if(o.get(se(E)))return;o.set(se(E),!0),n.push(E);return}case"root":{let E=Vd(x.href);if(/^\/[\w\d-]+\/?$/.test(E)||s.has(se(E)))return;s.add(se(E)),i.push(E);return}case"absolute":{if(x.content)return;let E=ia(x.href);if(E&&E.pathType!=="list"){l??=https://i.ytimg.com/vi/${E.videoId}/mqdefault.jpg;return}let v=x.href.match(m)?.[1];v&&p.add(v);return}default:return}case"icon":case"strongIcon":{if(x.pathType==="root"||a.has(se(x.path)))return;a.add(se(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 E=x.src.match(m)?.[1];E&&p.add(E)}if(x.type==="image"){let E=x.link.match(m)?.[1];E&&p.add(E)}return}case"helpfeel":f.add(x.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let E of x.nodes)h(E);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"?zd(x.nodes[0].raw):x.nodes.map(E=>E.raw).join("").trim().slice(0,200));for(let E of x.nodes)h(E);continue;case"codeBlock":u.length<5&&u.push(zd(x.content));continue;case"table":{for(let E of x.cells)for(let v of E)for(let b of v)h(b);if(!["infobox","cosense"].includes(x.fileName))continue;g.push(...x.cells.map(E=>E.map(v=>v.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,E)=>x+[...E].length,0)]},zd=e=>\${e.trim().replaceAll("","\\").slice(0,198)}\`,Vd=e=>e.replace(/#a-f\d{24,32}$/,"");var co=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));var Yd=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?t.trimStart().slice(2):[]);function*Xd(e,t,r){let o=t.flatMap(g=>(Ce(g)?g:g.text).split(`
));for(let g of gp(e.lines,o,{userId:r}))yield g;let[n,s,i,a,c,l,u,p,f,m,h]=Kd(o.join(
));(e.title!==n||!e.persistent)&&(yield{title:n}),co(e.links,s)||(yield{links:s}),co(e.projectLinks,i)||(yield{projectLinks:i}),co(e.icons,a)||(yield{icons:a}),e.image!==c&&(yield{image:c}),co(e.descriptions,l)||(yield{descriptions:l}),co(e.files,u)||(yield{files:u}),co(Yd(e.lines),p)||(yield{helpfeels:p}),co(e.infoboxDefinition,f)||(yield{infoboxDefinition:f}),yield{linesCount:m},yield{charsCount:h}}var Jd=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,o=t?.[2]?parseInt(t[2])+1:2;return${r}_${o}};var Qd=()=>Number.MAX_SAFE_INTEGER-Math.floor(Date.now()/1e3);var Me=(e,t,r,o)=>Mo(e,t,async(n,s,i,a)=>{if(a==="DuplicateTitleError"){let m=Jd(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?[]:[...Xd(n,u,n.userId)];return p!==void 0&&(p&&n.pin===0||!p&&n.pin>0)&&f.push({pin:p?Qd():0}),f},o);var Zd=(e,t,r)=>Mo(e,t,o=>o.persistent?[{deleted:!0}]:[],r);var aa=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i}=me(o??{}),a=await Tr(o);if(W(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":J(a),...n?{Cookie:be(n)}:{}},body:JSON.stringify({from:t,to:r})}),l=await i(c);return W(l)?l:Te(await Oe(_e(J(l)),async u=>await He(u,["NotFoundError","NotLoggedInError","NotMemberError"])??u),async u=>{let{message:p}=await u.json();return parseInt(p.match(/\d+/)?.[0]??"0")})};var eh=(e,t)=>{let{sid:r,hostName:o,followingId:n}=me(t??{});return new Request(https://${o}/api/pages/${e}/search/titles${n??followingId=${n}:""},r?{headers:{Cookie:be(r)}}:void 0)},th=async e=>Te(await Oe(_e(e),async t=>t.response.status===422?{name:"InvalidFollowingIdError",message:await t.response.text()}:await He(t,["NotFoundError","NotLoggedInError"])??t),t=>t.json().then(r=>({pages:r,followingId:t.headers.get("X-following-id")??""}))),R_=(()=>{let e=async(t,r)=>{let o=await me(r??{}).fetch(eh(t,r));return W(o)?o:th(J(o))};return e.toRequest=eh,e.fromResponse=th,e})();async function*rh(e,t){let r;do{let o=await R_(e,{followingId:r,...t});if(W(o)){yield o;return}let n=J(o);yield oe(n.pages),r=n.followingId}while(r)}var oh=async(e,t,r)=>{let{sid:o,hostName:n,fetch:s}=me(r??{}),i=new Request(https://${n}/api/pages/${t}/search/query?q=${encodeURIComponent(e)},o?{headers:{Cookie:be(o)}}:void 0),a=await s(i);return W(a)?a:Te(await Oe(_e(J(a)),async c=>await He(c,["NotFoundError","NotLoggedInError","NotMemberError","NoQueryError"])??c),c=>c.json())};var nh=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=me(t??{}),s=await Tr(t);if(W(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":J(s),...r?{Cookie:be(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return W(a)?a:Te(await Oe(_e(J(a)),async c=>await He(c,["SessionError","BadRequestError","InvalidURLError"])??c),async c=>{let{title:l}=await c.json();return l})};var sh=async(e,t)=>{let{sid:r,hostName:o,fetch:n}=me(t??{}),s=await Tr(t);if(W(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":J(s),...r?{Cookie:be(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await n(i);return W(a)?a:Oe(await Te(_e(J(a)),c=>c.json()),async c=>c.response.status===422?{name:"InvalidURLError",message:(await c.response.json()).message}:await He(c,["SessionError","BadRequestError"])??c)};var ih=async e=>{let{fetch:t,sid:r,hostName:o,gyazoTeamsName:n}=me(e??{}),s=new Request(https://${o}/api/login/gyazo/oauth-upload/token${n??gyazoTeamsName=${n}:""},r?{headers:{Cookie:be(r)}}:void 0),i=await t(s);return W(i)?i:Te(await Oe(_e(J(i)),async a=>await He(a,["NotLoggedInError"])??a),a=>a.json().then(c=>c.token))};var ah=(e,t,r,o)=>{let{sid:n,hostName:s}=me(o??{});return new Request(https://${s}/api/code/${e}/${ge(t)}/${ge(r)},n?{headers:{Cookie:be(n)}}:void 0)},ch=async e=>Te(await Oe(_e(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 He(t,["NotLoggedInError","NotMemberError"])??t),t=>t.text()),ca=(()=>{let e=async(t,r,o,n)=>{let s=ah(t,r,o,n),i=await me(n??{}).fetch(s);return W(i)?i:ch(J(i))};return e.toRequest=ah,e.fromResponse=ch,e})();var uh=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(yp),n=0,s=0,i=0;[r,o,n,s,i]=ph(r,o,n,s,i,t);let a=yp-n;a<9&&(a+=yp);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]=ph(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},yp=64,H=(e,t)=>e<<t|e>>>32-t,vt=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24,lh=(e,t)=>{let[r,o,n,s]=e,i=vt(t,0),a=vt(t,4),c=vt(t,8),l=vt(t,12),u=vt(t,16),p=vt(t,20),f=vt(t,24),m=vt(t,28),h=vt(t,32),g=vt(t,36),y=vt(t,40),x=vt(t,44),E=vt(t,48),v=vt(t,52),b=vt(t,56),T=vt(t,60);return r=o+H(((n^s)&o^s)+r+i+3614090360,7),s=r+H(((o^n)&r^n)+s+a+3905402710,12),n=s+H(((r^o)&s^o)+n+c+606105819,17),o=n+H(((s^r)&n^r)+o+l+3250441966,22),r=o+H(((n^s)&o^s)+r+u+4118548399,7),s=r+H(((o^n)&r^n)+s+p+1200080426,12),n=s+H(((r^o)&s^o)+n+f+2821735955,17),o=n+H(((s^r)&n^r)+o+m+4249261313,22),r=o+H(((n^s)&o^s)+r+h+1770035416,7),s=r+H(((o^n)&r^n)+s+g+2336552879,12),n=s+H(((r^o)&s^o)+n+y+4294925233,17),o=n+H(((s^r)&n^r)+o+x+2304563134,22),r=o+H(((n^s)&o^s)+r+E+1804603682,7),s=r+H(((o^n)&r^n)+s+v+4254626195,12),n=s+H(((r^o)&s^o)+n+b+2792965006,17),o=n+H(((s^r)&n^r)+o+T+1236535329,22),r=o+H(((o^n)&s^n)+r+a+4129170786,5),s=r+H(((r^o)&n^o)+s+f+3225465664,9),n=s+H(((s^r)&o^r)+n+x+643717713,14),o=n+H(((n^s)&r^s)+o+i+3921069994,20),r=o+H(((o^n)&s^n)+r+p+3593408605,5),s=r+H(((r^o)&n^o)+s+y+38016083,9),n=s+H(((s^r)&o^r)+n+T+3634488961,14),o=n+H(((n^s)&r^s)+o+u+3889429448,20),r=o+H(((o^n)&s^n)+r+g+568446438,5),s=r+H(((r^o)&n^o)+s+b+3275163606,9),n=s+H(((s^r)&o^r)+n+l+4107603335,14),o=n+H(((n^s)&r^s)+o+h+1163531501,20),r=o+H(((o^n)&s^n)+r+v+2850285829,5),s=r+H(((r^o)&n^o)+s+c+4243563512,9),n=s+H(((s^r)&o^r)+n+m+1735328473,14),o=n+H(((n^s)&r^s)+o+E+2368359562,20),r=o+H((o^n^s)+r+p+4294588738,4),s=r+H((r^o^n)+s+h+2272392833,11),n=s+H((s^r^o)+n+x+1839030562,16),o=n+H((n^s^r)+o+b+4259657740,23),r=o+H((o^n^s)+r+a+2763975236,4),s=r+H((r^o^n)+s+u+1272893353,11),n=s+H((s^r^o)+n+m+4139469664,16),o=n+H((n^s^r)+o+y+3200236656,23),r=o+H((o^n^s)+r+v+681279174,4),s=r+H((r^o^n)+s+i+3936430074,11),n=s+H((s^r^o)+n+l+3572445317,16),o=n+H((n^s^r)+o+f+76029189,23),r=o+H((o^n^s)+r+g+3654602809,4),s=r+H((r^o^n)+s+E+3873151461,11),n=s+H((s^r^o)+n+T+530742520,16),o=n+H((n^s^r)+o+c+3299628645,23),r=o+H((n^(o|~s))+r+i+4096336452,6),s=r+H((o^(r|~n))+s+m+1126891415,10),n=s+H((r^(s|~o))+n+b+2878612391,15),o=n+H((s^(n|~r))+o+p+4237533241,21),r=o+H((n^(o|~s))+r+E+1700485571,6),s=r+H((o^(r|~n))+s+l+2399980690,10),n=s+H((r^(s|~o))+n+y+4293915773,15),o=n+H((s^(n|~r))+o+a+2240044497,21),r=o+H((n^(o|~s))+r+h+1873313359,6),s=r+H((o^(r|~n))+s+T+4264355552,10),n=s+H((r^(s|~o))+n+f+2734768916,15),o=n+H((s^(n|~r))+o+v+1309151649,21),r=o+H((n^(o|~s))+r+u+4149444226,6),s=r+H((o^(r|~n))+s+x+3174756917,10),n=s+H((r^(s|~o))+n+c+718787259,15),o=n+H((s^(n|~r))+o+g+3951481745,21),[e[0]+r>>>0,e[1]+o>>>0,e[2]+n>>>0,e[3]+s>>>0]},ph=(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=lh(e,t);let a=i;for(;a+64<=s.length;)e=lh(e,s.slice(a,a+64)),a+=64;t.fill(0).set(s.slice(a),0),r=s.length-a}return[o,n]=T_(o,n,s.length),[e,t,r,o,n]},T_=(e,t,r)=>(e+=r,e>4294967295&&(t+=1),[e>>>0,t]);var __=new TextEncoder().encode("0123456789abcdef"),mh=new Uint8Array(128).fill(16);__.forEach((e,t)=>mh[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>mh[e]=t+10);function fh(e){return e*2}function dh(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 hh(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 gh=new TextEncoder().encode("0123456789abcdef"),yh=new Uint8Array(128).fill(16);gh.forEach((e,t)=>yh[e]=t);new TextEncoder().encode("ABCDEF").forEach((e,t)=>yh[e]=t+10);function xh(e){typeof e=="string"?e=new TextEncoder().encode(e):e instanceof ArrayBuffer?e=new Uint8Array(e).slice():e=e.slice();let[t,r]=hh(e,fh(e.length));return dh(t,r,0,gh),new TextDecoder().decode(t)}var bh=async(e,t,r)=>{let o=${xh(uh(await e.arrayBuffer()))},n=await P_(e,t,o,r);if(W(n))return n;let s=J(n);if("embedUrl"in s)return oe(s);let i=await O_(s.signedUrl,e,r);return W(i)?i:S_(t,s.fileId,o,r)},P_=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=me(o??{}),c={md5:r,size:e.size,contentType:e.type,name:e.name},l=await Yi(na(a),()=>Tr(o));if(W(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":J(l),...n?{Cookie:be(n)}:{}}}),p=await i(u);return W(p)?p:Te(await Oe(_e(J(p)),async f=>f.response.status===402?{name:"FileCapacityError",message:(await f.response.json()).message}:f),f=>f.json())},O_=async(e,t,r)=>{let{sid:o,fetch:n}=me(r??{}),s=await n(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...o?{Cookie:be(o)}:{}}});return W(s)?s:Co(await Oe(_e(J(s)),async i=>i.response.headers.get("Content-Type")?.includes?.("/xml")?{name:"GCSError",message:await i.response.text()}:i),()=>{})},S_=async(e,t,r,o)=>{let{sid:n,hostName:s,fetch:i,csrf:a}=me(o??{}),c=await Yi(na(a),()=>Tr(o));if(W(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":J(c),...n?{Cookie:be(n)}:{}}}),u=await i(l);return W(u)?u:Te(await Oe(_e(J(u)),async p=>p.response.status===404?{name:"NotFoundError",message:(await p.response.json()).message}:p),p=>p.json())};function Rt(e){return e.val}function Dt(e){return e.err}var wh=" must not return ",N_="transformer",L_="recoverer",C_="defaultValue",la=N_+wh,Ao="called with ",pa=C_+" must not be ",ua=L_+wh;var M_="Ok",Eh="Err",kh=Ao+Eh,vh=Ao+M_,A_="Carrying E in "+Eh+" instead of throwing it directly. See .cause",xp="an instance of Error of the current realm.",h8="The thrown value is not "+xp,g8="The contained E should be "+xp,I_="This .cause is not "+xp;function We(e){return e.ok}function le(e){return{ok:!0,val:e,err:null}}function G(e){return!e.ok}function ee(e){return{ok:!1,val:null,err:e}}function z(e){return Rh(e,kh)}function ne(e){return Th(e,vh)}function Rh(e,t){if(G(e))throw new TypeError(t);return e.val}function Th(e,t){if(We(e))throw new TypeError(t);return e.err}async function Gt(e,t){if(G(e))return e;let r=Rt(e),o=await t(r);return le(o)}function bp(e,t,r){if(We(e)){let n=Rt(e);return r(n)}let o=Dt(e);return t(o)}var ma="null",k5=la+ma,U_=Ao+ma,v5=pa+ma,R5=ua+ma;var fa="undefined",S5=la+fa,$_=Ao+fa,N5=pa+fa,L5=ua+fa;var Ph=async e=>{let t=e.title??".watchlistrc",r="projectsLastAccessed.json",o=await ca(e.project,t,r),n=G(o)?{}:JSON.parse(z(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 Me(e.project,t,()=>[t,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","",code:${r}, ${c},""])};var qt=!1,da=e=>{qt=typeof e=="boolean"?e:new Set(e)},Mn=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},wp,...o)];case"log":case"info":case"debug":return[t,(...o)=>{qt!==!0&&(!qt||!qt.has(e))||r(%c${e},wp,...o)}];case"assert":return[t,(o,...n)=>{qt!==!0&&(!qt||!qt.has(e))||r(o,%c${e},wp,...n)}];case"time":case"timeEnd":return[t,o=>{qt!==!0&&(!qt||!qt.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(qt!==!0&&(!qt||!qt.has(e))))return r(...o)}]}})),wp="color: gray";var Hr=globalThis.scrapbox;var ha=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}};var Oh=e=>{let{accessToken:t,fetch:r,page:o,per:n}=ha(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 An="Gyazo Viewer",Sh=e=>{let t=Promise.resolve(),r=globalThis.GM_fetch;Hr.PageMenu.addMenu({title:r?An:"Open Gyazo",icon:"kamon kamon-gyazo",onClick:r?()=>{t=t.then(()=>B_({per:e.maxCount??10,accessToken:e.accessToken,fetch:r,onClick:e.onClick}))}:()=>globalThis.open("https://gyazo.com/captures")})},B_=async e=>{let t;try{let r=Oh({page:0,...e});t=setTimeout(()=>{Hr.PageMenu(An).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),Hr.PageMenu(An).removeAllItems();for(let s of n)s.image_id&&Hr.PageMenu(An).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),Hr.PageMenu(An).removeAllItems(),Hr.PageMenu(An).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 u$}from"https://scrapbox.io/api/code/takker-memex/GYAZO_ACCESS_TOKEN/auth.js";var ba,te,Mh,H_,Io,Nh,Ah,Ih,Fh,Tp,Ep,kp,Dh,Ss={},Uh=[],W_=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ns=Array.isArray;function Wr(e,t){for(var r in t)e[r]=t[r];return e}function _p(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Gr(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?ba.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 ya(e,i,o,n,null)}function ya(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??++Mh,__i:-1,__u:0};return n==null&&te.vnode!=null&&te.vnode(s),s}function Q(e){return e.children}function fr(e,t){this.props=e,this.context=t}function In(e,t){if(t==null)return e.__?In(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"?In(e):null}function $h(e){var t,r;if((e=e.__)!=null&&e.__c!=null){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if((r=e.__k[t])!=null&&r.__e!=null){e.__e=e.__c.base=r.__e;break}return $h(e)}}function vp(e){(!e.__d&&(e.__d=!0)&&Io.push(e)&&!xa.__r++||Nh!=te.debounceRendering)&&((Nh=te.debounceRendering)||Ah)(xa)}function xa(){for(var e,t,r,o,n,s,i,a=1;Io.length;)Io.length>a&&Io.sort(Ih),e=Io.shift(),a=Io.length,e.__d&&(r=void 0,n=(o=(t=e).__v).__e,s=[],i=[],t.__P&&((r=Wr({},o)).__v=o.__v+1,te.vnode&&te.vnode(r),Pp(t.__P,r,o,t.__n,t.__P.namespaceURI,32&o.__u?[n]:null,s,n??In(o),!!(32&o.__u),i),r.__v=o.__v,r.__.__k[r.__i]=r,Hh(s,r,i),r.__e!=n&&$h(r)));xa.__r=0}function jh(e,t,r,o,n,s,i,a,c,l,u){var p,f,m,h,g,y,x,E=o&&o.__k||Uh,v=t.length;for(c=G_(r,t,E,c,v),p=0;p<v;p++)(m=r.__k[p])!=null&&(f=m.__i==-1?Ss:E[m.__i]||Ss,m.__i=p,y=Pp(e,m,f,n,s,i,a,c,l,u),h=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&Op(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=Bh(m,c,e,x):typeof m.type=="function"&&y!==void 0?c=y:h&&(c=h.nextSibling),m.__u&=-7);return r.__e=g,c}function G_(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"?(c=s+f,(i=e.__k[s]=typeof i=="string"||typeof i=="number"||typeof i=="bigint"||i.constructor==String?ya(null,i,null,null,null):Ns(i)?ya(Q,{children:i},null,null,null):i.constructor==null&&i.__b>0?ya(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):i).__=e,i.__b=e.__b+1,a=null,(l=i.__i=q_(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=In(a)),Gh(a,a));return o}function Bh(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=Bh(n[s],t,r,o));return t}e.__e!=t&&(o&&(t&&e.type&&!t.parentNode&&(t=In(e)),r.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function lo(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ns(e)?e.some(function(r){lo(r,t)}):t.push(e)),t}function q_(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&&e.key==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 Lh(e,t,r){t[0]=="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||W_.test(t)?r:r+"px"}function ga(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||Lh(e.style,t,"");if(r)for(t in r)o&&r[t]==o[t]||Lh(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")s=t!=(t=t.replace(Fh,"$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.u=o.u:(r.u=Tp,e.addEventListener(t,s?kp:Ep,s)):e.removeEventListener(t,s?kp:Ep,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 Ch(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t.t==null)t.t=Tp++;else if(t.t<r.u)return;return r(te.event?te.event(t):t)}}}function Pp(e,t,r,o,n,s,i,a,c,l){var u,p,f,m,h,g,y,x,E,v,b,T,R,L,C,M,O,_=t.type;if(t.constructor!=null)return null;128&r.__u&&(c=!!(32&r.__u),s=[a=t.__e=r.__e]),(u=te.__b)&&u(t);e:if(typeof _=="function")try{if(x=t.props,E="prototype"in _&&_.prototype.render,v=(u=_.contextType)&&o[u.__c],b=u?v?v.props.value:u.__:o,r.__c?y=(p=t.__c=r.__c).__=p.__E:(E?t.__c=p=new _(x,b):(t.__c=p=new fr(x,b),p.constructor=_,p.render=V_),v&&v.sub(p),p.props=x,p.state||(p.state={}),p.context=b,p.__n=o,f=p.__d=!0,p.__h=[],p._sb=[]),E&&p.__s==null&&(p.__s=p.state),E&&_.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Wr({},p.__s)),Wr(p.__s,_.getDerivedStateFromProps(x,p.__s))),m=p.props,h=p.state,p.__v=t,f)E&&_.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),E&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(E&&_.getDerivedStateFromProps==null&&x!==m&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(x,b),!p.__e&&p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(x,p.__s,b)===!1||t.__v==r.__v){for(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(P){P&&(P.__=t)}),T=0;T<p._sb.length;T++)p.__h.push(p._sb[T]);p._sb=[],p.__h.length&&i.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(x,p.__s,b),E&&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,R=te.__r,L=0,E){for(p.state=p.__s,p.__d=!1,R&&R(t),u=p.render(p.props,p.state,p.context),C=0;C<p._sb.length;C++)p.__h.push(p._sb[C]);p._sb=[]}else do p.__d=!1,R&&R(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++L<25);p.state=p.__s,p.getChildContext!=null&&(o=Wr(Wr({},o),p.getChildContext())),E&&!f&&p.getSnapshotBeforeUpdate!=null&&(g=p.getSnapshotBeforeUpdate(m,h)),M=u,u!=null&&u.type===Q&&u.key==null&&(M=Wh(u.props.children)),a=jh(e,Ns(M)?M:[M],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(P){if(t.__v=null,c||s!=null)if(P.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(O=s.length;O--;)_p(s[O]);Rp(t)}else t.__e=r.__e,t.__k=r.__k,P.then||Rp(t);te.__e(P,t,r)}else s==null&&t.__v==r.__v?(t.__k=r.__k,t.__e=r.__e):a=t.__e=z_(r.__e,t,r,o,n,s,i,c,l);return(u=te.diffed)&&u(t),128&t.__u?void 0:a}function Rp(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(Rp)}function Hh(e,t,r){for(var o=0;o<r.length;o++)Op(r[o],r[++o],r[++o]);te.__c&&te.__c(t,e),e.some(function(n){try{e=n.__h,n.__h=[],e.some(function(s){s.call(n)})}catch(s){te.__e(s,n.__v)}})}function Wh(e){return typeof e!="object"||e==null||e.__b&&e.__b>0?e:Ns(e)?e.map(Wh):Wr({},e)}function z_(e,t,r,o,n,s,i,a,c){var l,u,p,f,m,h,g,y=r.props,x=t.props,E=t.type;if(E=="svg"?n="http://www.w3.org/2000/svg":E=="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==!!E&&(E?m.localName==E:m.nodeType==3)){e=m,s[l]=null;break}}if(e==null){if(E==null)return document.createTextNode(x);e=document.createElementNS(n,E,x.is&&x),a&&(te.__m&&te.__m(t,s),a=!1),s=null}if(E==null)y===x||a&&e.data==x||(e.data=x);else{if(s=s&&ba.call(e.childNodes),y=r.props||Ss,!a&&s!=null)for(y={},l=0;l<e.attributes.length;l++)y[(m=e.attributes[l]).name]=m.value;for(l in y)if(m=y[l],l!="children"){if(l=="dangerouslySetInnerHTML")p=m;else if(!(l in x)){if(l=="value"&&"defaultValue"in x||l=="checked"&&"defaultChecked"in x)continue;ga(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||ga(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=""),jh(t.type=="template"?e.content:e,Ns(f)?f:[f],t,r,o,E=="foreignObject"?"http://www.w3.org/1999/xhtml":n,s,i,s?s[0]:r.__k&&In(r,0),a,c),s!=null)for(l=s.length;l--;)_p(s[l]);a||(l="value",E=="progress"&&h==null?e.removeAttribute("value"):h!=null&&(h!==e[l]||E=="progress"&&!h||E=="option"&&h!=y[l])&&ga(e,l,h,y[l],n),l="checked",g!=null&&g!=e[l]&&ga(e,l,g,y[l],n))}return e}function Op(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){te.__e(n,r)}}function Gh(e,t,r){var o,n;if(te.unmount&&te.unmount(e),(o=e.ref)&&(o.current&&o.current!=e.__e||Op(o,null,t)),(o=e.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(s){te.__e(s,t)}o.base=o.__P=null}if(o=e.__k)for(n=0;n<o.length;n++)o[n]&&Gh(o[n],t,r||typeof e.type!="function");r||_p(e.__e),e.__c=e.__=e.__e=void 0}function V_(e,t,r){return this.constructor(e,r)}function ft(e,t,r){var o,n,s,i;t==document&&(t=document.documentElement),te.__&&te.__(e,t),n=(o=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],Pp(t,e=(!o&&r||t).__k=Gr(Q,null,[e]),n||Ss,Ss,t.namespaceURI,!o&&r?[r]:n?null:t.firstChild?ba.call(t.childNodes):null,s,!o&&r?r:n?n.__e:t.firstChild,o,i),Hh(s,e,i)}function Ls(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,vp(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"+Dh++,t.__=e,t.Provider=t.__l=(t.Consumer=function(r,o){return r.children(o)}).contextType=t,t}ba=Uh.slice,te={__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}},Mh=0,H_=function(e){return e!=null&&e.constructor==null},fr.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Wr({},this.state),typeof e=="function"&&(e=e(Wr({},r),this.props)),e&&Wr(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),vp(this))},fr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),vp(this))},fr.prototype.render=Q,Io=[],Ah=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ih=function(e,t){return e.__v.__b-t.__v.__b},xa.__r=0,Fh=/(PointerCapture)$|Capture$/i,Tp=0,Ep=Ch(!1),kp=Ch(!0),Dh=0;var Fo,Fe,Sp,qh,Cs=0,Zh=[],Ve=te,zh=Ve.__b,Vh=Ve.__r,Kh=Ve.diffed,Yh=Ve.__c,Xh=Ve.unmount,Jh=Ve.__;function Ms(e,t){Ve.__h&&Ve.__h(Fe,e,Cs||t),Cs=0;var r=Fe.__H||(Fe.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function X(e){return Cs=1,po(eg,e)}function po(e,t,r){var o=Ms(Fo++,2);if(o.t=e,!o.__c&&(o.__=[r?r(t):eg(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=Fe,!Fe.__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.forEach(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};Fe.__f=!0;var s=Fe.shouldComponentUpdate,i=Fe.componentWillUpdate;Fe.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)},Fe.shouldComponentUpdate=n}return o.__N||o.__}function Z(e,t){var r=Ms(Fo++,3);!Ve.__s&&Lp(r.__H,t)&&(r.__=e,r.u=t,Fe.__H.__h.push(r))}function Ea(e,t){var r=Ms(Fo++,4);!Ve.__s&&Lp(r.__H,t)&&(r.__=e,r.u=t,Fe.__h.push(r))}function rt(e){return Cs=5,U(function(){return{current:e}},[])}function U(e,t){var r=Ms(Fo++,7);return Lp(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function A(e,t){return Cs=8,U(function(){return e},t)}function qr(e){var t=Fe.context[e.__c],r=Ms(Fo++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(Fe)),t.props.value):e.__}function K_(){for(var e;e=Zh.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(wa),e.__H.__h.forEach(Np),e.__H.__h=[]}catch(t){e.__H.__h=[],Ve.__e(t,e.__v)}}Ve.__b=function(e){Fe=null,zh&&zh(e)},Ve.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Jh&&Jh(e,t)},Ve.__r=function(e){Vh&&Vh(e),Fo=0;var t=(Fe=e.__c).__H;t&&(Sp===Fe?(t.__h=[],Fe.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})):(t.__h.forEach(wa),t.__h.forEach(Np),t.__h=[],Fo=0)),Sp=Fe},Ve.diffed=function(e){Kh&&Kh(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Zh.push(t)!==1&&qh===Ve.requestAnimationFrame||((qh=Ve.requestAnimationFrame)||Y_)(K_)),t.__H.__.forEach(function(r){r.u&&(r.__H=r.u),r.u=void 0})),Sp=Fe=null},Ve.__c=function(e,t){t.some(function(r){try{r.__h.forEach(wa),r.__h=r.__h.filter(function(o){return!o.__||Np(o)})}catch(o){t.some(function(n){n.__h&&(n.__h=[])}),t=[],Ve.__e(o,r.__v)}}),Yh&&Yh(e,t)},Ve.unmount=function(e){Xh&&Xh(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(o){try{wa(o)}catch(n){t=n}}),r.__H=void 0,t&&Ve.__e(t,r.__v))};var Qh=typeof requestAnimationFrame=="function";function Y_(e){var t,r=function(){clearTimeout(o),Qh&&cancelAnimationFrame(t),setTimeout(e)},o=setTimeout(r,35);Qh&&(t=requestAnimationFrame(r))}function wa(e){var t=Fe,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),Fe=t}function Np(e){var t=Fe;e.__c=e.__(),Fe=t}function Lp(e,t){return!e||e.length!==t.length||t.some(function(r,o){return r!==e[o]})}function eg(e,t){return typeof t=="function"?t(e):t}function Ue(e){return typeof e=="number"}var X_=(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}},J_=X_,Cp=class e extends Error{constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,e),this.name=this.constructor.name}};function tg(e,t,r={}){if(!t(e))throw new Cp(r.message??J_(e,t,r.name))}function Mp(e,t,r={}){return tg(e,t,r),e}function dt(e){return typeof e>"u"}var ka=!1,rg=null,og=()=>{scrapbox.addListener("lines:changed",()=>ka=!1),scrapbox.addListener("layout:changed",()=>ka=!1),og=void 0},ng=()=>(og?.(),ka||(rg=scrapbox.Page.lines,ka=!0),rg);var sg=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var ig=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var ag=()=>va(document.getElementById("editor"),"div#editor"),As=()=>va(document.getElementsByClassName("lines").item(0),"div.lines");var ot=()=>{let e=document.getElementById("text-input");if(e)return ig(e,"textarea#text-input"),e};var cg=()=>va(document.getElementsByClassName("popup-menu")?.[0],"div.popup-menu");var lg=()=>va(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),va=(e,t)=>{if(e)return sg(e,t),e};var Ut=()=>{let e=As();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 zr=e=>e.match(/^(\s*)/)?.[1]?.length??0,Do=(e,t)=>{let r=zr(pg(e,t)),o=0;for(;e+o+1<t.length&&zr(pg(e+o+1,t))>r;)o++;return o},pg=(e,t)=>{let r=t[e];return Ce(r)?r:r.text};var Ap=e=>{if(dt(e))return;if(Ue(e))return Ra(e)?.id;if(Ce(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)},ug=e=>{if(dt(e))return;if(Ue(e))return e;let t=Ap(e);return t?Ut().findIndex(r=>r.id===t):-1};var Ra=e=>{if(dt(e))return;if(Ue(e))return Ut()[e];let t=Ap(e);return t?Ut().find(r=>r.id===t):void 0},Uo=e=>{if(mg(e))return e;let t=Ap(e);if(dt(t))return t;let r=document.getElementById(L${t});if(!dt(r))return r},mg=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var Pr=()=>Mp(ng(),ur),nt=e=>{if(dt(e))return;if(Ue(e)||Ce(e))return Ra(e)?.text;if(!(e instanceof HTMLElement))return;if(mg(e))return Ra(e)?.text;if(e.classList.contains("char-index"))return e.textContent??void 0;if(e.classList.contains("line")||e.getElementsByClassName("lines")?.[0])return Ut().map(({text:o})=>o).join(
);let t=[],r=Ra(e);if(!dt(r)){for(let o of Z_(e))t.push(eP(o));return r.text.slice(Math.min(...t),Math.max(...t)+1)}};var fg=()=>{let e=As()?.firstElementChild;if(!dt(e))return e},dg=()=>{let e=As()?.lastElementChild;if(!dt(e))return e};var Ip=e=>{let t=ug(e);if(!dt(t))return Do(t,Pr())};function*Z_(e){let t=e.getElementsByClassName("char-index");for(let r=0;r<t.length;r++)yield t[0]}var Fp=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index"),eP=e=>{if(!Fp(e))throw Error("A char DOM is required.");let t=e.className.match(/c-(\d+)/)?.[1];if(dt(t))throw Error('.char-index must have ".c-{\\d}"');return parseInt(t)},hg=e=>{let t=e?.getElementsByClassName?.("c-0")?.[0];return Fp(t)?t:void 0};var Is=(e,t)=>{let r=Uo(e)?.getElementsByClassName?.(c-${t})?.[0];return Fp(r)?r:void 0};var ht=(e,t)=>{let{noModifiedKeys:r=!1,...o}=t??{},n={bubbles:!0,cancelable:!0,keyCode:tP[e],...r?{}:{...o}},s=ot();if(!s)throw Error("#text-input must exist.");s.dispatchEvent(new KeyboardEvent("keydown",n)),s.dispatchEvent(new KeyboardEvent("keyup",n))},tP={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 Dp=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 De(10)};var Ge=()=>{let e=ot();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 Up=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=globalThis.innerHeight};function Tt(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 gg=()=>{ht("Home"),ht("Home")};var yg=async()=>{let e=fg();if(!e)throw Error(".line:first-of-type can't be found.");Up(e)||e.scrollIntoView({block:"center"});let t=hg(e);if(!t)throw Error(".line:first-of-type .c-0 can't be found.");let{left:r,top:o}=t.getBoundingClientRect();await Dp(e,{X:r,Y:o})},xg=async()=>{await wg(dg())},bg=async e=>{await wg(Uo(e))},wg=async e=>{if(!e)throw Error("The target line DOM is failed to find.");Up(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:o}=e.getElementsByClassName("text")0.getBoundingClientRect();await Dp(e,{X:t+1,Y:r+o/2})};var Eg=(e=1)=>{for(let t of Tt(1,e))ht("z",{ctrlKey:!0})},kg=(e=1)=>{for(let t of Tt(1,e))ht("z",{shiftKey:!0,ctrlKey:!0})};var Ta=async(e,t,r)=>{await bg(e),gg();for(let o of Tt(e,t))ht("ArrowDown",{shiftKey:!0});ht("End",{shiftKey:!0}),await Je(r)};var _a=(e=1)=>{for(let t of Tt(1,e))ht("ArrowRight",{ctrlKey:!0})},Pa=(e=1)=>{for(let t of Tt(1,e))ht("ArrowLeft",{ctrlKey:!0})};var Oa=(e=1)=>{for(let t of Tt(1,e))ht("ArrowUp",{ctrlKey:!0})},Sa=(e=1)=>{for(let t of Tt(1,e))ht("ArrowDown",{ctrlKey:!0})},Na=(e=1)=>{for(let t of Tt(1,e))ht("ArrowRight",{altKey:!0})},La=(e=1)=>{for(let t of Tt(1,e))ht("ArrowLeft",{altKey:!0})};var Ca=(e=1)=>{for(let t of Tt(1,e))ht("ArrowUp",{altKey:!0})},Ma=(e=1)=>{for(let t of Tt(1,e))ht("ArrowDown",{altKey:!0})},Je=e=>{let t=ot();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 $e=()=>{let e=lg();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=vg(...r);o&&t.append(o)},dispose:()=>t.remove(),Symbol.dispose:()=>t.remove()}},vg=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":returnoP();case"check-circle":returnnP();case"exclamation-triangle":returnsP();case"text":returnAa(o.text);case"group":{let n=vg(...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},Aa=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},oP=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Aa(e)},nP=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Aa(e)},sP=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Aa(e)};var Fn=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_${se(e.to.title)}]=r,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var iP=(e,t,r)=>{let o=new URL(/${e}/${ge(t)},location.href);if(r?.body&&(o.search=?body=${encodeURIComponent(r.body)}),r?.id&&(o.hash=#${r.id}),r?.context&&Fn({...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()},$p=(e,t,r)=>iP(e,t,{newTab:!1,reload:!1,body:r});var Dn=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}},Ia=async(e,t)=>{let r=t.clone();return await(await caches.open(aP(new Date))).put(e,r)},aP=e=>api-${e.getFullYear()}-${${e.getMonth()+1}.padStart(2,"0")}-${${e.getDate()}.padStart(2,"0")};var Nt=()=>{let e=ot();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 uo=()=>Nt().cursor;var Fa=()=>Nt().selection;var Fs=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),Rg=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 Da=new Map,jp=new Map,Bp=()=>{scrapbox.on("layout:changed",()=>{let e=ot();if(e)for(lett,rof Da)for(leto,nof r)for(let s of n)e.addEventListener(t,o,Rg(s))}),Bp=void 0},Tg=(e,t,r)=>{Bp?.();let o=Da.get(e)??new Map,n=o.get(t)??new Set;if(n.has(Fs(r)))return;if(n.add(Fs(r)),o.set(t,n),Da.set(e,o),typeof r=="object"&&r?.once){let i=jp.get(t)??new Map,a=Fs(r),c=function(u){return Hp(e,t,r),i.delete(a),t.call(this,u)};i.set(a,c),jp.set(t,i);let l=ot();if(!l)return;l.addEventListener(e,c,r)}let s=ot();s&&s.addEventListener(e,t,r)},Hp=(e,t,r)=>{Bp?.();let o=Da.get(e);if(!o)return;let n=o.get(t);if(!n)return;let s=Fs(r);if(n.delete(s),typeof r=="object"&&r?.once){let a=jp.get(t);if(!a)return;let c=a.get(s);if(!c)return;let l=ot();if(!l)return;l.removeEventListener(e,c,r),a.delete(s);return}let i=ot();i&&i.removeEventListener(e,t,r)};var _g={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\[","]":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},cP=new RegExp(${Object.values(_g).join("")},"gu");function Pg(e){return e.replaceAll(cP,t=>_g[t]).replace(/^[0-9a-zA-Z]/,t=>\\x${t.codePointAt(0).toString(16)})}var lP=0,$7=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:--lP,__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 te.vnode&&te.vnode(l),l}var Og=({project:e,title:t,words:r,lines:o,query:n,close:s})=>{let i=A(c=>{Fn({type:"search",query:n,to:{project:e,title:t}}),!(c.metaKey||c.ctrlKey||c.altKey||c.shiftKey)&&s()},[e,t,n,s]),a=U(()=>{let c=new RegExp((${r.map(l=>Pg(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}/${ge(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 Sg=e=>{let[t,r]=X(e),o=A(()=>r(!0),[]),n=A(()=>r(!1),[]),s=A(()=>r(i=>!i),[]);return[t,{open:o,close:n,toggle:s}]};var Ng=(e,t)=>{let[r,o]=X(),[n,s]=X(!1),i=rt(Promise.resolve());return Z(()=>{if(t===""){o(void 0);return}let a=!1;return i.current=(async()=>{if(await i.current,!a){s(!0);try{let c=await oh(t,e);if(a)return;o(Ie(c)?J(c):void 0)}finally{s(!1)}}})(),()=>a=!0},[t,e]),{loading:n,result:r}};var Lg=()=>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 pP=()=>d("i",{className:"spinner"}),Cg=({exportOps:e})=>{let[t,r]=X(""),o=scrapbox.Project.name,{loading:n,result:s}=Ng(o,t),i=A(m=>{r(m.currentTarget.value)},[]),[a,{open:c,close:l,toggle:u}]=Sg(!1),p=rt({open:c,close:l,toggle:u});Z(()=>{Object.assign(p.current,{open:c,close:l,toggle:u})},[]),Z(()=>e(p.current),[e]);let f=A(m=>{m.target instanceof HTMLElement&&m.target.id==="background"&&l()},[]);return d(Q,{children:[d(Lg,{}),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(pP,{}),${s?.pages?.length??0} pages]})]}),s?.pages&&s.pages.length>0&&d("ul",{className:"result",children:s.pages.map(m=>d("li",{children:d(Og,{...m,project:o,query:t,close:l})},m.title))})]})]})};var Mg=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>{ft(d(Cg,{exportOps:r}),t)})};var Ua=(e,t)=>Object.hasOwn(e,t),Ag={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:">"},Ug=e=>{let t=e.toLowerCase();return Ua(Ag,t)?Ag[t]:e},Ig={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:"/","?"},uP=(e,t)=>{if(e.startsWith("Key")){let r=e.slice(3);return t||(r=r.toLowerCase()),r}return Ua(Ig,e)?Iget?1:0:e},Fg={"<":"lt",">":"gt"},mP=/^($|Unidentified$|Process$|Dead$|Alt|Control|Hyper|Meta|Shift|Super|OS)/,Wp=e=>{let t=e.shiftKey,r=e.key||"Unidentified";if(r==="Unidentified"?r=uP(e.code||"",t):(r=Ug(r),r===" "&&(r="Space")),mP.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-"),Ua(Fg,r)&&(r=Fgr),o||r.length>1?<${o}${r}>:r},Dg={a:"altKey",c:"ctrlKey",m:"metaKey",s:"shiftKey"},fP=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:Ug(o)};for(let s of r.split("-").slice(0,-1)){let i=s.toLowerCase();if(!Ua(Dg,i))return{ok:!1,value:{name:"UnknownModifierError",modifier:s,context:e,message:${e}: Unknown modifier: ${s}}};let a=Dgi;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}},$g=e=>{let t=fP(e);return t.ok?{ok:!0,value:Wp(t.value)}:t},jg=e=>e.match(/<^<>\s+>|\s\S|^$/g);var tr=!1;var Bg=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)=>{tr!==!0&&(!tr||!tr.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{tr!==!0&&(!tr||!tr.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{tr!==!0&&(!tr||!tr.has(e))||r(${e} ${o})}];default:returnt,(...o)=>{if(!(tr!==!0&&(!tr||!tr.has(e))))return r(...o)}}}));var $o=Bg("ScrapBindings:mod.ts"),$a=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=Hg(s);if(!a.ok){for(let l of a.value)$o.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 $o.debug("Binded the following commands:",n),this.emitChange(),o}unbind(...t){for(let r of t){let o=Hg(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()),$o.debug("reset the sequence")};handleKeydown=t=>{if(!t.isTrusted)return;let r=Wp(t);if(!r)return;if(clearTimeout(this.timer),t.isComposing){this.backToInitial();return}this.currentSequence+=r,$o.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=()=>{$o.debug(run ${s});try{i(t)}catch(a){$o.error(a)}finally{this.backToInitial()}}}let n=this.filtered.size;if($o.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)}},dP={name:"InvalidSequenceError",message:"cannot parse the sequence"},Hg=e=>{let t=jg(e);if(!t)return{ok:!1,value:dP};let r="",o=[];for(let n of t){let s=$g(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 Wg=()=>{if(scrapbox.Layout!=="page")return{selectionRange:{start:{line:0,char:0},end:{line:0,char:0}},selectedText:""};let{selectionRange:e,selectedText:t,position:r}=Ge();if(!t){let u=Ip(r.line)??0,p={start:{line:r.line,char:0},end:{line:r.line+u,char:nt(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 Gp=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=n.replaceAll("[","").replaceAll("]","").trim(),a=Math.min(...[n,...s].map(l=>zr(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}]}};Gp.hookName="default-hook";var Vr=e=>{let{project:t=scrapbox.Project.name,mode:r="newtab"}=e??{},o=[...e?.hooks??[],Gp],{selectionRange:{start:n,end:s},selectedText:i}=Wg();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:Ut().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}=$e();try{if(p.pages.length>0){let y=p.pages.length;m({type:"spinner"},{type:"text",text:Create new ${y} pages...});let x=await wt(e?.socket);if(G(x))throw ne(x);f=z(x);let E=0;await Promise.all(p.pages.map(async v=>{let b=Array.isArray(v.lines)?T=>[...T.map(R=>R.text),...v.lines]:v.lines;await Me(v.project,v.title,b,{socket:f}),m({type:"spinner"},{type:"text",text:Create ${y-++E} pages...})}))}m({type:"spinner"},{type:"text",text:${p.pages.length>0?"Created. ":""}Removing cut text...});let g=p.text;if(i===g)return;await Me(scrapbox.Project.name,scrapbox.Page.title,y=>{let x=y.map(E=>E.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?$p(y.project,y.title):globalThis.open(https://scrapbox.io/${y.project}/${ge(y.title)},"_self");break;case"newtab":globalThis.open(https://scrapbox.io/${y.project}/${ge(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=De(1e3);f&&await Et(f),await g,h()}};return u.hookName=c,u};var hP=Math.pow(10,8)*24*60*60*1e3,gQ=-hP,jo=6048e5,qp=864e5,Or=6e4,mo=36e5,ja=1e3;var Ba=3600;var zp=Ba*24,gP=zp*7,Gg=zp*365.2425,qg=Gg/12,yP=qg*3,Vp=Symbol.for("constructDateFrom");function S(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Vp in e?e[Vp](t):e instanceof Date?new e.constructor(t):new Date(t)}function w(e,t){return S(t||e,e)}var xP={};function dr(){return xP}function Ae(e,t){let r=dr(),o=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=w(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 hr(e,t){let r=w(e,t?.in);return r.setHours(0,0,0,0),r}function Qe(e,...t){let r=S.bind(null,e||t.find(o=>typeof o=="object"));return t.map(r)}function fo(e,t){let[r,o]=Qe(e,t.start,t.end);return{start:r,end:o}}function Ds(e,t){let{start:r,end:o}=fo(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(S(r,i)),i.setDate(i.getDate()+a),i.setHours(0,0,0,0);return n?c.reverse():c}function st(e,t,r){let[o,n]=Qe(r?.in,e,t);return+hr(o)==+hr(n)}function gr(e,t){let r=e<0?"-":"",o=Math.abs(e).toString().padStart(t,"0");return r+o}var Kp={y(e,t){let r=e.getFullYear(),o=r>0?r:1-r;return gr(t==="yy"?o%100:o,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):gr(r+1,2)},d(e,t){return gr(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 gr(e.getHours()%12||12,t.length)},H(e,t){return gr(e.getHours(),t.length)},m(e,t){return gr(e.getMinutes(),t.length)},s(e,t){return gr(e.getSeconds(),t.length)},S(e,t){let r=t.length,o=e.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return gr(n,t.length)}};function zg(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function $t(e){return!(!zg(e)&&typeof e!="number"||isNaN(+w(e)))}var bP=/(\w)\1*|''|'(''|[^'])+('|$)|./g,wP=/^'([^]*?)'?$/,EP=/''/g,kP=/[a-zA-Z]/;function pe(e,t){let r=w(e);if(!$t(r))throw new RangeError("Invalid time value");let o=t.match(bP);return o?o.map(n=>{if(n==="''")return"'";let s=n[0];if(s==="'")return vP(n);let i=Kp[s];if(i)return i(r,n);if(s.match(kP))throw new RangeError("Format string contains an unescaped latin alphabet character "+s+"");return n}).join(""):""}function vP(e){let t=e.match(wP);return t?t[1].replace(EP,"'"):e}function Pe(e,t,r){let o=w(e,r?.in);return isNaN(t)?S(r?.in||e,NaN):(t&&o.setDate(o.getDate()+t),o)}function jt(e,t,r){return Pe(e,-t,r)}function Us(e,t,r){return S(r?.in||e,+w(e)+t)}function $s(e,t,r){return Us(e,t*1e3,r)}function Bo(e,t,r){return Pe(e,t*7,r)}function js(e,t){return w(e,t?.in).getDate()}function Ho(e,t){let r=w(e,t?.in),o=r.getFullYear(),n=dr(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=S(t?.in||e,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=Ae(i,t),c=S(t?.in||e,0);c.setFullYear(o,0,s),c.setHours(0,0,0,0);let l=Ae(c,t);return+r>=+a?o+1:+r>=+l?o:o-1}var RP={};function TP(){return RP}function Yp(e,t){let r=TP(),o=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=Ho(e,t),s=S(t?.in||e,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),Ae(s,t)}function ho(e,t){let r=w(e,t?.in),o=+Ae(r,t)-+Yp(r,t);return Math.round(o/jo)+1}function Kg(e,t){return w(e,t?.in).getMonth()}function Wo(e,t){return w(e,t?.in).getFullYear()}var Yg=e=>{let t=new Map;for(let r of e){let o=${Wo(r)}-${Kg(r)}-${js(r)},n=t.get(o);n&&n.getTime()>r.getTime()||t.set(o,r)}return[...t.values()]};function Bs(e,t,r){let o=w(e,r?.in);if(isNaN(t))return S(r?.in||e,NaN);if(!t)return o;let n=o.getDate(),s=S(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 Xp(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=w(e,r?.in),p=n||o?Bs(u,n+o*12):u,f=i||s?Pe(p,i+s*7):p,m=c+a*60,h=(l+m*60)*1e3;return S(r?.in||e,+f+h)}function Xg(e,t){let r=w(e,t?.in),o=r.getFullYear(),n=r.getMonth(),s=S(r,0);return s.setFullYear(o,n+1,0),s.setHours(0,0,0,0),s.getDate()}function Jp(e,t,r){let o=w(e,r?.in),n=o.getFullYear(),s=o.getDate(),i=S(r?.in||e,0);i.setFullYear(n,t,15),i.setHours(0,0,0,0);let a=Xg(i);return o.setMonth(t,Math.min(s,a)),o}function Jg(e,t,r){let o=w(e,r?.in);return isNaN(+o)?S(r?.in||e,NaN):(t.year!=null&&o.setFullYear(t.year),t.month!=null&&(o=Jp(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 Qg(e,t){return w(e,t?.in).getMinutes()}function Sr(e,t,r){let o=w(e,r?.in);return o.setTime(o.getTime()+t*Or),o}function Go(e){return t=>{let r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}function Ha(e,t){return+w(e)-+w(t)}function go(e,t,r){let o=Ha(e,t)/Or;return Go(r?.roundingMethod)(o)}function Zg(e,t){return w(e,t?.in).getHours()}function Qp(e,t,r){return Us(e,t*mo,r)}function Wa(e,t){let r=w(e,t?.in);return r.setHours(23,59,59,999),r}function Kr(e){let t=w(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 Yr(e,t,r){let[o,n]=Qe(r?.in,e,t),s=hr(o),i=hr(n),a=+s-Kr(s),c=+i-Kr(i);return Math.round((a-c)/qp)}function ey(e,t,r){return Bo(e,-t,r)}function Ga(e,t,r){let o=w(e,r?.in),n=ho(o,r)-t;return o.setDate(o.getDate()-n*7),w(o,r?.in)}function ty(e,t){let{start:r,end:o}=fo(t?.in,e),n=+r>+o,s=n?Ae(o,t):Ae(r,t),i=n?Ae(r,t):Ae(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(S(r,c)),c=Bo(c,l),c.setHours(15);return n?u.reverse():u}function qa(e,t,r){let[o,n]=Qe(r?.in,e,t),s=o.getFullYear()-n.getFullYear(),i=o.getMonth()-n.getMonth();return s*12+i}function qo(e,t){let r=+w(e)-+w(t);return r<0?-1:r>0?1:r}function zo(e,t){return+w(e)>+w(t)}var ry=e=>e==null,yo=e=>typeof e=="string";async function*oy(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 it=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 Un=e=>e.record?.start??e.plan?.start??e.base,ny=e=>e.record?.end??(ry(e.plan?.duration)?e.base:$s(Un(e),e.plan.duration));var ke=({title:e,base:t,plan:r,record:o})=>["",pe(t,"yyyy-MM-dd")," ",r?.start?pe(r.start,"HH:mm"):" ".repeat(5)," ",r?.duration?${r.duration/60}.padStart(4,"0"):" ".repeat(4)," ",o?.start?pe(o?.start,"HH:mm:ss"):" ".repeat(8)," ",o?.end?pe(o?.end,"HH:mm:ss"):" ".repeat(8),"",e].join("");function*sy(e){for(let t of Vo(e))yo(t)||(yield t)}function*Vo(e){for(let t=0;t<e.length;t++){let r=e[t],o=yo(r)?r:r.text,n=Do(t,e),s=it(o);if(!s){yield o;continue}yield{...s,lines:e.slice(t+1,t+1+n).map(i=>yo(i)?i:i.text)},t+=n}}var _P=5*60,Hs=async()=>{let e=Ge().position.line,t=it(nt(e)??""),r=t?.base??new Date,o={start:t?.plan?.start?$s(t.plan.start,_P+(t.plan.duration??0)):void 0,duration:t?.plan?.duration};scrapbox.Page.insertLine(ke({title:"",base:r,plan:o,record:{}}),e+1),await scrapbox.Page.waitForSave()};var Ko=async()=>{let e=Ge().position.line,t=it(nt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;o||(scrapbox.Page.updateLine(ke({record:{start:r?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var Xr=async()=>{let e=Ge().position.line,t=it(nt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;r&&(scrapbox.Page.updateLine(ke({record:{start:r,end:o?void 0:new Date},...n}),e),await scrapbox.Page.waitForSave())};var Zp=async()=>{let e=Ge().position.line,t=it(nt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(!r){await Ko();return}if(!o){await Xr();return}scrapbox.Page.updateLine(ke({record:{},...n}),e),await scrapbox.Page.waitForSave()};var Ws=async()=>{let e=Ge().position.line,t=it(nt(e)??"");if(!t)return;let{record:{start:r,end:o},...n}=t;if(r){if(o)return;await Xr();return}if(o)return;let s;for(let{text:a}of Pr().slice(0,(e??0)+1).reverse()){let{record:c}=it(a)??{};if(c?.end){s=c.end;break}}let i=new Date;scrapbox.Page.updateLine(ke({record:{start:s??i,end:i},...n}),e),await scrapbox.Page.waitForSave()};var Yo=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=Ge();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var eu=(e,t=7)=>new Date((e+2592e3*((t+1)**1.5-1)/5221.154823442138)*1e3);var tu=(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 PP){let l=n.match(a);if(!l)continue;let u=c(l),p=u.isDuration?Xp(t,u):Jg(t,u);return s==="s"?{name:o.trimEnd(),start:p,...r!==void 0?{duration:parseInt(r)*60}:{}}:{name:o.trimEnd(),start:eu(t.getTime()/1e3,(p.getTime()-t.getTime())/(24*60*60*1e3)),...r!==void 0?{duration:parseInt(r)*60}:{}}}},PP=[{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 Xo=async()=>{let e=new Date,[t,r]=Yo(),o=Pr().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}=tu(i,e)??{};return!a||!c&&!l?s:[ke({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 za=async(e,t,r)=>{let o=[];for(let n=e;n<=t;n++){let s=nt(n)??"",i=it(s);if(!i){o.push(s);continue}o.push(ke(r(i,n)))}for(let n=e;n<=t;n++)scrapbox.Page.updateLine(o[n-e],n);await scrapbox.Page.waitForSave()};var Gs=async(e=1)=>{let[t,r]=Yo();await za(t,r,o=>(o.base=Pe(o.base,e),o))};var qs=async()=>{let[e,t]=Yo(),r=new Date;await za(e,t,o=>(st(o.base,r)||(o.base=r),o))};var OP="日刊記録sheet",SP=/日刊記録sheet (\d{4})-(\d{2})-(\d{2})/,zs=["[** 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 ru=e=>{let t=e.match(SP);if(!t)return;let[,r,o,n]=t,s=new Date(parseInt(r),parseInt(o)-1,parseInt(n));return $t(s)?s:void 0},yr=e=>pe(e,'${OP}' yyyy-MM-dd),Jo=e=>{let t=ru(e[0]);if(!t)return e;let r=NP(t),o=[],n=[];for(let a of Vo(e.slice(1))){if(typeof a=="string"){if(zs.includes(a)||r!==""&&r===a)continue;n.push(a);continue}o.push(a)}let s=o.sort((a,c)=>qo(Un(a),Un(c)));if(s.length===0)return[e[0],r,...zs,...n];let i=[0,0,0,0,0,0,0,0];for(let a=1;a<zs.length;a++){let c=Qp(new Date(t.getFullYear(),t.getMonth(),t.getDate()),3*a),l=s.findIndex(m=>zo(Un(m),c));if(l<0){i[a]=-1;continue}if(l===0)continue;let u=s[l-1],p=Un(u),f=ny(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?[zs[u]]:[]),ke(a),...a.lines]),...i.flatMap((a,c)=>a===-1?[zs[c]]:[]),...n]},NP=e=>yesterday: ${yr(jt(e,1))};var Vs=async(e,t)=>{let r=()=>{},o=setTimeout(()=>{let{render:n,dispose:s}=$e();r=s,n({type:"spinner"},{type:"text",text:"formatting..."})},500);await Me(e,t,n=>Jo(n.map(s=>s.text))),clearTimeout(o),r()};async function*ou(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++)st(o[c].base,i)&&(a.push(...o.splice(c,1)),c--);n.push((async()=>(await Me(e,yr(i),c=>Jo([...c.map(l=>l.text),...a.flatMap(l=>[ke(l),...l.lines??[]])]),r),{date:i,size:a.length}))())}yield*oy(n)}var Qo=async({from:{project:e,title:t},to:r})=>{let o=await er(e,t);if(G(o))throw ne(o);let n=ru(t),{lines:s}=z(o),i=[];for(let p of sy(s))n&&st(p.base,n)||i.push(p);let{render:a,dispose:c}=$e();a({type:"spinner"},{type:"text",text:copying ${i.length} tasks...});let l=await wt();if(G(l))throw ne(l);let u=z(l);try{let p=0,f=!1;for await(let m of ou(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 Me(e,t,m=>{let h=[];for(let g of Vo(m)){if(yo(g)){h.push(g);continue}n&&st(g.base,n)&&h.push(ke(g),...g.lines)}return h},{socket:u}),a({type:"check-circle"},{type:"text",text:"Moved"})}finally{await Et(u),await De(1e3),c()}};var Va=e=>e.match(/^(\s*)/)?.[1]?.length??0;var xr=e=>${e}.padStart(2,"0");var Zo=e=>"hours"in e,rr=(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,Nr=e=>${${e.year}.padStart(4,"0")}-${xr(e.month)}-${xr(e.date)}${"hours"in e?T${xr(e.hours)}:${xr(e.minutes)}:""},we=e=>{let t=Nr(e);return new Date(t.includes("T")?t:${t}T00:00)},Lt=e=>({year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes()});var ay=e=>{switch(e.toLowerCase()){case"y":return"yearly";case"m":return"monthly";case"w":return"weekly";case"d":return"daily";default:return}};var cy=e=>{switch(e){case"+":return"todo";case"-":return"note";case"!":return"deadline";case".":return"done";case"~":return"up-down";default:return}},ly=e=>{switch(e){case"todo":return"+";case"note":return"-";case"deadline":return"!";case"done":return".";case"up-down":return"~"}};var or=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,E,v,b,T,R,L,C,M,O,_,P,N,I,F,j,D,V]=t,B=${e.slice(0,t.index).trim()}${e.slice((t.index??0)+r.length).trim()},K=py(s,i,a,c,l);if(!$t(we(K)))return ee({name:"InvalidDateError",message:The reference point of the task "${Nr(K)}" is an invalid date.});let Y=uy(K,f,m,h,u||g,p||y,x);if(Y!==void 0){if(Ue(Y)&&isNaN(Y)||!Ue(Y)&&!$t(we(Y)))return ee({name:"InvalidDateError",message:The estimated end of the task${Ue(Y)?"": "${Nr(Y)}"} is an invalid date.});if(Ue(Y)&&Y<0||!Ue(Y)&&rr(Y,K))return ee({name:"TaskRangeError",message:The reference point of an task cannot be after its estimated end.
reference point:${Nr(K)}
estimated end:${Nr(Ue(Y)?Lt(Sr(we(K),Y)):Y)}})}let ue=/^[\uFE00-\uFE0F]*[✅❌]/.test(e)?"done":cy(o),re=ue?{status:ue,refDate:K}:void 0;re&&n&&(re.speed=parseInt(n));let ut=py(R||s,L||i,C||a,b||M||c,T||O||l);if(!$t(we(ut)))return ee({name:"InvalidDateError",message:The start of the task/event "${Nr(ut)}" is an invalid date.});let Le=uy(ut,N||f,I||m,F||h,_||j||u||g,P||D||p||y,V||x),$=Zo(ut)&&Ue(Le)?{start:ut,duration:Le}:void 0;if($){let xt={name:B,executed:$,generated:!1,raw:e};return re&&(xt.freshness=re),(E||v)&&(xt.recurrence={frequency:ay(E??"D")??"daily",count:v?parseInt(v):1}),le(xt)}if(!re)return ee({name:"InvalidDateError",message:"Task requires freshness to be spec"});let Re={name:B,freshness:re,generated:!1,raw:e};return Y&&(Re.estimated=Y),le($?{...Re,executed:$}:Re)},Lr=e=>!("executed"in e),xo=e=>"recurrence"in e,my=e=>!("executed"in e||"freshness"in e&&Zo(e.freshness.refDate)&&e.estimated&&(Ue(e.estimated)||Zo(e.estimated))),Ys=e=>"executed"in e?e.executed.duration:Ue(e.estimated)?e.estimated:void 0,Cr=e=>Lr(e)?e.freshness.refDate:e.executed.start,fy=e=>{if(!Lr(e)){let r=we(e.executed.start);return Lt(Sr(r,e.executed.duration))}if(Ue(e.estimated)&&Zo(e.freshness.refDate)){let r=we(e.freshness.refDate);return Lt(Sr(r,e.estimated))}let t=we(Ue(e.estimated)?e.freshness.refDate:e.estimated??e.freshness.refDate);return t.setHours(0),t.setMinutes(0),Lt(Pe(t,1))},FP=e=>{let t=e.freshness?${ly(e.freshness.status)}${e.freshness.speed??""}:"",r=${Nr(Cr(e))},o=Ys(e);return${t}@${r}${o===void 0?"":D${o}}${e.name}},Ka=(e,t)=>{let r=Lt(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(qa(we(r),we(n.start))%(o.count??1)!==0)return;break}case"weekly":case"daily":{let a=o.frequency==="weekly"?7:1;if(Yr(we(r),we(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},Ya=e=>e.freshness?e.generated?FP(e):e.raw:e.generated?void 0:e.raw,py=(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}},uy=(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!Zo(e)||!Zo(f)?f:Math.round((we(f).getTime()-we(e).getTime())/(60*1e3))};var en=(e,t)=>{if(!e.generated&&xo(e)){let s=Ka(e,t);return s?en(s,t):void 0}let r=we(Lr(e)?e.freshness.refDate:e.executed.start),o=Ys(e),n=Ya(e);return{title:n!==void 0?${n}:e.name,base:r,plan:{start:my(e)?void 0:r,duration:o!==void 0?o*60:void 0},record:{}}};var nu={あさごはん:"#log-breakfast",ひるごはん:"#log-lunch",よるごはん:"#log-dinner"},tn=(e,{title:t,projectTo:r,mode:o})=>{let[n,...s]=e.split(
),i=it(n);if(!i)return;if(s.length===0)return{text:e,pages:[]};let{title:a,base:c,record:l,...u}=i,p=DP(a,c,l),f=ke({title:${p},base:c,record:l,...u}),m=Math.min(...s.map(g=>Va(g))),h=[.../[\[\]]/.test(a)&&a!==${p}?[a]:[],...t in nu?[...s.map(g=>g.slice(m)),"",nu[t],"#log-eatenfood"]:[...s.map(g=> ${g.slice(m)}),""]];return{text:f,pages:[{project:r,title:p,lines:dy(t,h,[l.start??c]),mode:o}]}};tn.hookName="task-hook";var DP=(e,t,r)=>{let o=pe(r.start??t,"yyyy-MM-dd");if(e in nu)return${o} ${e};if(or(e.slice(1,-1)))return e.slice(1,-1);let n=e.replace(/[\[\]]/g,"").trim();return${n}${n.endsWith(o)?"": ${o}}},rn=(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=>Va(p))),l=r.startsWith("takker")?Yg([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(Va(s))}${a},pages:[{project:r,title:a,lines:dy(t,u,l),mode:o}]}};rn.hookName="new-page-hook";var on=(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=>se(a[1])),i=n.replaceAll("[","").replaceAll("]","");return{text:${o}${i},pages:[{project:t,title:i,lines:(a,{links:c})=>{let l=c.map(u=>se(u));if(!s.every(u=>l.includes(u)))return[...a.map(u=>u.text),n]},mode:r}]}};on.hookName="splitted-link-hook";var dy=(e,t,r)=>(o,{links:n})=>{let s=n.map(p=>se(p)),i=s.includes(se(e))?[]:[from ${e}],a=r.flatMap(p=>{let f=pe(p,"yyyy-MM-dd");if(s.includes(f))return[];let m=pe(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 hy=e=>e.preventDefault(),gy=e=>e.stopPropagation(),yy={"<A-a><A-t>":async e=>{hy(e),gy(e);let[t,r]=UP(),o=Pr().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=or(i);if(!a||W(a))return s;let c=J(a);if(c.freshness?.status==="done")return s;let l=en(c,new Date);return l?(l.title=${i},ke(l)):s}).join(
);await Ta(t,r,o),await Xo()},"<A-a><A-m>":e=>{scrapbox.Layout==="page"&&(hy(e),gy(e),Qo({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"}))}},UP=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=Ge();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var nn=e=>e.preventDefault(),sn=e=>e.stopPropagation(),su={"<A-a><A-a>":e=>{nn(e),sn(e),Hs()},"<A-a><A-s>":e=>{nn(e),sn(e),Ko()},"<A-a><A-e>":e=>{nn(e),sn(e),Xr()},"<A-a><A-0>":e=>{nn(e),sn(e),Ws()},"<A-a><A-1>":e=>{nn(e),sn(e),Gs(1)},"<A-a><A-t>":e=>{nn(e),sn(e),qs()},"<A-a><A-S>":e=>{scrapbox.Layout==="page"&&(nn(e),sn(e),Vs(scrapbox.Project.name,scrapbox.Page.title))}};var at=e=>e.preventDefault(),ct=e=>e.stopPropagation(),an=(e,t)=>{let r=cg()?.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&&(at(e),ct(e),o.click())},$P={"-":e=>an(e,""),"]":e=>an(e,""),c:e=>an(e,"Copy plain"),$:e=>an(e,""),"{":e=>an(e,/{{c\d+}}/),"}":e=>an(e,"reset cloze"),n:e=>an(e,"make note")},jP={"<C-]>":e=>{let{position:{line:t,char:r}}=Ge(),o=Is(t,r)?.closest("a.page-link")??Uo(t)?.querySelector?.("a.page-link");o instanceof HTMLAnchorElement&&(at(e),ct(e),o.click())},"<C-o>":e=>{at(e),ct(e),history.back()}},BP={"<C-home>":e=>{at(e),ct(e),yg()},"<C-end>":e=>{at(e),ct(e),xg()}},xy=[tn,rn,on],HP={"<C-X>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(at(e),ct(e),Vr({project:t,mode:"self",hooks:xy})?.())},"<C-D>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(at(e),ct(e),Vr({project:t,mode:"noopen",hooks:xy})?.())},"<C-h>":e=>{at(e),ct(e),Pa()},"<C-j>":e=>{at(e),ct(e),Sa()},"<C-k>":e=>{at(e),ct(e),Oa()},"<C-l>":e=>{at(e),ct(e),_a()},"<A-h>":e=>{at(e),ct(e),La()},"<A-j>":e=>{at(e),ct(e),Ma()},"<A-k>":e=>{at(e),ct(e),Ca()},"<A-l>":e=>{at(e),ct(e),Na()}};scrapbox.TimeStamp.removeAllFormats();var WP={"<A-t><A-t>":e=>{at(e),ct(e),Je(pe(new Date,"#yyyy-MM-dd HH:mm:ss "))},"<A-t><A-j>":e=>{at(e),ct(e),Je(pe(new Date,"yyyy-MM-dd HH:mm:ss "))},"<A-t><A-k>":e=>{at(e),ct(e),Je(pe(new Date,"HH:mm:ss "))},"<A-t><A-l>":e=>{at(e),ct(e),Je(pe(new Date,"yyyy-MM-dd"))}},by={...$P,...jP,...BP,...HP,...WP,...yy};var{render:GP}=$e(),iu,qP=e=>{iu!==void 0&&cancelAnimationFrame(iu),iu=requestAnimationFrame(()=>GP({type:"text",text:e}))},au=new $a({addEventListener:Tg,removeEventListener:Hp},{onSequenceUpdate:qP}),wy=au.bind({...by,...scrapbox.Project.name==="takker-memex"?su:{}});wy.size>0&&alert([...wy.entries()].map(([e,t])=>${e}:
${t.map(r=>- ${r}).join(`
)}).join(`
));var zP=/https?:\/\/vimeo\.com\/([0-9]+)/i,Ey=e=>{let t=e.match(zP);if(t)return t[1]};var VP=/https?:\/\/open\.spotify\.com\/(track|artist|playlist|album|episode|show)\/([a-zA-Z\d_-]+)(?:\?[^\s]{0,100}|)/,ky=e=>{let t=e.match(VP);if(!t)return;let[,r,o]=t;return{videoId:o,pathType:r}};var KP=/https?:\/\/anchor\.fm\/[a-zA-Z\d_-]+\/episodes\/([a-zA-Z\d_-]+(?:\/[a-zA-Z\d_-]+)?)(?:\?[^\s]{0,100}|)/,vy=e=>{let t=e.match(KP);if(!t)return;let[,r]=t;return r};var Ry=e=>{let{type:t,pathType:r,content:o,href:n,...s}=e;if(o===""){let i=ia(n);if(i)return{type:"youtube",href:n,...i,...s};let a=Ey(n);if(a)return{type:"vimeo",videoId:a,href:n,...s};let c=ky(n);if(c)return{type:"spotify",href:n,...c,...s};let l=vy(n);if(l)return{type:"anchor-fm",videoId:l,href:n,...s};if(XP(n))return{type:"video",href:n,...s}}return YP(n)?{type:"audio",content:o,href:n,...s}:{type:"absoluteLink",content:o,href:n,...s}},YP=e=>/\.(?:mp3|ogg|wav|aac)$/.test(e),XP=e=>/\.(?:mp4|webm)$/.test(e);var Ty=" must not return ",JP="transformer",QP="recoverer",ZP="defaultValue",dfe=JP+Ty,_y="called with ",hfe=ZP+" must not be ",gfe=QP+Ty,eO="Ok",Py="Err",tO=_y+Py,yfe=_y+eO,xfe="Carrying E in "+Py+" instead of throwing it directly. See .cause",cu="an instance of Error of the current realm.",bfe="The thrown value is not "+cu,wfe="The contained E should be "+cu,Efe="This .cause is not "+cu;function Ze(e){return e.ok}function Ct(e){return!e.ok}function bo(e){return Oy(e,tO)}function Oy(e,t){if(Ct(e))throw new TypeError(t);return e.val}var Ny=" must not return ",oO="transformer",nO="recoverer",sO="defaultValue",iO=oO+Ny,aO="called with ",cO=sO+" must not be ",lO=nO+Ny,Xa="null",ude=iO+Xa,mde=aO+Xa,fde=cO+Xa,dde=lO+Xa;var Ly=" must not return ",pO="transformer",uO="recoverer",mO="defaultValue",fO=pO+Ly,dO="called with ",hO=mO+" must not be ",gO=uO+Ly,Ja="undefined",gde=fO+Ja,yde=dO+Ja,xde=hO+Ja,bde=gO+Ja;var Cy=" must not return ",yO="transformer",xO="recoverer",bO="defaultValue",Pde=yO+Cy,My="called with ",Ode=bO+" must not be ",Sde=xO+Cy;var wO="Ok",Ay="Err",Nde=My+Ay,Lde=My+wO,Cde="Carrying E in "+Ay+" instead of throwing it directly. See .cause",lu="an instance of Error of the current realm.",Mde="The thrown value is not "+lu,Ade="The contained E should be "+lu,Ide="This .cause is not "+lu;var Iy=" must not return ",EO="transformer",kO="recoverer",vO="defaultValue",Ude=EO+Iy,Fy="called with ",$de=vO+" must not be ",jde=kO+Iy;var RO="Ok",Dy="Err",Bde=Fy+Dy,Hde=Fy+RO,Wde="Carrying E in "+Dy+" instead of throwing it directly. See .cause",pu="an instance of Error of the current realm.",Gde="The thrown value is not "+pu,qde="The contained E should be "+pu,zde="This .cause is not "+pu;var Uy=" must not return ",TO="transformer",_O="recoverer",PO="defaultValue",Zde=TO+Uy,$y="called with ",ehe=PO+" must not be ",the=_O+Uy,OO="Ok",jy="Err",rhe=$y+jy,ohe=$y+OO,nhe="Carrying E in "+jy+" instead of throwing it directly. See .cause",uu="an instance of Error of the current realm.",she="The thrown value is not "+uu,ihe="The contained E should be "+uu,ahe="This .cause is not "+uu;var By=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(Ct(o))return r;let n=bo(o).projects.map(s=>s.id);return r.filter(s=>!n.includes(s))}catch(t){if(!(t instanceof SyntaxError))throw t;return[]}};var LO;(e=>{})(LO||={});var Qa="0.16.9",mu,fu,Hy=e=>{let t=https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${e}/katex.min.js;if(fu)throw fu;if(!document.querySelector(scriptsrc="${t}")){let r=document.createElement("script");r.src=t,mu=new Promise((o,n)=>{r.onload=()=>o(window.katex),r.onerror=s=>{fu=s,n(s)},document.head.append(r)})}return mu||new Promise(r=>{let o=setInterval(()=>{window.katex&&(clearInterval(o),r(window.katex))},500)})};var Za=(e,t)=>{let[r,o]=X("");return{ref:A(s=>{s&&Hy(Qa).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 Wy=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*code:/,"");return{indent:o,type:"codeBlock",fileName:s,content:r.map(i=>i.text.substring(o+1)).join(
)}};var ce=(e,{parseOnNested:t,parseOnQuoted:r,patterns:o})=>(n,s,i)=>{if(!t&&s.nested)return i?.()??[];if(!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??0)),p=e(c[0]??"",s);return[...Mt(l,s),...p,...Mt(u,s)]}return i?.()??[]};var he=e=>[{type:"plain",raw:e,text:e}],Gy=ce(he,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]});var CO=/\[\s+\]/,MO=(e,t)=>t.context==="table"?he(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],qy=ce(MO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[CO]});var AO=/.*?/,IO=(e,t)=>t.context==="table"?he(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],zy=ce(IO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[AO]});var FO=/^[$%] .+$/,DO=(e,t)=>{if(t.context==="table")return he(e,t);let r=e[0]??"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:r,text:o}]},Vy=ce(DO,{parseOnNested:!1,parseOnQuoted:!1,patterns:[FO]});var UO=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,$O=(e,t)=>{if(t.context==="table")return he(e,t);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:Mt(n,{...t,nested:!0})}]},Ky=ce($O,{parseOnNested:!1,parseOnQuoted:!0,patterns:[UO]});var jO=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,BO=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,HO=/\[https?:\/\/[^\s\]]+\]/,WO=/https?:\/\/[^\s]+/,GO=(e,t)=>{if(t.context==="table")return he(e,t);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?.[0]===void 0)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()}]},Yy=ce(GO,{parseOnNested:!0,parseOnQuoted:!0,patterns:[jO,BO,HO,WO]});var qO=/\[\$ .+? \]/,zO=/\[\$ [^\]]+\]/,VO=(e,t)=>t.context==="table"?he(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],Xy=ce(VO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[qO,zO]});var Jy=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Qy=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,KO=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}},YO=(e,t)=>{if(t.context==="table")return he(e,t);let r=e.match(Jy)??e.match(Qy);if(r===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,n="",s=""]=o?r:[r[0],r[2],r[1]],{latitude:i,longitude:a,zoom:c}=KO(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:e,latitude:i,longitude:a,zoom:c,place:s,url:l}]},Zy=ce(YO,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Jy,Qy]});var XO=/(?:^|\s)#\S+/,JO=(e,t)=>{if(t.context==="table")return he(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),o=e.substring(1);return[...he(r,t),{type:"hashTag",raw:o,href:o.substring(1)}]},ex=ce(JO,{parseOnNested:!0,parseOnQuoted:!0,patterns:[XO]});var QO=/^\? .+$/,ZO=(e,t)=>t.context==="table"?he(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],tx=ce(ZO,{parseOnNested:!1,parseOnQuoted:!1,patterns:[QO]});var eS=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/,tS=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}))},rx=ce(tS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[eS]});var rS=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,oS=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)(?:\?[^\]\s]+)?\]/i,nS=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,sS=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,iS=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg|webp)(\?[^\]\s]+)?$/i.test(e)||aS(e),aS=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),cS=(e,t)=>{if(t.context==="table")return he(e,t);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]=iS(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}]},ox=ce(cS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[rS,oS,nS,sS]});var lS=/\[\/?[^[\]]+\]/,pS=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},nx=ce(pS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[lS]});var uS=/^[0-9]+\. .*$/,mS=(e,t)=>{if(t.context==="table")return he(e,t);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:Mt(s,{...t,nested:!1})}]},sx=ce(mS,{parseOnNested:!1,parseOnQuoted:!1,patterns:[uS]});var fS=/^>.*$/,dS=(e,t)=>t.context==="table"?he(e,t):[{type:"quote",raw:e,nodes:Mt(e.substring(1),{...t,quoted:!0})}],ix=ce(dS,{parseOnNested:!1,parseOnQuoted:!1,patterns:[fS]});var hS=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,gS=(e,t)=>{if(t.context==="table")return he(e,t);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}))},ax=ce(gS,{parseOnNested:!1,parseOnQuoted:!0,patterns:[hS]});var yS=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i,xS=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,bS=(e,t)=>{if(t.context==="table")return he(e,t);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}]},cx=ce(bS,{parseOnNested:!1,parseOnQuoted:!0,patterns:[yS,xS]});var wS=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,ES=(e,t)=>t.context==="table"?he(e,t):[{type:"strong",raw:e,nodes:Mt(e.substring(2,e.length-2),{...t,nested:!0})}],lx=ce(ES,{parseOnNested:!1,parseOnQuoted:!0,patterns:[wS]});var kS=(e,t,r)=>e===""?[]:r?.()??[],vS=(...e)=>(t,r)=>e.reduceRight((o,n)=>()=>n(t,r,o),()=>Gy(t,r))(),Mt=vS(kS,ix,tx,sx,zy,Vy,qy,Ky,Xy,cx,ax,lx,ox,Yy,rx,Zy,nx,ex);var px=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:Mt(r.substring(t),{nested:!1,quoted:!1,context:"line"})}};var ux=e=>{let{rows:[t,...r]}=e,{indent:o=0,text:n=""}=t??{},s=n.replace(/^\s*table:/,"");return{indent:o,type:"table",fileName:s,cells:r.map(i=>i.text.substring(o+1)).map(i=>i.split(" ").map(a=>Mt(a,{nested:!1,quoted:!1,context:"table"})))}};var mx=e=>({type:"title",text:e.rows[0].text});var fx=e=>{switch(e.type){case"title":return mx(e);case"codeBlock":return Wy(e);case"table":return ux(e);case"line":return px(e)}};var RS=(e,t)=>(e.type==="codeBlock"||e.type==="table")&&t.indent>(e.rows[0]?.indent??0),dx=(e,t)=>{let r=e[e.length-1];return r!==void 0&&RS(r,t)?(r.rows.push(t),e):(e.push({type:/^\s*code:/.test(t.text)?"codeBlock":/^\s*table:/.test(t.text)?"table":"line",rows:[t]}),e)},hx=(e,t)=>{if(t.hasTitle??!0){let[r,...o]=e;return r===void 0?[]:[{type:"title",rows:[r]},...o.reduce(dx,[])]}return e.reduce(dx,[])};var gx=e=>e.split(
).map(t=>({indent:/^\s+/.exec(t)?.[0]?.length??0,text:t}));var Xs=(e,t)=>{let r=gx(e);return hx(r,{hasTitle:t?.hasTitle??!0}).map(fx)};var yx=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 TS="0.6.5",wx=ScrapBubble-${TS},xx=await globalThis.caches.open(wx);(async()=>{for(let e of await globalThis.caches.keys())e.startsWith("ScrapBubble-")&&e!==wx&&(await globalThis.caches.delete(e),console.log(ScrapBubble deleted old cache :"${e}"))})();var bx=yx(3);async function*ec(e,t){let r=((t?.saveFailedResponse?xx.match(e):void 0)??Dn(e,t)).then(i=>["cache",i]);{let i=De(1e3).then(()=>"timeout"),a=await Promise.race([r,i]);if(a!=="timeout"){a[1]&&(yield["cache",a[1]]);let c=await bx(()=>fetch(e));!c.ok&&t?.saveFailedResponse&&await xx.put(e,c.clone()),yield["network",c]}}let o=bx(()=>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 Ex=(e,t)=>new Date(e.headers.get("Date")??0).getTime()/1e3+t<new Date().getTime()/1e3;var tc=()=>{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 zt=!1,kx=e=>{zt=typeof e=="boolean"?e:new Set(e)},wo=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)=>{zt!==!0&&(!zt||!zt.has(e))||r(%c${e},"color: gray",...o)}];case"assert":return[t,(o,...n)=>{zt!==!0&&(!zt||!zt.has(e))||r(o,%c${e},"color: gray",...n)}];case"time":case"timeEnd":return[t,o=>{zt!==!0&&(!zt||!zt.has(e))||r(${e} ${o})}];default:return[t,(...o)=>{if(!(zt!==!0&&(!zt||!zt.has(e))))return r(...o)}]}}));var du=tc(),rc=new Map,_S=wo("ScrapBubble:useProject.ts"),vx=e=>{let[t,r]=X();return Z(()=>{du.on(e,r);let o=rc.get(e);return o?r(o.loading?void 0:o.value):(rc.set(e,{loading:!0}),r(void 0),(async()=>{try{let n=Br.toRequest(e);for await(let[,s]of ec(n)){let i=await Br.fromResponse(s);rc.set(e,{loading:!1,value:i}),du.dispatch(e,i);break}}catch(n){_S.error(n),rc.delete(e)}})()),()=>du.off(e,r)},[e]),t};var PS=["default-light","default-dark","default-minimal"],OS=["paper-light","paper-dark-dark","paper-dark"],Rx=["blue","purple","green","orange","red"],SS=["hacker1","hacker2"],Tx=["winter","spring","summer","automn"],_x=["tropical"],Px=["kyoto","newyork","paris"],Ox=["mred","lgreen"],ube=["default-light","default-minimal","paper-light",...Rx,...Tx,..._x,...Px,...Ox];var NS=[...PS,...OS,...Rx,...SS,...Tx,..._x,...Px,...Ox];function Sx(e){return NS.includes(e)}var Nx="default-light",ln=e=>{let t=vx(e);return U(()=>{if(!t||Ct(t))return Nx;let r=bo(t).theme;return Sx(r)?r:Nx},[t])};var $n=(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 Lx=({project:e,title:t,descriptions:r,thumbnail:o,linkTo:n,bubble:s,delay:i,prefetch:a})=>{let c=U(()=>o?[]:Xs(r.join(
),{hasTitle:!1}),[o,r]),l=ln(e),u=A(async({currentTarget:f})=>{a(e,t),await $n(f,i)&&s({project:e,title:t,linkTo:n,type:"link",position:jn(f)})},[e,t,i,n?.project,n?.titleLc]),p=U(()=>n?()=>{Fn({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}/${ge(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(Cx,{node:h,project:e}))},m)]:[])})]})]})},Cx=({node:e,project:t})=>{switch(e.type){case"code":return d("code",{children:e.text});case"formula":return d(LS,{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(Q,{children:e.nodes.map(r=>d(Cx,{node:r,project:t}))});case"icon":case"strongIcon":return d(CS,{node:e,project:t});case"hashTag":return d(MS,{node:e});case"link":return d(AS,{node:e});case"plain":case"blank":return d(Q,{children:e.text});default:return}},LS=({node:{formula:e}})=>{let{ref:t,error:r}=Za(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},CS=({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}/${ge(n)}/icon})},MS=({node:{href:e}})=>d("span",{class:"page-link",children:["#",e]}),AS=({node:{pathType:e,href:t,content:r}})=>e!=="absolute"?d("span",{class:"page-link",children:t}):d("span",{class:"link",children:r||t});var ve=(e,t)=>/${e.toLowerCase()}/${se(t)},oc=e=>{let t=e.match("/([^/]+)/(.+)");if(!t)throw SyntaxError("${e}" cannnot match "/(^/+)/(.+)");return{project:t[1],titleLc:t[2]}};var Ux=Symbol.for("immer-nothing"),Mx=Symbol.for("immer-draftable"),Ee=Symbol.for("immer-state");function nr(e,...t){throw new Error(Immer minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf)}var Bn=Object.getPrototypeOf;function Hn(e){return!!e&&!!e[Ee]}function Zr(e){return e?$x(e)||Array.isArray(e)||!!e[Mx]||!!e.constructor?.[Mx]||cc(e)||lc(e):!1}var IS=Object.prototype.constructor.toString();function $x(e){if(!e||typeof e!="object")return!1;let t=Bn(e);if(t===null)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return r===Object?!0:typeof r=="function"&&Function.toString.call(r)===IS}function Js(e,t){ac(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,o)=>t(o,r,e))}function ac(e){let t=e[Ee];return t?t.type_:Array.isArray(e)?1:cc(e)?2:lc(e)?3:0}function yu(e,t){return ac(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function jx(e,t,r){let o=ac(e);o===2?e.set(t,r):o===3?e.add(r):e[t]=r}function FS(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function cc(e){return e instanceof Map}function lc(e){return e instanceof Set}function gt(e){return e.copy_||e.base_}function xu(e,t){if(cc(e))return new Map(e);if(lc(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=$x(e);if(t===!0||t==="class_only"&&!r){let o=Object.getOwnPropertyDescriptors(e);delete o[Ee];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(Bn(e),o)}else{let o=Bn(e);if(o!==null&&r)return{...e};let n=Object.create(o);return Object.assign(n,e)}}function ku(e,t=!1){return pc(e)||Hn(e)||!Zr(e)||(ac(e)>1&&(e.set=e.add=e.clear=e.delete=DS),Object.freeze(e),t&&Object.entries(e).forEach(([r,o])=>ku(o,!0))),e}function DS(){nr(2)}function pc(e){return Object.isFrozen(e)}var bu={};function pn(e){let t=bu[e];return t||nr(0,e),t}function US(e,t){bu[e]||(bu[e]=t)}var Qs;function nc(){return Qs}function $S(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Ax(e,t){t&&(pn("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function wu(e){Eu(e),e.drafts_.forEach(jS),e.drafts_=null}function Eu(e){e===Qs&&(Qs=e.parent_)}function Ix(e){return Qs=$S(Qs,e)}function jS(e){let t=e[Ee];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Fx(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[Ee].modified_&&(wu(t),nr(4)),Zr(e)&&(e=sc(t,e),t.parent_||ic(t,e)),t.patches_&&pn("Patches").generateReplacementPatches_(r[Ee].base_,e,t.patches_,t.inversePatches_)):e=sc(t,r,[]),wu(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ux?e:void 0}function sc(e,t,r){if(pc(t))return t;let o=t[Ee];if(!o)return Js(t,(n,s)=>Dx(e,o,t,n,s,r)),t;if(o.scope_!==e)return t;if(!o.modified_)return ic(e,o.base_,!0),o.base_;if(!o.finalized_){o.finalized_=!0,o.scope_.unfinalizedDrafts_--;let n=o.copy_,s=n,i=!1;o.type_===3&&(s=new Set(n),n.clear(),i=!0),Js(s,(a,c)=>Dx(e,o,n,a,c,r,i)),ic(e,n,!1),r&&e.patches_&&pn("Patches").generatePatches_(o,r,e.patches_,e.inversePatches_)}return o.copy_}function Dx(e,t,r,o,n,s,i){if(Hn(n)){let a=s&&t&&t.type_!==3&&!yu(t.assigned_,o)?s.concat(o):void 0,c=sc(e,n,a);if(jx(r,o,c),Hn(c))e.canAutoFreeze_=!1;else return}else i&&r.add(n);if(Zr(n)&&!pc(n)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;sc(e,n),(!t||!t.scope_.parent_)&&typeof o!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,o)&&ic(e,n)}}function ic(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ku(t,r)}function BS(e,t){let r=Array.isArray(e),o={type_:r?1:0,scope_:t?t.scope_:nc(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},n=o,s=vu;r&&(n=[o],s=Zs);let{revoke:i,proxy:a}=Proxy.revocable(n,s);return o.draft_=a,o.revoke_=i,a}var vu={get(e,t){if(t===Ee)return e;let r=gt(e);if(!yu(r,t))return HS(e,r,t);let o=r[t];return e.finalized_||!Zr(o)?o:o===hu(e.base_,t)?(gu(e),e.copy_[t]=ei(o,e)):o},has(e,t){return t in gt(e)},ownKeys(e){return Reflect.ownKeys(gt(e))},set(e,t,r){let o=Bx(gt(e),t);if(o?.set)return o.set.call(e.draft_,r),!0;if(!e.modified_){let n=hu(gt(e),t),s=n?.[Ee];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(FS(r,n)&&(r!==void 0||yu(e.base_,t)))return!0;gu(e),Qr(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 hu(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,gu(e),Qr(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=gt(e),o=Reflect.getOwnPropertyDescriptor(r,t);return o&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:o.enumerable,value:r[t]}},defineProperty(){nr(11)},getPrototypeOf(e){return Bn(e.base_)},setPrototypeOf(){nr(12)}},Zs={};Js(vu,(e,t)=>{Zs[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Zs.deleteProperty=function(e,t){return Zs.set.call(this,e,t,void 0)};Zs.set=function(e,t,r){return vu.set.call(this,e[0],t,r,e[0])};function hu(e,t){let r=e[Ee];return(r?gt(r):e)[t]}function HS(e,t,r){let o=Bx(t,r);return o?"value"in o?o.value:o.get?.call(e.draft_):void 0}function Bx(e,t){if(!(t in e))return;let r=Bn(e);for(;r;){let o=Object.getOwnPropertyDescriptor(r,t);if(o)return o;r=Bn(r)}}function Qr(e){e.modified_||(e.modified_=!0,e.parent_&&Qr(e.parent_))}function gu(e){e.copy_||(e.copy_=xu(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var WS=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,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"&&nr(6),o!==void 0&&typeof o!="function"&&nr(7);let n;if(Zr(t)){let s=Ix(this),i=ei(t,void 0),a=!0;try{n=r(i),a=!1}finally{a?wu(s):Eu(s)}return Ax(s,o),Fx(n,s)}else if(!t||typeof t!="object"){if(n=r(t),n===void 0&&(n=t),n===Ux&&(n=void 0),this.autoFreeze_&&ku(n,!0),o){let s=[],i=[];pn("Patches").generateReplacementPatches_(t,n,s,i),o(s,i)}return n}else nr(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)}createDraft(e){Zr(e)||nr(8),Hn(e)&&(e=GS(e));let t=Ix(this),r=ei(e,void 0);return r[Ee].isManual_=!0,Eu(t),r}finishDraft(e,t){let r=e&&e[Ee];(!r||!r.isManual_)&&nr(9);let{scope_:o}=r;return Ax(o,t),Fx(void 0,o)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}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=pn("Patches").applyPatches_;return Hn(e)?o(e,t):this.produce(e,n=>o(n,t))}};function ei(e,t){let r=cc(e)?pn("MapSet").proxyMap_(e,t):lc(e)?pn("MapSet").proxySet_(e,t):BS(e,t);return(t?t.scope_:nc()).drafts_.push(r),r}function GS(e){return Hn(e)||nr(10,e),Hx(e)}function Hx(e){if(!Zr(e)||pc(e))return e;let t=e[Ee],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=xu(e,t.scope_.immer_.useStrictShallowCopy_)}else r=xu(e,!0);return Js(r,(o,n)=>{jx(r,o,Hx(n))}),t&&(t.finalized_=!1),r}function Wx(){class e extends Map{constructor(c,l){super(),this[Ee]={type_:2,parent_:l,scope_:l?l.scope_:nc(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return gt(this[Ee]).size}has(c){return gt(this[Ee]).has(c)}set(c,l){let u=this[Ee];return i(u),(!gt(u).has(c)||gt(u).get(c)!==l)&&(r(u),Qr(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[Ee];return i(l),r(l),Qr(l),l.base_.has(c)?l.assigned_.set(c,!1):l.assigned_.delete(c),l.copy_.delete(c),!0}clear(){let c=this[Ee];i(c),gt(c).size&&(r(c),Qr(c),c.assigned_=new Map,Js(c.base_,l=>{c.assigned_.set(l,!1)}),c.copy_.clear())}forEach(c,l){let u=this[Ee];gt(u).forEach((p,f,m)=>{c.call(l,this.get(f),f,this)})}get(c){let l=this[Ee];i(l);let u=gt(l).get(c);if(l.finalized_||!Zr(u)||u!==l.base_.get(c))return u;let p=ei(u,l);return r(l),l.copy_.set(c,p),p}keys(){return gt(this[Ee]).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[Ee]={type_:3,parent_:l,scope_:l?l.scope_:nc(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return gt(this[Ee]).size}has(c){let l=this[Ee];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[Ee];return i(l),this.has(c)||(s(l),Qr(l),l.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let l=this[Ee];return i(l),s(l),Qr(l),l.copy_.delete(c)||(l.drafts_.has(c)?l.copy_.delete(l.drafts_.get(c)):!1)}clear(){let c=this[Ee];i(c),gt(c).size&&(s(c),Qr(c),c.copy_.clear())}values(){let c=this[Ee];return i(c),s(c),c.copy_.values()}entries(){let c=this[Ee];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(Zr(c)){let l=ei(c,a);a.drafts_.set(c,l),a.copy_.add(l)}else a.copy_.add(c)}))}function i(a){a.revoked_&&nr(3,JSON.stringify(gt(a)))}US("MapSet",{proxyMap_:t,proxySet_:n})}var Vt=new WS,uc=Vt.produce,Abe=Vt.produceWithPatches.bind(Vt),Ibe=Vt.setAutoFreeze.bind(Vt),Fbe=Vt.setUseStrictShallowCopy.bind(Vt),Dbe=Vt.applyPatches.bind(Vt),Ube=Vt.createDraft.bind(Vt),$be=Vt.finishDraft.bind(Vt);Wx();var Gx=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},qx=(e,t)=>uc(e,r=>{if(!r)return t;if(r.updated<t.updated){let{lines:o,linked:n,projectLinked:s,...i}=t;Object.assign(r,i),Ru(t)||(r.lines=o),n&&(r.linked??=n),s&&(r.projectLinked??=s);return}Ru(r)&&!Ru(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)}),Ru=e=>e.lines[0].id==="dummy";var zx=(e,t)=>{let r=new Map,o=se(t.title);for(let c of t.links){let l=Tu(e,c);l.linked=[o],r.set(ve(e,c),l)}let n=ve(e,o),s=t.projectLinks.map(c=>{let l=oc(c);return ve(l.project,l.titleLc)}),i={...mc(e,t),linked:[],projectLinked:[]};r.set(n,i);let a=t.links.map(c=>se(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=ve(e,f),h=r.get(m)??Tu(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=ve(e,c.titleLc),u=mc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}for(let c of t.relatedPages.projectLinks1hop){let l=ve(c.projectName,c.titleLc);s.includes(l)||i.projectLinked.push(l);let u=mc(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=ve(e,f),h=r.get(m)??Tu(e,f);if(!h.linked){h.linked=[c.titleLc];continue}h.linked.push(c.titleLc)}let l=ve(e,c.titleLc),u=mc(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}return r},mc=(e,t)=>({project:e,titleLc:"titleLc"in t?t.titleLc:se(t.title),exists:"persistent"in t?t.persistent:!0,descriptions: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}),Tu=(e,t)=>({project:e,titleLc:se(t),exists:!1,descriptions:[],image:null,lines:[{text:t,id:"dummy",userId:"dummy",updated:0,created:0}],updated:0,isLinkedCorrect:!1});var fc=wo("ScrapBubble:bubble.ts"),_u=new Map,dc=new Set,Pu=tc();function*Kx(e){for(let t of e)yield _u.get(t)}var Yx=(e,t)=>Pu.on(e,t),Xx=(e,t)=>Pu.off(e,t),Jx=async(e,t,r,o)=>{let n=[];for(let s of[...t].reverse()){let i=ve(s,e);dc.has(i)||n.push(qS(s,e,r,o))}await Promise.all(n)},Vx=0,qS=async(e,t,r,o)=>{let n=ve(e,t);if(dc.has(n))return;dc.add(n);let s=Vx++,i=${s} Check update ${n};fc.time(i);try{let a=er.toRequest(e,t,{followRename:!0,projects:[...r]});for await(let[c,l]of ec(a,{ignoreSearch:!0,saveFailedResponse:!0})){fc.debug(${s}${c} ${n});let u=await er.fromResponse(l);if(Ze(u)){let p=zx(e,bo(u));for(let[f,m]of p){let h=_u.get(f),g=qx(h,m);g&&h!==g&&(_u.set(f,g),Pu.dispatch(f,m))}}if(o?.ignoreFetch===!0||c==="cache"&&!Ex(l,o?.maxAge??60))break}}catch(a){fc.error(a)}finally{dc.delete(n),fc.timeEnd(i),Vx--}};var Qx=wo("ScrapBubble:useBubbleData.ts"),Wn=e=>{let[t,r]=X(Ou(e));return Z(()=>{r(Ou(e));let o,n=()=>{clearTimeout(o),o=setTimeout(()=>{Qx.debug(Update ${e.length} pages),r(Ou(e))},10)};return e.forEach(s=>Yx(s,n)),()=>e.forEach(s=>Xx(s,n))},e),t},Ou=e=>{let t=[...Kx(e)].flatMap(r=>r?[r]:[]);return Qx.debug(Required: ${e.length} pages, ${t.length} found,t),t};var Zx=({source:e,linked:t,externalLinked:r,projectsForSort:o,...n})=>{let s=U(()=>[...t.keys(),...r.keys()],[t,r]),i=Wn(s),a=U(()=>[...o],[o]),c=U(()=>{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=U(()=>({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=ve(u,p),y=t.get(g)??r.get(g);return d("li",{children:d(Lx,{project:u,title:f,linkTo:y,descriptions:m,thumbnail:h??"",...n})},g)})})};var Gn=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 Su=(e,t)=>t.some(r=>{let o=!e.project;switch(r.type){case"hashTag":return o&&se(r.href)===e.titleLc;case"link":{if(r.pathType=="absolute"||r.pathType==="relative"!==o)return!1;let{project:n,title:s=""}=Gn({pathType:r.pathType,href:r.href});return o?!n&&se(s)===e.titleLc:n===e.project&&se(s)===e.titleLc}case"quote":case"strong":case"decoration":return Su(e,r.nodes)}});var Eo=Ls({title:"",project:"",whiteList:new Set,bubble:()=>{},hide:()=>{},delay:0,prefetch:()=>{}}),tb=({lines:e,project:t,title:r,whiteList:o,noIndent:n,hash:s,linkTo:i,...a})=>{let c=U(()=>e.flatMap(m=>typeof m=="string"?[]:[m.id]),[e]),l=U(()=>{let m=0;return Xs(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=U(()=>{if(s&&c.includes(s))return s;if(i)return l.find(m=>m.type!=="line"?!1:Su(i,m.nodes))?.id},[l,c,s,i?.project,i?.titleLc]),p=rt(null);Z(()=>{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=ln(t);return d("div",{className:"lines","data-theme":f,ref:p,children:d(Eo.Provider,{value:{project:t,title:r,whiteList:o,...a},children:l.map(m=>{switch(m.type){case"title":return d(Q,{children:[d(zn,{index:m.id,indent:0,noIndent:n,permalink:m.id===u,children:d("a",{className:"page-link",type:"link",href:/${t}/${ge(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(zS,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"table":return d(VS,{block:m,noIndent:n,ids:m.ids,scrollId:u},m.ids[0]);case"line":return d(zn,{index:m.id,indent:m.indent,noIndent:n,permalink:m.id===u,children:m.nodes.length>0?m.nodes.map(h=>d(qn,{node:h},h.raw)):d("br",{})},m.id)}})})})},zn=({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}),zS=({block:{fileName:e,content:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=qr(Eo),[a,c]=X(""),l=A(async u=>{u.preventDefault(),u.stopPropagation();try{await navigator.clipboard.writeText(t),c("Copied"),await De(1e3),c("")}catch(p){alert(Failed to copy the code block
Error: ${p})}},[t]);return d(Q,{children:[d(zn,{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}/${ge(i)}/${e},target:"_blank",children:e})}),d("span",{className:"copy",title:"Copy",onClick:l,children:a})]})}),d(Q,{children:t.split(
).map((u,p)=>d(zn,{index:o[p+1],indent:r,permalink:o[p+1]===n,children:d("code",{className:"code-block",children:u})}))})]})},VS=({block:{fileName:e,cells:t,indent:r},ids:o,scrollId:n})=>{let{project:s,title:i}=qr(Eo);return d(Q,{children:[d(zn,{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}/${ge(i)}/${e}.csv,target:"_blank",children:e})})})}),d(Q,{children:t.map((a,c)=>d(zn,{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(qn,{node:p},p.raw))}))})}))})]})},qn=({node:e})=>{switch(e.type){case"code":return d("code",{className:"code",children:e.text});case"formula":return d(KS,{node:e});case"commandLine":return d(XS,{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(qn,{node:t},t.raw))});case"strong":return d("strong",{children:e.nodes.map(t=>d(qn,{node:t},t.raw))});case"decoration":return d(YS,{node:e});case"plain":case"blank":return d(Q,{children:e.text});case"hashTag":return d(ZS,{node:e});case"link":return d(eN,{node:e});case"googleMap":return d(JS,{node:e});case"icon":return d(eb,{node:e});case"strongIcon":return d(eb,{node:e,strong:!0});case"image":return d(QS,{node:e});case"strongImage":return d("img",{className:"image strong-image",src:e.src});case"numberList":return d(Q,{children:[${e.number}. ,e.nodes.map(t=>d(qn,{node:t},t.raw))]})}},KS=({node:{formula:e}})=>{let{ref:t,error:r}=Za(e);return d("span",{className:formula ${r?" error":""},children:r?d("code",{children:e}):d("span",{className:"katex-display",ref:t})})},YS=({node:{decos:e,nodes:t}})=>d("span",{className:e.map(r=>deco-${r}).join(" "),children:t.map(r=>d(qn,{node:r},r.raw))}),XS=({node:e})=>{let[t,r]=X(""),o=A(async n=>{n.preventDefault(),n.stopPropagation();try{await navigator.clipboard.writeText(e.text),r("Copied"),await De(1e3),r("")}catch(s){alert(Failed to copy the code block
Error: ${s})}},[e.text]);return d(Q,{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})})]})},JS=({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}})})}),eb=({node:{pathType:e,path:t},strong:r})=>{let{project:o}=qr(Eo),[n,s]=e==="relative"?[o,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[o,t],i=ge(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})})},QS=({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})})},ZS=({node:{href:e}})=>{let{project:t}=qr(Eo),r=rb(t,e),o=ob(t,e,"hashtag");return d("a",{href:/${t}/${ge(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]})},eN=({node:{pathType:e,...t}})=>{switch(e){case"relative":case"root":return d(tN,{pathType:e,href:t.href});case"absolute":{let r=Ry({pathType:e,...t});switch(r.type){case"youtube":return d(rN,{...r});case"vimeo":return d(oN,{...r});case"spotify":return d(nN,{...r});case"anchor-fm":return d(sN,{...r});case"audio":return d(iN,{...r});case"video":return d(cN,{...r});case"absoluteLink":return d("a",{className:"link",href:r.href,rel:"noopener noreferrer",target:"_blank",children:r.content||r.href})}}}},tN=({pathType:e,href:t})=>{let{project:r}=qr(Eo),{project:o=r,title:n,hash:s=""}=Gn({pathType:e,href:t}),i=ob(o,n,"link",s),a=rb(o,n??"");return d("a",{className:page-link${n!==void 0&&a?" empty-page-link":""},type:"link",href:/${o}${n===void 0?"":/${ge(n)}${s===""?"":#${s}}},rel:o===scrapbox.Project.name?"route":"noopener noreferrer",target:o===scrapbox.Project.name?"":"_blank",onPointerEnter:i,children:t})},rN=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})})},oN=({videoId:e})=>d("div",{className:"iframe-video-player",children:d("iframe",{src:https://player.vimeo.com/video/${e},allowFullScreen:!0})}),nN=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})}),sN=e=>d("div",{className:"iframe-video-player",children:d("iframe",{className:"anchor-fm",src:e.href.replace("/episodes/","/embed/episodes/"),allowFullScreen:!0})}),iN=e=>e.content===""?d("audio",{className:"audio-player",preload:"none",controls:!0,src:e.href}):d(aN,{...e}),aN=({href:e,content:t})=>{let r=rt(null),o=A(()=>{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})]})},cN=({href:e})=>d("div",{className:"video-player",children:d("video",{class:"video",style:{display:"inline-block"},controls:!0,loop:!0,src:e})}),rb=(e,t)=>{let{whiteList:r}=qr(Eo),o=U(()=>(r.has(e)?[...r]:[e,...r]).map(s=>ve(s,t)),[r,e]),n=Wn(o);return U(()=>Gx(n),n)},ob=(e,t,r,o)=>{let{delay:n,bubble:s,prefetch:i}=qr(Eo);return A(async({currentTarget:a})=>{t&&(i(e,t),await $n(a,n)&&s({project:e,title:t,hash:o,type:r,position:jn(a)}))},[e,t,o,r,n,i,s])};var nb=({pages:e,onClick:t,source:r,whiteList:o,...n})=>{let[s,i]=X(ve(e[0].project,e[0].titleLc)),a=U(()=>({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(lN,{project:c.project,titleLc:c.titleLc,selected:s===ve(c.project,c.titleLc),tabSelector:i},ve(c.project,c.titleLc)))}),e.map(c=>d(pN,{selected:s===ve(c.project,c.titleLc),...c,title:c.lines[0].text,hash:r.hash,linkTo:r.linkTo,whiteList:o,...n},ve(c.project,c.titleLc)))]})},lN=({project:e,titleLc:t,tabSelector:r,selected:o})=>{let n=A(()=>r(ve(e,t)),[e,t]),s=ln(e);return d("button",{type:"button",role:"tab","aria-selected":o,"data-theme":s,tabIndex:-1,onClick:n,children:e})},pN=({selected:e,...t})=>{let r=ln(t.project);return d("div",{role:"tabpanel","data-theme":r,hidden:!e,children:d(tb,{...t})})};var sb=wo("ScrapBubble:Bubble.tsx"),ib=({source:e,parentTitles:t,whiteList:r,...o})=>{let n=U(()=>r.has(e.project)?new Set([e.project,...r]):new Set([e.project]),[r,e.project]),[s,i,a]=mN(e,n,r,t);return d(Q,{children:[uN(a)&&d(nb,{pages:a,source:e,whiteList:r,onClick:o.hide,...o}),d(Zx,{linked:s,externalLinked:i,onClick:o.hide,source:e,projectsForSort:n,...o})]})},uN=e=>e.length>0,mN=(e,t,r,o)=>{let[[n,s,i],a]=X([new Map,new Map,[]]),c=U(()=>{let p=[...t].map(f=>ve(f,e.title));return sb.debug("projects",p),p},[t,e.title]),l=Wn(c),u=U(()=>o.map(p=>se(p)),[o]);return Ea(()=>{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:E,titleLc:v}=oc(x);u.includes(v)&&r.has(E)||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 E=ve(h.project,x);p.has(E)||p.set(E,y)}u.includes(h.titleLc)||h.exists&&m.push(h)}a(uc(h=>{sb.debug(depth: ${u.length}, bubbled from ${ve(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 ab=(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 cb=e=>{let t=U(()=>ab(e.style,import.meta.url),[e.style]);return d(Q,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var lb=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 pb=e=>e instanceof HTMLSpanElement&&e.matches(".line-title .text"),hc=e=>e instanceof HTMLAnchorElement&&e.classList.contains("page-link");var ub=()=>{let[e,t]=X([{bubble:o=>r(0,o),hide:()=>r(0)}]),r=A((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 Nu=(e,t,r,o,n)=>{Z(()=>(e.addEventListener(t,r,o),()=>e.removeEventListener(t,r,o)),[e,t,o,...n??[]])};var Lu="scrap-bubble",mb=({delay:e,whiteList:t,watchList:r,style:o})=>{let[{bubble:n,hide:s},...i]=ub(),a=A((c,l)=>Jx(l,t.has(c)?t:new Set([c]),r),[t,r]);return Nu(document,"pointerenter",async c=>{let l=c.target;if(!hc(l)&&!pb(l))return;let{project:u=scrapbox.Project.name,title:p,hash:f=""}=hc(l)?Gn({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 $n(l,e)&&n({project:u,title:m,hash:f,position:jn(l),type:fN(l)})},{capture:!0},[e,t,r]),Nu(document,"click",c=>{c.target.dataset.userscriptName!==Lu&&s()},{capture:!0},[s]),Z(()=>(scrapbox.addListener("page:changed",s),()=>scrapbox.removeListener("page:changed",s)),[s]),d(Q,{children:[d("link",{rel:"stylesheet",href:https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${Qa}/katex.min.css}),d("style",{children:lb}),d(cb,{style:o}),i.map(c=>d(ib,{...c,whiteList:t,delay:e,prefetch:a},ve(c.source.project,c.source.title)))]})},fN=e=>hc(e)?e.type==="link"?"link":"hashtag":"title";var fb=async e=>{let{delay:t=500,whiteList:r=[],watchList:o=(await By()).slice(0,100),style:n="",debug:s=!1}=e??{};kx(s);let i=document.createElement("div");i.dataset.userscriptName=Lu,document.body.append(i);let a=i.attachShadow({mode:"open"});ft(d(mb,{delay:t,whiteList:new Set([scrapbox.Project.name,...r]),watchList:new Set(o),style:n}),a)};var dN=["takker-memex","takker-private","takker","takker-books","villagepump"],un=[];switch(scrapbox.Project.name){case"hub":case"villagepump":case"verbalizing-community":un.push("villagepump","hub","verbalizing-community");break;case"programming-notes":case"customize":case"scrapboxlab":un.push("programming-notes","customize","scrapboxlab");break;case"sta":un.push("sta-taskmanagement");break;case"sta-taskmanagement":case"taskmanagement":un.push("sta-taskmanagement","taskmanagement");break;case"plurality-japanese":un.push("nishio","tkgshn");case"takker-books":un.push("work4ai");break}fb({delay:/mobile/i.test(navigator.userAgent)?300:500,whiteList:[...dN,...un],style:@import "/api/code/takker/kakeruの背景を白にするUserCSS/style.css";
@import "/api/code/takker/アイコン記法を画像記法っぽくするUserCSS/style2.css";});var db=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 hb=(e,t,r)=>{if(r.length===0)return[];let o=r.map(a=>a.text).join(
),n=kt(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}=db(a.fileName),u=s.get(c);s.set(c,{path:u?.path??https://scrapbox.io/api/code/${e}/${ge(t)}/${ge(c)},lang:u?.lang??l,startIds:[...u?.startIds??[],r[i].id]}),i+=a.content.split(
).length+1;break}}return s.values()};function Mu(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(br(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(br(s)),t(o[s])}},r=new gc;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),Cu(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function gb(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return Vn(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[Vn(r.read())]=t();return a}default:throw new Error("Invalid packet")}},r=new gc(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 gc=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);Cu(this.buf,t,r)}write(t){let r=this._write(4+t.length);Cu(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 Au(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}},br,Vn,yb;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;br=r=>e.encode(r),Vn=r=>t.decode(r),yb='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(br("")instanceof Uint8Array))throw new Error(Invariant violation: "${yb} 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 Au(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function Cu(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var ti="0.24.0";var et=JSON.stringify,xb="warning",bb="silent";function wb(e){if(yt(e,"target"),e.indexOf(",")>=0)throw new Error(Invalid target: ${e});return e}var bc=()=>null,je=e=>typeof e=="boolean"?null:"a boolean",q=e=>typeof e=="string"?null:"a string",wc=e=>e instanceof RegExp?null:"a RegExp object",fn=e=>typeof e=="number"&&e===(e|0)?null:"an integer",vb=e=>typeof e=="function"?null:"a function",qe=e=>Array.isArray(e)?null:"an array",sr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",gN=e=>typeof e=="object"&&e!==null?null:"an array or an object";var Eb=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",Rb=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",yN=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",xN=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",Tb=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(${et(r)} must be ${s});return n}function lt(e,t,r){for(let o in e)if(!(o in t))throw new Error(Invalid option ${r}: ${et(o)})}function _b(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 ${et(r)} in mangle cache to map to either a string or false)}}return t}function Ec(e,t,r,o,n){let s=k(t,r,"color",je),i=k(t,r,"logLevel",q),a=k(t,r,"logLimit",fn);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 yt(e,t,r){if(typeof e!="string")throw new Error(Expected value for ${t}${r!==void 0?" "+et(r):""} to be a string, got ${typeof e} instead);return e}function Pb(e,t,r){let o=k(t,r,"legalComments",q),n=k(t,r,"sourceRoot",q),s=k(t,r,"sourcesContent",je),i=k(t,r,"target",xN),a=k(t,r,"format",q),c=k(t,r,"globalName",q),l=k(t,r,"mangleProps",wc),u=k(t,r,"reserveProps",wc),p=k(t,r,"mangleQuoted",je),f=k(t,r,"minify",je),m=k(t,r,"minifySyntax",je),h=k(t,r,"minifyWhitespace",je),g=k(t,r,"minifyIdentifiers",je),y=k(t,r,"lineLimit",fn),x=k(t,r,"drop",qe),E=k(t,r,"dropLabels",qe),v=k(t,r,"charset",q),b=k(t,r,"treeShaking",je),T=k(t,r,"ignoreAnnotations",je),R=k(t,r,"jsx",q),L=k(t,r,"jsxFactory",q),C=k(t,r,"jsxFragment",q),M=k(t,r,"jsxImportSource",q),O=k(t,r,"jsxDev",je),_=k(t,r,"jsxSideEffects",je),P=k(t,r,"define",sr),N=k(t,r,"logOverride",sr),I=k(t,r,"supported",sr),F=k(t,r,"pure",qe),j=k(t,r,"keepNames",je),D=k(t,r,"platform",q),V=k(t,r,"tsconfigRaw",yN);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(wb).join(",")}):e.push(--target=${wb(i)})),a&&e.push(--format=${a}),c&&e.push(--global-name=${c}),D&&e.push(--platform=${D}),V&&e.push(--tsconfig-raw=${typeof V=="string"?V:JSON.stringify(V)}),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}),v&&e.push(--charset=${v}),b!==void 0&&e.push(--tree-shaking=${b}),T&&e.push("--ignore-annotations"),x)for(let B of x)e.push(--drop:${yt(B,"drop")});if(E&&e.push(--drop-labels=${Array.from(E).map(B=>yt(B,"dropLabels")).join(",")}),l&&e.push(--mangle-props=${l.source}),u&&e.push(--reserve-props=${u.source}),p!==void 0&&e.push(--mangle-quoted=${p}),R&&e.push(--jsx=${R}),L&&e.push(--jsx-factory=${L}),C&&e.push(--jsx-fragment=${C}),M&&e.push(--jsx-import-source=${M}),O&&e.push("--jsx-dev"),_&&e.push("--jsx-side-effects"),P)for(let B in P){if(B.indexOf("=")>=0)throw new Error(Invalid define: ${B});e.push(--define:${B}=${yt(PB,"define",B)})}if(N)for(let B in N){if(B.indexOf("=")>=0)throw new Error(Invalid log override: ${B});e.push(--log-override:${B}=${yt(NB,"log override",B)})}if(I)for(let B in I){if(B.indexOf("=")>=0)throw new Error(Invalid supported: ${B});let K=I[B];if(typeof K!="boolean")throw new Error(Expected value for supported ${et(B)} to be a boolean, got ${typeof K} instead);e.push(--supported:${B}=${K})}if(F)for(let B of F)e.push(--pure:${yt(B,"pure")});j&&e.push("--keep-names")}function bN(e,t,r,o,n){let s=[],i=[],a=Object.create(null),c=null,l=null;Ec(s,t,a,r,o),Pb(s,t,a);let u=k(t,a,"sourcemap",Rb),p=k(t,a,"bundle",je),f=k(t,a,"splitting",je),m=k(t,a,"preserveSymlinks",je),h=k(t,a,"metafile",je),g=k(t,a,"outfile",q),y=k(t,a,"outdir",q),x=k(t,a,"outbase",q),E=k(t,a,"tsconfig",q),v=k(t,a,"resolveExtensions",qe),b=k(t,a,"nodePaths",qe),T=k(t,a,"mainFields",qe),R=k(t,a,"conditions",qe),L=k(t,a,"external",qe),C=k(t,a,"packages",q),M=k(t,a,"alias",sr),O=k(t,a,"loader",sr),_=k(t,a,"outExtension",sr),P=k(t,a,"publicPath",q),N=k(t,a,"entryNames",q),I=k(t,a,"chunkNames",q),F=k(t,a,"assetNames",q),j=k(t,a,"inject",qe),D=k(t,a,"banner",sr),V=k(t,a,"footer",sr),B=k(t,a,"entryPoints",gN),K=k(t,a,"absWorkingDir",q),Y=k(t,a,"stdin",sr),ue=k(t,a,"write",je)??n,re=k(t,a,"allowOverwrite",je),ut=k(t,a,"mangleCache",sr);if(a.plugins=!0,lt(t,a,in ${e}() call),u&&s.push(--sourcemap${u===!0?"":=${u}}),p&&s.push("--bundle"),re&&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}),E&&s.push(--tsconfig=${E}),C&&s.push(--packages=${C}),v){let $=[];for(let Re of v){if(yt(Re,"resolve extension"),Re.indexOf(",")>=0)throw new Error(Invalid resolve extension: ${Re});$.push(Re)}s.push(--resolve-extensions=${$.join(",")})}if(P&&s.push(--public-path=${P}),N&&s.push(--entry-names=${N}),I&&s.push(--chunk-names=${I}),F&&s.push(--asset-names=${F}),T){let $=[];for(let Re of T){if(yt(Re,"main field"),Re.indexOf(",")>=0)throw new Error(Invalid main field: ${Re});$.push(Re)}s.push(--main-fields=${$.join(",")})}if(R){let $=[];for(let Re of R){if(yt(Re,"condition"),Re.indexOf(",")>=0)throw new Error(Invalid condition: ${Re});$.push(Re)}s.push(--conditions=${$.join(",")})}if(L)for(let $ of L)s.push(--external:${yt($,"external")});if(M)for(let $ in M){if($.indexOf("=")>=0)throw new Error(Invalid package name in alias: ${$});s.push(--alias:${$}=${yt(M$,"alias",$)})}if(D)for(let $ in D){if($.indexOf("=")>=0)throw new Error(Invalid banner file type: ${$});s.push(--banner:${$}=${yt(D$,"banner",$)})}if(V)for(let $ in V){if($.indexOf("=")>=0)throw new Error(Invalid footer file type: ${$});s.push(--footer:${$}=${yt(V$,"footer",$)})}if(j)for(let $ of j)s.push(--inject:${yt($,"inject")});if(O)for(let $ in O){if($.indexOf("=")>=0)throw new Error(Invalid loader extension: ${$});s.push(--loader:${$}=${yt(O$,"loader",$)})}if(_)for(let $ in _){if($.indexOf("=")>=0)throw new Error(Invalid out extension: ${$});s.push(--out-extension:${$}=${yt(_$,"out extension",$)})}if(B)if(Array.isArray(B))for(let $=0,Re=B.length;$<Re;$++){let xt=B[$];if(typeof xt=="object"&&xt!==null){let Ur=Object.create(null),$r=k(xt,Ur,"in",q),vr=k(xt,Ur,"out",q);if(lt(xt,Ur,"in entry point at index "+$),$r===void 0)throw new Error('Missing property "in" for entry point at index '+$);if(vr===void 0)throw new Error('Missing property "out" for entry point at index '+$);i.push([vr,$r])}else i.push(["",yt(xt,"entry point at index "+$)])}else for(let $ in B)i.push([$,yt(B[$],"entry point",$)]);if(Y){let $=Object.create(null),Re=k(Y,$,"contents",Tb),xt=k(Y,$,"resolveDir",q),Ur=k(Y,$,"sourcefile",q),$r=k(Y,$,"loader",q);lt(Y,$,'in "stdin" object'),Ur&&s.push(--sourcefile=${Ur}),$r&&s.push(--loader=${$r}),xt&&(l=xt),typeof Re=="string"?c=br(Re):Re instanceof Uint8Array&&(c=Re)}let Le=[];if(b)for(let $ of b)$+="",Le.push($);return{entries:i,flags:s,write:ue,stdinContents:c,stdinResolveDir:l,absWorkingDir:K,nodePaths:Le,mangleCache:_b(ut)}}function wN(e,t,r,o){let n=[],s=Object.create(null);Ec(n,t,s,r,o),Pb(n,t,s);let i=k(t,s,"sourcemap",Rb),a=k(t,s,"sourcefile",q),c=k(t,s,"loader",q),l=k(t,s,"banner",q),u=k(t,s,"footer",q),p=k(t,s,"mangleCache",sr);return lt(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:_b(p)}}function Ob(e){let t={},r={didClose:!1,reason:""},o={},n=0,s=0,i=new Uint8Array(16*1024),a=0,c=v=>{let b=a+v.length;if(b>i.length){let R=new Uint8Array(b*2);R.set(i),i=R}i.set(v,a),a+=v.length;let T=0;for(;T+4<=a;){let R=Au(i,T);if(T+4+R>a)break;T+=4,h(i.subarray(T,T+R)),T+=R}T>0&&(i.copyWithin(0,T,a),a-=T)},l=v=>{r.didClose=!0,v&&(r.reason=": "+(v.message||v));let b="The service was stopped"+r.reason;for(let T in o)o[T](b,null);o={}},u=(v,b,T)=>{if(r.didClose)return T("The service is no longer running"+r.reason,null);let R=n++;o[R]=(L,C)=>{try{T(L,C)}finally{v&&v.unref()}},v&&v.ref(),e.writeToStdin(Mu({id:R,isRequest:!0,value:b}))},p=(v,b)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(Mu({id:v,isRequest:!1,value:b}))},f=async(v,b)=>{try{if(b.command==="ping"){p(v,{});return}if(typeof b.key=="number"){let T=t[b.key];if(!T)return;let R=T[b.command];if(R){await R(v,b);return}}throw new Error("Invalid command: "+b.command)}catch(T){let R=[mn(T,e,null,void 0,"")];try{p(v,{errors:R})}catch{}}},m=!0,h=v=>{if(m){m=!1;let T=String.fromCharCode(...v);if(T!==ti)throw new Error(Cannot start service: Host version "${ti}" does not match binary version ${et(T)});return}let b=gb(v);if(b.isRequest)f(b.id,b.value);else{let T=o[b.id];delete o[b.id],b.value.error?T(b.value.error,{}):T(null,b.value)}};return{readFromStdout:c,afterClose:l,service:{buildOrContext:({callName:v,refs:b,options:T,isTTY:R,defaultWD:L,callback:C})=>{let M=0,O=s++,_={},P={ref(){++M===1&&b&&b.ref()},unref(){--M===0&&(delete t[O],b&&b.unref())}};t[O]=_,P.ref(),EN(v,O,u,p,P,e,_,T,R,L,(N,I)=>{try{C(N,I)}finally{P.unref()}})},transform:({callName:v,refs:b,input:T,options:R,isTTY:L,fs:C,callback:M})=>{let O=Sb(),_=P=>{try{if(typeof T!="string"&&!(T instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:N,mangleCache:I}=wN(v,R,L,bb),F={command:"transform",flags:N,inputFS:P!==null,input:P!==null?br(P):typeof T=="string"?br(T):T};I&&(F.mangleCache=I),u(b,F,(j,D)=>{if(j)return M(new Error(j),null);let V=Kn(D.errors,O),B=Kn(D.warnings,O),K=1,Y=()=>{if(--K===0){let ue={warnings:B,code:D.code,map:D.map,mangleCache:void 0,legalComments:void 0};"legalComments"in D&&(ue.legalComments=D?.legalComments),D.mangleCache&&(ue.mangleCache=D?.mangleCache),M(null,ue)}};if(V.length>0)return M(ri("Transform failed",V,B),null);D.codeFS&&(K++,C.readFile(D.code,(ue,re)=>{ue!==null?M(ue,null):(D.code=re,Y())})),D.mapFS&&(K++,C.readFile(D.map,(ue,re)=>{ue!==null?M(ue,null):(D.map=re,Y())})),Y()})}catch(N){let I=[];try{Ec(I,R,{},L,bb)}catch{}let F=mn(N,e,O,void 0,"");u(b,{command:"error",flags:I,error:F},()=>{F.detail=O.load(F.detail),M(ri("Transform failed",[F],[]),null)})}};if((typeof T=="string"||T instanceof Uint8Array)&&T.length>1024*1024){let P=_;_=()=>C.writeFile(T,P)}_(null)},formatMessages:({callName:v,refs:b,messages:T,options:R,callback:L})=>{if(!R)throw new Error(Missing second argument in ${v}() call);let C={},M=k(R,C,"kind",q),O=k(R,C,"color",je),_=k(R,C,"terminalWidth",fn);if(lt(R,C,in ${v}() call),M===void 0)throw new Error(Missing "kind" in ${v}() call);if(M!=="error"&&M!=="warning")throw new Error(Expected "kind" to be "error" or "warning" in ${v}() call);let P={command:"format-msgs",messages:eo(T,"messages",null,"",_),isWarning:M==="warning"};O!==void 0&&(P.color=O),_!==void 0&&(P.terminalWidth=_),u(b,P,(N,I)=>{if(N)return L(new Error(N),null);L(null,I.messages)})},analyzeMetafile:({callName:v,refs:b,metafile:T,options:R,callback:L})=>{R===void 0&&(R={});let C={},M=k(R,C,"color",je),O=k(R,C,"verbose",je);lt(R,C,in ${v}() call);let _={command:"analyze-metafile",metafile:T};M!==void 0&&(_.color=M),O!==void 0&&(_.verbose=O),u(b,_,(P,N)=>{if(P)return L(new Error(P),null);L(null,N.result)})}}}}function EN(e,t,r,o,n,s,i,a,c,l,u){let p=Sb(),f=e==="context",m=(y,x)=>{let E=[];try{Ec(E,a,{},c,xb)}catch{}let v=mn(y,s,p,void 0,x);r(n,{command:"error",flags:E,error:v},()=>{v.detail=p.load(v.detail),u(ri(f?"Context failed":"Build failed",[v],[]),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"),"");kN(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,E){let v=s.hasFS,{entries:b,flags:T,write:R,stdinContents:L,stdinResolveDir:C,absWorkingDir:M,nodePaths:O,mangleCache:_}=bN(e,a,c,xb,v);if(R&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let P={command:"build",key:t,entries:b,flags:T,write:R,stdinContents:L,stdinResolveDir:C,absWorkingDir:M||l,nodePaths:O,context:f};y&&(P.plugins=y),_&&(P.mangleCache=_);let N=(j,D)=>{let V={errors:Kn(j.errors,p),warnings:Kn(j.warnings,p),outputFiles:void 0,metafile:void 0,mangleCache:void 0},B=V.errors.slice(),K=V.warnings.slice();j.outputFiles&&(V.outputFiles=j.outputFiles.map(RN)),j.metafile&&(V.metafile=JSON.parse(j.metafile)),j.mangleCache&&(V.mangleCache=j.mangleCache),j.writeToStdout!==void 0&&console.log(Vn(j.writeToStdout).replace(/\n$/,"")),x(V,(Y,ue)=>{if(B.length>0||Y.length>0){let re=ri("Build failed",B.concat(Y),K.concat(ue));return D(re,null,Y,ue)}D(null,V,Y,ue)})},I,F;f&&(i["on-end"]=(j,D)=>new Promise(V=>{N(D,(B,K,Y,ue)=>{let re={errors:Y,warnings:ue};F&&F(B,K),I=void 0,F=void 0,o(j,re),V()})})),r(n,P,(j,D)=>{if(j)return u(new Error(j),null);if(!f)return N(D,(K,Y)=>(E(),u(K,Y)));if(D.errors.length>0)return u(ri("Context failed",D.errors,D.warnings),null);let V=!1,B={rebuild:()=>(I||(I=new Promise((K,Y)=>{let ue;F=(ut,Le)=>{ue||(ue=()=>ut?Y(ut):K(Le))};let re=()=>{r(n,{command:"rebuild",key:t},(Le,$)=>{Le?Y(new Error(Le)):ue?ue():re()})};re()})),I),watch:(K={})=>new Promise((Y,ue)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');lt(K,{},"in watch() call"),r(n,{command:"watch",key:t},Le=>{Le?ue(new Error(Le)):Y(void 0)})}),serve:(K={})=>new Promise((Y,ue)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let re={},ut=k(K,re,"port",fn),Le=k(K,re,"host",q),$=k(K,re,"servedir",q),Re=k(K,re,"keyfile",q),xt=k(K,re,"certfile",q),Ur=k(K,re,"fallback",q),$r=k(K,re,"onRequest",vb);lt(K,re,"in serve() call");let vr={command:"serve",key:t,onRequest:!!$r};ut!==void 0&&(vr.port=ut),Le!==void 0&&(vr.host=Le),$!==void 0&&(vr.servedir=$),Re!==void 0&&(vr.keyfile=Re),xt!==void 0&&(vr.certfile=xt),Ur!==void 0&&(vr.fallback=Ur),r(n,vr,(vf,hT)=>{if(vf)return ue(new Error(vf));$r&&(i["serve-request"]=(gT,yT)=>{$r(yT.args),o(gT,{})}),Y(hT)})}),cancel:()=>new Promise(K=>{if(V)return K();r(n,{command:"cancel",key:t},()=>{K()})}),dispose:()=>new Promise(K=>{if(V)return K();V=!0,r(n,{command:"dispose",key:t},()=>{K(),E(),n.unref()})})};n.ref(),u(null,B)})}}var kN=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 T={};if(typeof b!="object")throw new Error(Plugin at index ${g} must be an object);let R=k(b,T,"name",q);if(typeof R!="string"||R==="")throw new Error(Plugin at index ${g} is missing a name);try{let L=k(b,T,"setup",vb);if(typeof L!="function")throw new Error("Plugin is missing a setup function");lt(b,T,on plugin ${et(R)});let C={name:R,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};g++;let O=L({initialOptions:i,resolve:(_,P={})=>{if(!x)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof _!="string")throw new Error("The path to resolve must be a string");let N=Object.create(null),I=k(P,N,"pluginName",q),F=k(P,N,"importer",q),j=k(P,N,"namespace",q),D=k(P,N,"resolveDir",q),V=k(P,N,"kind",q),B=k(P,N,"pluginData",bc),K=k(P,N,"with",sr);return lt(P,N,"in resolve() call"),new Promise((Y,ue)=>{let re={command:"resolve",path:_,key:e,pluginName:R};if(I!=null&&(re.pluginName=I),F!=null&&(re.importer=F),j!=null&&(re.namespace=j),D!=null&&(re.resolveDir=D),V!=null)re.kind=V;else throw new Error('Must specify "kind" when calling "resolve"');B!=null&&(re.pluginData=c.store(B)),K!=null&&(re.with=vN(K,"with")),t(o,re,(ut,Le)=>{ut!==null?ue(new Error(ut)):Y({errors:Kn(Le.errors,c),warnings:Kn(Le.warnings,c),path:Le.path,external:Le.external,sideEffects:Le.sideEffects,namespace:Le.namespace,suffix:Le.suffix,pluginData:c.load(Le.pluginData)})})})},onStart(_){let P='This error came from the "onStart" callback registered here:',N=yc(new Error(P),n,"onStart");l.push({name:R,callback:_,note:N}),C.onStart=!0},onEnd(_){let P='This error came from the "onEnd" callback registered here:',N=yc(new Error(P),n,"onEnd");u.push({name:R,callback:_,note:N}),C.onEnd=!0},onResolve(_,P){let N='This error came from the "onResolve" callback registered here:',I=yc(new Error(N),n,"onResolve"),F={},j=k(_,F,"filter",wc),D=k(_,F,"namespace",q);if(lt(_,F,in onResolve() call for plugin ${et(R)}),j==null)throw new Error("onResolve() call is missing a filter");let V=h++;p[V]={name:R,callback:P,note:I},C.onResolve.push({id:V,filter:j.source,namespace:D||""})},onLoad(_,P){let N='This error came from the "onLoad" callback registered here:',I=yc(new Error(N),n,"onLoad"),F={},j=k(_,F,"filter",wc),D=k(_,F,"namespace",q);if(lt(_,F,in onLoad() call for plugin ${et(R)}),j==null)throw new Error("onLoad() call is missing a filter");let V=h++;f[V]={name:R,callback:P,note:I},C.onLoad.push({id:V,filter:j.source,namespace:D||""})},onDispose(_){m.push(_)},esbuild:n.esbuild});O&&await O,y.push(C)}catch(L){return{ok:!1,error:L,pluginName:R}}}s["on-start"]=async(b,T)=>{c.clear();let R={errors:[],warnings:[]};await Promise.all(l.map(async({name:L,callback:C,note:M})=>{try{let O=await C();if(O!=null){if(typeof O!="object")throw new Error(Expected onStart() callback in plugin ${et(L)} to return an object);let _={},P=k(O,_,"errors",qe),N=k(O,_,"warnings",qe);lt(O,_,from onStart() callback in plugin ${et(L)}),P!=null&&R.errors.push(...eo(P,"errors",c,L,void 0)),N!=null&&R.warnings.push(...eo(N,"warnings",c,L,void 0))}}catch(O){R.errors.push(mn(O,n,c,M&&M(),L))}})),r(b,R)},s["on-resolve"]=async(b,T)=>{let R={},L="",C,M;for(let O of T.ids)try{({name:L,callback:C,note:M}=p[O]);let _=await C({path:T.path,importer:T.importer,namespace:T.namespace,resolveDir:T.resolveDir,kind:T.kind,pluginData:c.load(T.pluginData),with:T.with});if(_!=null){if(typeof _!="object")throw new Error(Expected onResolve() callback in plugin ${et(L)} to return an object);let P={},N=k(_,P,"pluginName",q),I=k(_,P,"path",q),F=k(_,P,"namespace",q),j=k(_,P,"suffix",q),D=k(_,P,"external",je),V=k(_,P,"sideEffects",je),B=k(_,P,"pluginData",bc),K=k(_,P,"errors",qe),Y=k(_,P,"warnings",qe),ue=k(_,P,"watchFiles",qe),re=k(_,P,"watchDirs",qe);lt(_,P,from onResolve() callback in plugin ${et(L)}),R.id=O,N!=null&&(R.pluginName=N),I!=null&&(R.path=I),F!=null&&(R.namespace=F),j!=null&&(R.suffix=j),D!=null&&(R.external=D),V!=null&&(R.sideEffects=V),B!=null&&(R.pluginData=c.store(B)),K!=null&&(R.errors=eo(K,"errors",c,L,void 0)),Y!=null&&(R.warnings=eo(Y,"warnings",c,L,void 0)),ue!=null&&(R.watchFiles=xc(ue,"watchFiles")),re!=null&&(R.watchDirs=xc(re,"watchDirs"));break}}catch(_){R={id:O,errors:[mn(_,n,c,M&&M(),L)]};break}r(b,R)},s["on-load"]=async(b,T)=>{let R={},L="",C,M;for(let O of T.ids)try{({name:L,callback:C,note:M}=f[O]);let _=await C({path:T.path,namespace:T.namespace,suffix:T.suffix,pluginData:c.load(T.pluginData),with:T.with});if(_!=null){if(typeof _!="object")throw new Error(Expected onLoad() callback in plugin ${et(L)} to return an object);let P={},N=k(_,P,"pluginName",q),I=k(_,P,"contents",Tb),F=k(_,P,"resolveDir",q),j=k(_,P,"pluginData",bc),D=k(_,P,"loader",q),V=k(_,P,"errors",qe),B=k(_,P,"warnings",qe),K=k(_,P,"watchFiles",qe),Y=k(_,P,"watchDirs",qe);lt(_,P,from onLoad() callback in plugin ${et(L)}),R.id=O,N!=null&&(R.pluginName=N),I instanceof Uint8Array?R.contents=I:I!=null&&(R.contents=br(I)),F!=null&&(R.resolveDir=F),j!=null&&(R.pluginData=c.store(j)),D!=null&&(R.loader=D),V!=null&&(R.errors=eo(V,"errors",c,L,void 0)),B!=null&&(R.warnings=eo(B,"warnings",c,L,void 0)),K!=null&&(R.watchFiles=xc(K,"watchFiles")),Y!=null&&(R.watchDirs=xc(Y,"watchDirs"));break}}catch(_){R={id:O,errors:[mn(_,n,c,M&&M(),L)]};break}r(b,R)};let E=(b,T)=>T([],[]);u.length>0&&(E=(b,T)=>{(async()=>{let R=[],L=[];for(let{name:C,callback:M,note:O}of u){let _,P;try{let N=await M(b);if(N!=null){if(typeof N!="object")throw new Error(Expected onEnd() callback in plugin ${et(C)} to return an object);let I={},F=k(N,I,"errors",qe),j=k(N,I,"warnings",qe);lt(N,I,from onEnd() callback in plugin ${et(C)}),F!=null&&(_=eo(F,"errors",c,C,void 0)),j!=null&&(P=eo(j,"warnings",c,C,void 0))}}catch(N){_=[mn(N,n,c,O&&O(),C)]}if(_){R.push(..._);try{b.errors.push(..._)}catch{}}if(P){L.push(...P);try{b.warnings.push(...P)}catch{}}}T(R,L)})()});let v=()=>{for(let b of m)setTimeout(()=>b(),0)};return x=!0,{ok:!0,requestPlugins:y,runOnEndCallbacks:E,scheduleOnDisposeCallbacks:v}};function Sb(){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 yc(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=Nb(t,s,r);if(i)return o={text:e.message,location:i},o}catch{}}}function mn(e,t,r,o,n){let s="Internal error",i=null;try{s=(e&&e.message||e)+""}catch{}try{i=Nb(t,(e.stack+"").split(
),"")}catch{}return{id:"",pluginName:n,text:s,location:i,notes:o?[o]:[],detail:r?r.store(e):-1}}function Nb(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:br(c.slice(0,l)).length,length:br(c.slice(l,l+u)).length,lineText:c+
+t.slice(1).join(
),suggestion:""}}break}}return null}function ri(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 Kn(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function kb(e,t,r){if(e==null)return null;let o={},n=k(e,o,"file",q),s=k(e,o,"namespace",q),i=k(e,o,"line",fn),a=k(e,o,"column",fn),c=k(e,o,"length",fn),l=k(e,o,"lineText",q),u=k(e,o,"suggestion",q);if(lt(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 eo(e,t,r,o,n){let s=[],i=0;for(let a of e){let c={},l=k(a,c,"id",q),u=k(a,c,"pluginName",q),p=k(a,c,"text",q),f=k(a,c,"location",Eb),m=k(a,c,"notes",qe),h=k(a,c,"detail",bc),g=in element ${i} of "${t}";lt(a,c,g);let y=[];if(m)for(let x of m){let E={},v=k(x,E,"text",q),b=k(x,E,"location",Eb);lt(x,E,g),y.push({text:v||"",location:kb(b,g,n)})}s.push({id:l||"",pluginName:u||o,text:p||"",location:kb(f,g,n),notes:y,detail:r?r.store(h):-1}),i++}return s}function xc(e,t){let r=[];for(let o of e){if(typeof o!="string")throw new Error(${et(t)} must be an array of strings);r.push(o)}return r}function vN(e,t){let r=Object.create(null);for(let o in e){let n=e[o];if(typeof n!="string")throw new Error(key ${et(o)} in object ${et(t)} must be a string);r[o]=n}return r}function RN({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=Vn(n)),o}}}var Cb=ti,vc=e=>Rc().build(e),Mb=(e,t)=>Rc().transform(e,t),Ab=(e,t)=>Rc().formatMessages(e,t),Ib=(e,t)=>Rc().analyzeMetafile(e,t);var dn,Lb,kc,Rc=()=>{if(kc)return kc;throw dn?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')},Tc=e=>{let t=e.wasm,r=e.worker;if(dn)throw new Error('Cannot call "initialize" more than once');return dn=TN(t,r),dn.catch(()=>{dn=void 0}),dn},TN=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}=Ob({writeToStdin(c){r.postMessage(c)},isSync:!1,hasFS:!1,esbuild:{build:vc,transform:Mb,formatMessages:Ab,analyzeMetafile:Ib,version:Cb,initialize:Tc}});await s,Lb=()=>{r.terminate(),dn=void 0,Lb=void 0,kc=void 0},kc={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 Pt(e){if(typeof e!="string")throw new TypeError(Path must be a string. Received ${JSON.stringify(e)})}function Mr(e){return e===47||e===92}function to(e){return e>=97&&e<=122||e>=65&&e<=90}function Oc(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError("Must be a file URL.");return e}function Fb(e){e=Oc(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}function Fu(e){Pt(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return Mr(r)?!0:!!(to(r)&&t>2&&e.charCodeAt(1)===58&&Mr(e.charCodeAt(2)))}var Sc=class extends Error{constructor(t){super(t),this.name="AssertionError"}};function Nc(e,t=""){if(!e)throw new Sc(t)}var UN={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function Lc(e){return e.replaceAll(/[\s]/g,t=>UN[t]??t)}function $b(e){if(!Fu(e))throw new TypeError("Must be an absolute path.");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=Lc(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError("Invalid hostname.");return o}function ro(e){return e===47}function Bb(e){return e=Oc(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function Uu(e){return Pt(e),e.length>0&&ro(e.charCodeAt(0))}function Wb(e){if(!Uu(e))throw new TypeError("Must be an absolute path.");let t=new URL("file:///");return t.pathname=Lc(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}var XN=(()=>{let{Deno:e}=globalThis;if(typeof e?.build?.os=="string")return e.build.os;let{navigator:t}=globalThis;return t?.appVersion?.includes?.("Win")?"windows":"linux"})(),Ke=XN==="windows";var Yn=Ke?"\\":"/";function Cc(e){return Ke?Fb(e):Bb(e)}function ni(e){return Ke?$b(e):Wb(e)}function Mc(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function Ac(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 Gb(e){return Mc(e)&&(e.imports!==void 0?$u(e.imports):!0)&&(e.scopes!==void 0?ju(e.scopes):!0)}function $u(e){return Mc(e)}function ju(e){return Mc(e)&&Object.values(e).every(t=>Bu(t))}function Bu(e){return Mc(e)}function Ic(e){try{return new URL(e),!0}catch{return!1}}function zb(e,t){let r={};for(let[o,n]of Object.entries(e)){let s=QN(o,t);if(s===null)continue;if(typeof n!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let i=Hu(n,t);if(i===null){console.warn("the address was invalid."),r[s]=null;continue}if(o.endsWith("/")&&!Ar(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]=Ar(i)}return Ac(r)}function Ar(e){return e.href}function JN(e,t){let r={};for(let[n,s]of Object.entries(e)){if(!Bu(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=Ar(i);r[a]=zb(s,t)}let o={};for(let n of Object.keys(r))o[n]=Ac(r[n]);return Ac(o)}function QN(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=Hu(e,t);return r!==null?Ar(r):e}function Hu(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 ZN=["ftp","file","http","https","ws","wss"];function eL(e){return ZN.some(t=>Ar(e).startsWith(t))}function qb(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(!Ic(n))throw new TypeError("resolutionResult must be an URL.");return n}else if(o.endsWith("/")&&e.startsWith(o)&&(t===null||eL(t))){if(n===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!Ic(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(!Ic(i))throw new TypeError("url must be an URL.");if(!Ar(i).startsWith(n))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return Ar(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 Wu(e,t){let r={};if(!Gb(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(!$u(o))throw new TypeError('"imports" top-level key needs to be an object.');r=zb(o,t)}let s={};if(n!==void 0){if(!ju(n))throw new TypeError('"scopes" top-level key needs to be an object.');s=JN(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 Vb(e,{imports:t={},scopes:r={}},o){let n=Ar(o),s=Hu(e,o),i=s!==null?Ar(s):e;for(let[c,l]of Object.entries(r))if(c===n||c.endsWith("/")&&n.startsWith(c)){let u=qb(i,s,l);if(u!==null)return u}let a=qb(i,s,t);if(a!==null)return a;if(s!==null)return Ar(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}function Yb(e,{allowTrailingComma:t=!0}={}){if(new.target)throw new TypeError("parse is not a constructor");return new Gu(e,{allowTrailingComma:t}).parse()}var Kb=globalThis.JSON.parse,Gu=class{#i=new Set( \r
);#o=new Set([..."[]{}:,/",...this.#i]);#t;#e;#s;#a;constructor(t,r){this.#t=${t},this.#e=this.#t.length,this.#s=this.#m(),this.#a=r}parse(){let t=this.#n(),r=this.#p(t),{done:o,value:n}=this.#s.next();if(!o)throw new SyntaxError(vo(n));return r}#n(){let{done:t,value:r}=this.#s.next();if(t)throw new SyntaxError("Unexpected end of JSONC input");return r}*#m(){for(let t=0;t<this.#e;t++)if(!this.#i.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.#o.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.#r();case"NullOrTrueOrFalseOrNumber":return this.#g(t);case"String":return this.#h(t);default:throw new SyntaxError(vo(t))}}#f(){let t={};for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndObject")return t;if(o.type!=="String")throw new SyntaxError(vo(o));let n=this.#h(o),s=this.#n();if(s.type!=="NameSeparator")throw new SyntaxError(vo(s));let i=this.#n();Object.defineProperty(t,n,{value:this.#p(i),writable:!0,enumerable:!0,configurable:!0});let a=this.#n();if(a.type==="EndObject")return t;if(a.type!=="ValueSeparator")throw new SyntaxError(vo(a))}}#r(){let t=[];for(let r=!0;;r=!1){let o=this.#n();if((r||this.#a.allowTrailingComma)&&o.type==="EndArray")return t;t.push(this.#p(o));let n=this.#n();if(n.type==="EndArray")return t;if(n.type!=="ValueSeparator")throw new SyntaxError(vo(n))}}#h(t){let r;try{r=Kb(t.sourceText)}catch{throw new SyntaxError(vo(t))}return Nc(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=Kb(t.sourceText)}catch{throw new SyntaxError(vo(t))}return Nc(typeof r=="number"),r}};function vo({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 Dc(e){if(e.protocol==="file:")return{path:Cc(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}}async function qu(e){let t=await Deno.readTextFile(e),r=Yb(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 Xb(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 rL=${Yn}node_modules${Yn},oL=${Yn}node_modules;function Fc(e){return e.includes(rL)||e.endsWith(oL)}function zu(e){return(e.namespace===""||e.namespace==="file")&&(Fc(e.resolveDir)||Fc(e.path)||Fc(e.importer))}function Vu(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 qu(e.configPath);if(i.imports!==void 0||i.scopes!==void 0){let a={imports:i.imports,scopes:i.scopes};Xb(a),r=Wu(a,ni(e.configPath))}else i.importMap!==void 0&&(s=new URL(i.importMap,ni(e.configPath)).href)}else e.importMapURL!==void 0&&(s=e.importMapURL);if(s){let i=await fetch(s),a=await i.json();r=Wu(a,new URL(i.url))}}),t.onResolve({filter:/.*/},async function(s){if(zu(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(${ni(s.resolveDir).href}/);else return;let a;if(r!==null){let p=Vb(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}=Dc(a);return await t.resolve(c,{namespace:l,kind:s.kind})})}}}var NPe=new TextEncoder;var nL=[],sL=[],Ku="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";for(let e=0,t=Ku.length;e<t;++e)nL[e]=Ku[e],sL[Ku.charCodeAt(e)]=e;var JPe=Deno.env.get("DENO_REGISTRY_URL")??"https://jsr.io";var fL=await Deno.permissions.query({name:"run"}).then(e=>e.state!=="granted")?"portable":"native";var Jb=Vu;var Qb=" must not return ",dL="transformer",hL="recoverer",gL="defaultValue",Xn=dL+Qb,oo="called with ",Jn=gL+" must not be ",Qn=hL+Qb;var Uc="null or undefined",Zn=Xn+Uc,yL=oo+Uc,Yu=Jn+Uc,$c=Qn+Uc;function wr(e){return e!=null}var xL="Ok",Zb="Err",ew=oo+Zb,tw=oo+xL,bL="Carrying E in "+Zb+" instead of throwing it directly. See .cause",Xu="an instance of Error of the current realm.",zOe="The thrown value is not "+Xu,VOe="The contained E should be "+Xu,wL="This .cause is not "+Xu;function pt(e){return e.ok}function At(e){return{ok:!0,val:e,err:null}}function Bt(e){return!e.ok}function Kt(e){return{ok:!1,val:null,err:e}}function hn(e){return rw(e,ew)}function es(e){return ow(e,tw)}function rw(e,t){if(Bt(e))throw new TypeError(t);return e.val}function ow(e,t){if(pt(e))throw new TypeError(t);return e.err}function Ju(e,t){if(wr(e))return At(e);let r=t();return Kt(r)}var nw=e=>!!(EL.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),EL=["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"];function To(e){if(typeof e!="string")throw new TypeError(Path must be a string, received "${JSON.stringify(e)}")}function gn(e){return e===47}function jc(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 ts(e){return e=jc(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function sw(e){e instanceof URL&&(e=ts(e)),To(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(gn(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 iw(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 aw(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 cw(e,t){if(To(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(Suffix must be a string, received "${JSON.stringify(t)}")}function lw(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 pw(e,t=""){e instanceof URL&&(e=ts(e)),cw(e,t);let r=aw(e,gn),o=lw(r,gn);return t?iw(o,t):o}function uw(){let e=globalThis,t=e.Deno?.build?.os;return typeof t=="string"?t==="windows":e.navigator?.platform?.startsWith("Win")??e.process?.platform?.startsWith("win")??!1}var Bc=uw();function mw(e){e=jc(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}function fw(e){return Bc?mw(e):ts(e)}var vL={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function Hc(e){return e.replaceAll(/[\s]/g,t=>vL[t]??t)}function dw(e){return To(e),e.length>0&&gn(e.charCodeAt(0))}function hw(e){if(!dw(e))throw new TypeError(Path must be absolute: received "${e}");let t=new URL("file:///");return t.pathname=Hc(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}function Zu(e){return e===47||e===92}function gw(e){return e>=97&&e<=122||e>=65&&e<=90}function yw(e){To(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return Zu(r)?!0:!!(gw(r)&&t>2&&e.charCodeAt(1)===58&&Zu(e.charCodeAt(2)))}function xw(e){if(!yw(e))throw new TypeError(Path must be absolute: received "${e}");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),o=new URL("file:///");if(o.pathname=Hc(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(o.hostname=t,!o.hostname))throw new TypeError(Invalid hostname: "${o.hostname}");return o}function bw(e){return Bc?xw(e):hw(e)}var ww=e=>{if(e.protocol==="file:")return{path:fw(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},em=e=>e.namespace==="file"?bw(e.path):new URL(${e.namespace}:${e.path});var Ew=(e,t)=>{let r=Ju(NL(e),()=>({name:"NotFoundError",message:"Source map URL is not found"}));if(G(r))return r;let{url:o,start:n,end:s}=z(r);return URL.canParse(o,t)?le({url:new URL(o,t),start:n,end:s}):ee({name:"InvalidURLError",message:Invalid URL: ${o}})},NL=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 LL=["base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx"],kw=e=>LL.includes(e),vw=e=>/^js|^ts|css$/.test(e),Rw=e=>{let t=e.url,r=pw(t);if(kw(r))return r;if(r==="mjs")return"js";let o=new URL(t);o.search="",o.hash="";let n=sw(o.href).slice(1);if(kw(n))return n;if(n==="mjs")return"js";let i=(e.headers.get("Content-Type")??"text/plain").split(";")[0]?.trim?.()??"text/plain";return CL(i)},CL=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 Wc(e,t){if(isNaN(e)||isNaN(t))throw new Error("Cannot compare against non-numbers");return e===t?0:e<t?-1:1}function Pw(e=[],t=[]){return e.length&&!t.length?-1:!e.length&&t.length?1:0}function rm(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 rs="0|[1-9]\\d*",ML="\\d*[a-zA-Z-][a-zA-Z0-9-]*",AL=(?<major>${rs})\\.(?<minor>${rs})\\.(?<patch>${rs}),Tw=(?:${rs}|${ML}),Ow=(?:-(?<prerelease>${Tw}(?:\\.${Tw})*)),_w="[0-9A-Za-z-]+",Sw=(?:\\+(?<buildmetadata>${_w}(?:\\.${_w})*)),Nw=v?${AL}${Ow}?${Sw}?,Lw=new RegExp(^${Nw}$),Cw="(?:<|>)?=?",IL="x|X|\\*",tm=${rs}|${IL},Gc=v=\\s*(?<major>${tm})(?:\\.(?<minor>${tm})(?:\\.(?<patch>${tm})${Ow}?${Sw}?)?)?,Mw=new RegExp(^(?<operator>~>?|\\^|${Cw})\\s*${Gc}$),Aw=new RegExp(^(?<operator>${Cw})\\s*(${Nw})$|^$);function om(e){return typeof e=="number"&&!Number.isNaN(e)&&(!Number.isFinite(e)||0<=e&&e<=Number.MAX_SAFE_INTEGER)}var nm=256;var FL=new RegExp(^${rs}$);function Yt(e){return e.split(".").filter(Boolean).map(t=>{if(FL.test(t)){let r=Number(t);if(om(r))return r}return t})}function Ir(e){return e.split(".").filter(Boolean)}function _o(e,t){let r=Number(e);if(!om(r))throw new TypeError(t);return r}function yn(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 ir(e,t){return e===t?0:Wc(e.major,t.major)||Wc(e.minor,t.minor)||Wc(e.patch,t.patch)||Pw(e.prerelease,t.prerelease)||rm(e.prerelease,t.prerelease)}function sm(e){return e.toFixed(0)}function xn(e){let t=sm(e.major),r=sm(e.minor),o=sm(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 DL(e,t){if(yn(t))return!0;let r=ir(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 qc(e,t){for(let r of t)if(!DL(e,r))return!1;if(e.prerelease&&e.prerelease.length>0){for(let r of t){if(yn(r))continue;let{major:o,minor:n,patch:s,prerelease:i}=r;if(i&&i.length>0&&e.major===o&&e.minor===n&&e.patch===s)return!0}return!1}return!0}function zc(e,t){return t.some(r=>qc(e,r))}var Vc={major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]},os={operator:void 0,...Vc};function Iw(e,t){return ir(e,t)>0}function si(e,t){let r;for(let o of e)zc(o,t)&&(r=r&&Iw(r,o)?r:o);return r}function UL(e){let r=e.match(Aw)?.groups;if(!r)return null;let{operator:o,prerelease:n,buildmetadata:s}=r,i=r.major?{major:_o(r.major,Cannot parse comparator ${e}: invalid major version),minor:_o(r.minor,Cannot parse comparator ${e}: invalid minor version),patch:_o(r.patch,Cannot parse comparator ${e}: invalid patch version),prerelease:n?Yt(n):[],build:s?Ir(s):[]}:Vc;return{operator:o||void 0,...i}}function Ne(e){return!e||e.toLowerCase()==="x"||e==="*"}function $L(e){if(!Ne(e.major))return Ne(e.minor)?{operator:">=",major:+e.major,minor:0,patch:0,prerelease:[],build:[]}:Ne(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?Yt(e.prerelease):[],build:[]}}function jL(e){if(!Ne(e.major))return Ne(e.minor)?{operator:"<",major:+e.major+1,minor:0,patch:0,prerelease:[],build:[]}:Ne(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:Yt(e.prerelease),build:[]}:{operator:"<=",major:+e.major,minor:+e.minor,patch:+e.patch,prerelease:[],build:[]}}function BL(e){let t=e.match(new RegExp(^${Gc})),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(^${Gc}\\s*$))?.groups;if(!a)return null;let c=$L(r),l=jL(a);return[c,l].filter(Boolean)}function HL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[os];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=Yt(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 WL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[os];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=Yt(e.prerelease??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a},{operator:"<",major:n,minor:s+1,patch:0}]}function GL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(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=Yt(e.prerelease??""),c=Ir(e.build??"");return[{operator:"<",major:n,minor:s,patch:i,prerelease:a,build:c}]}function qL(e){let t=Ne(e.minor),r=Ne(e.patch),o=+e.major,n=+e.minor,s=+e.patch;if(t)return r?[{operator:"<",major:o+1,minor:0,patch:0}]:[{operator:"<",major:o,minor:n+1,patch:0}];if(r)return[{operator:"<",major:o,minor:n+1,patch:0}];let i=Yt(e.prerelease??""),a=Ir(e.build??"");return[{operator:"<=",major:o,minor:n,patch:s,prerelease:i,build:a}]}function zL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(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=Yt(e.prerelease??""),c=Ir(e.build??"");return[{operator:">",major:n,minor:s,patch:i,prerelease:a,build:c}]}function VL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[os];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=Yt(e.prerelease??""),c=Ir(e.build??"");return[{operator:">=",major:n,minor:s,patch:i,prerelease:a,build:c}]}function KL(e){let t=Ne(e.major),r=Ne(e.minor),o=Ne(e.patch),n=+e.major,s=+e.minor,i=+e.patch;if(t)return[os];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=Yt(e.prerelease??""),c=Ir(e.build??"");return[{operator:void 0,major:n,minor:s,patch:i,prerelease:a,build:c}]}function YL(e){let t=e.match(Mw)?.groups;if(!t)return UL(e);switch(t.operator){case"^":return HL(t);case"~":case"~>":return WL(t);case"<":return GL(t);case"<=":return qL(t);case">":return zL(t);case">=":return VL(t);case"=":case"":return KL(t);default:throw new Error(Cannot parse version range: '${t.operator}' is not a valid operator)}}function XL(e){return e.split(/\s+/).flatMap(YL)}function Fw(e){let t=e.replaceAll(/(?<=<|>|=|~|\^)(\s+)/g,"").split(/\s*\|\|\s*/).map(r=>BL(r)||XL(r));if(t.some(r=>r.includes(null)))throw new TypeError(Cannot parse version range: range "${e}" is invalid);return t}function im(e){if(typeof e!="string")throw new TypeError(Cannot parse version as version must be a string: received ${typeof e});if(e.length>nm)throw new TypeError(Cannot parse version as version length is too long: length is ${e.length}, max length is ${nm});e=e.trim();let t=e.match(Lw)?.groups;if(!t)throw new TypeError(Cannot parse version: ${e});let r=_o(t.major,Cannot parse version ${e}: invalid major version),o=_o(t.minor,Cannot parse version ${e}: invalid minor version),n=_o(t.patch,Cannot parse version ${e}: invalid patch version),s=t.prerelease?Yt(t.prerelease):[],i=t.buildmetadata?Ir(t.buildmetadata):[];return{major:r,minor:o,patch:n,prerelease:s,build:i}}function am(e){try{return Fw(e)}catch{return}}function cm(e){try{return im(e)}catch{return}}var ii={operator:void 0,major:Number.NaN,minor:Number.NaN,patch:Number.NaN,prerelease:[],build:[]};var Po=async e=>{try{let t=await fetch(e);return t.ok?le([t,!1]):ee({name:"HTTPError",message:${t.status} ${t.statusText},response:t})}catch(t){if(t instanceof TypeError)return ee({name:"NetworkError",message:t.message,request:e});if(t instanceof DOMException)return ee({name:"AbortError",message:t.message,request:e});throw t}};var lm="https://jsr.io",Dw=async(e,t)=>{let r=await(t?.fetch??Po)(new Request(${t?.endpoint??lm}/${e}/meta.json),t?.cacheFirst);return Gt(r,([o])=>o.json())};var Uw=async(e,t,r)=>{let o=await(r?.fetch??Po)(new Request(${r?.endpoint??lm}/${e}/${t}_meta.json),r?.cacheFirst);return Gt(o,([n])=>n.json())};var $w=async(e,t)=>{let r=await(t?.fetch??Po)(new Request(${t?.endpoint??"https://registry.npmjs.org"}/${e}),t?.cacheFirst);return Gt(r,([o])=>o.json())};var Hw=(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}),Kc=(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}),Ww=async(e,t)=>{if(t?.resolvedVersions){let c=new Map(t.resolvedVersions.get(e.name)??[]),l=si([...c.keys()],e.range);if(l){let u=c.get(l)??ai,p=u[e.entryPoint];return typeof p!="string"&&console.log(p),p?le(jw(e.name,xn(l),p)):ee(Kc(e,Object.keys(u)))}}let r=await $w(e.name,t);if(G(r))return r;let o=z(r),n=new Map(Object.entries(o.versions).flatMap(([c,{exports:l}])=>{let u=cm(c);return u?[[u,l??ai]]:[]})),s=si([...n.keys()],e.range);if(!s)return ee(Hw(e,Object.keys(o.versions)));let i={...ai};for(let c of Object.keys(n.get(s)??ai))i[c]=c;let a=i[e.entryPoint];return a?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[s,i]]),le(jw(e.name,xn(s),a))):ee(Kc(e,Object.keys(i)))},jw=(e,t,r)=>new URL(r,https://esm.sh/${e}@${t}/),Gw=async(e,t)=>{if(t?.resolvedVersions){let a=new Map(t.resolvedVersions.get(e.name)??[]),c=si([...a.keys()],e.range);if(c){let l=a.get(c)??ai,u=l[e.entryPoint];return u?le(Bw(e.name,xn(c),u)):ee(Kc(e,Object.keys(l)))}}let r=await JL(e,t);if(G(r))return r;let o=z(r),n=await Uw(e.name,xn(o),t);if(G(n))return n;let s=z(n).exports,i=s[e.entryPoint];return i?(t?.resolvedVersions?.set(e.name,[...t.resolvedVersions.get(e.name)??[],[o,s]]),le(Bw(e.name,xn(o),i))):ee(Kc(e,Object.keys(z(n).exports)))},Bw=(e,t,r)=>new URL(r,https://jsr.io/${e}/${t}/),JL=async(e,t)=>{let r=await Dw(e.name,t);if(G(r))return r;let o=z(r),n=Object.keys(o.versions).flatMap(i=>{let a=cm(i);return a?[a]:[]}),s=si(n,e.range);return s?le(s):ee(Hw(e,Object.keys(o.versions)))},ai={".":"./"};var QL=e=>({name:"OnlyScopeProvidedError",specifier:e}),qw=e=>({name:"PackageNotFoundError",specifier:e}),zw=e=>{if(e.protocol!=="npm:")return ee({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 ee(QL(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 ee(qw(e));let s=t.slice(r,n),i=decodeURIComponent(t.slice(n+1,o)),a=i?am(i)??[[ii]]:[[ii]],c=t.slice(o+1),l=c?./${c}:".",u={name:s,range:a,entryPoint:l};return i&&(u.tag=i),le(u)},Vw=e=>{if(e.protocol!=="jsr:")return ee({name:"NotJsrProtocolError",specifier:e});let t=e.pathname,r=t[0]==="/"?1:0;if(t[r]!=="@")return ee({name:"ScopeNotFoundError",specifier:e});let o=t.indexOf("/",r);if(o===-1)return ee(qw(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?am(a)??[[ii]]:[[ii]],l=t.slice(n+1),u=l?./${l}:".",p={name:i,range:c,entryPoint:u};return a&&(p.tag=a),le(p)};var Kw=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 Jw=e=>{let t=new Map,r=async o=>{let n=o.namespace==="npm",s=(n?zw:Vw)(em(o));if(G(s)){let a=ne(s);return{errors:[{text:a.name,detail:a}]}}let i=await(n?Ww:Gw)(z(s),{resolvedVersions:t,...e});if(G(i)){let a=ne(i);return{errors:[{text:${a.name} ${a.message},detail:a}]}}return ww(z(i))};return{name:"remote-loader",setup({onLoad:o,onResolve:n,initialOptions:s}){for(let i of[...Yw,...Xw])n({filter:/.*/,namespace:i.slice(0,-1)},ZL);n({filter:/.*/,namespace:"npm"},r),n({filter:/.*/,namespace:"jsr"},r);for(let i of Yw)o({filter:/.*/,namespace:i.slice(0,-1)},a=>e1(em(a),{...e,sourcemap:s.sourcemap!==!1&&s.sourcemap!==void 0}));for(let i of Xw)o({filter:/.*/,namespace:i.slice(0,-1)},()=>{throw new Error(${i} import is not supported yet.)})}}},ZL=e=>({path:e.path,namespace:e.namespace}),Yw=["http:","https:","data:"],Xw=["node:"],e1=async(e,t)=>{let r=t.reload?t.reload===!0?!1:!t.reload.some(l=>l.test(e)):!0,o=t.fetch??Po,n=await o(new Request(e),r);if(G(n))return{errors:[{text:${ne(n).message} Failed to fetch ${e},detail:ne(n)}]};let[s,i]=z(n),a=Rw(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&&vw(a)){let l=await c.text(),u=Ew(l,e);if(We(u)){let{url:p,start:f,end:m}=z(u);if(p.protocol!=="data:"){let h=await o(new Request(p),r);if(G(h))return{contents:l,loader:a,warnings:[{text:${ne(h).message} Failed to fetch the source map URL,notes:[{text:Source map URL: ${p}},{text:Original URL: ${e}}],detail:ne(h)}]};let g=await z(h)[0].blob().then(Kw);return{contents:l.slice(0,f)+g+l.slice(m),loader:a}}}}return{contents:new Uint8Array(await c.arrayBuffer()),loader:a}};var pi=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"}},t1=/[$_\p{ID_Start}]/u,r1=/[$_\u200C\u200D\p{ID_Continue}]/u,um=".*";function o1(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function eE(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&&t1.test(c)||a!==o+1&&r1.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(!o1(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 tE(e,t={}){let r=eE(e);t.delimiter??="/#?",t.prefixes??="./";let o=^${ar(t.delimiter)}+?,n=[],s=0,i=0,a="",c=new Set,l=v=>{if(i<r.length&&r[i].type===v)return r[i++].value},u=()=>l("OTHER_MODIFIER")??l("ASTERISK"),p=v=>{let b=l(v);if(b!==void 0)return b;let{type:T,index:R}=r[i];throw new TypeError(Unexpected ${T} at ${R}, expected ${v})},f=()=>{let v="",b;for(;b=l("CHAR")??l("ESCAPED_CHAR");)v+=b;return v},m=v=>v,h=t.encodePart||m,g="",y=v=>{g+=v},x=()=>{g.length&&(n.push(new pi(3,"","",h(g),"",3)),g="")},E=(v,b,T,R,L)=>{let C=3;switch(L){case"?":C=1;break;case"*":C=0;break;case"+":C=2;break}if(!b&&!T&&C===3){y(v);return}if(x(),!b&&!T){if(!v)return;n.push(new pi(3,"","",h(v),"",C));return}let M;T?T==="*"?M=um:M=T:M=o;let O=2;M===o?(O=1,M=""):M===um&&(O=0,M="");let _;if(b?_=b:T&&(_=s++),c.has(_))throw new TypeError(Duplicate name '${_}'.);c.add(_),n.push(new pi(O,_,h(v),M,h(R),C))};for(;i<r.length;){let v=l("CHAR"),b=l("NAME"),T=l("REGEX");if(!b&&!T&&(T=l("ASTERISK")),b||T){let L=v??"";t.prefixes.indexOf(L)===-1&&(y(L),L=""),x();let C=u();E(L,b,T,"",C);continue}let R=v??l("ESCAPED_CHAR");if(R){y(R);continue}if(l("OPEN")){let L=f(),C=l("NAME"),M=l("REGEX");!C&&!M&&(M=l("ASTERISK"));let O=f();p("CLOSE");let _=u();E(L,C,M,O,_);continue}x(),p("END")}return n}function ar(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Qw(e){return e&&e.ignoreCase?"ui":"u"}function n1(e,t,r){return rE(tE(e,r),t,r)}function ns(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function rE(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+=ar(a.value):o+=(?:${ar(a.value)})${ns(a.modifier)};continue}t&&t.push(a.name);let c=^${ar(r.delimiter)}+?,l=a.value;if(a.type===1?l=c:a.type===0&&(l=um),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?o+=(${l})${ns(a.modifier)}:o+=((?:${l})${ns(a.modifier)});continue}if(a.modifier===3||a.modifier===1){o+=(?:${ar(a.prefix)}(${l})${ar(a.suffix)}),o+=ns(a.modifier);continue}o+=(?:${ar(a.prefix)},o+=((?:${l})(?:,o+=ar(a.suffix),o+=ar(a.prefix),o+=(?:${l}))*)${ar(a.suffix)}),a.modifier===0&&(o+="?")}let n=${ar(r.endsWith)}|$,s=${ar(r.delimiter)};if(r.end)return r.strict||(o+=${s}?),r.endsWith.length?o+=(?=${n}):o+="$",new RegExp(o,Qw(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,Qw(r))}var So={delimiter:"",prefixes:"",sensitive:!0,strict:!0},s1={delimiter:".",prefixes:"",sensitive:!0,strict:!0},i1={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function a1(e,t){return e.length?e[0]==="/"?!0:!t||e.length<2?!1:(e[0]=="\\"||e[0]=="{")&&e[1]=="/":!1}function oE(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function c1(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}function nE(e){return!e||e.length<2?!1:e[0]==="["||(e[0]==="\\"||e[0]==="{")&&e[1]==="["}var sE=["ftp","file","http","https","ws","wss"];function iE(e){if(!e)return!0;for(let t of sE)if(e.test(t))return!0;return!1}function l1(e,t){if(e=oE(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 p1(e,t){if(e=oE(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 u1(e,t){return t||e===""?e:nE(e)?lE(e):cE(e)}function m1(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.password=e,r.password}function f1(e,t){if(t||e==="")return e;let r=new URL("https://example.com");return r.username=e,r.username}function d1(e,t,r){if(r||e==="")return e;if(t&&!sE.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 h1(e,t,r){return aE(t)===e&&(e=""),r||e===""?e:pE(e)}function g1(e,t){return e=c1(e,":"),t||e===""?e:mm(e)}function aE(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function mm(e){if(e==="")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(Invalid protocol '${e}'.)}function y1(e){if(e==="")return e;let t=new URL("https://example.com");return t.username=e,t.username}function x1(e){if(e==="")return e;let t=new URL("https://example.com");return t.password=e,t.password}function cE(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 lE(e){if(e==="")return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(Invalid IPv6 hostname '${e}');return e.toLowerCase()}function pE(e){if(e===""||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(Invalid port '${e}'.)}function b1(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 w1(e){return e===""?e:new URL(data:${e}).pathname}function E1(e){if(e==="")return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function k1(e){if(e==="")return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var v1=class{#i;#o=[];#t={};#e=0;#s=1;#a=0;#n=0;#m=0;#p=0;#f=!1;constructor(e){this.#i=e}get result(){return this.#t}parse(){for(this.#o=eE(this.#i,!0);this.#e<this.#o.length;this.#e+=this.#s){if(this.#s=1,this.#o[this.#e].type==="END"){if(this.#n===0){this.#g(),this.#u()?this.#r(9,1):this.#d()?this.#r(8,1):this.#r(7,0);continue}else if(this.#n===2){this.#y(5);continue}this.#r(10,0);break}if(this.#m>0)if(this.#_())this.#m-=1;else continue;if(this.#T()){this.#m+=1;continue}switch(this.#n){case 0:this.#E()&&this.#y(1);break;case 1:if(this.#E()){this.#S();let e=7,t=1;this.#k()?(e=2,t=3):this.#f&&(e=2),this.#r(e,t)}break;case 2:this.#b()?this.#y(3):(this.#w()||this.#d()||this.#u())&&this.#y(5);break;case 3:this.#v()?this.#r(4,1):this.#b()&&this.#r(5,1);break;case 4:this.#b()&&this.#r(5,1);break;case 5:this.#P()?this.#p+=1:this.#O()&&(this.#p-=1),this.#R()&&!this.#p?this.#r(6,1):this.#w()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 6:this.#w()?this.#r(7,0):this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 7:this.#d()?this.#r(8,1):this.#u()&&this.#r(9,1);break;case 8:this.#u()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port="")}#r(e,t){switch(this.#n){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.#n!==0&&e!==10&&([1,2,3,4].includes(this.#n)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=""),[1,2,3,4,5,6].includes(this.#n)&&[8,9].includes(e)&&(this.#t.pathname??=this.#f?"/":""),[1,2,3,4,5,6,7].includes(this.#n)&&e===9&&(this.#t.search??="")),this.#h(e,t)}#h(e,t){this.#n=e,this.#a=this.#e+t,this.#e+=t,this.#s=0}#g(){this.#e=this.#a,this.#s=0}#y(e){this.#g(),this.#n=e}#x(e){return e<0&&(e=this.#o.length-e),e<this.#o.length?this.#o[e]:this.#o[this.#o.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")}#E(){return this.#c(this.#e,":")}#k(){return this.#c(this.#e+1,"/")&&this.#c(this.#e+2,"/")}#b(){return this.#c(this.#e,"@")}#v(){return this.#c(this.#e,":")}#R(){return this.#c(this.#e,":")}#w(){return this.#c(this.#e,"/")}#d(){if(this.#c(this.#e,"?"))return!0;if(this.#o[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.#o[this.#e].type=="OPEN"}#_(){return this.#o[this.#e].type=="CLOSE"}#P(){return this.#c(this.#e,"[")}#O(){return this.#c(this.#e,"]")}#l(){let e=this.#o[this.#e],t=this.#x(this.#a).index;return this.#i.substring(t,e.index)}#S(){let e={};Object.assign(e,So),e.encodePart=mm;let t=n1(this.#l(),void 0,e);this.#f=iE(t)}},pm=["protocol","username","password","hostname","port","pathname","search","hash"],Oo="*";function Zw(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 so(e,t){return t?li(e):e}function ci(e,t,r){let o;if(typeof t.baseURL=="string")try{o=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=so(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=so(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=so(o.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=so(o.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=so(o.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=so(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=so(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=so(o.hash.substring(1,o.hash.length),r))}catch{throw new TypeError(invalid baseURL '${t.baseURL}'.)}if(typeof t.protocol=="string"&&(e.protocol=g1(t.protocol,r)),typeof t.username=="string"&&(e.username=f1(t.username,r)),typeof t.password=="string"&&(e.password=m1(t.password,r)),typeof t.hostname=="string"&&(e.hostname=u1(t.hostname,r)),typeof t.port=="string"&&(e.port=h1(t.port,e.protocol,r)),typeof t.pathname=="string"){if(e.pathname=t.pathname,o&&!a1(e.pathname,r)){let n=o.pathname.lastIndexOf("/");n>=0&&(e.pathname=so(o.pathname.substring(0,n+1),r)+e.pathname)}e.pathname=d1(e.pathname,e.protocol,r)}return typeof t.search=="string"&&(e.search=p1(t.search,r)),typeof t.hash=="string"&&(e.hash=l1(t.hash,r)),e}function li(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function R1(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function T1(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let r=".*",o=^${R1(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)}}${ns(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+=ns(a.modifier))}return s}var uE=class{#i;#o={};#t={};#e={};#s={};#a=!1;constructor(e={},t,r){try{let o;if(typeof t=="string"?o=t:r=t,typeof e=="string"){let a=new v1(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:Oo,protocol:Oo,username:Oo,password:Oo,hostname:Oo,port:Oo,search:Oo,hash:Oo};this.#i=ci(s,e,!0),aE(this.#i.protocol)===this.#i.port&&(this.#i.port="");let i;for(i of pm){if(!(i in this.#i))continue;let a={},c=this.#i[i];switch(this.#t[i]=[],i){case"protocol":Object.assign(a,So),a.encodePart=mm;break;case"username":Object.assign(a,So),a.encodePart=y1;break;case"password":Object.assign(a,So),a.encodePart=x1;break;case"hostname":Object.assign(a,s1),nE(c)?a.encodePart=lE:a.encodePart=cE;break;case"port":Object.assign(a,So),a.encodePart=pE;break;case"pathname":iE(this.#o.protocol)?(Object.assign(a,i1,n),a.encodePart=b1):(Object.assign(a,So,n),a.encodePart=w1);break;case"search":Object.assign(a,So,n),a.encodePart=E1;break;case"hash":Object.assign(a,So,n),a.encodePart=k1;break}try{this.#s[i]=tE(c,a),this.#o[i]=rE(this.#s[i],this.#t[i],a),this.#e[i]=T1(this.#s[i],a),this.#a=this.#a||this.#s[i].some(l=>l.type===2)}catch{throw new TypeError(invalid ${i} pattern '${this.#ii}'.)}}}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=ci(r,e,!1):r=ci(r,Zw(e,t),!1)}catch{return!1}let o;for(o of pm)if(!this.#o[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=ci(r,e,!1):r=ci(r,Zw(e,t),!1)}catch{return null}let o={};t?o.inputs=[e,t]:o.inputs=[e];let n;for(n of pm){let s=this.#o[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 pi(3,"","","","",3),s=new pi(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.#s[e],[s]):!t.#e[e]&&r.#e[e]?i([s],r.#s[e]):i(t.#s[e],r.#s[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=uE);var mE,fE=async(e,t)=>(mE??=Tc({wasm:e,worker:t}),await mE,async r=>{let{outputFiles:o}=await vc({entryPoints:[r],format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[Jb(),Jw({fetch:_1,reload:[new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"})]})],write:!1});return{contents:o[0].text}}),_1=async(e,t)=>{let r=nw(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let o=await fm(e);if(o)return o}try{let o=await r(e);return o.ok?(r===GM_fetch&&!e.url.startsWith("data:")&&await Ia(e,o),le([o,!1])):await fm(e)??ee({name:"HTTPError",message:${o.status} ${o.statusText},response:o})}catch(o){let n=await fm(e);if(n)return n;if(o instanceof TypeError)return ee({name:"NetworkError",message:o.message,request:e});if(o instanceof DOMException)return ee({name:"AbortError",message:o.message,request:e});throw o}},fm=async e=>{if(e.url.startsWith("data:"))return;let t=await Dn(e);if(t)return t.url||Object.defineProperty(t,"url",{value:e.url}),le([t,!0])};var dE=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e);var hE=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},gE=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},yE=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},xE=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var bE=()=>{let e;return{show:(o,{x:n,y:s})=>{e=P1(),e.append(O1(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?.()}}},P1=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},O1=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 wE=()=>{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}=bE();return{component:e,setStatus:async(s,i)=>{switch(e.textContent="",await o(),s){case"loading":e.append(yE());break;case"pass":e.append(hE());break;case"fail":e.append(gE());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 EE=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(xE()),t.addEventListener("click",e),t};var kE=e=>{let{component:t,setStatus:r}=wE(),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(EE(e),t),{menu:o,setStatus:r}};function vE(e){return new Promise(t=>setTimeout(t,e))}function RE(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 vE(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 TE,_E=async(e,t)=>{let r=[],n=RE(async()=>{r.forEach(({menu:i,setStatus:a})=>{a("none"),i.remove()});let s=hb(scrapbox.Project.name,scrapbox.Page.title??"",Ut());for(let i of s){let a=i.lang.toLowerCase();if(dE(a))for(let c of i.startIds){let l=document.getElementById(L${c}),{menu:u,setStatus:p}=kE(async()=>{await p("loading");try{TE??=await fE(e,t);let{contents:f}=await TE(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 N1(e,t){for(var r in t)e[r]=t[r];return e}function PE(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 Xc(e,t){var r=t(),o=X({t:{__:r,u:t}}),n=o[0].t,s=o[1];return Ea(function(){n.__=r,n.u=t,dm(n)&&s({t:n})},[e,r,t]),Z(function(){return dm(n)&&s({t:n}),e(function(){dm(n)&&s({t:n})})},[e]),r}function dm(e){var t,r,o=e.u,n=e.__;try{var s=o();return!((t=n)===(r=s)&&(t!==0||1/t==1/r)||t!=t&&r!=r)}catch{return!0}}function OE(e,t){this.props=e,this.context=t}(OE.prototype=new fr).isPureReactComponent=!0,OE.prototype.shouldComponentUpdate=function(e,t){return PE(this.props,e)||PE(this.state,t)};var SE=te.__b;te.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),SE&&SE(e)};var KAe=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;var L1=te.__e;te.__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)}L1(e,t,r,o)};var NE=te.unmount;function FE(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=N1({},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 FE(o,t,r)})),e}function DE(e,t,r){return e&&r&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(o){return DE(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 hm(){this.__u=0,this.o=null,this.__b=null}function UE(e){var t=e.__.__c;return t&&t.__a&&t.__a(e)}function Yc(){this.i=null,this.l=null}te.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),NE&&NE(e)},(hm.prototype=new fr).__c=function(e,t){var r=t.__c,o=this;o.o==null&&(o.o=[]),o.o.push(r);var n=UE(o.__v),s=!1,i=function(){s||(s=!0,r.__R=null,n?n(a):a())};r.__R=i;var a=function(){if(!--o.__u){if(o.state.__a){var c=o.state.__a;o.__v.__k[0]=DE(c,c.__c.__P,c.__c.__O)}var l;for(o.setState({__a:o.__b=null});l=o.o.pop();)l.forceUpdate()}};o.__u++||32&t.__u||o.setState({__a:o.__b=o.__v.__k[0]}),e.then(i,i)},hm.prototype.componentWillUnmount=function(){this.o=[]},hm.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]=FE(this.__b,r,o.__O=o.__P)}this.__b=null}var n=t.__a&&Gr(Q,null,e.fallback);return n&&(n.__u&=-33),[Gr(Q,null,t.__a?null:e.children),n]};var LE=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]}};(Yc.prototype=new fr).__a=function(e){var t=this,r=UE(t.__v),o=t.l.get(e);return o[0]++,function(n){var s=function(){t.props.revealOrder?(o.push(n),LE(t,e,o)):n()};r?r(s):s()}},Yc.prototype.render=function(e){this.i=null,this.l=new Map;var t=lo(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},Yc.prototype.componentDidUpdate=Yc.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,r){LE(e,r,t)})};var C1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,M1=/^(?: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]/,A1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,I1=/[A-Z0-9]/g,F1=typeof document<"u",D1=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};fr.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(fr.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var CE=te.event;function U1(){}function $1(){return this.cancelBubble}function j1(){return this.defaultPrevented}te.event=function(e){return CE&&(e=CE(e)),e.persist=U1,e.isPropagationStopped=$1,e.isDefaultPrevented=j1,e.nativeEvent=e};var $E,B1={enumerable:!1,configurable:!0,get:function(){return this.class}},ME=te.vnode;te.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||F1&&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"||D1(r.type)?c==="onfocus"?i="onfocusin":c==="onblur"?i="onfocusout":A1.test(i)&&(i=c):c=i="oninput":s&&M1.test(i)?i=i.replace(I1,"-$&").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=lo(r.children).forEach(function(l){l.props.selected=n.value.indexOf(l.props.value)!=-1})),o=="select"&&n.defaultValue!=null&&(n.value=lo(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",B1)):(r.className&&!r.class||r.class&&r.className)&&(n.class=n.className=r.className),t.props=n}(e),e.$$typeof=C1,ME&&ME(e)};var AE=te.__r;te.__r=function(e){AE&&AE(e),$E=e.__c};var IE=te.diffed;te.diffed=function(e){IE&&IE(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),$E=null};var Jc=e=>[...e].map((t,r)=>t===" "?"_":!H1.includes(t)||r===e.length-1&&W1.includes(t)?encodeURIComponent(t):t).join(""),H1='@$&+=:;",',W1=':;",';var jE=({title:e,projects:t,selected:r,confirm:o})=>d("div",{className:candidate${r?" selected":""},children:[d(G1,{title:e,confirm:o}),t.map(n=>d(q1,{project:n.name,title:e,mark:n.mark,confirm:n.confirm}))]}),G1=({title:e,confirm:t})=>d("a",{className:"button",tabIndex:0,role:"menuitem",href:./${Jc(e)},onClick:BE(t),children:e}),q1=({project:e,title:t,mark:r,confirm:o})=>{let n=BE(o);return r===""?null:d("a",{className:"mark",tabIndex:0,href:../${e}/${Jc(t)},onClick:n,title:/${e}/${Jc(t)},children:r instanceof URL?d("img",{src:r.href}):${r}})},BE=e=>A(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var HE=(e,t)=>{let[r,o]=X(null),n=A(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=A(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=A(()=>o(e.length===0?null:t(e[0])),[e,t]),a=A(()=>o(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:n,prev:s,selectFirst:i,selectLast:a}};var WE=e=>{let[t,r]=X(null),o=U(()=>{let n=t?.getBoundingClientRect?.(),i=Is(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 ym="enableProjectsOnSuggestion",GE=(e,t)=>{let[r,o]=X(Qc([...e],t)),n=A((s,i)=>{z1(s,i,e,t),o(Qc([...e],t))},[e,t.enableSelfProjectOnStart]);return Z(()=>{let s=i=>{i.key===ym&&o(Qc([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:n}},gm=!0,Qc=(e,t)=>{try{let r=localStorage.getItem(ym);if(r===null)return Zc(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)?gm?o:o.filter(n=>n!==scrapbox.Project.name):gm?[...o,scrapbox.Project.name]:o:(Zc(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return Zc(e),e}},z1=(e,t,r,o)=>{let n=Qc([...r],o);o.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(gm=t),Zc(t?[...n,e]:n.filter(s=>s!==e))},Zc=e=>localStorage.setItem(ym,JSON.stringify(e));var qE=()=>U(()=>document.documentElement.dataset.os??"",[]);var ui=(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 zE=({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 KE=({position:e,start:t,enableSelfProjectOnStart:r,projects:o,...n})=>{let{projects:s,set:i}=GE(o,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:c,left:l,right:u}=WE({line:e.line,char:t}),p=qE();return d(Q,{children:[d(K1,{itemCount:n.items.length,enableProjects:s,projects:o,top:c,right:u,set:i,os:p,...n}),d(V1,{updateStandardElement:a,start:t,enableProjects:s,projects:o,top:c,left:l,os:p,...n})]})},V1=({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=A((O,_,P)=>{let N=[${_?/${_}/${O}:O}${P?.icon?".icon":""}];r((I,{line:F})=>[${...I.slice(0,e).join("")}${N}${...I.slice(e+...n.length).join("")},{line:F,char:e+[...N].length}])},[e,n]),y=U(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),x=U(()=>{let O=[];for(let _ of a){if(O.length===f)break;_.projects.some(P=>s.includes(P))&&O.push({title:_.title,projects:_.projects.flatMap(P=>s.includes(P)?[{name:P,mark:y?ui(m[P]??"",import.meta.url)||P[0]:"",confirm:N=>g(_.title,P,N)}]:[]),confirm:P=>g(_.title,void 0,P)})}return O},[s,y,a,f,m,g]),{selectedId:E,next:v,prev:b,selectLast:T,selectFirst:R}=HE(x,VE),L=A(O=>E===null?!1:(x.find(_=>VE(_)===E)?.confirm?.(O),!0),[E,x]);Z(()=>p(x.length===0?void 0:{selectNext:O=>(v(O),!0),selectPrev:O=>(b(O),!0),selectFirst:()=>(R(),!0),selectLast:()=>(T(),!0),confirm:L,cancel:()=>(o(),!0)}),[p,x.length,v,b,R,T,L]);let C=U(()=>x.length>0&&c!=null&&l!=null?{top:c,left:l}:{display:"none"},[x.length,c,l]),M=A(O=>{if(!O){t(O);return}let _=O.parentNode;if(!(_ instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(_.host.parentElement)},[t]);return d("div",{ref:M,className:"container candidates","data-os":h,style:C,children:[x.map(O=>d(jE,{...O,selected:E===O.title},O.title)),a.length>f&&d("div",{className:"counter",children:${a.length-f} more links}),d(zE,{progress:u})]})},K1=({enableProjects:e,projects:t,projectScore:r,mark:o,itemCount:n,top:s,right:i,set:a,os:c,freezeUntil:l})=>{let u=U(()=>[...t].sort((f,m)=>(r.get(m)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:ui(o[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),ot().focus()})}]:[]),[t,r,e,o]),p=U(()=>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(Y1,{...f},f.name))})},Y1=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}}),VE=e=>e.title;var YE=e=>{let t=U(()=>ui(e.style,import.meta.url),[e.style]);return d(Q,{children:t!==""&&(t instanceof URL?d("link",{rel:"stylesheet",href:t.href}):d("style",{children:t}))})};var XE=()=>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*JE(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 QE=(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(J1(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=X1(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"}},X1=(e,t)=>{for(let{whole:r,start:o}of JE(e))if(!(t<=o||o+[...r].length<=t))return{whole:r,start:o}},J1=(e,t)=>!(t.trim()===""||t.includes(
)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var ZE=()=>{let e=rt(scrapbox.Page.lines),t=rt(!1);return Z(()=>{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)}},[]),A(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var Q1=Mn("scrapbox-select-suggestion:useLifecycle.ts"),ek=()=>{let[e,t]=po(QE,{type:"ready"}),r=ZE(),o=U(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:c,selection:l}=Nt();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:c.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);Z(()=>{let i=()=>{o("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{o("selection:changed")},c=Fa();return c.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),c.removeChangeListener(a)}},[]),Z(()=>{if(e.context!=="input")return;let i=()=>{o("cursor:changed")},a=uo();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[n,s]=X(e);return n!==e&&(s(e),Q1.debug("Detect changes",e)),{state:e,setEnable:A(i=>t({type:i?"enable":"disable"}),[]),cancel:A(()=>t({type:"cancel"}),[]),freezeUntil:A(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:A(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:c,selection:l}=Nt(),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 Je(f),c.setPosition(m),c.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var tk=(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 ok=Symbol("Comlink.proxy"),Z1=Symbol("Comlink.endpoint"),wm=Symbol("Comlink.releaseProxy"),xm=Symbol("Comlink.finalizer"),tl=Symbol("Comlink.thrown"),nk=e=>typeof e=="object"&&e!==null||typeof e=="function",eC={canHandle:e=>nk(e)&&e[ok],serialize(e){let{port1:t,port2:r}=new MessageChannel;return ik(e,t),[r,[r]]},deserialize(e){return e.start(),Em(e)}},tC={canHandle:e=>nk(e)&&tl 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}},sk=new Map([["proxy",eC],["throw",tC]]);function rC(e,t){for(let r of e)if(t===r||r==="*"||r instanceof RegExp&&r.test(t))return!0;return!1}function ik(e,t=globalThis,r=["*"]){t.addEventListener("message",function o(n){if(!n||!n.data)return;if(!rC(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(bn),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]]=bn(n.data.value),l=!0;break;case"APPLY":l=p.apply(u,c);break;case"CONSTRUCT":{let f=new p(...c);l=km(f)}break;case"ENDPOINT":{let{port1:f,port2:m}=new MessageChannel;ik(e,m),l=aC(f,[f])}break;case"RELEASE":l=void 0;break;default:return}}catch(u){l={value:u,[tl]:0}}Promise.resolve(l).catch(u=>({value:u,[tl]:0})).then(u=>{let[p,f]=nl(u);t.postMessage(Object.assign(Object.assign({},p),{id:s}),f),i==="RELEASE"&&(t.removeEventListener("message",o),ak(t),xm in e&&typeof e[xm]=="function"&&e[xm]())}).catch(u=>{let[p,f]=nl({value:new TypeError("Unserializable return value"),[tl]:0});t.postMessage(Object.assign(Object.assign({},p),{id:s}),f)})}),t.start&&t.start()}function oC(e){return e.constructor.name==="MessagePort"}function ak(e){oC(e)&&e.close()}function Em(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)}}),bm(e,r,[],t)}function el(e){if(e)throw new Error("Proxy has been released and is not useable")}function ck(e){return ss(e,new Map,{type:"RELEASE"}).then(()=>{ak(e)})}var rl=new WeakMap,ol="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let t=(rl.get(e)||0)-1;rl.set(e,t),t===0&&ck(e)});function nC(e,t){let r=(rl.get(t)||0)+1;rl.set(t,r),ol&&ol.register(e,t,e)}function sC(e){ol&&ol.unregister(e)}function bm(e,t,r=[],o=function(){}){let n=!1,s=new Proxy(o,{get(i,a){if(el(n),a===wm)return()=>{sC(s),ck(e),t.clear(),n=!0};if(a==="then"){if(r.length===0)return{then:()=>s};let c=ss(e,t,{type:"GET",path:r.map(l=>l.toString())}).then(bn);return c.then.bind(c)}return bm(e,t,[...r,a])},set(i,a,c){el(n);let[l,u]=nl(c);return ss(e,t,{type:"SET",path:[...r,a].map(p=>p.toString()),value:l},u).then(bn)},apply(i,a,c){el(n);let l=r[r.length-1];if(l===Z1)return ss(e,t,{type:"ENDPOINT"}).then(bn);if(l==="bind")return bm(e,t,r.slice(0,-1));let[u,p]=rk(c);return ss(e,t,{type:"APPLY",path:r.map(f=>f.toString()),argumentList:u},p).then(bn)},construct(i,a){el(n);let[c,l]=rk(a);return ss(e,t,{type:"CONSTRUCT",path:r.map(u=>u.toString()),argumentList:c},l).then(bn)}});return nC(s,e),s}function iC(e){return Array.prototype.concat.apply([],e)}function rk(e){let t=e.map(nl);return[t.map(r=>r[0]),iC(t.map(r=>r[1]))]}var lk=new WeakMap;function aC(e,t){return lk.set(e,t),e}function km(e){return Object.assign(e,{[ok]:!0})}function nl(e){for(let[t,r]of sk)if(r.canHandle(e)){let[o,n]=r.serialize(e);return[{type:"HANDLER",name:t,value:o},n]}return[{type:"RAW",value:e},lk.get(e)||[]]}function bn(e){switch(e.type){case"HANDLER":return sk.get(e.name).deserialize(e.value);case"RAW":return e.value}}function ss(e,t,r,o){return new Promise(n=>{let s=cC();t.set(s,n),e.start&&e.start(),e.postMessage(Object.assign({id:s},r),o)})}function cC(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var is=Mn("scrapbox-select-suggestion:cancelableSearch.ts"),pk=e=>{let t=Em(e);return{load:async r=>{is.debug("start loading source");let o=await t.load([...r]);return is.debug(loaded ${o} candidates),o},search:(r,o)=>lC(r,o??5e3,t.search),[Symbol.dispose]:()=>{t[wm](),e instanceof MessagePort?e.close():e.terminate(),is.debug("shared worker closed.")}}},lC=(e,t,r)=>{if(is.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,km((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();is.debug(Comlink search completed for "${e}" in ${a}ms)}},cancel(){n=!0;let i=new Date().getTime()-o.getTime();is.debug(Comlink search cancelled for "${e}" after ${i}ms)}})};var sl=(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 mi=e=>e.query!=="",uk=e=>(t,r)=>{if("query"in r){if(r.query===t.query)return t;let i=mi(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:mi(t)?t.candidates:[]}}if(!mi(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 fi="SharedWorker"in globalThis;var mC=Mn("scrapbox-select-suggestion:useSearch.ts"),mk=(e,t)=>{let r=U(()=>pk(fi?new SharedWorker(t.workerUrl,{type:"module"}).port:new Worker(t.workerUrl,{type:"module"})),[t.workerUrl]);Z(()=>(r.load(t.projects),()=>{using i=r}),[r,t.projects]);let o=A(uk(i=>{let a=!1;return{run:async()=>{let c=sl((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 Z(()=>s({query:e}),[e]),U(()=>{if(!mi(n))return;let[i,a]=fC(n.candidates);return mC.debug("Detect changes",{progress:n.progress,items:a}),{progress:n.progress,projectScore:i,items:a}},[n])},fC=e=>{let t=new Map,r=[];for(let o of e.sort(tk)){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 fk=(e,t)=>{let r=rt({...t});Z(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),Z(()=>{e(r.current)},[e])};var dC={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},dk=e=>{let{state:t,setEnable:r,...o}=ek(),n=mk(t.type==="completion"?t.context==="input"?t.query.slice(1,-1):t.query:"",e),[s,i]=X(),{callback:a,style:c,...l}=e;return fk(a,{enable:A(()=>r(!0),[]),disable:A(()=>r(!1),[]),...t.type!=="completion"||!s?dC:s}),d(Q,{children:[d(XE,{}),d(YE,{style:c}),t.type==="completion"&&n&&d(KE,{callback:i,...n,...t,...o,...l})]})};var hk=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 da(n),new Promise(u=>ft(d(dk,{limit:o,projects:l,mark:s,style:i,callback:u,enableSelfProjectOnStart:a,workerUrl:c}),r))};var Xt=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*gk(e,t){for(let[r,o]of t.entries()){let n=e.get(r);if(n&&Xt(n.blocks)===Xt(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 as={};Di(as,{getTitle:()=>qd,parse:()=>kt});var yk=e=>{let t=new Map;if(e.length===0)return t;let r=kt(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 xk=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 il=class{constructor(t,r){this._filename=t;this._preview=xk(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||Xt(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=Uo(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 bk=({previewers:e})=>{let t=new Map,r=()=>{let s=yk(Ut());for(let{changed:i,filename:a}of gk(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 il(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 di=e=>{let t=new FileReader,r=new Promise(o=>t.onload=()=>o(t.result));return t.readAsDataURL(e),r};var wk=async e=>{if(!("after"in e))return;let t=Xt(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 di(new Blob([t],{type:"image/svg+xml"})),s=document.createElement("img");s.src=n,e.render(s)};var vm={};Di(vm,{default:()=>vk});var GC=Object.create,kk=Object.defineProperty,qC=Object.getOwnPropertyDescriptor,zC=Object.getOwnPropertyNames,VC=Object.getPrototypeOf,KC=Object.prototype.hasOwnProperty,YC=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),XC=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of zC(t))!KC.call(e,n)&&n!==r&&kk(e,n,{get:()=>t[n],enumerable:!(o=qC(t,n))||o.enumerable});return e},JC=(e,t,r)=>(r=e!=null?GC(VC(e)):{},XC(t||!e||!e.__esModule?kk(r,"default",{value:e,enumerable:!0}):r,e)),QC=YC((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)}}),Ek=JC(QC()),vk=Ek.default??Ek;var Rm={};Di(Rm,{default:()=>_k});var ZC=Object.create,Tk=Object.defineProperty,eM=Object.getOwnPropertyDescriptor,tM=Object.getOwnPropertyNames,rM=Object.getPrototypeOf,oM=Object.prototype.hasOwnProperty,nM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of tM(t))!oM.call(e,n)&&n!==r&&Tk(e,n,{get:()=>t[n],enumerable:!(o=eM(t,n))||o.enumerable});return e},iM=(e,t,r)=>(r=e!=null?ZC(rM(e)):{},sM(t||!e||!e.__esModule?Tk(r,"default",{value:e,enumerable:!0}):r,e)),aM=nM((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}}),Rk=iM(aM()),_k=Rk.default??Rk;var cM=(()=>{var e=globalThis;return{default:e}})(),lM=(()=>{var e=(...t)=>Object.assign({},...t);return{default:e}})(),cs=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(cM);case"is-function":return t(vm);case"parse-headers":return t(Rm);case"npm:xtend":return t(lM);default:return console.error('module "'+e+'" not found'),null}},pM=Object.create,Ok=Object.defineProperty,uM=Object.getOwnPropertyDescriptor,mM=Object.getOwnPropertyNames,fM=Object.getPrototypeOf,dM=Object.prototype.hasOwnProperty,al=(e=>typeof cs<"u"?cs:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof cs<"u"?cs:t)[r]}):e)(function(e){if(typeof cs<"u")return cs.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),hM=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gM=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mM(t))!dM.call(e,n)&&n!==r&&Ok(e,n,{get:()=>t[n],enumerable:!(o=uM(t,n))||o.enumerable});return e},yM=(e,t,r)=>(r=e!=null?pM(fM(e)):{},gM(t||!e||!e.__esModule?Ok(r,"default",{value:e,enumerable:!0}):r,e)),xM=hM((e,t)=>{"use strict";var r=al("npm:global/window"),o=al("is-function"),n=al("parse-headers"),s=al("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(F,j,D){h||(h=!0,m.callback(F,j,D))};function y(){b.readyState===4&&setTimeout(v,0)}function x(){var F=void 0;if(b.response?F=b.response:F=b.responseText||p(b),P)try{F=JSON.parse(F)}catch{}return F}function E(F){return clearTimeout(N),F instanceof Error||(F=new Error(""+(F||"Unknown XMLHttpRequest Error"))),F.statusCode=0,g(F,I)}function v(){if(!R){var F;clearTimeout(N),m.useXDR&&b.status===void 0?F=200:F=b.status===1223?204:b.status;var j=I,D=null;return F!==0?(j={body:x(),statusCode:F,method:C,headers:{},url:L,rawRequest:b},b.getAllResponseHeaders&&(j.headers=n(b.getAllResponseHeaders()))):D=new Error("Internal XMLHttpRequest Error"),g(D,j,j.body)}}var b=m.xhr||null;b||(m.cors||m.useXDR?b=new l.XDomainRequest:b=new l.XMLHttpRequest);var T,R,L=b.url=m.uri||m.url,C=b.method=m.method||"GET",M=m.body||m.data,O=b.headers=m.headers||{},_=!!m.sync,P=!1,N,I={body:void 0,headers:{},statusCode:0,method:C,url:L,rawRequest:b};if("json"in m&&m.json!==!1&&(P=!0,O.accept||O.Accept||(O.Accept="application/json"),C!=="GET"&&C!=="HEAD"&&(O["content-type"]||O["Content-Type"]||(O["Content-Type"]="application/json"),M=JSON.stringify(m.json===!0?M:m.json))),b.onreadystatechange=y,b.onload=v,b.onerror=E,b.onprogress=function(){},b.onabort=function(){R=!0},b.ontimeout=E,b.open(C,L,!_,m.username,m.password),_||(b.withCredentials=!!m.withCredentials),!_&&m.timeout>0&&(N=setTimeout(function(){if(!R){R=!0,b.abort("timeout");var F=new Error("XMLHttpRequest timeout");F.code="ETIMEDOUT",E(F)}},m.timeout)),b.setRequestHeader)for(T in O)O.hasOwnProperty(T)&&b.setRequestHeader(T,O[T]);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(M||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(){}}),Pk=yM(xM()),cl=Pk.default??Pk;var ll=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},y$e=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)}}}(),Lk=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},Ck=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}}(),Tm=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)},hi="";function bM(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 wM=
This page requires a browser that supports WebGL.<br/>
<a href="http://get.webgl.org">Click here to upgrade your browser.</a>
,EM=
It does not appear your computer can support WebGL.<br/>
<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>
,kM=1,vM=2;function RM(e,t,r){function o(i){var a=e.parentNode;a&&(a.innerHTML=bM(i))}function n(i,a){typeof r=="function"?r(i):o(a)}if(!window.WebGLRenderingContext)return n(kM,wM),null;var s=TM(e,t);return s?s.getExtension("OES_standard_derivatives"):n(vM,EM),s}function TM(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 ls(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:(hi=n.getShaderInfoLog(s),console.error("*** Error compiling shader "+s+":"+hi),e.trigger("error",{shader:s,source:t,type:r,error:hi,offset:o||0}),n.deleteShader(s),null)}function Sk(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:(hi=n.getProgramInfoLog(s),console.log("Error in program linking:"+hi),n.deleteProgram(s),null)}function _m(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(ll(n[0])==="object")for(s=0;s<n.length;s++)r.push.apply(r,Tm(_m(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":ll(n))==="object"&&r.push.apply(r,Tm(_m(n,o)))}return r}function _M(e){var t=e.getBoundingClientRect();return t.top+t.height>0&&t.top<(window.innerHeight||document.documentElement.clientHeight)}function Nk(e){return(e&e-1)===0}function PM(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function OM(e,t){return e&&t?e.toString()!==t.toString():!1}function SM(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(),t.status==200?t.responseText:""}function Mk(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,Tm(n))}}catch(f){a=!0,c=f}finally{try{!i&&l.return&&l.return()}finally{if(a)throw c}}}})}var Pm=function(){function e(t,r){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Lk(this,e),Mk(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 Ck(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)},PM()&&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=Nk(this.width)&&Nk(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}();Pm.getMaxTextureSize=function(e){return e.getParameter(e.MAX_TEXTURE_SIZE)};Pm.activeUnit=-1;var Ak=function(){function e(t,r,o){var n=this;Lk(this,e),Mk(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=RM(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");cl.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");cl.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 Ck(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 E=x.substring(15).replace(/\'|\"|\;|\s/g,"");if(E.endsWith("glsl")){if(o.deps[E]===void 0){var v="https://lygia.xyz"+E;o.deps[E]=SM(v)}o.fragmentString+=o.deps[E]+
#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=ls(this,this.vertexString,this.gl.VERTEX_SHADER),f=ls(this,this.fragmentString,this.gl.FRAGMENT_SHADER);f?this.isValid=!0:(f=ls(this,void main(){
gl_FragColor = vec4(1.0);
},this.gl.FRAGMENT_SHADER),this.isValid=!1);var m=Sk(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":ll(r))==="object"&&r.data&&r.width&&r.height?(o.data=r.data,o.width=r.width,o.height=r.height):(typeof r>"u"?"undefined":ll(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 Pm(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=_m(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=OM(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=_M(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=ls(r,r.vertexString,o.VERTEX_SHADER);for(var s in t){var i=t[s],a=ls(r,i.fragment,o.FRAGMENT_SHADER,1);a?r.isValid=!0:(a=ls(r,void main(){
gl_FragColor = vec4(1.0);
},o.FRAGMENT_SHADER),r.isValid=!1);var c=Sk(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 NM(){var e=document.getElementsByClassName("glslCanvas");if(e.length>0){window.glslCanvases=[];for(var t=0;t<e.length;t++){var r=new Ak(e[t]);r.isValid&&window.glslCanvases.push(r)}}}window.addEventListener("load",function(){NM()});var pl=Ak;var Ik=e=>{if(!("after"in e))return Promise.resolve(void 0);let t=document.createElement("canvas");return new pl(t).load(Xt(e.after)),e.render(t),Promise.resolve(void 0)};var Fk=e=>{let t="";for(let r=0;r<e.length;r+=3)r+2===e.length?t+=Om(e[r],e[r+1],0):r+1===e.length?t+=Om(e[r],0,0):t+=Om(e[r],e[r+1],e[r+2]);return t},ul=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?"_":"?"))),Om=(e,t,r)=>{let o=e>>2,n=(e&3)<<4|t>>4,s=(t&15)<<2|r>>6,i=r&63;return ul(o&63)+ul(n&63)+ul(s&63)+ul(i&63)};var Dk=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${Fk(o)}};var Uk=async e=>{if(!("after"in e))return;let t=document.createElement("img"),r=await Dk(Xt(e.after));t.src=r,e.render(t)};var Sm=Promise.resolve({log:new Uint8Array(0)}),ml,$k=(e,t,r,o)=>(Sm=(async()=>{await Sm,ml??=await LM(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),ml.removeEventListener("message",a))};ml.addEventListener("message",a)}),s={type:"compile",input:e};return ml.postMessage(s),n})(),Sm),LM=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 jk=(e,t)=>async r=>{if(!("after"in r))return;let o=CM(),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 $k(Xt(r.after),e,t,s);if(clearTimeout(a),!c){r.render(o.div),o.log(n);return}i.src=await di(new Blob([c],{type:"image/svg+xml"})),r.render(i)},CM=()=>{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 Ht(e,t){return Ae(e,{...t,weekStartsOn:1})}function wn(e,t){let r=w(e,t?.in),o=r.getFullYear(),n=S(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=Ht(n),i=S(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=Ht(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function gi(e,t){let r=wn(e,t),o=S(t?.in||e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Ht(o)}function Nm(e,t){let r,o=t?.in;return e.forEach(n=>{!o&&typeof n=="object"&&(o=S.bind(null,n));let s=w(n,o);(!r||r<s||isNaN(+s))&&(r=s)}),S(o,r||NaN)}function yi(e,t,r){let o=Ha(e,t)/1e3;return Go(r?.roundingMethod)(o)}function fl(e){return(t={})=>{let r=t.width?String(t.width):e.defaultWidth;return e.formats[r]||e.formats[e.defaultWidth]}}function ps(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 BM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},HM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},WM={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"]},GM={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"]},qM={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"}},zM={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"}},VM=(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"},KM={ordinalNumber:VM,era:ps({values:BM,defaultWidth:"wide"}),quarter:ps({values:HM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:ps({values:WM,defaultWidth:"wide"}),day:ps({values:GM,defaultWidth:"wide"}),dayPeriod:ps({values:qM,defaultWidth:"wide",formattingValues:zM,defaultFormattingWidth:"wide"})};function us(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)?XM(a,p=>p.test(i)):YM(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 YM(e,t){for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&t(e[r]))return r}function XM(e,t){for(let r=0;r<e.length;r++)if(t(e[r]))return r}function Gk(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 JM=/^(\d+)(th|st|nd|rd)?/i,QM=/\d+/i,ZM={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},eA={any:[/^b/i,/^(a|c)/i]},tA={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},rA={any:[/1/i,/2/i,/3/i,/4/i]},oA={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},nA={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]},sA={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},iA={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]},aA={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},cA={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}},lA={ordinalNumber:Gk({matchPattern:JM,parsePattern:QM,valueCallback:e=>parseInt(e,10)}),era:us({matchPatterns:ZM,defaultMatchWidth:"wide",parsePatterns:eA,defaultParseWidth:"any"}),quarter:us({matchPatterns:tA,defaultMatchWidth:"wide",parsePatterns:rA,defaultParseWidth:"any",valueCallback:e=>e+1}),month:us({matchPatterns:oA,defaultMatchWidth:"wide",parsePatterns:nA,defaultParseWidth:"any"}),day:us({matchPatterns:sA,defaultMatchWidth:"wide",parsePatterns:iA,defaultParseWidth:"any"}),dayPeriod:us({matchPatterns:aA,defaultMatchWidth:"any",parsePatterns:cA,defaultParseWidth:"any"})};var pA={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},uA={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},mA={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},UHe={date:fl({formats:pA,defaultWidth:"full"}),time:fl({formats:uA,defaultWidth:"full"}),dateTime:fl({formats:mA,defaultWidth:"full"})};function Lm(e,t){let r=w(e,t?.in),o=+Ht(r)-+gi(r);return Math.round(o/jo)+1}function qk(e,t){let r=w(e,t?.in).getDay();return r===0?7:r}function Cm(e){return Math.trunc(+w(e)/1e3)}function Vk(e,t,r){let o=w(e,r?.in),n=Lm(o,r)-t;return o.setDate(o.getDate()-n*7),o}function fs(e,t,r){let o=dr(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=w(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 Pe(s,l,r)}function Kk(e,t,r){let o=w(e,r?.in),n=qk(o,r),s=t-n;return Pe(o,s,r)}var kA=class{subPriority=0;validate(e,t){return!0}},vA=class extends kA{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 ye=class{run(e,t,r,o){let n=this.parse(e,t,r,o);return n?{setter:new vA(n.value,this.validate,this.set,this.priority,this.subPriority),rest:n.rest}:null}validate(e,t,r){return!0}},RA=class extends ye{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"});case"GGGG":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"]},Ye={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}/},Fr={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 Xe(e,t){return e&&{value:t(e.value),rest:e.rest}}function Be(e,t){let r=t.match(e);return r?{value:parseInt(r[0],10),rest:t.slice(r[0].length)}:null}function Dr(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*mo+s*Or+i*ja),rest:t.slice(r[0].length)}}function Yk(e){return Be(Ye.anyDigitsSigned,e)}function ze(e,t){switch(e){case 1:return Be(Ye.singleDigit,t);case 2:return Be(Ye.twoDigits,t);case 3:return Be(Ye.threeDigits,t);case 4:return Be(Ye.fourDigits,t);default:return Be(new RegExp("^\\d{1,"+e+"}"),t)}}function dl(e,t){switch(e){case 1:return Be(Ye.singleDigitSigned,t);case 2:return Be(Ye.twoDigitsSigned,t);case 3:return Be(Ye.threeDigitsSigned,t);case 4:return Be(Ye.fourDigitsSigned,t);default:return Be(new RegExp("^-?\\d{1,"+e+"}"),t)}}function Mm(e){switch(e){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function Xk(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 Jk(e){return e%400===0||e%4===0&&e%100!==0}var TA=class extends ye{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 Xe(ze(4,e),o);case"yo":return Xe(r.ordinalNumber(e,{unit:"year"}),o);default:return Xe(ze(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=Xk(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}},_A=class extends ye{priority=130;parse(e,t,r){let o=n=>({year:n,isTwoDigitYear:t==="YY"});switch(t){case"Y":return Xe(ze(4,e),o);case"Yo":return Xe(r.ordinalNumber(e,{unit:"year"}),o);default:return Xe(ze(t.length,e),o)}}validate(e,t){return t.isTwoDigitYear||t.year>0}set(e,t,r,o){let n=Ho(e,o);if(r.isTwoDigitYear){let i=Xk(r.year,n);return e.setFullYear(i,0,o.firstWeekContainsDate),e.setHours(0,0,0,0),Ae(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),Ae(e,o)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]},PA=class extends ye{priority=130;parse(e,t){return dl(t==="R"?4:t.length,e)}set(e,t,r){let o=S(e,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Ht(o)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]},OA=class extends ye{priority=130;parse(e,t){return dl(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"]},SA=class extends ye{priority=120;parse(e,t,r){switch(t){case"Q":case"QQ":return ze(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"});case"QQQQ":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"]},NA=class extends ye{priority=120;parse(e,t,r){switch(t){case"q":case"qq":return ze(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"});case"qqqq":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"]},LA=class extends ye{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 Xe(Be(Ye.month,e),o);case"MM":return Xe(ze(2,e),o);case"Mo":return Xe(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"});case"MMMM":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}},CA=class extends ye{priority=110;parse(e,t,r){let o=n=>n-1;switch(t){case"L":return Xe(Be(Ye.month,e),o);case"LL":return Xe(ze(2,e),o);case"Lo":return Xe(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"});case"LLLL":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"]},MA=class extends ye{priority=100;parse(e,t,r){switch(t){case"w":return Be(Ye.week,e);case"wo":return r.ordinalNumber(e,{unit:"week"});default:return ze(t.length,e)}}validate(e,t){return t>=1&&t<=53}set(e,t,r,o){return Ae(Ga(e,r,o),o)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]},AA=class extends ye{priority=100;parse(e,t,r){switch(t){case"I":return Be(Ye.week,e);case"Io":return r.ordinalNumber(e,{unit:"week"});default:return ze(t.length,e)}}validate(e,t){return t>=1&&t<=53}set(e,t,r){return Ht(Vk(e,r))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]},IA=[31,28,31,30,31,30,31,31,30,31,30,31],FA=[31,29,31,30,31,30,31,31,30,31,30,31],DA=class extends ye{priority=90;subPriority=1;parse(e,t,r){switch(t){case"d":return Be(Ye.date,e);case"do":return r.ordinalNumber(e,{unit:"date"});default:return ze(t.length,e)}}validate(e,t){let r=e.getFullYear(),o=Jk(r),n=e.getMonth();return o?t>=1&&t<=FA[n]:t>=1&&t<=IA[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"]},UA=class extends ye{priority=90;subpriority=1;parse(e,t,r){switch(t){case"D":case"DD":return Be(Ye.dayOfYear,e);case"Do":return r.ordinalNumber(e,{unit:"date"});default:return ze(t.length,e)}}validate(e,t){let r=e.getFullYear();return Jk(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"]},$A=class extends ye{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"});case"EEEE":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=fs(e,r,o),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]},jA=class extends ye{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 Xe(ze(t.length,e),n);case"eo":return Xe(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"});case"eeee":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=fs(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"]},BA=class extends ye{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 Xe(ze(t.length,e),n);case"co":return Xe(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"});case"cccc":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=fs(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"]},HA=class extends ye{priority=90;parse(e,t,r){let o=n=>n===0?7:n;switch(t){case"i":case"ii":return ze(t.length,e);case"io":return r.ordinalNumber(e,{unit:"day"});case"iii":return Xe(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 Xe(r.day(e,{width:"narrow",context:"formatting"}),o);case"iiiiii":return Xe(r.day(e,{width:"short",context:"formatting"})||r.day(e,{width:"narrow",context:"formatting"}),o);case"iiii":default:return Xe(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=Kk(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"]},WA=class extends ye{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"});case"aaaa":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(Mm(r),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]},GA=class extends ye{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"});case"bbbb":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(Mm(r),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]},qA=class extends ye{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"});case"BBBB":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(Mm(r),0,0,0),e}incompatibleTokens=["a","b","t","T"]},zA=class extends ye{priority=70;parse(e,t,r){switch(t){case"h":return Be(Ye.hour12h,e);case"ho":return r.ordinalNumber(e,{unit:"hour"});default:return ze(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"]},VA=class extends ye{priority=70;parse(e,t,r){switch(t){case"H":return Be(Ye.hour23h,e);case"Ho":return r.ordinalNumber(e,{unit:"hour"});default:return ze(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"]},KA=class extends ye{priority=70;parse(e,t,r){switch(t){case"K":return Be(Ye.hour11h,e);case"Ko":return r.ordinalNumber(e,{unit:"hour"});default:return ze(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"]},YA=class extends ye{priority=70;parse(e,t,r){switch(t){case"k":return Be(Ye.hour24h,e);case"ko":return r.ordinalNumber(e,{unit:"hour"});default:return ze(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"]},XA=class extends ye{priority=60;parse(e,t,r){switch(t){case"m":return Be(Ye.minute,e);case"mo":return r.ordinalNumber(e,{unit:"minute"});default:return ze(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"]},JA=class extends ye{priority=50;parse(e,t,r){switch(t){case"s":return Be(Ye.second,e);case"so":return r.ordinalNumber(e,{unit:"second"});default:return ze(t.length,e)}}validate(e,t){return t>=0&&t<=59}set(e,t,r){return e.setSeconds(r,0),e}incompatibleTokens=["t","T"]},QA=class extends ye{priority=30;parse(e,t){let r=o=>Math.trunc(o*Math.pow(10,-t.length+3));return Xe(ze(t.length,e),r)}set(e,t,r){return e.setMilliseconds(r),e}incompatibleTokens=["t","T"]},ZA=class extends ye{priority=10;parse(e,t){switch(t){case"X":return Dr(Fr.basicOptionalMinutes,e);case"XX":return Dr(Fr.basic,e);case"XXXX":return Dr(Fr.basicOptionalSeconds,e);case"XXXXX":return Dr(Fr.extendedOptionalSeconds,e);case"XXX":default:return Dr(Fr.extended,e)}}set(e,t,r){return t.timestampIsSet?e:S(e,e.getTime()-Kr(e)-r)}incompatibleTokens=["t","T","x"]},eI=class extends ye{priority=10;parse(e,t){switch(t){case"x":return Dr(Fr.basicOptionalMinutes,e);case"xx":return Dr(Fr.basic,e);case"xxxx":return Dr(Fr.basicOptionalSeconds,e);case"xxxxx":return Dr(Fr.extendedOptionalSeconds,e);case"xxx":default:return Dr(Fr.extended,e)}}set(e,t,r){return t.timestampIsSet?e:S(e,e.getTime()-Kr(e)-r)}incompatibleTokens=["t","T","X"]},tI=class extends ye{priority=40;parse(e){return Yk(e)}set(e,t,r){return[S(e,r*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"},rI=class extends ye{priority=20;parse(e){return Yk(e)}set(e,t,r){return[S(e,r),{timestampIsSet:!0}]}incompatibleTokens="*"},PGe={G:new RA,y:new TA,Y:new _A,R:new PA,u:new OA,Q:new SA,q:new NA,M:new LA,L:new CA,w:new MA,I:new AA,d:new DA,D:new UA,E:new $A,e:new jA,c:new BA,i:new HA,a:new WA,b:new GA,B:new qA,h:new zA,H:new VA,K:new KA,k:new YA,m:new XA,s:new JA,S:new QA,X:new ZA,x:new eI,t:new tI,T:new rI};var Qk=(e,t,r=0,o=[])=>{let[n,s]=X("uninitialized"),[i,a]=X({ok:!0,value:t}),c=A(e,o);return Z(()=>{(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 Zk=e=>{let t=e.flatMap(({changes:n,created:s,userId:i})=>n.flatMap(a=>{let c=cI(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}},cI=(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 Ot=e=>{let{fetch:t=(n,s)=>globalThis.fetch(n,s),baseURL:r="https://scrapbox.io/",...o}=e;return{fetch:t,baseURL:r,...o}};var It=e=>connect.sid=${e};var lI=(e,t,r)=>{let{sid:o,baseURL:n,head:s}=Ot(r??{});return new Request(${n}api/commits/${e}/${t}?head=${s??""},o?{headers:{Cookie:It(o)}}:void 0)},ev=(e,t,r)=>Ot(r??{}).fetch(lI(e,t,r));var tv="Cannot complete the mapping as an error was thrown from an item";function hl(e,t,r){let o=new TransformStream({async transform(n,s){try{let i=await n;s.enqueue(i)}catch(i){i instanceof AggregateError&&i.message===tv&&s.error(i)}}});return(async()=>{let n=o.writable.getWriter(),s=[];try{for await(let i of t){let a=Promise.resolve().then(()=>r(i));n.write(a);let c=a.then(()=>s.splice(s.indexOf(c),1));s.push(c),s.length>=e&&await Promise.race(s)}await Promise.all(s),n.close()}catch{let i=[];for(let a of await Promise.allSettled(s))a.status==="rejected"&&i.push(a.reason);n.write(Promise.reject(new AggregateError(i,tv))).catch(()=>{})}})(),Symbol.asyncIterator in o.readable&&typeof o.readable[Symbol.asyncIterator]=="function"?o.readable[Symbol.asyncIterator]():async function*(){let n=o.readable.getReader();for(;;){let{done:s,value:i}=await n.read();if(s)break;yield i}n.releaseLock()}()}var xi=e=>[...e].map((t,r)=>t===" "?"_":!mI.includes(t)||r===e.length-1&&fI.includes(t)?encodeURIComponent(t):t).join(""),mI='@$&+=:;",',fI=':;",';var dI=(e,t,r)=>{let{sid:o,baseURL:n,followRename:s,projects:i}=Ot(r??{}),a=new URLSearchParams([["followRename",${s??!0}],...i?.map?.(c=>["projects",c])??[]]);return new Request(${n}api/pages/${e}/${xi(t)}?${a},o?{headers:{Cookie:It(o)}}:void 0)},Am=(e,t,r)=>Ot(r??{}).fetch(dI(e,t,r));var rv=async(e,t)=>{let r=await ev(e,t);if(!r.ok)throw new Error(Failed to fetch commits for ${e}/${t}: ${r.statusText},{cause:r});return Zk((await r.json()).commits)};var ov=()=>{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=>ft(d(hI,{getController:o=>r(o)}),t))},hI=({getController:e})=>{let[t,r]=X(!0),o=A(()=>r(!1),[]),n=A(()=>r(!0),[]),s=A(()=>r(h=>!h),[]);Z(()=>e({open:o,close:n,toggle:s}),[e]);let i=A(h=>{h.target instanceof HTMLElement&&h.target.id==="background"&&n()},[]),{state:a,result:c}=Qk(async()=>{if(t||scrapbox.Layout!=="page")return;let h=await rv(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 E=Math.max(...[...y.keys()].filter(b=>b<g));if(E===g)return[];let v=y.get(E)?.text;return v===void 0?[]:[v]})}},{range:[],getSnapshot:()=>[]},1e3,[t]),[l,u]=X(0),[p,f]=X(0);Z(()=>{if(a!=="resolved")return;let h=Math.max(0,c.range.length-1);u(h),f(h)},[c]);let m=A(h=>f(parseInt(h.currentTarget.value)),[]);return d(Q,{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(Q,{children:[d("input",{type:"range",max:l,min:"0",step:"1",value:p,title:pe(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),onInput:m}),d("time",{dateTime:pe(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),children:pe(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 io=()=>/mobile/i.test(navigator.userAgent);async function*nv(e,t){if(e.length===0||e.every(({before:o,after:n})=>o===n))return;let r=J(await wt());try{let{readable:o,writable:n}=new TransformStream(void 0),s=n.getWriter(),i=hl(5,e,async l=>{let u=0,p=0;l.before===l.after&&(await s.ready,await s.write({link:l,projectCount:0,replaced:0,done:!0}));let f=hl(2,new Set(t),async m=>{let h=await gI(l,m,r);if(W(h))throw yI(Ln(h));u++,p+=J(h),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!1})});await Array.fromAsync(f),await s.ready,await s.write({link:l,projectCount:u,replaced:p,done:!0})}),a=Array.fromAsync(i).then(async()=>{await s.ready,await s.close()}),c=o.getReader();for(;;){let{done:l,value:u}=await c.read();if(l)return;yield u}await a}finally{await Et(r)}}var gI=async(e,t,r)=>{let[o]=await Promise.all([aa(t,e.before,e.after),Me(t,e.before,(n,{persistent:s})=>{if(s)return[e.after,...n.map(i=>i.text).slice(1)]},{socket:r})]);return o},ao=e=>e.split(
).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),yI=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var sv=e=>kt(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return xI(r);case"table":return bI(r);case"line":return wI(r)}}).map(r=>r).join(
),xI=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},bI=({fileName:e,cells:t,indent:r})=>{let o=" ".repeat(r);return[${o}table:${e},...t.map(n=>${o} ${n.map(s=>s.map(i=>bi(i)).join("")).join(" ")})]},wI=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${bi(r)}).join("")}],bi=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>bi(t)).join("")};case"strong":return${e.nodes.map(t=>bi(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=>bi(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=>ao(e).length>0?"":"",onClick:e=>{let t=sv(e);if(e!=t)return t}});var iv=e=>!e.includes(
)&&/\[[^\]]+\]/.test(e);scrapbox.PopupMenu.addButton({title:e=>iv(e)?"[][]":"",onClick:e=>{if(!iv(e))return;let t=e.replaceAll("[","").replaceAll("]","");return(async()=>{let{render:r,dispose:o}=$e();try{let n=scrapbox.Project.name;r({type:"spinner"},{type:"text",text:create /${n}/${t}}),await Me(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 De(2e3),o()}})(),${t}}});var cv=(e,t)=>{switch(e.type){case"title":return"";case"codeBlock":return[e.fileName,
\\`\`${PI(e.fileName)},e.content,"\n"].join(
);case"table":return EI(e);case"line":return vI(e,t)}},EI=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=>gs(i)).join("")).join(" | ")} |),n===0&&t.push(|${" -- |".repeat(r)})}),t.join(
)},kI=" ",vI=(e,t)=>{let r=e.nodes.map(n=>gs(n,{section:e.indent===t})).join("").trim();if(r==="")return"";if(e.indent===t)return r;let o=kI.repeat(e.indent-t-1);return/^\d+\. /.test(r)||(o+="- "),o+r},gs=(e,t)=>{let{section:r=!1}=t??{};switch(e.type){case"quote":return> ${e.nodes.map(o=>gs(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=>gs(o)).join("")}**;case"formula":return$${e.formula}$;case"decoration":{let o=e.nodes.map(n=>gs(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}/${av(n.join("/"))})}case"relative":return[${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${av(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=>gs(o)).join("")};case"blank":case"plain":return e.text}},av=e=>...e.map((t,r)=>t===" "?"_":!RI.includes(t)||r===e.length-1&&TI.includes(t)?encodeURIComponent(t):t).join(""),RI='@$&+=:;",',TI=':;",',_I=[{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"}],PI=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return _I.find(r=>r.extensions.includes(t))?.fileType??""};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{(async()=>{try{let t=as.parse(e,{hasTitle:!1}),r=Math.min(...t.map(o=>o.indent));await navigator.clipboard.writeText(t.map(o=>cv(o,r)).join(`
))}catch(t){alert(Failed to copy:
${JSON.stringify(t)})}})()}});var Im=(e,...t)=>{let r=t.reduce((o,n)=>Ce(o)?o:o instanceof Promise?o.then(s=>Ce(s)?s:n(s)):n(o),e);return r instanceof Promise?r.then(o=>${o}):${e}};var ys=e=>e.ok?le(e):ee({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var lv=e=>window.GM_fetch?.(https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x)?.then?.(t=>Gt(ys(t),r=>r.json()));var gl=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}},pv=e=>typeof e=="object"&&e!==null;var wi=class e extends Error{name="UnexpectedResponseError";status;statusText;body;path;constructor(t){super(${t.status} ${t.statusText} when fetching ${t.path.toString()}),this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.path=t.path,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};var yl=async e=>{let t=await e.text();if(e.ok)return le(t);if(e.status===400)return ee({name:"BadRequestError",message:t});try{let r=JSON.parse(t);if(!pv(r)||typeof r.message!="string")throw new wi({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)});switch(e.status){case 401:return ee({name:"UnauthorizedError",message:r.message});case 403:return ee({name:"NotPrivilegeError",message:r.message});case 404:return ee({name:"NotFoundError",message:r.message});case 422:return ee({name:"InvalidParameterError",message:r.message});case 429:return ee({name:"RateLimitError",message:r.message});default:throw new wi({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)})}}catch(r){throw r instanceof SyntaxError?new wi({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)}):r}};var uv=async(e,t)=>{let{title:r,description:o,metadataIsPublic:n,collectionId:s,refererURL:i,accessToken:a,created:c,app:l,fetch:u}=gl(t),p=new FormData;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});let f=await u("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:p}),m=await yl(f);return G(m)?m:le(JSON.parse(z(m)))};var mv=(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 xl="",fv=!1,bl=new Map,dv=async(e,t,r,o)=>{let n=bl.get(e.href);if(n)return n;if(e.hostname==="video.twimg.com"||${e}.endsWith(".svg")){let c=await GM_fetch(e);if(!c.ok)return;let l=c.headers.get("content-type")?.split?.(";")?.[0]??${e}.endsWith(".mp4")?"video/mp4":"video/webm",u=new File([await c.blob()],o||${t},{type:l});if(l==="video/mp4"){let m=await mv(u);if(m.ok){let h=new URL(await m.text());return bl.set(e.href,h),h}}let p=await bh(u,r);if(G(p))throw Error(ne(p).name);let f=new URL(z(p).embedUrl);return bl.set(e.href,f),f}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(fv){if(!xl)return}else{let c=await ih();if(fv=!0,G(c)){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(xl=z(c)||"",!xl){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let i=await uv(await s.blob(),{accessToken:xl,refererURL:t,description:o});if(G(i))throw Error(ne(i).name);let a=new URL(z(i).permalink_url);return bl.set(e.href,a),a};var yv=[["&","&amp;"],["<","&lt;"],[">","&gt;"],['"',"&quot;"],["'","&#39;"]],OI=Object.fromEntries([...yv.map(([e,t])=>[t,e]),["&apos;","'"],["&nbsp;"," "]]),SI=new Map(yv),Qot=new RegExp([${...SI.keys().join("")}],"g");var NI={entityList:OI},LI=1114111,CI=/&#([0-9]+);/g,MI=/&#x(\p{AHex}+);/gu,hv=new WeakMap;function Fm(e,t={}){let{entityList:r}={...NI,...t},o=hv.get(r);return o||(o=new RegExp((${Object.keys(r).sort((n,s)=>s.length-n.length).join("|")}),"g"),hv.set(r,o)),e.replaceAll(o,n=>r[n]).replaceAll(CI,(n,s)=>gv(s,10)).replaceAll(MI,(n,s)=>gv(s,16))}function gv(e,t){let r=parseInt(e,t);return r>LI?"�":String.fromCodePoint(r)}var wl=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:Fm(u)}),n.push(l),a=[...a].slice(c[1]-i).join(""),i=c[1]}a&&n.push({type:"plain",text:Fm(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=wl(e.parent)),e.quoted_tweet&&(s.quote=wl(e.quoted_tweet)),s};var AI=["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"],El=(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||AI.includes(o)?r:n?o===e?${decodeURIComponent(n)}:/${o}/${decodeURIComponent(n)}:/${o}};var xv=(e=II)=>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(lv(r)??sh(t.href));if(G(o))throw ne(o);let n=z(o);return e("images"in n?{...n,id:r}:n,t)})():t},II=async e=>{if("images"in e)return Ei(e);let{quote:t,replyTo:r,...o}=wl(e);return[...r?[...(await Ei(r)).split(
).map(n=> > ${n}),...r.quote?(await Ei(r.quote)).split(
).map(n=> > ${n}):[]]:[],...(await Ei(o)).split(
).map(n=>> ${n}),...t?(await Ei(t)).split(
).map(n=>> > ${n}):[]].join(
)},Ei=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[> @${Um(e.screenName)} ${t.origin}${t.pathname},...e.description?.split?.(
)?.map?.(n=>> ${Um(n)})??["> [/ no description provided]"],...e.images.length>0?[> ${e.images.map(n=>[${n}])}]:[]].join(
);let r=e.content,o=e.author.screenName;return[@${Um(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 Dm(n.mediai-1,t)}] [${await Dm(n.mediai,t)}]);return i===n.media.length&&s.push([${await Dm(n.mediai-1,t)}]),
${s.join(`
`)}
}case"url":return${El()(n.url)} }}))).join("").split(
)].join(
)},kl="",FI=async()=>{if(kl)return kl;let e=await Br(scrapbox.Project.name);if(G(e))throw new Error(ne(e).name);return kl=z(e).id,kl},Dm=async(e,t)=>await dv(e.url,t,await FI(),"")??e.url,Um=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]]\s*/g," ").trim();var bv=e=>window.GM_fetch?.(https://t.co/${e})?.then?.(t=>Gt(ys(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 wv=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=bv(e.pathname.slice(1));return r?r.then(o=>bp(o,()=>e,n=>n??e)):e};var Ev=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 kv=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 $m=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var vv=/charset=(^;+)/,Rv=e=>window.GM_fetch?.(${e})?.then?.(t=>Gt(ys(t),async r=>{let o=r.headers.get("content-type")?.match?.(vv)?.1??await DI(r.clone());return new TextDecoder(o).decode(await r.arrayBuffer())})),DI=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?.(vv)?.1??"utf-8"};var Tv=(e=UI)=>async t=>e(await $I(t),t),UI=(e,t)=>{let r=(Ce(e)?e:e.title).replace(/\s/g," ").replaceAll("","[").replaceAll("","]");return r?[${t.hash?${decodeURIComponent(t.hash.slice(1))} | :""}${r} ${t}]:${t}},$I=async e=>{let t=Rv(e);if(!t){let o=await nh(e);if(G(o))throw ne(o);return z(o)}let r=await t;if(G(r))throw ne(r);return new DOMParser().parseFromString(z(r),"text/html")};var _v=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 Pv=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 Ov=(e,...t)=>{if(e instanceof URL)return Im(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=Im(new URL(u),...t);return Ce(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}=$e(),l=()=>a({type:"spinner"},{type:"text",text:URL: ${o}/${r} converted, ${n} failed});return l(),Promise.all(i.map(async u=>{if(Ce(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 Sv=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 Nv=e=>kt(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return jI(r);case"table":return BI(r);case"line":return HI(r)}}).map(r=>r).join(`
),jI=({fileName:e,content:t,indent:r})=>{let o=" ".repeat(r);return[${o}code:${e},...t.split(
).map(n=>${o} ${n})]},BI=({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(" ")})]},HI=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${ki(r)}).join("")}],ki=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>ki(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=>ki(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=>ki(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=>ki(t)).join("")};case"blank":case"plain":return${e.text}}};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=Nv(e);if(e!==t)return t}});var jm=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=>jm(e)?"replace":"",onClick:e=>{let t=jm(e);if(t!==void 0)return t}});var Lv=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 Cv=async(e,t)=>{let r=ao(e),o=await Lv([...new Set(r)]);if(!o.convert||o.links.length===0)return;let n=new Map(o.links.map(s=>[s.before,$e()]));for await(let{link:s,projectCount:i,replaced:a,done:c}of nv(o.links,t)){let l=n.get(s.before);if(!l)return;if(c){l.render({type:"check-circle"},{type:"text",text:"${s.after}", ${a}l. ${i}p.}),setTimeout(()=>l.dispose(),1e3);return}l.render({type:"spinner"},{type:"text",text:"${s.after}", ${a}l. ${i}p.})}};var Mv=async(e,t)=>{let r=ao(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}=$e(),i=z(await wt());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([aa(u,r,o),Me(u,r,(f,{persistent:m})=>{if(m)return[o,...f.map(h=>h.text).slice(1)]},{socket:i})]);if(G(p))throw n({type:"exclamation-triangle"},{type:"text",text:${ne(p).name} ${ne(p).message}}),WI(ne(p));return a++,n({type:"spinner"},{type:"text",text:Replacing links in ${t.length-a} projects...}),z(p)}))).reduce((u,p)=>u+p,0);n({type:"check-circle"},{type:"text",text:Successfully replaced ${l} links.})}finally{await Et(i),setTimeout(s,1e3)}},WI=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var Av=e=>{let t=[scrapbox.Project.name,...e];scrapbox.PopupMenu.addButton({title:r=>{let o=ao(r).length;return o>1?"update links":o===1?"update a link":""},onClick:r=>{let o=ao(r).length;o>1?Cv(r,t):o===1&&Mv(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 Iv=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+=vi(${n!==r?"\\item":""}\\begin{itemize},n*2)+
;if(o.indent<r)for(let n=r;n>o.indent;n--)t+=vi("\\end{itemize}",(n-1)*2)+
;r=o.indent,t+=vi(${r>0?"\\item ":""}${GI(o)},r*2)+
}for(let o=r;o>0;o--)t+=vi("\\end{itemize}",(o-1)*2)+
;return t},GI=e=>{switch(e.type){case"codeBlock":return qI(e);case"table":return zI(e);case"line":return VI(e)}},qI=e=>\\begin{lstlisting}language=${Wt(YI(e.fileName))},caption=${Wt(e.fileName)},label=lang:${e.fileName},numbers=left
${e.content}
\\end{lstlisting},zI=e=>{let t=\\caption{${Wt(e.fileName)}}\\label{table:${Wt(e.fileName)}},r=Math.max(...e.cells.map(n=>n.length)),o=e.cells.map(n=> ${n.map(s=>s.map(i=>xs(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}},VI=e=>e.nodes.map(t=>xs(t)).join(""),xs=e=>{switch(e.type){case"quote":return\\begin{quote}
${vi(e.nodes.map(t=>xs(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{${Wt(e.path)}};case"strong":return\\textbf{${e.nodes.map(t=>xs(t)).join("")}};case"formula":return$${e.formula}$;case"decoration":{let t=e.nodes.map(r=>xs(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=>xs(t)).join("")};case"helpfeel":return\\lstinline!? ${Wt(e.text)}!;case"code":return\\lstinline!${Wt(e.text)}!;case"commandLine":return\\lstinline!${Wt(e.symbol)} ${Wt(e.text)}!;case"link":return e.pathType==="absolute"?e.content===""?\\url{${e.href}}:\\href{${e.href}}{${Wt(e.content)}}:Wt(e.href);case"googleMap":return\\href{${e.url}}{${Wt(e.place)}};case"hashTag":return Wt(#${e.href});case"blank":case"plain":return Wt(e.text)}},KI=[{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"}],YI=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return KI.find(r=>r.extensions.includes(t))?.fileType??""},Wt=e=>e.replaceAll("\\","\\textbackslash ").replaceAll("#","\\#").replaceAll("%","\\%").replaceAll("$","\\$").replaceAll("&","\\&").replaceAll("~","\\textasciitilde ").replaceAll("^","\\textasciicircum ").replaceAll("_","\\_").replaceAll("{","\\{").replaceAll("}","\\}").replaceAll("|","\\textbar ").replaceAll("<","\\textless ").replaceAll(">","\\textgreater "),vi=(e,t)=>e.split(
).map(r=>${" ".repeat(t)}${r}).join(
);scrapbox.PopupMenu.addButton({title:"TeX",onClick:e=>{navigator.clipboard.writeText(Iv(kt(e))).catch(t=>{console.error(t),alert(${t.name} ${t.message}
${t.stack})})}});var vl="https://keicho.herokuapp.com/api/";var Fv=async(e,t)=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let r=await window.GM_fetch(${vl}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 Dv=()=>{let{popupMenu:e,render:t}=XI();ag()?.append?.(e);let r=uo(),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)}}},XI=()=>{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 Uv=async(e="normal")=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let t=await window.GM_fetch(${vl}web/create/?mode=${e},{mode:"cors"});return t.ok?{ok:!0,value:await t.text()}:{ok:!1,value:{name:"ResponseError",res:t}}};var $v=e=>https://keicho.netlify.app/#talk=${e};var jv=e=>{let t=e.split(
),r=t[1]??t[0],o=e===t[0]?"":t[0];return o?[o.trim(),r].join(
):r};var Rl=async(e,t,r)=>{let o=uo(),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 Fa().clear(),o.setPosition({line:n,char:[...s].length}),await Je(
${e}),o.getPosition().line};var Bv=e=>kt(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=>Tl(s))).join(" ")})].join(
).trimEnd();case"line":return${r}${t.nodes.map(o=>Tl(o)).join("")}.trimEnd()}}).join(
),Tl=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Tl(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=>Tl(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 bs=e=>/^[((]/.test(e);var Wv=async e=>{let t=scrapbox.Page.lines;if(!t)return;let{cursor:r,selection:o}=Nt(),n=e?.entire||o.hasSelectionAll(),s=n?t.map(P=>P.text).join(
):o.getSelectedText(),i=e?.botIcon??"[/nishio/nisbot.icon]",{render:a,visible:c,open:l,close:u,dispose:p}=Dv();u();let f=new Set,m=()=>{p();for(let P of f)P()},h=P=>f.add(P),g={text:"Exit",onClick:m},y=e?.talkId||Hv(s)||(n?"":Hv(t.slice(0,1+r.getPosition().line).map(P=>P.text).join(
))),x=!y;if(!y){let P=Uv(e?.mode),N=setTimeout(()=>{a({text:"Start talking..."}),l();let F=0;N=setInterval(()=>{a({text:Start talking${".".repeat(F%3)}}),F++},1e3)},1e3),I=await P;if(clearTimeout(N),!I.ok){if(I.value.name==="GMFetchNotAvailableError"){alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc.");return}if(I.value.name==="ResponseError"){a({text:Error: ${I.value.res.status} ${I.value.res.statusText}},g),l(),console.error(Error: ${I.value.res.status} ${I.value.res.statusText},await I.value.res.text());return}return}y=I.value}let E=y,v=o.normalizeOrder(o.getRange()),b=n?t.length-1:v.end.line,T=t[b],R=n?"":" ".repeat(Math.min(...t.slice(v.start.line,v.end.line+1).map(P=>zr(P.text)))),L=async P=>{let N=await Fv(P,E);if(!N.ok)switch(N.value.name){case"ResponseError":return a({text:Error: ${N.value.res.status} ${N.value.res.statusText}},g),l(),console.error(Error: ${N.value.res.status} ${N.value.res.statusText},await N.value.res.text()),N;case"GMFetchNotAvailableError":return alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc."),N}return N},C="",M=async P=>{let N=Bv(P).split(
).map(D=>D.trim()).join(
).trim();N.startsWith(C)&&(N=N.slice(C.length));let I=N.split(
);if(I.length===0)return;if(I.every(D=>bs(D))&&(C=N),I.filter(D=>!bs(D)).length<2){let D,V;for(let B of I){if(V=await L(B),!V.ok)return V;bs(B)||(D=V)}return D??V}let j=0;{let D;for(;j<I.length&&bs(I[j]);j++)if(D=await L(I[j]),!D.ok)return D}{let D=await L("まず聞いて");if(!D.ok)return D}for(;j<I.length&&!bs(I[j]);j++){let D=await L(I[j]);if(!D.ok)return D}return await L("おしまい")},O=async P=>{if(scrapbox.Layout!=="page"||P==="")return;let N=M(P),I=setTimeout(()=>{a({text:"Asking..."}),l();let B=0;I=setInterval(()=>{a({text:Asking${".".repeat(B%3)}}),B++},1e3)},1e3),F=await N;if(clearTimeout(I),!F||!F.ok)return;let{text:j,buttons:D}=F.value,V=jv(j);if(V.trim()){let B=${R}${i}${V.includes(`
)?
${V.split(`
).map(K=> ${R}${K}).join(
)}:V}
${R};b=await Rl(B,T,b),T=t[b]}a({text:"Send",onClick:_},{text:"🙂",onClick:()=>Je("🙂")},{text:"🙁",onClick:()=>Je("🙁")},...D.map(B=>({text:B,onClick:async()=>{b=await Rl(B,T,b),T=t[b],await O(B)}})),g),l()},_=async()=>{if(scrapbox.Layout!=="page")return;let P=scrapbox.Page.lines,N=r.getPosition().line,[I,F,j]=JI(P,N,i);I!==""&&(b=j,T=P[b],R=" ".repeat(Math.min(...P.slice(F,j+1).map(D=>zr(D.text)))),await O(I))};return x&&(b=await Rl($v(E),T,b),T=t[b]),await O(s),{ask:_,open:l,close:u,visible:c,exit:m,onExit:h}},Hv=e=>{for(let t of e.split(
).reverse()){let r=t.match(/https?:\/\/keicho\.netlify\.app\/#talk=(\w+)/)?.[1];if(r)return r}},JI=(e,t,r)=>{let o=Math.max(e.findLastIndex((s,i)=>i<t&&s.text.trim().startsWith(r)),1),n=o+Do(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 Gv=[tn,rn,on];scrapbox.PopupMenu.addButton({title:e=>{let t=Vr({project:scrapbox.Project.name,mode:"noopen",hooks:Gv});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&&Vr({project:e,mode:"noopen",hooks:Gv})?.()}});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 QI=[$m,wv,$m,kv,_v,El(),Pv,xv(),Ev,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,Sv,Tv()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=Ov(e,...QI);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return Je(r)})}});Av(["takker","takker-memex","takker-private","takker-books"]);if(!/mobile/i.test(navigator.userAgent)){let e=(t,r)=>{t.trim()!==""&&Wv({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())};ot().addEventListener("keydown",a),i(()=>ot().removeEventListener("keydown",a))})};scrapbox.PopupMenu.addButton({title:()=>"🤖",onClick:t=>e(t)})}var Ri=(e,t)=>t.map(r=>r.replace(/@yyyy-MM-dd HH:mm:ss@/g,pe(e,"yyyy-MM-dd HH:mm:ss")).replace(/@yyyy-MM-dd@/g,pe(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==="+"?Pe(e,parseInt(s)*(i==="w"?7:1)):jt(e,parseInt(s)*(i==="w"?7:1)):e;return pe(a?Pe(Ae(c),ZI(a)):c,"yyyy-MM-dd")}).replace(/@yyyy-ww@/g,${Wo(e)}-w${${ho(e)}.padStart(2,"0")}).replace(/@yyyy-ww([+-])(\d+)(w?)@/g,(o,n,s,i)=>{let a=n==="+"?Pe(e,parseInt(s)*(i==="w"?7:1)):jt(e,parseInt(s)*(i==="w"?7:1));return${Wo(a)}-w${${ho(a)}.padStart(2,"0")}}).replace(/@yyyy@/g,${Wo(e)}).replace(/@yyyy([+-])(\d+)y@/g,(o,n,s)=>{let i=parseInt(s);return${Wo(e)+(n==="+"?i:-i)}})),ZI=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 zv=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:Pe(l,1)},{render:p,dispose:f}=$e(),m;try{let h=await qv(t),g=await qv(r),y=Ds(u).filter(b=>{let T=Ri(b,h)[0],R=n.find(L=>L.title===T);return!R||!R.exists}),x=ty(u).filter(b=>{let T=Ri(b,g)[0],R=n.find(L=>L.title===T);return!R||!R.exists});if(y.length===0&&x.length===0)return;let E=y.length+x.length;p({type:"spinner"},{type:"text",text:create ${E} review pages...});let v=await wt();if(G(v))throw ne(v);m=z(v);for(let b of[...y.map(T=>Ri(T,h)),...x.map(T=>Ri(T,g))])await Me(e,b[0],(T,R)=>R.persistent?void 0:b,m?{socket:m}:{}),E--,p({type:"spinner"},{type:"text",text:create ${E} 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 Et(m),await De(1e3),f()}},i=s(),a=new Date,c=setInterval(()=>{let l=new Date;st(a,l)||(a=l,i.then(()=>i=s()))},1e4);return()=>(clearTimeout(c),i)},qv=async e=>{let t=await ca(e[0],e[1],e[2]);if(G(t)){let o=new Error;throw o.name=ne(t).name,o.message=${ne(t).message} at fetching /${e0}/${e1}/${e2},o}let r=z(t).split(
);if(r.length===0)throw new Error(template "/${e0}/${e1}/${e2}" is empty!);return r};var Vv=function(){};function _i(e,t={}){Vv.prototype.name=e;let r={};return new Proxy(Vv,{get(o,n){return n==="caller"?null:n==="__createMock__"?_i:n==="__unenv__"?!0:n in t?t[n]:r[n]=r[n]||_i(${e}.${n.toString()})},apply(o,n,s){return _i(${e}())},construct(o,n,s){return _i(${e})},enumerate(){return[]}})}var Bm=_i("mock");function eF(e){return new Error(unenv ${e} is not implemented yet!)}function fe(e){return Object.assign(()=>{throw eF(e)},{__unenv__:!0})}var tF=Object.freeze(Object.create(null,{__unenv__:{get:()=>!0}})),_l=Object.create(null),rF=globalThis.process?.env,Ti=e=>rF||globalThis.__env__||(e?_l:globalThis),oF=new Proxy(_l,{get(e,t){return Ti()[t]??_l[t]},has(e,t){let r=Ti();return t in r||t in _l},set(e,t,r){let o=Ti(!0);return o[t]=r,!0},deleteProperty(e,t){let r=Ti(!0);return delete r[t],!0},ownKeys(){let e=Ti();return Object.keys(e)}}),nF=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)}}),sF=globalThis.queueMicrotask?(e,...t)=>{globalThis.queueMicrotask(e.bind(void 0,...t))}:iF();function iF(){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 aF="unenv",cF=[],lF="",pF={ares:"",http_parser:"",icu:"",modules:"",node:"",openssl:"",uv:"",v8:"",zlib:""};function Er(){return Hm}var uF=Er,mF=Er,fF=Er,dF=Er,hF=Er,gF=Er,yF=function(e){return e==="message"||e==="multipleResolves"?Hm:!1},xF=Er,bF=Er,wF=function(e){return[]},EF=()=>0,kF=function(e){throw new Error("[unenv] process.binding is not supported")},Kv="/",vF=function(){return Kv},RF=function(e){Kv=e},TF=function(){return 0},_F=function(){return 1e3},PF=function(){return 1e3},OF=function(){return 1e3},SF=function(){return 1e3},NF=function(){return[]},LF=e=>{},CF=fe("process.abort"),MF=new Set,AF="",IF="",FF=tF,DF=!1,UF=()=>0,$F=()=>0,jF=fe("process.cpuUsage"),BF=0,HF=fe("process.dlopen"),WF=Er,GF=Er,qF=fe("process.eventNames"),zF=[],VF="",KF=fe("process.exit"),YF=Object.create({inspector:void 0,debug:void 0,uv:void 0,ipv6:void 0,tls_alpn:void 0,tls_sni:void 0,tls_ocsp:void 0,tls:void 0,cached_builtins:void 0}),XF=()=>[],JF=fe("process.getMaxListeners"),QF=fe("process.kill"),ZF=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0}),eD=1e3,tD="",rD=1e3,oD=fe("process.rawListeners"),nD=Object.create({name:"",lts:"",sourceUrl:void 0,headersUrl:void 0}),sD=Object.create({compact:void 0,directory:void 0,filename:void 0,getReport:fe("process.report.getReport"),reportOnFatalError:void 0,reportOnSignal:void 0,reportOnUncaughtException:void 0,signal:void 0,writeReport:fe("process.report.writeReport")}),iD=fe("process.resourceUsage"),aD=fe("process.setegid"),cD=fe("process.seteuid"),lD=fe("process.setgid"),pD=fe("process.setgroups"),uD=fe("process.setuid"),mD=fe("process.setMaxListeners"),fD=fe("process.setSourceMapsEnabled"),dD=Bm.__createMock__("process.stdout"),hD=Bm.__createMock__("process.stderr"),gD=Bm.__createMock__("process.stdin"),yD=!1,xD=()=>0,bD=0,wD=fe("process.setUncaughtExceptionCaptureCallback"),ED=()=>!1,kD=!1,vD=fe("process.loadEnvFile"),RD=void 0,TD={has:()=>!1},_D={ref(){},unref(){}},PD=!1,OD={register(){},unregister(){},registerBeforeExit(){}},SD=fe("process.assert"),ND=fe("process.openStdin"),LD=fe("process._debugEnd"),CD=fe("process._debugProcess"),MD=fe("process._fatalException"),AD=fe("process._getActiveHandles"),ID=fe("process._getActiveRequests"),FD=fe("process._kill"),DD=[],UD=fe("process._rawDebug"),$D=fe("process._startProfilerIdleNotifier"),jD=fe("process.__stopProfilerIdleNotifier"),BD=fe("process._tickCallback"),Iit=fe("process._linkedBinding"),HD=void 0,WD=fe("process.initgroups"),GD=[],qD=Er,zD=!1,VD=[],KD=0,YD=0,Hm={_events:VD,_eventsCount:KD,_exiting:zD,_maxListeners:YD,_debugEnd:LD,_debugProcess:CD,_fatalException:MD,_getActiveHandles:AD,_getActiveRequests:ID,_kill:FD,_preload_modules:DD,_rawDebug:UD,_startProfilerIdleNotifier:$D,_stopProfilerIdleNotifier:jD,_tickCallback:BD,domain:HD,initgroups:WD,moduleLoadList:GD,reallyExit:qD,exitCode:bD,abort:CF,addListener:mF,allowedNodeEnvironmentFlags:MF,hasUncaughtExceptionCaptureCallback:ED,setUncaughtExceptionCaptureCallback:wD,loadEnvFile:vD,sourceMapsEnabled:kD,throwDeprecation:PD,mainModule:RD,permission:TD,channel:_D,arch:AF,argv:cF,argv0:IF,assert:SD,binding:kF,chdir:RF,config:FF,connected:DF,constrainedMemory:UF,availableMemory:$F,cpuUsage:jF,cwd:vF,debugPort:BF,dlopen:HF,disconnect:WF,emit:yF,emitWarning:GF,env:oF,eventNames:qF,execArgv:zF,execPath:VF,exit:KF,finalization:OD,features:YF,getBuiltinModule:LF,getegid:_F,geteuid:PF,getgid:OF,getgroups:NF,getuid:SF,getActiveResourcesInfo:XF,getMaxListeners:JF,hrtime:nF,kill:QF,listeners:wF,listenerCount:EF,memoryUsage:ZF,nextTick:sF,on:uF,off:dF,once:fF,openStdin:ND,pid:eD,platform:tD,ppid:rD,prependListener:xF,prependOnceListener:bF,rawListeners:oD,release:nD,removeAllListeners:gF,removeListener:hF,report:sD,resourceUsage:iD,setegid:aD,seteuid:cD,setgid:lD,setgroups:pD,setuid:uD,setMaxListeners:mD,setSourceMapsEnabled:fD,stderr:hD,stdin:gD,stdout:dD,title:aF,traceDeprecation:yD,umask:TF,uptime:xD,version:lF,versions:pF},Pi=Hm;var XD=Object.create,eR=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,QD=Object.getOwnPropertyNames,ZD=Object.getPrototypeOf,eU=Object.prototype.hasOwnProperty,tR=(e=>typeof Lo<"u"?Lo:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof Lo<"u"?Lo:t)[r]}):e)(function(e){if(typeof Lo<"u")return Lo.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),rR=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tU=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of QD(t))!eU.call(e,n)&&n!==r&&eR(e,n,{get:()=>t[n],enumerable:!(o=JD(t,n))||o.enumerable});return e},oR=(e,t,r)=>(r=e!=null?XD(ZD(e)):{},tU(t||!e||!e.__esModule?eR(r,"default",{value:e,enumerable:!0}):r,e)),rU=rR((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in Pi&&"node"in Pi.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[tR][0](${"node","util".join(":")})}catch{r=null}t.exports=r}),oU=rR((e,t)=>{var r=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in Pi&&"node"in Pi.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{r=[tR][0](${"node","fs".join(":")})}catch{r=null}t.exports=r}),nU={},Pl=sU(globalThis,nU);function sU(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 Yv=["debug","info","warning","error","fatal"];function Xv(e,t){let r=Yv.indexOf(e);if(r<0)throw new TypeError(Invalid log level: ${JSON.stringify(e)}.);let o=Yv.indexOf(t);if(o<0)throw new TypeError(Invalid log level: ${JSON.stringify(t)}.);return r-o}function Oi(e=[]){return nR.getLogger(e)}var Wm=Symbol.for("logtape.rootLogger"),nR=class No{static getLogger(t=[]){let r=Wm in Pl?Pl[Wm]??null:null;return r==null&&(r=new No(null,[]),Pl[Wm]=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 No?o:o?.deref();return n==null&&(n=new No(this,[...this.category,r]),this.children[r]="WeakRef"in Pl?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 No?t:t.deref())?.resetDescendants();this.reset()}with(t){return new iU(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||Xv(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||Xv(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),aU.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=No.getLogger().contextLocalStorage?.getStore()??{},i,a=typeof o=="function"?{category:this.category,level:t,timestamp:Date.now(),get message(){return Jv(r,this.properties)},rawMessage:r,get properties(){return i==null&&(i={...s,...o()}),i}}:{category:this.category,level:t,timestamp:Date.now(),message:Jv(r,{...s,...o}),rawMessage:r,properties:{...s,...o}};this.emit(a,n)}logLazily(t,r,o={}){let n=No.getLogger().contextLocalStorage?.getStore()??{},s,i;function a(){if((i==null||s==null)&&(i=r((c,...l)=>(s=c,Qv(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=No.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:t,message:Qv(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)}},iU=class sR{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 sR(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)}},aU=nR.getLogger(["logtape","meta"]);function Jv(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 Qv(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 cU=oR(rU()),Ol=cU.default,Zv={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},iR="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}):Ol!=null&&"inspect"in Ol&&typeof Ol.inspect=="function"?(e,t)=>Ol.inspect(e,{maxArrayLength:1/0,maxStringLength:1/0,...t}):e=>JSON.stringify(e);function aR(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??iR,n=e.level==null||e.level==="ABBR"?i=>Zv[i]:e.level==="abbr"?i=>Zv[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 Uit=aR(),Gm="\x1B[0m",qm={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},zm={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},lU={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function pU(e={}){let t=e.format,r=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=${r==null?"":zmr}${o==null?"":qmo},s=r==null&&o==null?"":Gm,i=typeof e.levelStyle>"u"?"bold":e.levelStyle,a=e.levelColors??lU,c=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,l=e.categoryColor??null,u=${c==null?"":zmc}${l==null?"":qml},p=c==null&&l==null?"":Gm;return aR({timestamp:"date-time-tz",value(f){return iR(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?"":zmi}${x==null?"":qmx}${m}${i==null&&x==null?"":Gm},t==null?${f} ${m} ${u}${h}:${p} ${g}:t({timestamp:f,level:m,category:${u}${h}${p},message:g,record:y})}})}var $it=pU();var uU=oR(oU()),mU=uU.default;function ws(){throw new Error("File sink is not available in the browser.")}var fU={openSync:ws,writeSync:ws,flushSync:ws,closeSync:ws,statSync:ws,renameSync:ws},En=mU,jit=En==null?fU:{openSync(e){return En.openSync(e,"a")},writeSync:En.writeSync,flushSync:En.fsyncSync,closeSync:En.closeSync,statSync:En.statSync,renameSync:En.renameSync};var Sl="null",Yat=Xn+Sl,gU=oo+Sl,Xat=Jn+Sl,Jat=Qn+Sl;var Nl="undefined",rct=Xn+Nl,yU=oo+Nl,oct=Jn+Nl,nct=Qn+Nl;async function*lR(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(Bt(a)){r=n;break}for(let c of hn(a).projects)o.has(c.name)&&(yield At({...c,checked:o.get(c.name)??0}))}for(let s of r){let i=await Br(s);yield pt(i)?At({...hn(i),checked:o.get(s)??0}):Kt({...es(i),project:s})}}var Ym=(e,t)=>t.some(r=>e instanceof r),pR,uR;function bU(){return pR||(pR=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function wU(){return uR||(uR=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Xm=new WeakMap,Vm=new WeakMap,Ll=new WeakMap;function EU(e){let t=new Promise((r,o)=>{let n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(kn(e.result)),n()},i=()=>{o(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)});return Ll.set(t,e),t}function kU(e){if(Xm.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)});Xm.set(e,t)}var Jm={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Xm.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return kn(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 hR(e){Jm=e(Jm)}function vU(e){return wU().includes(e)?function(...t){return e.apply(Qm(this),t),kn(this.request)}:function(...t){return kn(e.apply(Qm(this),t))}}function RU(e){return typeof e=="function"?vU(e):(e instanceof IDBTransaction&&kU(e),Ym(e,bU())?new Proxy(e,Jm):e)}function kn(e){if(e instanceof IDBRequest)return EU(e);if(Vm.has(e))return Vm.get(e);let t=RU(e);return t!==e&&(Vm.set(e,t),Ll.set(t,e)),t}var Qm=e=>Ll.get(e);function gR(e,t,{blocked:r,upgrade:o,blocking:n,terminated:s}={}){let i=indexedDB.open(e,t),a=kn(i);return o&&i.addEventListener("upgradeneeded",c=>{o(kn(i.result),c.oldVersion,c.newVersion,kn(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 TU=["get","getKey","getAll","getAllKeys","count"],_U=["put","add","delete","clear"],Km=new Map;function mR(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Km.get(t))return Km.get(t);let r=t.replace(/FromIndex$/,""),o=t!==r,n=_U.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!(n||TU.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 Km.set(t,s),s}hR(e=>({...e,get:(t,r,o)=>mR(t,r)||e.get(t,r,o),has:(t,r)=>!!mR(t,r)||e.has(t,r)}));var PU=["continue","continuePrimaryKey","advance"],fR={},Zm=new WeakMap,yR=new WeakMap,OU={get(e,t){if(!PU.includes(t))return e[t];let r=fR[t];return r||(r=fR[t]=function(...o){Zm.set(this,yR.get(this)[t](...o))}),r}};async function*SU(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,OU);for(yR.set(r,t),Ll.set(r,Qm(t));t;)yield r,t=await(Zm.get(r)||t.continue()),Zm.delete(r)}function dR(e,t){return t===Symbol.asyncIterator&&Ym(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&Ym(e,[IDBIndex,IDBObjectStore])}hR(e=>({...e,get(t,r,o){return dR(t,r)?SU:e.get(t,r,o)},has(t,r){return dR(t,r)||e.has(t,r)}}));var xR,ef=async()=>{let e=Oi(["@takker/cosense-storage","open"]);return xR??=await gR("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)}}),xR};var bR=(e,t)=>(tf||(tf=new BroadcastChannel(ER),tf.addEventListener("message",r=>wR(r.data))),Cl.set(t,new Set(e).union(Cl.get(t)??new Set)),()=>Cl.delete(t)),rf=(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};wR(r);let o=new BroadcastChannel(ER);o.postMessage(r),o.close()},wR=e=>{for(let[t,r]of Cl)r.has(e.project)&&t(e)},ER="scrapbox-storage-notify",tf,Cl=new Map;var kR=async(e,t)=>{let r=await ef(),o=Oi(["@takker/cosense-storage","check"]),n=new Map;try{{o.debugcheck updates of links...;let i=new Set,a=r.transaction("projects","readwrite"),c=Cm(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??NU(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=Cm(new Date);for await(let i of lR(n.values())){if(Bt(i)){let{project:h,name:g}=es(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}=hn(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 rh(c.name)){if(Bt(h)){let{name:E,message:v}=es(h);o.errorFailed to get links of "${c.name}" with ${E}: ${v};break}let g=hn(h),y={},x=r.transaction("titles","readwrite");await Promise.all(g.map(async E=>{let v={...E,project:c.name},b=await x.store.get(E.id);if(!b)return y.added?.set?.(E.id,v)??(y.added=new Map([[E.id,v]])),x.store.add(v);if(l.delete(E.id),!!LU(v,b))return y.updated?.set?.(E.id,[b,v])??(y.updated=new Map([[E.id,[b,v]]])),x.store.put(v)})),await x.done,u+=y.added?.size??0,p+=y.updated?.size??0,o.debugUpdating "/${c.name}": +${u} pages, ~${p} pages,rf(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}),rf(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}},Ml=async e=>{let t=[...new Set(e)];if(t.length===0)return[];let r=Date.now(),n=(await ef()).transaction("titles","readonly"),s=n.store.index("project"),i=(await Promise.all(t.map(c=>s.getAll(c)))).flat();return await n.done,Oi(["@takker/cosense-storage","load"]).debugRead ${i.length} links from ${t.length} projects in ${Date.now()-r}ms,i},NU=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}),LU=(e,t)=>e.updated>t.updated||e.links.sort().join()!==t.links.sort().join();var Ft=e=>${e.getFullYear()}-${xr(e.getMonth()+1)}-${xr(e.getDate())},Si=e=>{let[t,r,o]=e.split("-").map(n=>parseInt(n,10));return{year:t,month:r,date:o}},Ni=e=>${Ho(e)}-w${xr(ho(e))},Al=e=>{let[t,r]=e.split("-w").map(o=>parseInt(o,10));return Ae(Ga(new Date(t,0,1),r))};var vR="takker-memex",RR=async(e=new Date(2023,0,24))=>{if(scrapbox.Project.name!==vR)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=Ds({start:e,end:i}).filter(f=>{let m=yr(f),h=t.find(g=>g.title===m);return!h||!h.exists});if(c.length===0)return;let{render:l,dispose:u}=$e(),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=>Ft(x));for(let{title:x,links:E,project:v}of await Ml(["takker","takker-memex"]))for(let b of[x,...E]){let T=or(b);if(!T)continue;if(G(T)){let{name:C,message:M}=ne(T);console.error(/${v}/${b}: ${C} ${M});continue}let R=se(b);if(m.has(R))continue;m.add(R);let L=z(T);if(L.freshness?.status!=="done")for(let C of c){let M=en(L,C);if(!M)continue;let O=Ft(M.base);h.includes(O)&&(f.set(O,[...f.get(O)??[],M]),xo(L))}}let g=await wt();if(G(g))throw ne(g);p=z(g);let y=0;l({type:"spinner"},{type:"text",text:create 0/${c.length} diary pages...});for(let x of c){let E=yr(x),v=f.get(Ft(x))?.map?.(R=>ke(R))??[],b=#${pe(x,"yyyy-MM-dd")},T=#${pe(x,"yyyy-MM-dd HH:mm:ss")};await Me(vR,E,(R,{persistent:L})=>{if(L)return;let C=[...R.map(M=>M.text),...v];return C.some(M=>M.includes(b))?Jo(C):Jo([...C,T])},{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 Et(p),await De(1e3),u()}},o=r(),n=new Date,s=setInterval(()=>{let i=new Date;st(n,i)||(n=i,o.then(()=>o=r()))},1e4);return()=>(clearTimeout(s),o)};RR(new Date(2024,11,24));var nf=(...e)=>{let t=e.flatMap(o=>{if(typeof o=="string")return[Il(o)];if(Array.isArray(o.type))return[TR(o.type)];switch(o.type){case"text":return[Il(o.text)];case"group":{let n=nf(...o.items);return n?[n]:[]}default:return[TR(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},Il=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},TR=e=>{if(Array.isArray(e)){let t=document.createElement("span");t.classList.add("fa-stack");let r=of(e[0]);r.classList.add("fa-stack-1x");let o=of(e[1]);return o.classList.add("fa-stack-1x"),t.append(r,o),Il(t)}return Il(of(e))},of=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:sf,selection:af}=Nt(),PR=e=>{let{className:t,display:r,onClick:o,context:n="page"}=e,s=document.createElement("div");t&&s.classList.add(t),_R(n)||(s.style.display="none");let i=(...l)=>{if(l.length===1&&l[0]===""){s.style.display="none";return}s.textContent="";let u=nf(...l);u&&s.append(u)},a=typeof r=="function"?r({cursor:sf,selection:af}):r;return i(...Array.isArray(a)?a:[a]),s.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),o({cursor:sf,selection:af,setDisplay:i})}),{status:s,context:n,update:()=>{if(_R(n)?s.removeAttribute("style"):s.style.display="none",typeof r=="function"){let l=r({cursor:sf,selection:af});i(...Array.isArray(l)?l:[l])}}}},_R=e=>e!=="stream"?scrapbox.Layout===e:scrapbox.Layout==="list"&&location.pathname.startsWith("/stream");var OR=()=>{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 cf=new Set,{cursor:CU,selection:MU}=Nt(),AU=OR();var lr=e=>{let t=PR(e);return cf.add(t),AU.append(t.status),()=>{t.status.remove(),cf.delete(t)}},lf=()=>{for(let{update:e}of cf)e()};CU.addChangeListener(()=>lf());MU.addChangeListener(()=>lf());scrapbox.addListener("layout:changed",lf);var SR=async(e,t)=>{try{let r=t.getSelectedText()||nt(e.getPosition().line);if(!r)return;await navigator.clipboard.writeText(r)}catch(r){console.error(r),alert(Faild to copy:
${JSON.stringify(r)})}},NR=async(e,t)=>{try{let r=t.hasSelection(),o=r?t.getRange().start.line:e.getPosition().line,n=r?t.getSelectedText():nt(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(),ht("Delete")}catch(r){console.error(r),alert(Faild to cut:
${JSON.stringify(r)})}},LR=async e=>{try{let t=await navigator.clipboard.readText();if(!t)return;e.focus(),await Je(t)}catch(t){console.error(t),alert(Faild to paste:
${JSON.stringify(t)})}},CR=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=uo();t.hasFocus||(e.preventDefault(),t.focus())});var pf=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")}},MR=new pf;var AR=e=>new Promise(t=>setTimeout(t,e));async function kr(e,{wait:t=1}={}){let r=MR.textInput;r.focus(),r.value=e;let o=document.createEvent("UIEvent");o.initEvent("input",!0,!1),r.dispatchEvent(o),await AR(t)}if(io()){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:()=>kr(pe(new Date,"#yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD HH:mm:ss ",onClick:()=>kr(pe(new Date,"yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD",onClick:()=>kr(pe(new Date,"yyyy-MM-dd"))}),scrapbox.PageMenu(e).addItem({title:"HH:mm:ss ",onClick:()=>kr(pe(new Date,"HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"⬜",onClick:()=>kr("⬜")}),scrapbox.PageMenu(e).addItem({title:"🚧",onClick:()=>kr("🚧")}),scrapbox.PageMenu(e).addItem({title:"⌛",onClick:()=>kr("⌛")}),scrapbox.PageMenu(e).addItem({title:"📝",onClick:()=>kr("📝")}),scrapbox.PageMenu(e).addItem({title:"✅",onClick:()=>kr("✅")}),scrapbox.PageMenu(e).addItem({title:"❌",onClick:()=>kr("❌")})}scrapbox.PageMenu.addItem({title:"Open kakeru",image:"https://i.kakeru.app/15c3b1a40b6b3c2ebd68f33f4c86b3f6-opaque.png",onClick:()=>window.open("https://kakeru.app")});var IR=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var uf=()=>DR(document.getElementsByClassName("lines").item(0),"div.lines");var FR=()=>DR(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),DR=(e,t)=>{if(e)return IR(e,t),e};var Li=()=>{let e=uf();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 UR=e=>{if(dt(e))return;if(Ue(e))return FU(e)?.id;if(Ce(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)};var FU=e=>{if(dt(e))return;if(Ue(e))return Li()[e];let t=UR(e);return t?Li().find(r=>r.id===t):void 0},mf=e=>{if(DU(e))return e;let t=UR(e);if(dt(t))return t;let r=document.getElementById(L${t});if(!dt(r))return r},DU=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var $R=()=>{let e=FR();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=jR(...r);o&&t.append(o)},dispose:()=>t.remove(),[Symbol.dispose]:()=>t.remove()}},jR=(...e)=>{let t=e.flatMap(o=>{switch(o.type){case"spinner":return[jU()];case"check-circle":return[BU()];case"exclamation-triangle":return[HU()];case"text":return[Dl(o.text)];case"group":{let n=jR(...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},Dl=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},jU=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Dl(e)},BU=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Dl(e)},HU=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Dl(e)};var BR=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}};var ff=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 GU=()=>{let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.right="0",e.style.textAlign="right",e},Es=new Map,Ul,df=()=>{for(let r of Es.values())r.remove();Es.clear();let e=sl(()=>qU(Li()),{interval:1e3,maxQueued:0}),t=()=>{e.clear(),e()};if(scrapbox.Layout!=="page"){if(scrapbox.removeListener("lines:changed",t),!Ul)return;clearInterval(Ul),Ul=void 0;return}t(),scrapbox.addListener("lines:changed",t),Ul=setInterval(t,60*1e3)},qU=e=>{for(let t of e){let r=it(t.text);if(!r?.record?.start){Es.get(t.id)?.remove?.(),Es.delete(t.id);continue}let o=Es.get(t.id)??GU();mf(t.id)?.append?.(o),Es.set(t.id,o),o.textContent=ff(go(r.record.end??new Date,r.record.start))}};scrapbox.Project.name==="takker-memex"&&(df(),scrapbox.addListener("page:changed",df),scrapbox.addListener("lines:changed",df));var zU=e=>{let[t,r]=e.reduce((o,{text:n})=>{let s=it(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 Nm(t)},VU=async(e,t)=>{let[r,o]=await Promise.all([Am(e,yr(t),{fetch:HR}),Am(e,yr(jt(t,1)),{fetch:HR})]),n=r.ok?(await r.json()).lines:[];return o.ok&&n.push(...(await o.json()).lines),n},HR=async(e,t)=>{let r=await BR(new Request(e,t));return!r||yi(new Date,new Date(${r.headers.get("Date")}))>=60?globalThis.fetch(e,t):r},{render:KU}=$R(),WR=async()=>{let e=zU(await VU("takker-memex",new Date))??hr(new Date);KU({type:"text",text:ff(go(new Date,e))})};WR();setInterval(WR,60*1e3);async function GR(e,{from:t,to:r,merge:o}){if(t===r)return{success:!0,dup:!1};let n=await er(t,e);if(G(n))return{success:!1,at:"from",name:ne(n).name,message:ne(n).message};let s=z(n);if(!s.persistent)return{success:!1,at:"from",name:"EmptyPageError",message:"The request page is empty."};let i=await er(r,e);if(G(i))return{success:!1,at:"to",name:ne(i).name,message:ne(i).message};let a=z(n);return a.persistent&&!o?{success:!1,at:"to",name:"NoEmptyPageError",message:The same page already exists in "/${r}"}:(await Me(r,e,c=>[...c,...s.lines.slice(1)].map(l=>l.text)),await Zd(t,e),{success:!0,dup:a.persistent})}var hf=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}=$e();o({type:"spinner"},{type:"text",text:/${t}/${e} → /${r}/${e}});try{let s=await GR(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}/${ge(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 hf()}});scrapbox.PageMenu.addItem({title:"Transport and Open",onClick:async()=>{let e=await hf();e&&window.open(e)}});var YU="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)}/${YU},{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}))}});Hr.PageMenu.addMenu({image:"https://img.icons8.com/ios/180/FFFFFF/inbox.png",title:"~task",onClick:()=>{let{cursor:e,selection:t}=Nt(),r=e.getPosition().line,o=t.getSelectedText(),n=o||e.lines[r].text,s=n.split(
).map(i=>i.replace(/^\s*(.+)$/g,$1~@${pe(new Date,"yyyy-MM-dd")})).join(
);o||t.setRange({start:{line:r,char:0},end:{line:r,char:n.length}}),Je(s)}});var Ci=e=>Xc(...U(()=>{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 kR(e,60),t={...t,loading:!1},o()})(),r);let n=()=>{r=(async()=>{await r,t={...t,loading:!0},o();let[s,i]=XU(await Ml(e));t={...t,tasks:s,errors:i,loading:!1},o()})()};return n(),bR(e,n)},()=>t]},e)),XU=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=se(a);if(t.has(c))continue;t.add(c);let l=or(a);if(l){if(G(l)){o.push({project:i,title:a,...ne(l)});continue}r.push({project:i,title:a,...z(l)})}}return[r,o]};var $l=()=>{let[e,t]=po(JU,{isOpen:!1,prevOverflowY:""}),r=rt(null),o=A(()=>{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=A(()=>{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=U(()=>{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}},JU=(e,t)=>{let r=t(e);return e.isOpen===r.isOpen&&e.prevOverflowY===r.prevOverflowY?e:r.isOpen?r:{isOpen:!1}};var Mi=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 ks=({text:e,title:t})=>{let[r,o]=X(""),n=A(async s=>{s.preventDefault(),s.stopPropagation();try{await navigator.clipboard.writeText(e),o("Copied"),await De(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 QU=60*60*24*1e3,qR=(e,t)=>{let r=we(e.refDate),o=(t.getTime()-r.getTime())/QU;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 VR=(e,t)=>{if(t.score!==e.score)return t.score-e.score;let r=zR(e.freshness),o=zR(t.freshness);return r!==o?o-r:rr(Cr(e),Cr(t))?-1:1},zR=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 Ai=({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 vs=()=>{let[e,t]=X(new Date);return Z(()=>{let r=setInterval(()=>t(new Date),6e4);return()=>{clearInterval(r)}},[]),e};var KR=e=>{switch(e){case"todo":return"ToDo";case"note":return"覚書";case"deadline":return"締切";case"up-down":return"浮遊";case"done":return"完了"}};var YR=(e,t)=>new URL(/${e.project}/${ge(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:YR({project:t,title:r}).pathname,...t===scrapbox.Project.name?{rel:"route"}:{rel:"noopener noreferrer",target:"_blank"},children:e});var XR=({action:e,pActions:t})=>{let r=U(()=>KR(e.freshness.status),[e.freshness.status]),o=U(()=>Nr(Cr(e)).slice(11)||" ",[Cr(e)]),n=U(()=>Ys(e),[e]),s=Math.floor(Math.round(e.score)/7),i=vs(),a=U(()=>e.executed!==void 0&&zo(Sr(we(e.executed.start),e.executed.duration),i),[e.executed?.start,e.executed?.duration,i]),c=U(()=>[...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:ZU(e).toFixed(2)}}:{},children:[d(ks,{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})]})},ZU=e=>Math.max(.8*Math.exp(Math.log(8/7)/7*e.score),.05);var JR=(e=Ft(new Date))=>{let[t,r]=X(e),o=A(()=>{r(s=>{switch(s){case"errors":return"expired";case"expired":return Ft(new Date);default:{let i=we(Si(s));return i.setDate(i.getDate()+1),Ft(i)}}})},[]),n=A(()=>{r(s=>{let i=Ft(new Date);switch(s){case"errors":return"errors";case"expired":return"errors";case i:return"expired";default:{let a=we(Si(s));return a.setDate(a.getDate()-1),Ft(a)}}})},[]);return{pageNo:t,next:o,prev:n}};var Bl=(e,t)=>Z(()=>(scrapbox.on(e,t),()=>scrapbox.off(e,t)),[]);var Ii=(e,t)=>{let r=rt({...t});Z(()=>(Object.assign(r.current,t),()=>{for(let o of Object.keys(t))delete r.current[o]}),[...Object.keys(t)].sort().map(o=>t[o])),Z(()=>{e(r.current)},[e])};var QR=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=>ft(d(e$,{getController:o,projects:e}),r))},e$=({getController:e,projects:t})=>{let{tasks:r,errors:o,load:n,loading:s}=Ci(t),{pageNo:i,next:a,prev:c}=JR(),l=U(()=>{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=>!Lr(y)&&rr(fy(y),Lt(g))&&y.freshness===void 0&&y.recurrence===void 0?[{...y,score:0,freshness:{refDate:y.executed.start,status:"todo"}}]:[]).sort((y,x)=>rr(Cr(y),Cr(x))?-1:0)}let h=we(Si(i));return r.flatMap(g=>{if(!g.freshness)return[];if(xo(g))return[];let y=qR(g.freshness,h);return y>-999?[{...g,score:y}]:[]}).sort(VR)},[r,o,i]),{ref:u,open:p,close:f}=$l();Ii(e,{open:p,close:f});let m=U(()=>[i,...l.map(h=> ${h.raw})].join(
),[l,i]);return Bl("page:changed",f),d(Q,{children:[d("style",{children:Mi}),d("dialog",{ref:u,children:[d("div",{className:"controller",children:[d(ks,{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(Ai,{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(XR,{action:h,pActions:l.slice(0,g)},h.raw))})]})]})};var Wl=(e,t)=>/${e}/${se(t)},Fi=new Map,gf=new Map,ZR=(e,t)=>{Fi.set(e,t);for(let r of gf.get(e)??[])r(t)},Hl=()=>{vn!==void 0&&(clearInterval(vn),vn=void 0);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Wl(e,t);if(!Fi.has(r))return;let o=Ut().map(n=>n.text);vn=setInterval(()=>{se(t)===se(o[0])&&(ZR(r,o),vn!==void 0&&(clearInterval(vn),vn=void 0))},1e3)},vn;scrapbox.on("page:changed",()=>{scrapbox.off("lines:changed",Hl);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=Wl(e,t);Fi.has(r)&&scrapbox.on("lines:changed",Hl)});var t$=(e,t)=>{let r=Wl(e,t),o=Fi.get(r);return o||(Fi.set(r,[]),er(e,t).then(n=>{if(G(n))return[];let s=z(n).lines.map(i=>i.text);ZR(r,s),t===scrapbox.Page.title&&!scrapbox.listeners("lines:changed").includes(Hl)&&scrapbox.on("lines:changed",Hl)})),o??[]},eT=(e,t)=>{let[r,o]=X(t$(e,t));return Z(()=>{let n=Wl(e,t),s=gf.get(n)??new Set;return s.add(o),gf.set(n,s),()=>{s.delete(o)}},[e,t]),r};var yf=e=>e.duration===void 0?void 0:Lt(Sr(we(e.start),e.duration)),xf=(e,t)=>{let r=we(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:yf(s),duration:e.duration-n}]};var Rn=e=>"title"in e,r$=e=>e.record?.duration!==void 0,tT=(e,t)=>Rn(e)&&e.status==="done"?e.status:r$(e)?Rn(e)&&e.executed?rr(Lt(t),e.executed.start)?"moved":"expired":"done":rr(yf(e.plan),Lt(t))?Rn(e)?"expired":"done":"undone";var rT=(e,t)=>{let r=or(e.title.slice(1,-1));if(!e.plan.start)return;let o={name:r&&We(r)?z(r).name:e.title,plan:{start:Lt(e.plan.start),duration:(e.plan.duration??0)/60}};if(e.record.start&&(o.record={start:Lt(e.record.start)},e.record.end&&(o.record.duration=go(e.record.end,e.record.start))),!r||G(r))return o;let n=z(r),s={...o,title:n.raw,project:t};return n.freshness&&(s.status=n.freshness.status),Lr(n)||(s.executed=n.executed),s},bf=(e,t)=>{let r=Ya(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 oT=(e,t,r)=>{let o=[wf(e,jt(t,1),r),wf(e,t,r),wf(e,Pe(t,1),r)],n=U(()=>o.flat(),o);return U(()=>{let s=hr(t),i=Wa(t);return n.flatMap(a=>{let[,c]=xf(a.plan,s);if(!c)return[];let[l]=xf(c,i);if(!l)return[];let{plan:u,...p}=a;return[{plan:l,...p}]}).sort((a,c)=>rr(a.plan.start,c.plan.start)?-1:0)},[n,t])},wf=(e,t,r)=>{let o=eT(e,yr(t)),n=U(()=>n$(o,e),[o,e]);return U(()=>n.length!==0?n:o$(t,r),[n,t,r])},o$=(e,t)=>t.flatMap(r=>{if(r.freshness?.status==="done")return[];if(Lr(r))return[];if(xo(r)){let n=Ka(r,e);return n?[bf(n,r.project)]:[]}let o=we(r.executed.start);return st(o,e)?[bf(r,r.project)]:[]}),n$=(e,t)=>{let r=[];for(let o of Vo(e)){if(yo(o))continue;let n=rT(o,t);n&&r.push(n)}return r};var nT=({event:e})=>{let t=U(()=>e.plan.start.hours+e.plan.start.minutes/60,[e.plan.start]),r=U(()=>--start: ${t}; --duration: ${e.plan.duration};,[t,e.plan.duration]),o=vs(),n=U(()=>tT(e,o),[e,o]);return Rn(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 sT=({project:e,date:t,tasks:r})=>{let o=oT(e,t,r),n=U(()=>o.flatMap(a=>Rn(a)?[${a.title}]:[]).join(
),[o]),s=vs(),i=U(()=>st(s,t)&&d("div",{className:"indicator",style:--start: ${Zg(s)+Qg(s)/60}}),[s,t]);return d("div",{className:"timeline",role:"gridcell",children:[o.map(a=>d(nT,{event:a},a.name)),i,d(ks,{text:n})]})};var Ef=({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:js(n)})},Ft(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":${xr(n)}:00},n))}),e.map(n=>d(sT,{project:r,date:n,tasks:t},Ft(n)))]})})]});var kf=(e,t,r)=>{let[o,n]=X(e),s=A(()=>n(t),[t]),i=A(()=>n(r),[t]),a=A(c=>n(c),[]);return{pageNo:o,next:s,prev:i,jump:a}};var iT=e=>{let t=rt(new Set),[r,o]=X(e),n=A(()=>{for(let l of t.current)l()},[]),s=A(()=>{o(!0),n()},[]),i=A(()=>o(!1),[]),a=A(()=>o(l=>(l||n(),!l)),[]),c=A(l=>(t.current.add(l),()=>t.current.delete(l)),[]);return{isOpen:r,open:s,close:i,toggle:a,onOpen:c}};var lT=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=>ft(d(s$,{getController:o,projects:e,mainProject:e[0]}),r))},pT=(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=>ft(d(i$,{getController:n,projects:e,mainProject:e[0],open:t}),o))},aT=!1,s$=({getController:e,projects:t,mainProject:r})=>{let{tasks:o,load:n,loading:s}=Ci(t),{pageNo:i,next:a,prev:c,jump:l}=kf(Ni(new Date),a$,c$),u=U(()=>{let y=Al(i);return[0,1,2,3,4,5,6].map(x=>Pe(y,x))},[i]),{ref:p,open:f,close:m,isOpen:h}=$l();aT||=h,Ii(e,{open:f,close:m,isOpen:h}),Bl("page:changed",m);let g=A(()=>l(Ni(new Date)),[l]);return d(Q,{children:[d("style",{children:Mi}),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(Ai,{loading:s,onClick:n}),d("button",{type:"button",className:"close",onClick:m,children:""})]}),aT&&d("div",{ref:uT,className:"result scheduler","data-page-no":i,children:d(Ef,{dateList:u,tasks:o,project:r})})]})]})},cT=!1,i$=({projects:e,mainProject:t,getController:r,open:o})=>{let{tasks:n,load:s,loading:i}=Ci(e),{pageNo:a,next:c,prev:l,jump:u}=kf(new Date,l$,p$),p=U(()=>[a],[a]),f=A(()=>u(new Date),[u]),{isOpen:m,open:h,close:g}=iT(o);return cT||=m,Ii(r,{open:h,close:g,isOpen:m}),d(Q,{children:[d("style",{children:Mi}),cT&&d("div",{className:wedget${m?" open":""},ref:uT,children:[d("div",{className:"controller",children:[d("span",{children:Ft(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(Ai,{loading:i,onClick:s})]}),d(Ef,{dateList:p,tasks:n,project:t,hasColumn:!1})]})]})},a$=e=>Ni(Bo(Al(e),1)),c$=e=>Ni(ey(Al(e),1)),l$=e=>Pe(e,1),p$=e=>jt(e,1),uT=e=>{let t=e?.getElementsByClassName?.("indicator")?.[0];if(!t)return;let r=globalThis.scrollY;t.scrollIntoView({block:"center"}),globalThis.scroll(0,r)};Ph({project:"takker-dist"});da(!0);Sh({maxCount:10,accessToken:u$,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)}}});Mg().then(e=>{scrapbox.PageMenu.addItem({title:"Fulltext Search",onClick:()=>{e.toggle()}})});var m$="https://scrapbox.io/files/67344295032adf96d1e4c276.wasm",f$="/api/code/takker-dist/for-any-project-min/esbuild-worker.js";(async()=>{let e=new Request(m$),t=await Dn(e);t||(t=await fetch(e),await Ia(e,t)),await _E(await WebAssembly.compileStreaming(t),f$)})();(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 hk({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;au.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)}})})();bk({previewers:[{when:/(?:^|\.)svg$/,preview:wk},{when:/(?:^|\.)glsl$/,preview:Ik},{when:/(?:^|\.)(?:plantuml|puml|pu)$/,preview:Uk},{when:/(?:^|\.)tikz\(tex\)$/,preview:jk("/api/code/takker-dist/for-any-project-min/tex-worker.js","https://scrapbox.io/files/65d1645c19cd8e002433c3df")}]});(async()=>{let{toggle:e}=await ov();scrapbox.PageMenu.addItem({title:"履歴スライダー",image:"https://1.bp.blogspot.com/-UZtkSEX0wh4/U5l5_dNcEsI/AAAAAAAAhWs/UzJGVzyiX8Y/s800/kaichu_dokei.png",onClick:e})})();zv("takker",["takker","振り返り(takker-workflow@0.0.1)のtemplate","txt"],["takker","1週間の振り返り(takker-workflow@0.0.1)のtemplate","txt"],new Date(2024,11,24));io()&&(lr({display:{type:"caret-left"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?La():Pa()}}),lr({display:{type:"caret-right"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Na():_a()}}),lr({display:{type:"caret-up"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ca():Oa()}}),lr({display:{type:"caret-down"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ma():Sa()}}),lr({display:{type:"copy"},onClick:async({cursor:e,selection:t})=>await SR(e,t)}),lr({display:{type:"cut"},onClick:async({cursor:e,selection:t})=>await NR(e,t)}),lr({display:{type:"clipboard"},onClick:async({cursor:e})=>await LR(e)}),lr({display:{type:"undo"},onClick:()=>Eg()}),lr({display:{type:"redo"},onClick:()=>kg()}),lr({display:({cursor:e})=>e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?{type:["i-cursor","slash"]}:{type:"i-cursor"},onClick:({cursor:e})=>CR(e)}));if(io()&&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:Xo}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>Qo({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})})}if(io()){let e="New Page",t=[tn,rn,on];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&&Vr({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&&Vr({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 QR(o);scrapbox.PageMenu.addMenu({title:e,image:"/assets/img/favicon/apple-touch-icon.png",onClick:n});let s=await lT(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 pT(o,a[c]),u=()=>{a[c]=!l.isOpen,l.isOpen?l.close():l.open?.(),localStorage.setItem(i,JSON.stringify(a))};io()?lr({display:{type:"calendar"},onClick:u}):scrapbox.PageMenu.addItem({title:"toggle wedget",onClick:u})}})();var mT=e=>String(e).padStart(2,"0"),fT=e=>${e.getFullYear()}-${mT(e.getMonth()+1)}-${mT(e.getDate())};for(let e of document.getElementsByClassName("new-button")){let t=#${fT(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=as.parse(e,{hasTitle:!1});if(console.log("Parserd text:"),console.log(t),navigator.clipboard){let r=d$(t).join(`
);console.log(r),navigator.clipboard.writeText(r).catch(o=>console.log(o)),console.log("Copied.")}}});function d$(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=>Gl(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 Gl(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=>Gl(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=>Gl(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=>Gl(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(io()){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:Zp}),scrapbox.PageMenu(e).addItem({title:"Add task",image:"https://img.icons8.com/ios/180/FFFFFF/plus-math.png",onClick:Hs}),scrapbox.PageMenu(e).addItem({title:"Start task",image:"https://img.icons8.com/ios/180/FFFFFF/start--v1.png",onClick:Ko}),scrapbox.PageMenu(e).addItem({title:"End task",image:"https://img.icons8.com/ios/180/FFFFFF/stop-squared.png",onClick:Xr}),scrapbox.PageMenu(e).addItem({title:"Posteriori end task",image:"https://img.icons8.com/ios/180/FFFFFF/end--v1.png",onClick:Ws}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:async()=>{let[t,r]=h$(),o=Pr().slice(t,r+1).map(n=>{let s=n.text,i=n.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=or(i);if(!a||!a.ok)return s;let c=a.value;if(c.freshness?.status==="done")return s;let l=en(c);return l.title=${i},l?ke(l):s}).join(
);await Ta(t,r,o),await Xo()}}),scrapbox.PageMenu(e).addItem({title:"Walk a day",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:()=>Gs()}),scrapbox.PageMenu(e).addItem({title:"Move today",image:"https://img.icons8.com/ios/180/FFFFFF/date-to.png",onClick:()=>qs()}),scrapbox.PageMenu(e).addItem({title:"Format",image:"https://img.icons8.com/ios/180/FFFFFF/sort-by-start-date.png",onClick:()=>Vs(scrapbox.Project.name,scrapbox.Page.title)}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>Qo({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 h$=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:o}=Ge();return r===""?[o.line,o.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var dT="scrapbox-episopass",ql=!1;scrapbox.PopupMenu.addButton({title:e=>ql?"remove EP":/https:\/\/scrapbox\.io\/files\/\w+\.html/.test(e)?"run EP":"",onClick:async e=>{if(document.getElementById(dT)?.remove(),ql){ql=!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="${dT}" src="${s}" width="800" height="400"></iframe>`),ql=!0;return}catch(r){console.error("Failed to load an EpisoPass html: ",r)}}});export{lr as addButton,Je as insertText,au 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 Y=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)t}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pr=(e,r)=>{if(e.length!==r.length)return!1;let t=...e.sort(),o=...r.sort();return t.every((n,a)=>n===oa)};function mr(e,r={}){let{signal:t,persistent:o=!0}=r;return t?.aborted?Promise.reject(t.reason):new Promise((n,a)=>{let s=()=>{clearTimeout(+i),a(t?.reason)},i=Dt(()=>{t?.removeEventListener("abort",s),n()},e);if(t?.addEventListener("abort",s,{once:!0}),o===!1)try{Deno.unrefTimer(i)}catch(u){if(!(u instanceof ReferenceError))throw u;console.error("persistent option is only available in Deno")}})}var fr=2**31-1;function Dt(e,r){let t=r=Math.trunc(Math.max(r,0)||0),o=Date.now(),n,a=()=>{t=r-(Date.now()-o),n=t>fr?setTimeout(a,fr):setTimeout(e,t)};return a(),{valueOf:()=>n}}var gr=Symbol("Comlink.proxy"),$t=Symbol("Comlink.endpoint"),Gt=Symbol("Comlink.releaseProxy"),Ce=Symbol("Comlink.finalizer"),de=Symbol("Comlink.thrown"),Er=e=>typeof e=="object"&&e!==null||typeof e=="function",Vt={canHandle:e=>Er(e)&&egr,serialize(e){let{port1:r,port2:t}=new MessageChannel;return ae(e,r),[t,t]},deserialize(e){return e.start(),zt(e)}},Wt={canHandle:e=>Er(e)&&de in e,serialize({value:e}){let r;return e instanceof Error?r={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:r={isError:!1,value:e},[r,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Rr=new Map("proxy",Vt],["throw",Wt);function qt(e,r){for(let t of e)if(r===t||t==="*"||t instanceof RegExp&&t.test(r))return!0;return!1}function ae(e,r=globalThis,t="*"){r.addEventListener("message",function o(n){if(!n||!n.data)return;if(!qt(t,n.origin)){console.warn(Invalid origin '${n.origin}' for comlink proxy);return}let{id:a,type:s,path:l}=Object.assign({path:[]},n.data),i=(n.data.argumentList||[]).map(K),u;try{let f=l.slice(0,-1).reduce((c,m)=>cm,e),p=l.reduce((c,m)=>cm,e);switch(s){case"GET":u=p;break;case"SET":f[l.slice(-1)0]=K(n.data.value),u=!0;break;case"APPLY":u=p.apply(f,i);break;case"CONSTRUCT":{let c=new p(...i);u=Qt(c)}break;case"ENDPOINT":{let{port1:c,port2:m}=new MessageChannel;ae(e,m),u=Zt(c,c)}break;case"RELEASE":u=void 0;break;default:return}}catch(f){u={value:f,de:0}}Promise.resolve(u).catch(f=>({value:f,de:0})).then(f=>{letp,c=Re(f);r.postMessage(Object.assign(Object.assign({},p),{id:a}),c),s==="RELEASE"&&(r.removeEventListener("message",o),yr(r),Ce in e&&typeof eCe=="function"&&eCe())}).catch(f=>{letp,c=Re({value:new TypeError("Unserializable return value"),de:0});r.postMessage(Object.assign(Object.assign({},p),{id:a}),c)})}),r.start&&r.start()}function Ht(e){return e.constructor.name==="MessagePort"}function yr(e){Ht(e)&&e.close()}function zt(e,r){let t=new Map;return e.addEventListener("message",function(o){let{data:n}=o;if(!n||!n.id)return;let a=t.get(n.id);if(a)try{a(n)}finally{t.delete(n.id)}}),Be(e,t,[],r)}function me(e){if(e)throw new Error("Proxy has been released and is not useable")}function hr(e){return X(e,new Map,{type:"RELEASE"}).then(()=>{yr(e)})}var ge=new WeakMap,Ee="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{let r=(ge.get(e)||0)-1;ge.set(e,r),r===0&&hr(e)});function Yt(e,r){let t=(ge.get(r)||0)+1;ge.set(r,t),Ee&&Ee.register(e,r,e)}function Kt(e){Ee&&Ee.unregister(e)}function Be(e,r,t=[],o=function(){}){let n=!1,a=new Proxy(o,{get(s,l){if(me(n),l===Gt)return()=>{Kt(a),hr(e),r.clear(),n=!0};if(l==="then"){if(t.length===0)return{then:()=>a};let i=X(e,r,{type:"GET",path:t.map(u=>u.toString())}).then(K);return i.then.bind(i)}return Be(e,r,...t,l)},set(s,l,i){me(n);letu,f=Re(i);return X(e,r,{type:"SET",path:...t,l.map(p=>p.toString()),value:u},f).then(K)},apply(s,l,i){me(n);let u=tt.length-1;if(u===$t)return X(e,r,{type:"ENDPOINT"}).then(K);if(u==="bind")return Be(e,r,t.slice(0,-1));letf,p=dr(i);return X(e,r,{type:"APPLY",path:t.map(c=>c.toString()),argumentList:f},p).then(K)},construct(s,l){me(n);leti,u=dr(l);return X(e,r,{type:"CONSTRUCT",path:t.map(f=>f.toString()),argumentList:i},u).then(K)}});return Yt(a,e),a}function Jt(e){return Array.prototype.concat.apply([],e)}function dr(e){let r=e.map(Re);return[r.map(t=>t0),Jt(r.map(t=>t1))]}var _r=new WeakMap;function Zt(e,r){return _r.set(e,r),e}function Qt(e){return Object.assign(e,{gr:!0})}function Re(e){for(letr,tof Rr)if(t.canHandle(e)){leto,n=t.serialize(e);return{type:"HANDLER",name:r,value:o},n}return[{type:"RAW",value:e},_r.get(e)||[]]}function K(e){switch(e.type){case"HANDLER":return Rr.get(e.name).deserialize(e.value);case"RAW":return e.value}}function X(e,r,t,o){return new Promise(n=>{let a=Xt();r.set(a,n),e.start&&e.start(),e.postMessage(Object.assign({id:a},t),o)})}function Xt(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var P=!1;var wr=e=>Object.fromEntries(...Object.entries(console).map((r,t)=>{if(typeof t!="function")returnr,t;switch(r){case"warn":case"error":return[r,(...o)=>t(%c${e},je,...o)];case"log":case"info":case"debug":return[r,(...o)=>{P!==!0&&(!P||!P.has(e))||t(%c${e},je,...o)}];case"assert":return[r,(o,...n)=>{P!==!0&&(!P||!P.has(e))||t(o,%c${e},je,...n)}];case"time":case"timeEnd":return[r,o=>{P!==!0&&(!P||!P.has(e))||t(${e} ${o})}];default:returnr,(...o)=>{if(!(P!==!0&&(!P||!P.has(e))))return t(...o)}}})),je="color: gray";var Or=function(){};function le(e,r={}){Or.prototype.name=e;let t={};return new Proxy(Or,{get(o,n){return n==="caller"?null:n==="__createMock__"?le:n==="__unenv__"?!0:n in r?rn:tn=tn||le(${e}.${n.toString()})},apply(o,n,a){return le(${e}())},construct(o,n,a){return le([${e}])},enumerate(){return[]}})}var De=le("mock");function eo(e){return new Error([unenv] ${e} is not implemented yet!)}function d(e){return Object.assign(()=>{throw eo(e)},{__unenv__:!0})}var ro=Object.freeze(Object.create(null,{__unenv__:{get:()=>!0}})),ye=Object.create(null),to=globalThis.process?.env,ie=e=>to||globalThis.__env__||(e?ye:globalThis),oo=new Proxy(ye,{get(e,r){return ie()r??yer},has(e,r){let t=ie();return r in t||r in ye},set(e,r,t){let o=ie(!0);return or=t,!0},deleteProperty(e,r){let t=ie(!0);return delete tr,!0},ownKeys(){let e=ie();return Object.keys(e)}}),no=Object.assign(function(e){let r=Date.now(),t=Math.trunc(r/1e3),o=r%1e3*1e6;if(e){let n=t-e0,a=o-e0;return a<0&&(n=n-1,a=1e9+a),n,a}returnt,o},{bigint:function(){return BigInt(Date.now()*1e6)}}),so=globalThis.queueMicrotask?(e,...r)=>{globalThis.queueMicrotask(e.bind(void 0,...r))}:ao();function ao(){let e=[],r=!1,t,o=-1;function n(){!r||!t||(r=!1,t.length>0?e=...t,...e:o=-1,e.length>0&&a())}function a(){if(r)return;let s=setTimeout(n);r=!0;let l=e.length;for(;l;){for(t=e,e=[];++o<l;)t&&to();o=-1,l=e.length}t=void 0,r=!1,clearTimeout(s)}return(s,...l)=>{e.push(s.bind(void 0,...l)),e.length===1&&!r&&setTimeout(a)}}var io="unenv",lo=[],uo="",co={ares:"",http_parser:"",icu:"",modules:"",node:"",openssl:"",uv:"",v8:"",zlib:""};function C(){return $e}var po=C,fo=C,mo=C,go=C,Eo=C,Ro=C,yo=function(e){return e==="message"||e==="multipleResolves"?$e:!1},ho=C,_o=C,wo=function(e){return[]},Oo=()=>0,To=function(e){throw new Error("unenv process.binding is not supported")},Tr="/",bo=function(){return Tr},xo=function(e){Tr=e},No=function(){return 0},ko=function(){return 1e3},Fo=function(){return 1e3},So=function(){return 1e3},Ao=function(){return 1e3},Lo=function(){return[]},Uo=e=>{},Io=d("process.abort"),Po=new Set,Mo="",vo="",Co=ro,Bo=!1,jo=()=>0,Do=()=>0,$o=d("process.cpuUsage"),Go=0,Vo=d("process.dlopen"),Wo=C,qo=C,Ho=d("process.eventNames"),zo=[],Yo="",Ko=d("process.exit"),Jo=Object.create({inspector:void 0,debug:void 0,uv:void 0,ipv6:void 0,tls_alpn:void 0,tls_sni:void 0,tls_ocsp:void 0,tls:void 0,cached_builtins:void 0}),Zo=()=>[],Qo=d("process.getMaxListeners"),Xo=d("process.kill"),en=Object.assign(()=>({arrayBuffers:0,rss:0,external:0,heapTotal:0,heapUsed:0}),{rss:()=>0}),rn=1e3,tn="",on=1e3,nn=d("process.rawListeners"),sn=Object.create({name:"",lts:"",sourceUrl:void 0,headersUrl:void 0}),an=Object.create({compact:void 0,directory:void 0,filename:void 0,getReport:d("process.report.getReport"),reportOnFatalError:void 0,reportOnSignal:void 0,reportOnUncaughtException:void 0,signal:void 0,writeReport:d("process.report.writeReport")}),ln=d("process.resourceUsage"),un=d("process.setegid"),cn=d("process.seteuid"),pn=d("process.setgid"),fn=d("process.setgroups"),mn=d("process.setuid"),dn=d("process.setMaxListeners"),gn=d("process.setSourceMapsEnabled"),En=De.__createMock__("process.stdout"),Rn=De.__createMock__("process.stderr"),yn=De.__createMock__("process.stdin"),hn=!1,_n=()=>0,wn=0,On=d("process.setUncaughtExceptionCaptureCallback"),Tn=()=>!1,bn=!1,xn=d("process.loadEnvFile"),Nn=void 0,kn={has:()=>!1},Fn={ref(){},unref(){}},Sn=!1,An={register(){},unregister(){},registerBeforeExit(){}},Ln=d("process.assert"),Un=d("process.openStdin"),In=d("process._debugEnd"),Pn=d("process._debugProcess"),Mn=d("process._fatalException"),vn=d("process._getActiveHandles"),Cn=d("process._getActiveRequests"),Bn=d("process._kill"),jn=[],Dn=d("process._rawDebug"),$n=d("process._startProfilerIdleNotifier"),Gn=d("process.__stopProfilerIdleNotifier"),Vn=d("process._tickCallback"),Sa=d("process._linkedBinding"),Wn=void 0,qn=d("process.initgroups"),Hn=[],zn=C,Yn=!1,Kn=[],Jn=0,Zn=0,$e={_events:Kn,_eventsCount:Jn,_exiting:Yn,_maxListeners:Zn,_debugEnd:In,_debugProcess:Pn,_fatalException:Mn,_getActiveHandles:vn,_getActiveRequests:Cn,_kill:Bn,_preload_modules:jn,_rawDebug:Dn,_startProfilerIdleNotifier:$n,_stopProfilerIdleNotifier:Gn,_tickCallback:Vn,domain:Wn,initgroups:qn,moduleLoadList:Hn,reallyExit:zn,exitCode:wn,abort:Io,addListener:fo,allowedNodeEnvironmentFlags:Po,hasUncaughtExceptionCaptureCallback:Tn,setUncaughtExceptionCaptureCallback:On,loadEnvFile:xn,sourceMapsEnabled:bn,throwDeprecation:Sn,mainModule:Nn,permission:kn,channel:Fn,arch:Mo,argv:lo,argv0:vo,assert:Ln,binding:To,chdir:xo,config:Co,connected:Bo,constrainedMemory:jo,availableMemory:Do,cpuUsage:$o,cwd:bo,debugPort:Go,dlopen:Vo,disconnect:Wo,emit:yo,emitWarning:qo,env:oo,eventNames:Ho,execArgv:zo,execPath:Yo,exit:Ko,finalization:An,features:Jo,getBuiltinModule:Uo,getegid:ko,geteuid:Fo,getgid:So,getgroups:Lo,getuid:Ao,getActiveResourcesInfo:Zo,getMaxListeners:Qo,hrtime:no,kill:Xo,listeners:wo,listenerCount:Oo,memoryUsage:en,nextTick:so,on:po,off:go,once:mo,openStdin:Un,pid:rn,platform:tn,ppid:on,prependListener:ho,prependOnceListener:_o,rawListeners:nn,release:sn,removeAllListeners:Ro,removeListener:Eo,report:an,resourceUsage:ln,setegid:un,seteuid:cn,setgid:pn,setgroups:fn,setuid:mn,setMaxListeners:dn,setSourceMapsEnabled:gn,stderr:Rn,stdin:yn,stdout:En,title:io,traceDeprecation:hn,umask:No,uptime:_n,version:uo,versions:co},ue=$e;var Qn=Object.create,Sr=Object.defineProperty,Xn=Object.getOwnPropertyDescriptor,es=Object.getOwnPropertyNames,rs=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty,Ar=(e=>typeof Y<"u"?Y:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof Y<"u"?Y:r)t}):e)(function(e){if(typeof Y<"u")return Y.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Lr=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),os=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of es(r))!ts.call(e,n)&&n!==t&&Sr(e,n,{get:()=>rn,enumerable:!(o=Xn(r,n))||o.enumerable});return e},Ur=(e,r,t)=>(t=e!=null?Qn(rs(e)):{},os(r||!e||!e.__esModule?Sr(t,"default",{value:e,enumerable:!0}):t,e)),ns=Lr((e,r)=>{var t=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ue&&"node"in ue.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{t=Ar0(${["node","util"].join(":")})}catch{t=null}r.exports=t}),ss=Lr((e,r)=>{var t=null;if(typeof window>"u"&&("process"in globalThis&&"versions"in ue&&"node"in ue.versions&&typeof globalThis.caches>"u"&&typeof globalThis.addEventListener!="function"||"Bun"in globalThis))try{t=Ar0(${["node","fs"].join(":")})}catch{t=null}r.exports=t}),as={},he=is(globalThis,as);function is(e,r){return new Proxy(e,{get(t,o,n){return o in r?ro:eo},set(t,o,n){return o in r&&delete ro,eo=n,!0},deleteProperty(t,o){let n=!1;return o in r&&(delete ro,n=!0),o in e&&(delete eo,n=!0),n},ownKeys(t){let o=Reflect.ownKeys(e),n=Reflect.ownKeys(r),a=new Set(n);return...o.filter(s=>!a.has(s)),...n},defineProperty(t,o,n){return o in r&&delete ro,Reflect.defineProperty(e,o,n),!0},getOwnPropertyDescriptor(t,o){return o in r?Reflect.getOwnPropertyDescriptor(r,o):Reflect.getOwnPropertyDescriptor(e,o)},has(t,o){return o in r||o in e}})}var br="debug","info","warning","error","fatal";function xr(e,r){let t=br.indexOf(e);if(t<0)throw new TypeError(Invalid log level: ${JSON.stringify(e)}.);let o=br.indexOf(r);if(o<0)throw new TypeError(Invalid log level: ${JSON.stringify(r)}.);return t-o}function ce(e=[]){return Ir.getLogger(e)}var Ge=Symbol.for("logtape.rootLogger"),Ir=class W{static getLogger(r=[]){let t=Ge in he?heGe??null:null;return t==null&&(t=new W(null,[]),heGe=t),typeof r=="string"?t.getChild(r):r.length===0?t:t.getChild(r)}constructor(r,t){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=r,this.children={},this.category=t,this.sinks=[],this.filters=[]}getChild(r){let t=typeof r=="string"?r:r0,o=this.childrent,n=o instanceof W?o:o?.deref();return n==null&&(n=new W(this,...this.category,t),this.childrent="WeakRef"in he?new WeakRef(n):n),typeof r=="string"||r.length===1?n:n.getChild(r.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 r of Object.values(this.children))(r instanceof W?r:r.deref())?.resetDescendants();this.reset()}with(r){return new ls(this,{...r})}filter(r){for(let t of this.filters)if(!t(r))return!1;return this.filters.length<1?this.parent?.filter(r)??!0:!0}*getSinks(r){if(!(this.lowestLevel===null||xr(r,this.lowestLevel)<0)){if(this.parent!=null&&this.parentSinks==="inherit")for(let t of this.parent.getSinks(r))yield t;for(let t of this.sinks)yield t}}emit(r,t){if(!(this.lowestLevel===null||xr(r.level,this.lowestLevel)<0||!this.filter(r))){for(let o of this.getSinks(r.level))if(!t?.has(o))try{o(r)}catch(n){let a=new Set(t);a.add(o),us.log("fatal","Failed to emit a log record to sink {sink}: {error}",{sink:o,error:n,record:r},a)}}}log(r,t,o,n){let a=W.getLogger().contextLocalStorage?.getStore()??{},s,l=typeof o=="function"?{category:this.category,level:r,timestamp:Date.now(),get message(){return Nr(t,this.properties)},rawMessage:t,get properties(){return s==null&&(s={...a,...o()}),s}}:{category:this.category,level:r,timestamp:Date.now(),message:Nr(t,{...a,...o}),rawMessage:t,properties:{...a,...o}};this.emit(l,n)}logLazily(r,t,o={}){let n=W.getLogger().contextLocalStorage?.getStore()??{},a,s;function l(){if((s==null||a==null)&&(s=t((i,...u)=>(a=i,kr(i,u))),a==null))throw new TypeError("No log record was made.");returns,a}this.emit({category:this.category,level:r,get message(){return l()0},get rawMessage(){return l()1},timestamp:Date.now(),properties:{...n,...o}})}logTemplate(r,t,o,n={}){let a=W.getLogger().contextLocalStorage?.getStore()??{};this.emit({category:this.category,level:r,message:kr(t,o),rawMessage:t,timestamp:Date.now(),properties:{...a,...n}})}debug(r,...t){typeof r=="string"?this.log("debug",r,t0??{}):typeof r=="function"?this.logLazily("debug",r):this.logTemplate("debug",r,t)}info(r,...t){typeof r=="string"?this.log("info",r,t0??{}):typeof r=="function"?this.logLazily("info",r):this.logTemplate("info",r,t)}warn(r,...t){typeof r=="string"?this.log("warning",r,t0??{}):typeof r=="function"?this.logLazily("warning",r):this.logTemplate("warning",r,t)}error(r,...t){typeof r=="string"?this.log("error",r,t0??{}):typeof r=="function"?this.logLazily("error",r):this.logTemplate("error",r,t)}fatal(r,...t){typeof r=="string"?this.log("fatal",r,t0??{}):typeof r=="function"?this.logLazily("fatal",r):this.logTemplate("fatal",r,t)}},ls=class Pr{constructor(r,t){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=r,this.properties=t}get category(){return this.logger.category}get parent(){return this.logger.parent}getChild(r){return this.logger.getChild(r).with(this.properties)}with(r){return new Pr(this.logger,{...this.properties,...r})}log(r,t,o,n){this.logger.log(r,t,typeof o=="function"?()=>({...this.properties,...o()}):{...this.properties,...o},n)}logLazily(r,t){this.logger.logLazily(r,t,this.properties)}logTemplate(r,t,o){this.logger.logTemplate(r,t,o,this.properties)}debug(r,...t){typeof r=="string"?this.log("debug",r,t0??{}):typeof r=="function"?this.logLazily("debug",r):this.logTemplate("debug",r,t)}info(r,...t){typeof r=="string"?this.log("info",r,t0??{}):typeof r=="function"?this.logLazily("info",r):this.logTemplate("info",r,t)}warn(r,...t){typeof r=="string"?this.log("warning",r,t0??{}):typeof r=="function"?this.logLazily("warning",r):this.logTemplate("warning",r,t)}error(r,...t){typeof r=="string"?this.log("error",r,t0??{}):typeof r=="function"?this.logLazily("error",r):this.logTemplate("error",r,t)}fatal(r,...t){typeof r=="string"?this.log("fatal",r,t0??{}):typeof r=="function"?this.logLazily("fatal",r):this.logTemplate("fatal",r,t)}},us=Ir.getLogger("logtape","meta");function Nr(e,r){let t=[],o="";for(let n=0;n<e.length;n++){let a=e.charAt(n),s=e.charAt(n+1);if(a==="{"&&s==="{")o=o+a,n++;else if(a==="}"&&s==="}")o=o+a,n++;else if(a==="{")t.push(o),o="";else if(a==="}"){let l;o.match(/^\s|\s$/)?l=o in r?ro:ro.trim():l=ro,t.push(l),o=""}else o=o+a}return t.push(o),t}function kr(e,r){let t=[];for(let o=0;o<e.length;o++)t.push(eo),o<r.length&&t.push(ro);return t}var cs=Ur(ns()),_e=cs.default,Fr={debug:"DBG",info:"INF",warning:"WRN",error:"ERR",fatal:"FTL"},Mr="Deno"in globalThis&&"inspect"in globalThis.Deno&&typeof globalThis.Deno.inspect=="function"?(e,r)=>globalThis.Deno.inspect(e,{strAbbreviateSize:1/0,iterableLimit:1/0,...r}):_e!=null&&"inspect"in _e&&typeof _e.inspect=="function"?(e,r)=>_e.inspect(e,{maxArrayLength:1/0,maxStringLength:1/0,...r}):e=>JSON.stringify(e);function vr(e={}){let r=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,t=e.category??"·",o=e.value??Mr,n=e.level==null||e.level==="ABBR"?s=>Frs:e.level==="abbr"?s=>Frs.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,a=e.format??(({timestamp:s,level:l,category:i,message:u})=>${s} [${l}] ${i}: ${u});return s=>{let l="";for(let p=0;p<s.message.length;p++)p%2===0?l+=s.messagep:l+=o(s.messagep);let i=r(s.timestamp),u=n(s.level),f=typeof t=="function"?t(s.category):s.category.join(t);return`${a({timestamp:i,level:u,category:f,message:l,record:s})}
}}var Ua=vr(),Ve="\x1B[0m",We={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"},qe={bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",strikethrough:"\x1B[9m"},ps={debug:"blue",info:"green",warning:"yellow",error:"red",fatal:"magenta"};function fs(e={}){let r=e.format,t=typeof e.timestampStyle>"u"?"dim":e.timestampStyle,o=e.timestampColor??null,n=${t==null?"":qet}${o==null?"":Weo},a=t==null&&o==null?"":Ve,s=typeof e.levelStyle>"u"?"bold":e.levelStyle,l=e.levelColors??ps,i=typeof e.categoryStyle>"u"?"dim":e.categoryStyle,u=e.categoryColor??null,f=${i==null?"":qei}${u==null?"":Weu},p=i==null&&u==null?"":Ve;return vr({timestamp:"date-time-tz",value(c){return Mr(c,{colors:!0})},...e,format({timestamp:c,level:m,category:E,message:T,record:k}){let v=l[k.level];return c=${n}${c}${a},m=${s==null?"":qes}${v==null?"":Wev}${m}${s==null&&v==null?"":Ve},r==null?${c} ${m} ${f}${E}:${p} ${T}:r({timestamp:c,level:m,category:${f}${E}${p},message:T,record:k})}})}var Ia=fs();var ms=Ur(ss()),ds=ms.default;function ee(){throw new Error("File sink is not available in the browser.")}var gs={openSync:ee,writeSync:ee,flushSync:ee,closeSync:ee,statSync:ee,renameSync:ee},J=ds,Pa=J==null?gs:{openSync(e){return J.openSync(e,"a")},writeSync:J.writeSync,flushSync:J.fsyncSync,closeSync:J.closeSync,statSync:J.statSync,renameSync:J.renameSync};function F(e){return e.val}function A(e){return e.err}var Cr=" must not return ",Es="transformer",Rs="recoverer",ys="defaultValue",re=Es+Cr,$="called with ",te=ys+" must not be ",oe=Rs+Cr;var hs="Ok",Br="Err",jr=$+Br,_s=$+hs,ws="Carrying E in "+Br+" instead of throwing it directly. See .cause",He="an instance of Error of the current realm.",Va="The thrown value is not "+He,Wa="The contained E should be "+He,Os="This .cause is not "+He;function _(e){return e.ok}function R(e){return{ok:!0,val:e,err:null}}function g(e){return!e.ok}function S(e){return{ok:!1,val:null,err:e}}function w(e){return Dr(e,jr)}function Dr(e,r){if(g(e))throw new TypeError(r);return e.val}async function O(e,r){if(g(e))return e;let t=F(e),o=await r(t);return R(o)}async function b(e,r){if(_(e))return e;let t=A(e),o=await r(t);return S(o)}var we="null",tl=re+we,xs=$+we,ol=te+we,nl=oe+we;var Oe="undefined",ul=re+Oe,Ns=$+Oe,cl=te+Oe,pl=oe+Oe;var x=e=>e.ok?R(e):S({name:"HTTPError",message:${e.status} ${e.statusText},response:e});var Vr=async(e,r)=>{let t=new Request(e,r);try{return R(await globalThis.fetch(t))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return S({name:"AbortError",message:o.message,request:t});if(o instanceof TypeError)return S({name:"NetworkError",message:o.message,request:t});throw o}};var y=e=>{let{fetch:r=Vr,hostName:t="scrapbox.io",...o}=e;return{fetch:r,hostName:t,...o}};var N=e=>connect.sid=${e};function Te(e,r={}){if(e===null)return"null";if(Array.isArray(e))return As(e,r);switch(typeof e){case"string":return JSON.stringify(e);case"bigint":return${e}n;case"object":return e.constructor?.name!=="Object"?e.constructor?.name:Ls(e,r);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function As(e,r){let{threshold:t=20}=r,o=e.map(s=>Te(s,r)),n=o.join(", ");if(n.length<=t)return${n};let a=o.join(,
);return[
${Wr(2,a)}
]}function Ls(e,r){let{threshold:t=20}=r,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(s=>${s.toString()}: ${Te(es,r)}),n=o.join(", ");if(n.length<=t)return{${n}};let a=o.join(,
);return{
${Wr(2,a)}
}}function Wr(e,r){let t=" ".repeat(e);return r.split(
).map(o=>${t}${o}).join(
)}function be(e,r,...t){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=${r}(${t.map(n=>Te(n)).join(", ")}),o)}})}function qr(e){return Array.isArray(e)}function Hr(e){return be(r=>qr(r)&&r.every(t=>e(t)),"isArrayOf",e)}function ze(e){let r=new Set(e);return be(t=>r.has(t),"isLiteralOneOf",e)}function Ye(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}function xe(e){return typeof e=="string"}var L=async(e,r)=>{let t=e.response.clone(),o=ze(r);try{let n=await t.json();if(!Ye(n))return;if(t.status===422){if(!xe(n.message))return;for(let a of["NoQueryError","InvalidURLError"])if(r.includes(a))return{name:a,message:n.message}}return!o(n.name)||!xe(n.message)?void 0:n.name==="NotLoggedInError"?!Ye(n.detals)||!xe(n.detals.project)||!Hr(Us)(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}},Us=ze(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var Ne="null or undefined",ne=re+Ne,Is=$+Ne,Ke=te+Ne,ke=oe+Ne;var Yr=(e,r)=>{let{sid:t,hostName:o}=y(r??{});return new Request(https://${o}/api/projects/${e},t?{headers:{Cookie:N(t)}}:void 0)},Kr=async e=>O(await b(x(e),async r=>await L(r,["NotFoundError","NotLoggedInError","NotMemberError"])??r),r=>r.json()),Qr=(()=>{let e=async(r,t)=>{let{fetch:o}=y(t??{}),n=Yr(r,t),a=await o(n);return g(a)?a:Kr(w(a))};return e.toRequest=Yr,e.fromResponse=Kr,e})(),Jr=(e,r)=>{let{sid:t,hostName:o}=y(r??{}),n=new URLSearchParams(e.map(a=>["ids",a]));return new Request(https://${o}/api/projects?${n},t?{headers:{Cookie:N(t)}}:void 0)},Zr=async e=>O(await b(x(e),async r=>await L(r,["NotLoggedInError"])??r),r=>r.json()),Xr=(()=>{let e=async(r,t)=>{let{fetch:o}=y(t??{}),n=await o(Jr(r,t));return g(n)?n:Zr(w(n))};return e.toRequest=Jr,e.fromResponse=Zr,e})();var et=(e,r)=>{let{sid:t,hostName:o,followingId:n}=y(r??{});return new Request(https://${o}/api/pages/${e}/search/titles${n??followingId=${n}:""},t?{headers:{Cookie:N(t)}}:void 0)},rt=async e=>O(await b(x(e),async r=>r.response.status===422?{name:"InvalidFollowingIdError",message:await r.response.text()}:await L(r,["NotFoundError","NotLoggedInError"])??r),r=>r.json().then(t=>({pages:t,followingId:r.headers.get("X-following-id")??""}))),vs=(()=>{let e=async(r,t)=>{let o=await y(t??{}).fetch(et(r,t));return g(o)?o:rt(w(o))};return e.toRequest=et,e.fromResponse=rt,e})();async function*tt(e,r){let t;do{let o=await vs(e,{followingId:t,...r});if(g(o)){yield o;return}let n=w(o);yield R(n.pages),t=n.followingId}while(t)}var Cs=new TextEncoder().encode("0123456789abcdef"),ot=new Uint8Array(128).fill(16);Cs.forEach((e,r)=>ot[e]=r);new TextEncoder().encode("ABCDEF").forEach((e,r)=>ot[e]=r+10);var Bs=new TextEncoder().encode("0123456789abcdef"),nt=new Uint8Array(128).fill(16);Bs.forEach((e,r)=>nt[e]=r);new TextEncoder().encode("ABCDEF").forEach((e,r)=>nt[e]=r+10);var st=" must not return ",js="transformer",Ds="recoverer",$s="defaultValue",Se=js+st,Z="called with ",Ae=$s+" must not be ",Le=Ds+st;var Gs="Ok",at="Err",it=Z+at,lt=Z+Gs,Vs="Carrying E in "+at+" instead of throwing it directly. See .cause",Je="an instance of Error of the current realm.",Ug="The thrown value is not "+Je,Ig="The contained E should be "+Je,Ws="This .cause is not "+Je;function h(e){return e.ok}function B(e){return{ok:!0,val:e,err:null}}function U(e){return!e.ok}function H(e){return{ok:!1,val:null,err:e}}function Q(e){return ut(e,it)}function se(e){return ct(e,lt)}function ut(e,r){if(U(e))throw new TypeError(r);return e.val}function ct(e,r){if(h(e))throw new TypeError(r);return e.err}var Ue="null",jE=Se+Ue,zs=Z+Ue,DE=Ae+Ue,$E=Le+Ue;var Ie="undefined",HE=Se+Ie,Ys=Z+Ie,zE=Ae+Ie,YE=Le+Ie;async function*ft(e){let r=[],t=[],o=new Map,n=[];for(let a of e)a.isValid&&(a.id?a.isMember||r.push(a.id):t.push(a.name),n.push(a.name),o.set(a.name,a.checked));for(let a=0;a<r.length;a+=50){let s=r.slice(a,a+50);if(s.length===0)break;s.length===1&&s.push(s[0]);let l=await Xr(s);if(U(l)){t=n;break}for(let i of Q(l).projects)o.has(i.name)&&(yield B({...i,checked:o.get(i.name)??0}))}for(let a of t){let s=await Qr(a);yield h(s)?B({...Q(s),checked:o.get(a)??0}):H({...se(s),project:a})}}var Xe=(e,r)=>r.some(t=>e instanceof t),mt,dt;function Js(){return mt||(mt=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Zs(){return dt||(dt=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var er=new WeakMap,Ze=new WeakMap,Pe=new WeakMap;function Qs(e){let r=new Promise((t,o)=>{let n=()=>{e.removeEventListener("success",a),e.removeEventListener("error",s)},a=()=>{t(z(e.result)),n()},s=()=>{o(e.error),n()};e.addEventListener("success",a),e.addEventListener("error",s)});return Pe.set(r,e),r}function Xs(e){if(er.has(e))return;let r=new Promise((t,o)=>{let n=()=>{e.removeEventListener("complete",a),e.removeEventListener("error",s),e.removeEventListener("abort",s)},a=()=>{t(),n()},s=()=>{o(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",a),e.addEventListener("error",s),e.addEventListener("abort",s)});er.set(e,r)}var rr={get(e,r,t){if(e instanceof IDBTransaction){if(r==="done")return er.get(e);if(r==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return z(e[r])},set(e,r,t){return e[r]=t,!0},has(e,r){return e instanceof IDBTransaction&&(r==="done"||r==="store")?!0:r in e}};function yt(e){rr=e(rr)}function ea(e){return Zs().includes(e)?function(...r){return e.apply(tr(this),r),z(this.request)}:function(...r){return z(e.apply(tr(this),r))}}function ra(e){return typeof e=="function"?ea(e):(e instanceof IDBTransaction&&Xs(e),Xe(e,Js())?new Proxy(e,rr):e)}function z(e){if(e instanceof IDBRequest)return Qs(e);if(Ze.has(e))return Ze.get(e);let r=ra(e);return r!==e&&(Ze.set(e,r),Pe.set(r,e)),r}var tr=e=>Pe.get(e);function ht(e,r,{blocked:t,upgrade:o,blocking:n,terminated:a}={}){let s=indexedDB.open(e,r),l=z(s);return o&&s.addEventListener("upgradeneeded",i=>{o(z(s.result),i.oldVersion,i.newVersion,z(s.transaction),i)}),t&&s.addEventListener("blocked",i=>t(i.oldVersion,i.newVersion,i)),l.then(i=>{a&&i.addEventListener("close",()=>a()),n&&i.addEventListener("versionchange",u=>n(u.oldVersion,u.newVersion,u))}).catch(()=>{}),l}function _t(e,{blocked:r}={}){let t=indexedDB.deleteDatabase(e);return r&&t.addEventListener("blocked",o=>r(o.oldVersion,o)),z(t).then(()=>{})}var ta=["get","getKey","getAll","getAllKeys","count"],oa=["put","add","delete","clear"],Qe=new Map;function gt(e,r){if(!(e instanceof IDBDatabase&&!(r in e)&&typeof r=="string"))return;if(Qe.get(r))return Qe.get(r);let t=r.replace(/FromIndex$/,""),o=r!==t,n=oa.includes(t);if(!(t in(o?IDBIndex:IDBObjectStore).prototype)||!(n||ta.includes(t)))return;let a=async function(s,...l){let i=this.transaction(s,n?"readwrite":"readonly"),u=i.store;return o&&(u=u.index(l.shift())),(await Promise.all([u[t](...l),n&&i.done]))[0]};return Qe.set(r,a),a}yt(e=>({...e,get:(r,t,o)=>gt(r,t)||e.get(r,t,o),has:(r,t)=>!!gt(r,t)||e.has(r,t)}));var na=["continue","continuePrimaryKey","advance"],Et={},or=new WeakMap,wt=new WeakMap,sa={get(e,r){if(!na.includes(r))return e[r];let t=Et[r];return t||(t=Et[r]=function(...o){or.set(this,wt.get(this)[r](...o))}),t}};async function*aa(...e){let r=this;if(r instanceof IDBCursor||(r=await r.openCursor(...e)),!r)return;r=r;let t=new Proxy(r,sa);for(wt.set(t,r),Pe.set(t,tr(r));r;)yield t,r=await(or.get(t)||r.continue()),or.delete(t)}function Rt(e,r){return r===Symbol.asyncIterator&&Xe(e,[IDBIndex,IDBObjectStore,IDBCursor])||r==="iterate"&&Xe(e,[IDBIndex,IDBObjectStore])}yt(e=>({...e,get(r,t,o){return Rt(r,t)?aa:e.get(r,t,o)},has(r,t){return Rt(r,t)||e.has(r,t)}}));var Ot,nr=async()=>{let e=ce(["@takker/cosense-storage","open"]);return Ot??=await ht("scrapbox-storage",4,{upgrade(r,t,o){e.infostart updating DB: ${t} -> ${o};let n=Date.now();for(let l of r.objectStoreNames)r.deleteObjectStore(l);r.createObjectStore("titles",{keyPath:"id"}).createIndex("project","project");let s=r.createObjectStore("projects",{keyPath:"id"});s.createIndex("checked","checked"),s.createIndex("name","name"),e.infofinish updating DB: ${Date.now()-n}ms},blocked(r,t){let o=The database "@takker/cosense-storage"(v${t}) is blocked because the older one (v${r}) is opened in other tabs.
Please close the other tabs and reload this page.;e.error(o),alert(o)},blocking(r,t){let o=The database "@takker/cosense-storage"(v${r}) is blocking the newer one (v${t}) opened.
Please close this page.;e.error(o),alert(o)}}),Ot};var Tt=(e,r)=>(sr||(sr=new BroadcastChannel(xt),sr.addEventListener("message",t=>bt(t.data))),Me.set(r,new Set(e).union(Me.get(r)??new Set)),()=>Me.delete(r)),ar=(e,r)=>{if((r.added?.size??0)+(r.updated?.size??0)+(r.deleted?.size??0)===0)return;let t={type:"links:changed",project:e,diff:r};bt(t);let o=new BroadcastChannel(xt);o.postMessage(t),o.close()},bt=e=>{for(let[r,t]of Me)t.has(e.project)&&r(e)},xt="scrapbox-storage-notify",sr,Me=new Map;var ia=Math.pow(10,8)*24*60*60*1e3,dh=-ia;var la=3600;var Nt=la*24,gh=Nt*7,ua=Nt*365.2425,ca=ua/12,Eh=ca*3,ir=Symbol.for("constructDateFrom");function kt(e,r){return typeof e=="function"?e(r):e&&typeof e=="object"&&ir in e?e[ir](r):e instanceof Date?new e.constructor(r):new Date(r)}function Ft(e,r){return kt(r||e,e)}function lr(e){return Math.trunc(+Ft(e)/1e3)}var St=async(e,r)=>{let t=await nr(),o=ce(["@takker/cosense-storage","check"]),n=new Map;try{{o.debugcheck updates of links...;let s=new Set,l=t.transaction("projects","readwrite"),i=lr(new Date),u=i-600;for await(let c of l.store.index("checked").iterate(IDBKeyRange.lowerBound(u,!0))){let m=c.value;if(m.isValid===!1){s.add(m.id);continue}s.add(m.name);let E=m.checked;if(E+r>i||m?.updating&&E>u)continue;let T=structuredClone(m);T.updating=!0,n.set(m.id,T),c.update(T)}let f=[],p=l.store.index("name");for(let c of e)s.has(c)||f.push(p.get(c).then(m=>{m?.updating&&(m?.checked??0)>u||n.set(c,m??pa(c))}));if(await Promise.all(f),await l.done,n.size===0){o.debugchecked. No project needs upgrade.;return}o.debugchecked. ${n.size} projects maybe need upgrade.}let a=lr(new Date);for await(let s of ft(n.values())){if(U(s)){let{project:E,name:T}=se(s);switch(T){default:continue;case"NotFoundError":o.warn("${E}" is not found.);break;case"NotMemberError":o.warn(You are not a member of "${E}".);break;case"NotLoggedInError":o.warn(You are not a member of "${E}" or You are not logged in yet.);break}n.set(E,{id:E,name:E,checked:a,updating:!1,isValid:!1,reason:T});continue}let{checked:l,...i}=Q(s);if(i.updated<l){o.debugno updates in "${i.name}",n.set(i.name,{...i,isValid:!0,checked:a,updating:!1});continue}o.debugstart downloading and storing links of "${i.name}";let u=new Set(await t.getAllKeysFromIndex("titles","project",i.name)),f=0,p=0;for await(let E of tt(i.name)){if(U(E)){let{name:j,message:D}=se(E);o.errorFailed to get links of "${i.name}" with ${j}: ${D};break}let T=Q(E),k={},v=t.transaction("titles","readwrite");await Promise.all(T.map(async j=>{let D={...j,project:i.name},fe=await v.store.get(j.id);if(!fe)return k.added?.set?.(j.id,D)??(k.added=new Map([[j.id,D]])),v.store.add(D);if(u.delete(j.id),!!fa(D,fe))return k.updated?.set?.(j.id,[fe,D])??(k.updated=new Map([[j.id,[fe,D]]])),v.store.put(D)})),await v.done,f+=k.added?.size??0,p+=k.updated?.size??0,o.debugUpdating "/${i.name}": +${f} pages, ~${p} pages,ar(i.name,k)}let c=t.transaction("titles","readwrite"),m=new Map((await Promise.all([...u].map(async E=>{let T=await c.store.get(E);if(!T)return[];let k=[[E,T]];return await c.store.delete(E),k}))).flat());await c.done,o.debugFinish downloading and storing links of "${i.name}",o.debugUpdate "/${i.name}": +${f} pages, ~${p} pages, -${m.size} pages,n.set(i.name,{...i,isValid:!0,checked:a,updating:!1}),ar(i.name,{deleted:m})}}finally{let a=t.transaction("projects","readwrite");await Promise.all([...n].map(([,s])=>(s.updating=!1,a.store.put({...s})))),await a.done}},At=async e=>{let r=[...new Set(e)];if(r.length===0)return[];let t=Date.now(),n=(await nr()).transaction("titles","readonly"),a=n.store.index("project"),s=(await Promise.all(r.map(i=>a.getAll(i)))).flat();return await n.done,ce(["@takker/cosense-storage","load"]).debugRead ${s.length} links from ${r.length} projects in ${Date.now()-t}ms,s},pa=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}),fa=(e,r)=>e.updated>r.updated||e.links.sort().join()!==r.links.sort().join();globalThis.Deno||_t("userscript-links").catch(e=>console.error(e));var pe=e=>e.replaceAll(" ","_").toLowerCase(),Lt=e=>e.replaceAll("_"," ");var Ut=e=>{let r=new Map,t=[...e].reverse();{let s=1;for(let l of t){r.set(l,(r.get(l)??0)|s);let i=l.toLowerCase();r.set(i,(r.get(i)??0)|s);let u=l.toUpperCase();r.set(u,(r.get(u)??0)|s),s<<=1}}let o=t.length,n=~(-1<<o),a=1<<o-1;return s=>{let l=0,i=n,u=[...s].reverse(),f=[],p=u.length;f[p]=o;for(let c of u){let m=r.get(c)??0,E=m|l,T=(m&i)+i^i|m,k=l|~(T|i),v=i&T;f[p-1]=f[p]+(k&a?1:v&a?-1:0),i=v<<1|~(E|k<<1),l=k<<1&E,p--}return f}};var ma=[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],It=e=>{let r=Lt(e.trim()).split(/\s+/).sort((t,o)=>o.length-t.length);if(!(r.length===0||r.every(t=>t==="")))return t=>r.reduce((o,n)=>da(n,o),t)},da=(e,r)=>{let t=[...e].length,o=ma[t],n=Ut(e);return r.flatMap(({title:a,dist:s,matches:l,...i})=>{l??=[],s??=0;let u=n(a).flatMap((p,c)=>p<=o&&l.every(([m,E])=>c+t<=m||E<c)?[[c,p]]:[]);if(u.length===0)return[];let f=u.reduce((p,[c,m])=>(p.dist<=m||(p.dist=m,p.start=c),p),{dist:t,start:0});return l.push([f.start,f.start+t-1]),[{title:a,dist:f.dist+s,matches:l,...i}]})};var Mt=e=>{let r=new Map;for(let t of e)ur(r,t);return r},vt=(e,r)=>{let t=new Map(e);if(r.added)for(let[,o]of r.added)ur(t,o);if(r.updated)for(let[,[o,n]]of r.updated)Pt(t,o),ur(t,n);if(r.deleted)for(let[,o]of r.deleted)Pt(t,o);return t},ur=(e,r)=>{let t=pe(r.title),o=e.get(t);if((o?.updated??0)>r.updated)return;let n=o?.metadata??new Map;n.set(r.project,{image:r.image}),e.set(t,{title:r.title,titleLc:t,updated:r.updated,linked:o?.linked??0,metadata:n});for(let a of r.links){let s=pe(a),l=e.get(s),i=l?.metadata??new Map;i.set(r.project,i.get(r.project)??{image:r.image}),e.set(s,{title:l?.title??a,titleLc:s,updated:l?.updated??0,linked:(l?.linked??0)+1,metadata:i})}},Pt=(e,r)=>{let t=pe(r.title),o=e.get(t);if(!o||(o.updated??0)>r.updated)return;let n=o.metadata;n.delete(r.project),n.size<=0?e.delete(t):e.set(t,{title:o.title,titleLc:t,updated:r.updated,linked:o.linked,metadata:n});for(let a of r.links){let s=pe(a),l=e.get(s);if(!l)continue;let i=l.metadata;i.delete(r.project),i.size<=0?e.delete(s):e.set(s,{title:l.title,titleLc:s,updated:r.updated,linked:l.linked-1,metadata:i})}};var cr=wr("scrapbox-select-suggestion:search.worker.ts"),ve=[],Ct=[],Bt=()=>{},jt={async load(e){if(cr.debug("start loading source"),!pr(Ct,e)){Ct=[...e],Bt();let t=await At(e),o=Mt(t);ve=[...o.values()],await St(e,600),Bt=Tt(e,({diff:n})=>{o=vt(o,n),ve=[...o.values()]})}return ve.length},async search(e,r,t){if(cr.debug("start searching: ",e),!e.trim())return;let o=It(e);if(!o){t([],1);return}let n=[...ve],a=Math.ceil(n.length/r);for(let s=0;s<a;s++){let l=(s+1)/a,i=[...o(n.values().drop(s*r).take(r))];if(cr.debug(${s}/${a} search result:`,i),await t(i,l))return;await mr(0)}}},ga=e=>typeof e=="object"&&!!e&&"SharedWorkerGlobalScope"in e;ga(self)?self.addEventListener("connect",e=>ae(jt,e.ports0)):ae(jt);
/*! 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}