SharedUserScripts-min
全プロジェクトで使うUserScript
code:script.js
var Dt=!1;scrapbox.addListener("lines:changed",()=>Dt=!1);scrapbox.addListener("layout:changed",()=>Dt=!1);var Ht=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var qt=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var pt=()=>oo(document.getElementsByClassName("lines").item(0),"div.lines");var ve=()=>{let e=document.getElementById("text-input");if(e)return qt(e,"textarea#text-input"),e};var oo=(e,t)=>{if(e)return Ht(e,t),e};var ut=()=>{let e=pt();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 et.return.stateNode.props.lines};var ft=e=>new Promise(t=>setTimeout(()=>t(),e));var Gt=async e=>{let t=ve();if(!t)throw Error("#text-input is not ditected.");t.focus(),t.value=e;let r=new InputEvent("input",{bubbles:!0});t.dispatchEvent(r),await ft(1)};var dt=e=>...e.map((t,r)=>t===" "?"_":!po.includes(t)||r===e.length-1&&uo.includes(t)?encodeURIComponent(t):t).join(""),po='@$&+=:;",',uo=':;",';var mt=async(e,t)=>{let r=await globalThis.caches.keys();for(let n of r.sort().reverse()){let s=await(await caches.open(n)).match(e,t);if(s)return s}},zt=async(e,t)=>{let r=t.clone();return r.headers.set("X-Serviceworker-Cached",${new Date(r.headers.get("date")??new Date).getTime()}),await(await caches.open(fo(new Date))).put(e,r)},fo=e=>api-${e.getFullYear()}-${${e.getMonth()+1}.padStart(2,"0")}-${${e.getDate()}.padStart(2,"0")};var Wt=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 go=new Map;scrapbox.on("layout:changed",()=>{let e=ve();if(e)for(lett,rof go)for(letn,oof r)for(let s of o)e.addEventListener(t,n,Wt(s))});var ho=e=>typeof e=="object"&&e!==null,xo=e=>ho(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,Vt=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return xo(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var Yt=!1;scrapbox.addListener("lines:changed",()=>Yt=!1);scrapbox.addListener("layout:changed",()=>Yt=!1);var Qt=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var Xt=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var Ce=()=>{let e=document.getElementById("text-input");if(e)return Xt(e,"textarea#text-input"),e};var Jt=()=>yo(document.getElementsByClassName("status-bar")?.0,"div.status-bar"),yo=(e,t)=>{if(e)return Qt(e,t),e};var er=()=>{let e=Jt();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 n=tr(...r);n&&t.append(n)},dispose:()=>t.remove()}},tr=(...e)=>{let t=e.flatMap(n=>{switch(n.type){case"spinner":returnko();case"check-circle":returnCo();case"exclamation-triangle":returnPo();case"text":returnFe(n.text);case"group":{let o=tr(...n.items);return o?o:[]}}});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},Fe=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},ko=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),Fe(e)},Co=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),Fe(e)},Po=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),Fe(e)};var be=e=>...e.map((t,r)=>t===" "?"_":!Mo.includes(t)||r===e.length-1&&Oo.includes(t)?encodeURIComponent(t):t).join(""),Mo='@$&+=:;",',Oo=':;",';var rr=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 So=new Map;scrapbox.on("layout:changed",()=>{let e=Ce();if(e)for(lett,rof So)for(letn,oof r)for(let s of o)e.addEventListener(t,n,rr(s))});var de=e=>typeof e=="string";var gt=(e,...t)=>{let r=e;for(let n of t){let o=r instanceof Promise?r.then(s=>de(s)?s:n(s)):n(r);if(de(o))return o;r=o instanceof URL?new URL(o):o.then(s=>de(s)?s:new URL(s))}return r instanceof Promise?r.then(n=>${n}):${e}};var Pe=e=>e.ok?void 0:{name:"HTTPError",message:${e.status} ${e.statusText},response:e};var nr=e=>{if(!window.GM_fetch)return;let t=window.GM_fetch;return(async()=>{let r=await t(https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x),n=Pe(r);return n?{ok:!1,value:n}:{ok:!0,value:await r.json()}})()};var Be=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}},or=e=>typeof e=="object"&&e!==null;var Ne=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 De=async e=>{let t=await e.text();if(e.ok)return{ok:!0,value:t};if(e.status===400)return{ok:!1,value:{name:"BadRequestError",message:t}};try{let r=JSON.parse(t);if(!or(r)||typeof r.message!="string")throw new Ne({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)});switch(e.status){case 401:return{ok:!1,value:{name:"UnauthorizedError",message:r.message}};case 403:return{ok:!1,value:{name:"NotPrivilegeError",message:r.message}};case 404:return{ok:!1,value:{name:"NotFoundError",message:r.message}};case 422:return{ok:!1,value:{name:"InvalidParameterError",message:r.message}};case 429:return{ok:!1,value:{name:"RateLimitError",message:r.message}};default:throw new Ne({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)})}}catch(r){throw r instanceof SyntaxError?new Ne({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)}):r}};var sr=async(e,t)=>{let{title:r,description:n,metadataIsPublic:o,collectionId:s,refererURL:a,accessToken:i,created:l,app:u,fetch:p}=Be(t),f=new FormData;f.append("imagedata",e),f.append("access_token",i),a&&f.append("referer_url",a.toString()),u!==void 0&&f.append("app",u),r!==void 0&&f.append("title",r),n!=null&&f.append("desc",n),s&&f.append("collection_id",s),o&&f.append("metadata_is_public","true"),l!==void 0&&f.append("created_at",${l});let w=await p("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:f}),E=await De(w);return E.ok?{ok:!0,value:JSON.parse(E.value)}:E};var F=e=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...n}=e;return{fetch:t,hostName:r,...n}};var me=class e extends Error{constructor(r){super(${r.status} ${r.statusText} when fetching ${r.url});this.response=r;Error.captureStackTrace&&Error.captureStackTrace(this,e)}name="UnexpectedResponseError"},z=async e=>{let t=e.clone(),r=await t.text(),n=Vt(r);if(!n)throw new me(t);return{ok:!1,value:n}};var ir=async e=>{let{sid:t,hostName:r,fetch:n}=F(e??{}),o=new Request(https://${r}/api/users/me,t?{headers:{Cookie:q(t)}}:void 0),s=await n(o);if(!s.ok)throw new me(s);return await s.json()};var q=e=>connect.sid=${e},ge=async e=>globalThis._csrf?globalThis._csrf:(await ir(e)).csrfToken;var ar=(e,t,r)=>{let{sid:n,hostName:o,followRename:s,projects:a}=F(r??{}),i=new URLSearchParams;i.append("followRename",${s??!0});for(let u of a??[])i.append("projects",u);let l=https://${o}/api/pages/${e}/${be(t)}?${i.toString()};return new Request(l,n?{headers:{Cookie:q(n)}}:void 0)},lr=async e=>e.ok?{ok:!0,value:await e.json()}:e.status===414?{ok:!1,value:{name:"TooLongURIError",message:"project ids may be too much."}}:z(e),ht=async(e,t,r)=>{let{fetch:n}=F(r??{}),o=ar(e,t,r),s=await n(o);return await lr(s)};ht.toRequest=ar;ht.fromResponse=lr;var cr=(e,t)=>{let{sid:r,hostName:n,sort:o,limit:s,skip:a}=F(t??{}),i=new URLSearchParams;o!==void 0&&i.append("sort",o),s!==void 0&&i.append("limit",${s}),a!==void 0&&i.append("skip",${a});let l=https://${n}/api/pages/${e}?${i.toString()};return new Request(l,r?{headers:{Cookie:q(r)}}:void 0)},pr=async e=>e.ok?{ok:!0,value:await e.json()}:z(e),ur=async(e,t)=>{let{fetch:r}=F(t??{}),n=await r(cr(e,t));return await pr(n)};ur.toRequest=cr;ur.fromResponse=pr;var fr=(e,t,r,n)=>{let{sid:o,hostName:s}=F(n??{}),a=https://${s}/api/table/${e}/${be(t)}/${encodeURIComponent(r)}.csv;return new Request(a,o?{headers:{Cookie:q(o)}}:void 0)},dr=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:z(e),mr=async(e,t,r,n)=>{let{fetch:o}=F(n??{}),s=fr(e,t,r,n),a=await o(s);return await dr(a)};mr.toRequest=fr;mr.fromResponse=dr;var gr=(e,t)=>{let{sid:r,hostName:n}=F(t??{});return new Request(https://${n}/api/projects/${e},r?{headers:{Cookie:q(r)}}:void 0)},hr=async e=>e.ok?{ok:!0,value:await e.json()}:z(e),He=async(e,t)=>{let{fetch:r}=F(t??{}),n=gr(e,t),o=await r(n);return hr(o)};He.toRequest=gr;He.fromResponse=hr;var xr=(e,t)=>{let{sid:r,hostName:n}=F(t??{}),o=new URLSearchParams;for(let s of e)o.append("ids",s);return new Request(https://${n}/api/projects?${o.toString()},r?{headers:{Cookie:q(r)}}:void 0)},yr=async e=>e.ok?{ok:!0,value:await e.json()}:z(e),br=async(e,t)=>{let{fetch:r}=F(t??{}),n=await r(xr(e,t));return yr(n)};br.toRequest=xr;br.fromResponse=yr;var wr=async(e,t)=>{let{sid:r,hostName:n,fetch:o,csrf:s}=F(t??{}),a=new Request(https://${n}/api/embed-text/url?url=${encodeURIComponent(e.toString())},{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":s??await ge(t),...r?{Cookie:q(r)}:{}},body:JSON.stringify({timeout:3e3})}),i=await o(a);if(!i.ok)return i.status===422?{ok:!1,value:{name:"InvalidURLError",message:(await i.json()).message}}:z(i);let{title:l}=await i.json();return{ok:!0,value:l}};var Er=async(e,t)=>{let{sid:r,hostName:n,fetch:o,csrf:s}=F(t??{}),a=new Request(https://${n}/api/embed-text/twitter?url=${encodeURIComponent(e.toString())},{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":s??await ge(t),...r?{Cookie:q(r)}:{}},body:JSON.stringify({timeout:3e3})}),i=await o(a);return i.ok?{ok:!0,value:await i.json()}:i.status===422?{ok:!1,value:{name:"InvalidURLError",message:(await i.json()).message}}:z(i)};var vr=async e=>{let{sid:t,hostName:r,gyazoTeamsName:n}=F(e??{}),o=new Request(https://${r}/api/login/gyazo/oauth-upload/token${n??gyazoTeamsName=${n}:""},t?{headers:{Cookie:q(t)}}:void 0),s=await fetch(o);if(!s.ok)return z(s);let{token:a}=await s.json();return{ok:!0,value:a}};var Rr=(e,t,r,n)=>{let{sid:o,hostName:s}=F(n??{}),a=https://${s}/api/code/${e}/${be(t)}/${be(r)};return new Request(a,o?{headers:{Cookie:q(o)}}:void 0)},Lr=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404&&e.headers.get("Content-Type")?.includes?.("text/plain")?{ok:!1,value:{name:"NotFoundError",message:"Code block is not found"}}:z(e),Tr=async(e,t,r,n)=>{let{fetch:o}=F(n??{}),s=Rr(e,t,r,n),a=await o(s);return await Lr(a)};Tr.toRequest=Rr;Tr.fromResponse=Lr;var kr=new TextEncoder().encode("0123456789abcdef");function Cr(e){let t=new Uint8Array(e.length*2);for(let r=0;r<t.length;r++){let n=er;tr*2=krn>>4,tr*2+1=krn&15}return t}var Pr="md5: data is invalid type",Re=64,Ie=class{#e;#t;#r;#n;#o;#i;#s;#a;constructor(){this.#e=1732584193,this.#t=4023233417,this.#r=2562383102,this.#n=271733878,this.#o=new Uint8Array(Re),this.#i=0,this.#s=0,this.#a=0}#c(t){let r=this.#s;r+=t,r>4294967295&&(this.#a+=1),this.#s=r>>>0}#l(t){let r=this.#e,n=this.#t,o=this.#r,s=this.#n,a=T=>tT|tT+1<<8|tT+2<<16|tT+3<<24,i=(T,M)=>T<<M|T>>>32-M,l=a(0),u=a(4),p=a(8),f=a(12),w=a(16),E=a(20),U=a(24),D=a(28),S=a(32),H=a(36),K=a(40),v=a(44),x=a(48),g=a(52),d=a(56),L=a(60);r=n+i(((o^s)&n^s)+r+l+3614090360,7),s=r+i(((n^o)&r^o)+s+u+3905402710,12),o=s+i(((r^n)&s^n)+o+p+606105819,17),n=o+i(((s^r)&o^r)+n+f+3250441966,22),r=n+i(((o^s)&n^s)+r+w+4118548399,7),s=r+i(((n^o)&r^o)+s+E+1200080426,12),o=s+i(((r^n)&s^n)+o+U+2821735955,17),n=o+i(((s^r)&o^r)+n+D+4249261313,22),r=n+i(((o^s)&n^s)+r+S+1770035416,7),s=r+i(((n^o)&r^o)+s+H+2336552879,12),o=s+i(((r^n)&s^n)+o+K+4294925233,17),n=o+i(((s^r)&o^r)+n+v+2304563134,22),r=n+i(((o^s)&n^s)+r+x+1804603682,7),s=r+i(((n^o)&r^o)+s+g+4254626195,12),o=s+i(((r^n)&s^n)+o+d+2792965006,17),n=o+i(((s^r)&o^r)+n+L+1236535329,22),r=n+i(((n^o)&s^o)+r+u+4129170786,5),s=r+i(((r^n)&o^n)+s+U+3225465664,9),o=s+i(((s^r)&n^r)+o+v+643717713,14),n=o+i(((o^s)&r^s)+n+l+3921069994,20),r=n+i(((n^o)&s^o)+r+E+3593408605,5),s=r+i(((r^n)&o^n)+s+K+38016083,9),o=s+i(((s^r)&n^r)+o+L+3634488961,14),n=o+i(((o^s)&r^s)+n+w+3889429448,20),r=n+i(((n^o)&s^o)+r+H+568446438,5),s=r+i(((r^n)&o^n)+s+d+3275163606,9),o=s+i(((s^r)&n^r)+o+f+4107603335,14),n=o+i(((o^s)&r^s)+n+S+1163531501,20),r=n+i(((n^o)&s^o)+r+g+2850285829,5),s=r+i(((r^n)&o^n)+s+p+4243563512,9),o=s+i(((s^r)&n^r)+o+D+1735328473,14),n=o+i(((o^s)&r^s)+n+x+2368359562,20),r=n+i((n^o^s)+r+E+4294588738,4),s=r+i((r^n^o)+s+S+2272392833,11),o=s+i((s^r^n)+o+v+1839030562,16),n=o+i((o^s^r)+n+d+4259657740,23),r=n+i((n^o^s)+r+u+2763975236,4),s=r+i((r^n^o)+s+w+1272893353,11),o=s+i((s^r^n)+o+D+4139469664,16),n=o+i((o^s^r)+n+K+3200236656,23),r=n+i((n^o^s)+r+g+681279174,4),s=r+i((r^n^o)+s+l+3936430074,11),o=s+i((s^r^n)+o+f+3572445317,16),n=o+i((o^s^r)+n+U+76029189,23),r=n+i((n^o^s)+r+H+3654602809,4),s=r+i((r^n^o)+s+x+3873151461,11),o=s+i((s^r^n)+o+L+530742520,16),n=o+i((o^s^r)+n+p+3299628645,23),r=n+i((o^(n|~s))+r+l+4096336452,6),s=r+i((n^(r|~o))+s+D+1126891415,10),o=s+i((r^(s|~n))+o+d+2878612391,15),n=o+i((s^(o|~r))+n+E+4237533241,21),r=n+i((o^(n|~s))+r+x+1700485571,6),s=r+i((n^(r|~o))+s+f+2399980690,10),o=s+i((r^(s|~n))+o+K+4293915773,15),n=o+i((s^(o|~r))+n+u+2240044497,21),r=n+i((o^(n|~s))+r+S+1873313359,6),s=r+i((n^(r|~o))+s+L+4264355552,10),o=s+i((r^(s|~n))+o+U+2734768916,15),n=o+i((s^(o|~r))+n+g+1309151649,21),r=n+i((o^(n|~s))+r+w+4149444226,6),s=r+i((n^(r|~o))+s+v+3174756917,10),o=s+i((r^(s|~n))+o+p+718787259,15),n=o+i((s^(o|~r))+n+H+3951481745,21),this.#e=this.#e+r>>>0,this.#t=this.#t+n>>>0,this.#r=this.#r+o>>>0,this.#n=this.#n+s>>>0}update(t){let r;if(typeof t=="string")r=new TextEncoder().encode(t);else if(typeof t=="object")if(t instanceof ArrayBuffer||ArrayBuffer.isView(t))r=new Uint8Array(t);else throw new TypeError(Pr);else throw new TypeError(Pr);let n=this.#i,o=Re-n;if(r.length<o)this.#o.set(r,n),n+=r.length;else{this.#o.set(r.slice(0,o),n),this.#l(this.#o);let s=o;for(;s+Re<=r.length;)this.#l(r.slice(s,s+Re)),s+=Re;this.#o.fill(0).set(r.slice(s),0),n=r.length-s}return this.#i=n,this.#c(r.length),this}digest(){let t=Re-this.#i;t<9&&(t+=Re);let r=new Uint8Array(t);r0=128;let n=this.#s<<3,o=this.#a<<3|this.#s>>>29;rr.length-8=n&255,rr.length-7=n>>>8&255,rr.length-6=n>>>16&255,rr.length-5=n>>>24&255,rr.length-4=o&255,rr.length-3=o>>>8&255,rr.length-2=o>>>16&255,rr.length-1=o>>>24&255,this.update(r.buffer);let s=new ArrayBuffer(16),a=new DataView(s);return a.setUint32(0,this.#e,!0),a.setUint32(4,this.#t,!0),a.setUint32(8,this.#r,!0),a.setUint32(12,this.#n,!0),s}toString(t="hex"){let r=this.digest();switch(t){case"hex":return new TextDecoder().decode(Cr(new Uint8Array(r)));case"base64":{let n=new Uint8Array(r),o="";for(let s=0;s<n.length;++s)o+=String.fromCharCode(ns);return btoa(o)}default:throw new Error("md5: invalid format")}}};var Mr=async(e,t,r)=>{let n=new Ie().update(await e.arrayBuffer()).toString(),o=await No(e,t,n,r);if(!o.ok)return o;if("embedUrl"in o.value)return{ok:!0,value:o.value};let s=await Io(o.value.signedUrl,e,r);return s.ok?_o(t,o.value.fileId,n,r):s},No=async(e,t,r,n)=>{let{sid:o,hostName:s,fetch:a,csrf:i}=F(n??{}),l={md5:r,size:e.size,contentType:e.type,name:e.name},u=i??await ge(),p=new Request(https://${s}/api/gcs/${t}/upload-request,{method:"POST",body:JSON.stringify(l),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":u,...o?{Cookie:q(o)}:{}}}),f=await a(p);return f.ok?{ok:!0,value:await f.json()}:z(f)},Io=async(e,t,r)=>{let{sid:n,fetch:o}=F(r??{}),s=await o(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...n?{Cookie:q(n)}:{}}});if(!s.ok){if(s.headers.get("Content-Type")?.includes?.("/xml"))return{ok:!1,value:{name:"GCSError",message:await s.text()}};throw new me(s)}return{ok:!0,value:void 0}},_o=async(e,t,r,n)=>{let{sid:o,hostName:s,fetch:a,csrf:i}=F(n??{}),l=i??await ge(),u=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":l,...o?{Cookie:q(o)}:{}}}),p=await a(u);if(!p.ok){try{if(p.status===404)return{ok:!1,value:{name:"NotFoundError",message:(await p.json()).message}}}catch{throw new me(p)}throw new me(p)}return{ok:!0,value:await p.json()}};var Or=(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 qe="",Ar=!1,Ke=new Map,Sr=async(e,t,r,n)=>{let o=Ke.get(e.href);if(o)return o;if(e.hostname==="video.twimg.com"||${e}.endsWith(".svg")){let l=await GM_fetch(e);if(!l.ok)return;let u=l.headers.get("content-type")?.split?.(";")?.0??${e}.endsWith(".mp4")?"video/mp4":"video/webm",p=new File(await l.blob(),n||${t},{type:u});if(u==="video/mp4"){let E=await Or(p);if(E.ok){let U=new URL(await E.text());return Ke.set(e.href,U),U}}let f=await Mr(p,r);if(!f.ok)throw Error(f.value.name);let w=new URL(f.value.embedUrl);return Ke.set(e.href,w),w}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(Ar){if(!qe)return}else{let l=await vr();if(Ar=!0,!l.ok){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(qe=l.value||"",!qe){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let a=await sr(await s.blob(),{accessToken:qe,refererURL:t,description:n});if(!a.ok)throw Error(a.value.name);let i=new URL(a.value.permalink_url);return Ke.set(e.href,i),i};var Uo={"<":"<",">":">","&":"&",""":'"',"'":"'","`":""},xt=e=>e.replace(/&(lt|gt|amp|quot|#x27|#x60);/g,t=>Uo[t]);var Me=e=>{let t={name:e.user.name,screenName:e.user.screen_name},r=new Date(e.created_at),n=[...e.entities.hashtags.map(a=>({type:"hashtag",...a})),...e.entities.symbols.map(a=>({type:"symbol",...a})),...e.entities.user_mentions.map(a=>({type:"mention",name:a.name,screenName:a.screen_name,indices:a.indices})),...e.entities.urls.map(a=>{let i={type:"url",indices:a.indices,url:new URL(a.expanded_url)};if(e.card&&e.card?.url===a.url){let{description:l,title:u}=e.card.binding_values,p="STRING";l?.type===p&&(i.description=l.string_value),u?.type===p&&(i.title=u.string_value)}return i}),...e.entities.media?.map?.(a=>({type:"media",indices:a.indices,media:e.mediaDetails?.flatMap?.(i=>i.url===a.url?[{type:i.type,url:new URL(i.video_info?.variants?.sort?.((l,u)=>(u.bitrate??0)-(l.bitrate??0))?.[0].url??i.media_url_https)}]:[])??[]}))??[]].sort((a,i)=>a.indices[0]-i.indices[0]),o=[];{let a=0,i=e.text;for(let{indices:l,...u}of n){let p=[...i].slice(0,l[0]-a).join("");o.push({type:"plain",text:xt(p)}),o.push(u),i=[...i].slice(l[1]-a).join(""),a=l[1]}i&&o.push({type:"plain",text:xt(i)})}let s={id:e.id_str,content:o,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=Me(e.parent)),e.quoted_tweet&&(s.quote=Me(e.quoted_tweet)),s};var jo=["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"],Ge=(e=scrapbox.Project.name,t=location.host)=>r=>{if(r.host!==t)return r;let[,n,o]=r.pathname.match(/^\/([\w\d][\w\d-]{0,22}[\w\d])(?:\/?|\/(.+))$/)??[];return!n||jo.includes(n)?r:o?n===e?${decodeURIComponent(o)}:/${n}/${decodeURIComponent(o)}:/${n}};var $r=(e=Fo)=>t=>{let[,r]=t.href.match(/^https:\/\/(?:(?:www\.|mobile\.|m\.)?twitter|x)\.com\/[\w\d_]+\/(?:status|statuses)\/(\d+)/)??[];return r?(async()=>{let n=await(nr(r)??Er(t.href));if(!n.ok)throw n.value;return e("images"in n.value?{...n.value,id:r}:n.value,t)})():t},Fo=async e=>{if("images"in e)return he(e);let{quote:t,replyTo:r,...n}=Me(e);return[...r?[...(await he(r)).split( ).map(o=> > ${o}),...r.quote?(await he(r.quote)).split(
).map(o=> > ${o}):[]]:[],...(await he(n)).split(
).map(o=>> ${o}),...t?(await he(t)).split(
).map(o=>> > ${o}):[]].join(
)?.map?.(o=>> ${bt(o)})??["> [/ no description provided]"],...e.images.length>0?[> ${e.images.map(o=>[${o}])}]:[]].join(
);let r=e.content,n=e.author.screenName;return[@${bt(n)} ${t},...(await Promise.all(r.map(async o=>{switch(o.type){case"plain":return o.text;case"hashtag":return #${o.text} ;case"symbol":return #$${o.text} ;case"mention":return@${o.screenName};case"media":{let s=[],a=1;for(;a<o.media.length;a+=2)s.push([${await yt(o.mediaa-1,t)}] [${await yt(o.mediaa,t)}]);return a===o.media.length&&s.push([${await yt(o.mediaa-1,t)}]), ${s.join(`
`)}
}case"url":return${Ge()(o.url)} }}))).join("").split(
)].join(
)},ze="",Bo=async()=>{if(ze)return ze;let e=await He(scrapbox.Project.name);if(!e.ok)throw new Error(e.value.name);return ze=e.value.id,ze},yt=async(e,t)=>await Sr(e.url,t,await Bo(),"")??e.url,bt=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]]\s*/g," ").trim();var Nr=e=>{if(!window.GM_fetch)return;let t=window.GM_fetch;return(async()=>{let r=await t(https://t.co/${e}),n=Pe(r);return n?{ok:!1,value:n}:{ok:!0,value:new DOMParser().parseFromString(await r.text(),"text/html").title}})()};var Ir=e=>{if("bit.ly","amzn.to","amzn.asia","goo.gl","s.nikkei.com","apple.co","nico.ms","w.wiki".includes(e.hostname)&&window.GM_fetch)return window.GM_fetch(e).then(r=>r.ok?new URL(r.url):e);if(e.hostname!=="t.co")return e;let t=Nr(e.pathname.slice(1));return t?(async()=>{let r=await t;if(!r.ok)throw r.value;try{return new URL(r.value)}catch(n){if(n instanceof TypeError)return e;throw n}})():e};var _r=e=>{if(!e.pathname.startsWith("/wiki/"))return e;if(!/^\w+\.wikipedia\.org$/.test(e.hostname)){let,o=e.hostname.match(/^(\w+)\.m\.wikipedia\.org$/)??[];if(!o)return e;e.hostname=${o}.wikipedia.org}let t=decodeURIComponent(e.pathname.slice(6)),r=e.hash?decodeURIComponent(e.hash.slice(1)):"",n=${e.origin}/wiki/${t};return r?[${r} | ${t} - Wikipedia ${n}#${r}]:[${t} - Wikipedia ${n}]};var Ur=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 wt=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var jr=/charset=(^;+)/,Fr=e=>{if(!window.GM_fetch)return;let t=window.GM_fetch;return(async()=>{let r=await t(${e}),n=Pe(r);if(n)return{ok:!1,value:n};let o=r.headers.get("content-type")?.match?.(jr)?.1??await Do(r.clone());return{ok:!0,value:new TextDecoder(o).decode(await r.arrayBuffer())}})()},Do=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?.(jr)?.1??"utf-8"};var Br=(e=Ho)=>async t=>e(await qo(t),t),Ho=(e,t)=>{let r=(de(e)?e:e.title).replace(/\s/g," ").replaceAll("","[").replaceAll("","]");return r?[${t.hash?${decodeURIComponent(t.hash.slice(1))} | :""}${r} ${t}]:${t}},qo=async e=>{let t=Fr(e);if(!t){let n=await wr(e);if(!n.ok)throw n.value;return n.value}let r=await t;if(!r.ok)throw r.value;return new DOMParser().parseFromString(r.value,"text/html")};var Dr=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 Hr=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 qr=(e,...t)=>{if(e instanceof URL)return gt(new URL(e),...t);let r=0,n=0,o=0,s=!1,a=e.split(/(https?:\/\/\S+)/g).map(p=>{if(!/^https?:\/\/\S+$/.test(p))return p;r++;try{let f=gt(new URL(p),...t);return de(f)?(n++,f):(s=!0,f,p)}catch(f){return console.error(f),o++,p}});if(!s)return a.join("");let{render:i,dispose:l}=er(),u=()=>i({type:"spinner"},{type:"text",text:URL: ${n}/${r} converted, ${o} failed});return u(),Promise.all(a.map(async p=>{if(de(p))return p;try{let f=await p0;return n++,f}catch(f){return console.error(f),o++,p1}finally{u()}})).then(p=>(i({type:"check-circle"},{type:"text",text:URL: ${n}/${r} converted, ${o} failed}),p.join(""))).finally(()=>{setTimeout(l,1e3)})};var Kr=async e=>{if("images"in e)return he(e);let{quote:t,...r}=Me(e);return[...t?(await he(t)).split(` ).map(n=>> ${n}):[],...(await he(r)).split(
).map(n=>> ${n})].join(
)};var Ko=[wt,Ir,wt,Ur,Dr,Ge(),Hr,$r(Kr),_r,e=>{if(e.hostname==="raw.githubusercontent.com")return${e};if(e.hostname!=="github.com")return e;let[t,r,n]=e.pathname.match(/^\/([^\\]+)\/([^\\]+)\/blob\/(.+)$/)?.slice?.(1)??[];if(!t||!r||!n)return e;let[,o,s]=e.hash.match(/L(\d+)-L(\d+)/)??e.hash.match(/L(\d+)/)??[];return[https://code2svg.vercel.app/svg/${o&&s?L${o}-${s}/:o?L${o}/:""}https://raw.githubusercontent.com/${t}/${r}/${n}#.svg ${e}]},Br()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=qr(e,...Ko);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return Gt(r)})}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[([^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~][^\[\]]*)\]/g,"$1")).join( );if(e!=t)return t}});scrapbox.PopupMenu.addButton({title:"[]",onClick:e=>{let t=e.split(/\n/).map(r=>r.replace(/\[([^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~][^\[\]]*)\]/g,"$1")).join( );if(e!=t)return t}});scrapbox.PopupMenu.addButton({title:"$",onClick:e=>$ ${e}});scrapbox.PopupMenu.addButton({title:"LaTeX→Scb",onClick:e=>e.replace(/\$(.+?)\$/g,"[$ $1 ]").replace(/\\\((.+?)\\\)/g,"[$ $1 ]").replace(/\$\$(.+?)\$\$/gs,(t,r)=>"[$ "+r.replace(/\n/g," ").replace(/\s*>/g,"")+" ]").replace(/\\\[(.+?)\\\]/gs,(t,r)=>"[$ "+r.replace(/\n/g," ").replace(/\s*>/g,"")+" ]")});function Go(e){let t=/[,&;]|and|\n/gi,r=new RegExp("[\\d†\\*]|(\\s[a-z])+(\\s*$)|ORCID|View ORCID Profile|Author links open overlay panel|https?:\\/\\/\\S+","gi"),n=s=>s.toLowerCase().split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ");return e.replace(t,",").split(",").map(s=>s.replace(r,"").trim()).filter(s=>s.length>1).map(s=>${n(s)}).join(", ")}scrapbox.PopupMenu.addButton({title:"link authors",onClick:Go});scrapbox.PopupMenu.addButton({title:"md→cs",onClick:e=>(e=e.split(/\n/).map(t=>t.replace(/^[\*\-\+] /g," ")).join( ),e=e.split(/\n/).map(t=>t.replace(/[\*\-\+] /g,"")).join(
),e=e.split(/\n/).map(t=>t.replace(/ {4}/g," ")).join(
),e=e.split(/\n/).map(t=>t.replace(/^([0-9]+\. )/g," $1")).join(
),e=e.split(/\n/).map(t=>t.replace(/\*{2}([^*]+)\*{2}/g,"[* $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/\_{2}([^_]+)\_{2}/g,"[* $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/\~\~(\~+|[^~]+)\~\~/g,"[- $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/^# (.*)/g,"[******* $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/^#{2} (.*)/g,"[****** $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/^#{3} (.*)/g,"[***** $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/^#{4} (.*)/g,"[**** $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/^#{5} (.*)/g,"[*** $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/^#{6} (.*)/g,"[** $1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/!?\[\]\((https?:\/\/[\w/:%#\$&\?\(\)~\.=\+\-]+)\)/g,"[$1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/!\[([^\]]+)\]\((https?:\/\/[\w/:%#\$&\?\(\)~\.=\+\-]+)\)/g,"[$1 $2]")).join(
),e=e.split(/\n/).map(t=>t.replace(/\[([^\]]+)\]\((https?:\/\/[\w/:%#\$&\?\(\)~\.=\+\-]+)\)/g,"[$1 $2]")).join(
),e=e.split(/\n/).map(t=>t.replace(/<(https?:\/\/[\w/:%#\$&\?\(\)~\.=\+\-]+)>/g,"[$1]")).join(
),e=e.split(/\n/).map(t=>t.replace(/^([\*|\-|\_]){3,}/g,"[/icons/hr.icon]")).join(
),e=e.split(/\n/).map(t=>t.replace(/\\([\\||\*|_|\{|\}|\|\|\(|\)|#|\+|\-|\.|\!])/g,"$1")).join(` ),e)});scrapbox.TimeStamp.removeAllFormats();scrapbox.TimeStamp.addFormat("YYYY/M/D");scrapbox.TimeStamp.addFormat("[[]YYYY/M/D[]]");scrapbox.TimeStamp.addFormat("YYYY/M/D HH:mm:ss");var zo=e=>({type:"title",text:e.rows[0].text}),Wo=e=>{let{rows:[t,...r]}=e,{indent:n=0,text:o=""}=t??{},s=o.replace(/^\s*code:/,"");return{indent:n,type:"codeBlock",fileName:s,content:r.map(a=>a.text.substring(n+1)).join(
)}},Z=(e,{parseOnNested:t,parseOnQuoted:r,patterns:n})=>(o,s,a)=>{var i,l,u,p,f,w;if(!t&&s.nested)return(i=a?.())!==null&&i!==void 0?i:[];if(!r&&s.quoted)return(l=a?.())!==null&&l!==void 0?l:[];for(let E of n){let U=E.exec(o);if(U===null)continue;let D=o.substring(0,U.index),S=o.substring(U.index+((p=(u=U[0])===null||u===void 0?void 0:u.length)!==null&&p!==void 0?p:0)),H=e((f=U[0])!==null&&f!==void 0?f:"",s);return[...we(D,s),...H,...we(S,s)]}return(w=a?.())!==null&&w!==void 0?w:[]},re=e=>[{type:"plain",raw:e,text:e}],Vo=Z(re,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),Yo=/^>.*$/,Qo=(e,t)=>t.context==="table"?re(e,t):[{type:"quote",raw:e,nodes:we(e.substring(1),{...t,quoted:!0})}],Xo=Z(Qo,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Yo]}),Jo=/^\? .+$/,Zo=(e,t)=>t.context==="table"?re(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],es=Z(Zo,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Jo]}),ts=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,rs=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,ns=(e,t)=>{if(t.context==="table")return re(e,t);let r=e.substring(2,e.length-2),n=/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(r);return[{type:"strongImage",raw:e,src:n?${r}/thumb/1000:r}]},os=Z(ns,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ts,rs]}),ss=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function zr(e){return(t,r)=>{if(e==="strongIcon"&&r.context==="table")return re(t,r);let n=e==="icon"?t.substring(1,t.length-1):t.substring(2,t.length-2),o=n.lastIndexOf(".icon"),s=n.substring(0,o),a=s.startsWith("/")?"root":"relative",i=n.substring(o+5,n.length),l=i.startsWith("*")?parseInt(i.substring(1),10):1;return new Array(l).fill({}).map(()=>({path:s,pathType:a,type:e,raw:t}))}}var is=zr("icon"),as=Z(is,{parseOnNested:!0,parseOnQuoted:!0,patterns:[ss]}),ls=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,cs=zr("strongIcon"),ps=Z(cs,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ls]}),us=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,fs=(e,t)=>t.context==="table"?re(e,t):[{type:"strong",raw:e,nodes:we(e.substring(2,e.length-2),{...t,nested:!0})}],ds=Z(fs,{parseOnNested:!1,parseOnQuoted:!0,patterns:[us]}),ms=/\[\$ .+? \]/,gs=/\[\$ [^\]]+\]/,hs=(e,t)=>t.context==="table"?re(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],xs=Z(hs,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ms,gs]}),ys=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,bs=(e,t)=>{if(t.context==="table")return re(e,t);let r=e.indexOf(" "),n=e.substring(1,r),o=e.substring(r+1,e.length-1),s=new Set(n);if(s.has("*")){let a=n.split("*").length-1;s.delete("*"),s.add(*-${Math.min(a,10)})}return[{type:"decoration",raw:e,rawDecos:n,decos:Array.from(s),nodes:we(o,{...t,nested:!0})}]},ws=Z(bs,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ys]}),Es=/.*?/,vs=(e,t)=>t.context==="table"?re(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],Rs=Z(vs,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Es]}),Ls=/^[$%] .+$/,Ts=(e,t)=>{var r;if(t.context==="table")return re(e,t);let n=(r=e[0])!==null&&r!==void 0?r:"",o=e.substring(2);return[{type:"commandLine",raw:e,symbol:n,text:o}]},ks=Z(Ts,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Ls]}),Cs=/\[\s+\]/,Ps=(e,t)=>t.context==="table"?re(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],Ms=Z(Ps,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Cs]}),Os=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,As=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,Ss=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,$s=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,Ns=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||Is(e),Is=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),_s=(e,t)=>{if(t.context==="table")return re(e,t);let r=e.search(/\s/),n=r!==-1?e.substring(1,r):e.substring(1,e.length-1),o=r!==-1?e.substring(r,e.length-1).trimLeft():"",[s,a]=Ns(o)?[o,n]:[n,o];return[{type:"image",raw:e,src:/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}$/.test(s)?${s}/thumb/1000:s,link:a}]},Us=Z(_s,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Os,As,Ss,$s]}),js=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,Fs=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,Bs=/\[https?:\/\/[^\s\]]+\]/,Ds=/https?:\/\/[^\s]+/,Hs=(e,t)=>{if(t.context==="table")return re(e,t);let r=e.startsWith("[")&&e.endsWith("]")?e.substring(1,e.length-1):e,n=/^https?:\/\/[^\s\]]/.test(r),o=(n?/^https?:\/\/[^\s\]]+/:/https?:\/\/[^\s\]]+$/).exec(r);if(o?.[0]===void 0)return[];let s=n?r.substring(o[0].length):r.substring(0,o.index-1);return[{type:"link",raw:e,pathType:"absolute",href:o[0],content:s.trim()}]},qs=Z(Hs,{parseOnNested:!0,parseOnQuoted:!0,patterns:[js,Fs,Bs,Ds]}),Wr=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Vr=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,Ks=e=>{let[t="",r="",n=""]=e.split(","),o=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),a=/^Z\d+$/.test(n)?parseInt(n.replace(/^Z/,""),10):14;return{latitude:o,longitude:s,zoom:a}},Gs=(e,t)=>{var r;if(t.context==="table")return re(e,t);let n=(r=e.match(Wr))!==null&&r!==void 0?r:e.match(Vr);if(n===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,s="",a=""]=o?n:[n[0],n[2],n[1]],{latitude:i,longitude:l,zoom:u}=Ks(s),p=a!==""?https://www.google.com/maps/place/${encodeURIComponent(a)}/@${i},${l},${u}z:https://www.google.com/maps/@${i},${l},${u}z;return[{type:"googleMap",raw:e,latitude:i,longitude:l,zoom:u,place:a,url:p}]},zs=Z(Gs,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Wr,Vr]}),Ws=/\[\/?[^[\]]+\]/,Vs=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},Ys=Z(Vs,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Ws]}),Qs=/(?:^|\s)#\S+/,Xs=(e,t)=>{if(t.context==="table")return re(e,t);if(e.startsWith("#"))return[{type:"hashTag",raw:e,href:e.substring(1)}];let r=e.substring(0,1),n=e.substring(1);return[...re(r,t),{type:"hashTag",raw:n,href:n.substring(1)}]},Js=Z(Xs,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Qs]}),Zs=/^[0-9]+\. .*$/,ei=(e,t)=>{if(t.context==="table")return re(e,t);let r=e.indexOf(" "),n=e.substring(0,r-1),o=parseInt(n,10),s=e.substring(r+1,e.length);return[{type:"numberList",raw:e,rawNumber:n,number:o,nodes:we(s,{...t,nested:!0})}]},ti=Z(ei,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Zs]}),ri=(e,t,r)=>{var n;return e===""?[]:(n=r?.())!==null&&n!==void 0?n:[]},ni=(...e)=>(t,r)=>e.reduceRight((n,o)=>()=>o(t,r,n),()=>Vo(t,r))(),we=ni(ri,Xo,es,Rs,ks,xs,Ms,ws,os,ps,ds,Us,qs,as,zs,Ys,Js,ti),oi=e=>{let{rows:[t,...r]}=e,{indent:n=0,text:o=""}=t??{},s=o.replace(/^\s*table:/,"");return{indent:n,type:"table",fileName:s,cells:r.map(a=>a.text.substring(n+1)).map(a=>a.split(" ").map(i=>we(i,{nested:!1,quoted:!1,context:"table"})))}},si=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:we(r.substring(t),{nested:!1,quoted:!1,context:"line"})}},ii=e=>{switch(e.type){case"title":return zo(e);case"codeBlock":return Wo(e);case"table":return oi(e);case"line":return si(e)}},ai=e=>e.split( ).map(t=>{var r,n,o;return{indent:(o=(n=(r=/^\s+/.exec(t))===null||r===void 0?void 0:r[0])===null||n===void 0?void 0:n.length)!==null&&o!==void 0?o:0,text:t}}),li=(e,t)=>{var r,n;return(e.type==="codeBlock"||e.type==="table")&&t.indent>((n=(r=e.rows[0])===null||r===void 0?void 0:r.indent)!==null&&n!==void 0?n:0)},Gr=(e,t)=>{let r=e[e.length-1];return r!==void 0&&li(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)},ci=(e,t)=>{var r;if(!((r=t.hasTitle)!==null&&r!==void 0)||r){let[n,...o]=e;return n===void 0?[]:[{type:"title",rows:[n]},...o.reduce(Gr,[])]}return e.reduce(Gr,[])},Yr=(e,t)=>{var r;let n=ai(e);return ci(n,{hasTitle:(r=t?.hasTitle)!==null&&r!==void 0?r:!0}).map(ii)};var Qr=(e,t,r)=>{if(r.length===0)return[];let n=r.map(i=>i.text).join(
),o=Yr(n,{hasTitle:!0}),s=new Map,a=0;for(let i of o)switch(i.type){case"title":case"line":{a++;break}case"table":a+=i.cells.length+1;break;case"codeBlock":{let l=s.get(i.fileName);s.set(i.fileName,{dir:l?.dir??https://scrapbox.io/api/code/${e}/${dt(t)},lang:l?.lang??i.fileName.split(".").pop()??"text",startIds:[...l?.startIds??[],r[a].id],lines:[...l?.lines??[],...i.content.split( )]}),a+=i.content.split(
).length+1;break}}return[...s.entries()].map(([i,l])=>({filename:i,...l}))};function vt(e){let t=n=>{if(n===null)r.write8(0);else if(typeof n=="boolean")r.write8(1),r.write8(+n);else if(typeof n=="number")r.write8(2),r.write32(n|0);else if(typeof n=="string")r.write8(3),r.write(ae(n));else if(n instanceof Uint8Array)r.write8(4),r.write(n);else if(n instanceof Array){r.write8(5),r.write32(n.length);for(let o of n)t(o)}else{let o=Object.keys(n);r.write8(6),r.write32(o.length);for(let s of o)r.write(ae(s)),t(n[s])}},r=new We;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),Et(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function Xr(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return Oe(r.read());case 4:return r.read();case 5:{let a=r.read32(),i=[];for(let l=0;l<a;l++)i.push(t());return i}case 6:{let a=r.read32(),i={};for(let l=0;l<a;l++)i[Oe(r.read())]=t();return i}default:throw new Error("Invalid packet")}},r=new We(e),n=r.read32(),o=(n&1)===0;n>>>=1;let s=t();if(r.ptr!==e.length)throw new Error("Invalid packet");return{id:n,isRequest:o,value:s}}var We=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);Et(this.buf,t,r)}write(t){let r=this._write(4+t.length);Et(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 Rt(this.buf,this._read(4))}read(){let t=this.read32(),r=new Uint8Array(t),n=this._read(r.length);return r.set(this.buf.subarray(n,n+t)),r}},ae,Oe,Jr;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;ae=r=>e.encode(r),Oe=r=>t.decode(r),Jr='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(ae("")instanceof Uint8Array))throw new Error(Invariant violation: "${Jr} 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 Rt(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function Et(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var _e="0.21.5";var Q=JSON.stringify,Zr="warning",en="silent";function tn(e){if(ee(e,"target"),e.indexOf(",")>=0)throw new Error(Invalid target: ${e});return e}var Qe=()=>null,W=e=>typeof e=="boolean"?null:"a boolean",b=e=>typeof e=="string"?null:"a string",Xe=e=>e instanceof RegExp?null:"a RegExp object",Te=e=>typeof e=="number"&&e===(e|0)?null:"an integer",on=e=>typeof e=="function"?null:"a function",Y=e=>Array.isArray(e)?null:"an array",se=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",ui=e=>typeof e=="object"&&e!==null?null:"an array or an object",fi=e=>e instanceof WebAssembly.Module?null:"a WebAssembly.Module",rn=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",sn=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",di=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",mi=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",an=e=>typeof e=="string"||e instanceof Uint8Array?null:"a string or a Uint8Array",gi=e=>typeof e=="string"||e instanceof URL?null:"a string or a URL";function c(e,t,r,n){let o=e[r];if(t[r+""]=!0,o===void 0)return;let s=n(o);if(s!==null)throw new Error(${Q(r)} must be ${s});return o}function X(e,t,r){for(let n in e)if(!(n in t))throw new Error(Invalid option ${r}: ${Q(n)})}function ln(e){let t=Object.create(null),r=c(e,t,"wasmModule",fi),n=c(e,t,"workerURL",gi);return X(e,t,"in initialize() call"),{wasmModule:r,workerURL:n}}function cn(e){let t;if(e!==void 0){t=Object.create(null);for(let r in e){let n=e[r];if(typeof n=="string"||n===!1)t[r]=n;else throw new Error(Expected ${Q(r)} in mangle cache to map to either a string or false)}}return t}function Je(e,t,r,n,o){let s=c(t,r,"color",W),a=c(t,r,"logLevel",b),i=c(t,r,"logLimit",Te);s!==void 0?e.push(--color=${s}):n&&e.push("--color=true"),e.push(--log-level=${a||o}),e.push(--log-limit=${i||0})}function ee(e,t,r){if(typeof e!="string")throw new Error(Expected value for ${t}${r!==void 0?" "+Q(r):""} to be a string, got ${typeof e} instead);return e}function pn(e,t,r){let n=c(t,r,"legalComments",b),o=c(t,r,"sourceRoot",b),s=c(t,r,"sourcesContent",W),a=c(t,r,"target",mi),i=c(t,r,"format",b),l=c(t,r,"globalName",b),u=c(t,r,"mangleProps",Xe),p=c(t,r,"reserveProps",Xe),f=c(t,r,"mangleQuoted",W),w=c(t,r,"minify",W),E=c(t,r,"minifySyntax",W),U=c(t,r,"minifyWhitespace",W),D=c(t,r,"minifyIdentifiers",W),S=c(t,r,"lineLimit",Te),H=c(t,r,"drop",Y),K=c(t,r,"dropLabels",Y),v=c(t,r,"charset",b),x=c(t,r,"treeShaking",W),g=c(t,r,"ignoreAnnotations",W),d=c(t,r,"jsx",b),L=c(t,r,"jsxFactory",b),T=c(t,r,"jsxFragment",b),M=c(t,r,"jsxImportSource",b),C=c(t,r,"jsxDev",W),m=c(t,r,"jsxSideEffects",W),h=c(t,r,"define",se),R=c(t,r,"logOverride",se),$=c(t,r,"supported",se),I=c(t,r,"pure",Y),A=c(t,r,"keepNames",W),P=c(t,r,"platform",b),N=c(t,r,"tsconfigRaw",di);if(n&&e.push(--legal-comments=${n}),o!==void 0&&e.push(--source-root=${o}),s!==void 0&&e.push(--sources-content=${s}),a&&(Array.isArray(a)?e.push(--target=${Array.from(a).map(tn).join(",")}):e.push(--target=${tn(a)})),i&&e.push(--format=${i}),l&&e.push(--global-name=${l}),P&&e.push(--platform=${P}),N&&e.push(--tsconfig-raw=${typeof N=="string"?N:JSON.stringify(N)}),w&&e.push("--minify"),E&&e.push("--minify-syntax"),U&&e.push("--minify-whitespace"),D&&e.push("--minify-identifiers"),S&&e.push(--line-limit=${S}),v&&e.push(--charset=${v}),x!==void 0&&e.push(--tree-shaking=${x}),g&&e.push("--ignore-annotations"),H)for(let k of H)e.push(--drop:${ee(k,"drop")});if(K&&e.push(--drop-labels=${Array.from(K).map(k=>ee(k,"dropLabels")).join(",")}),u&&e.push(--mangle-props=${u.source}),p&&e.push(--reserve-props=${p.source}),f!==void 0&&e.push(--mangle-quoted=${f}),d&&e.push(--jsx=${d}),L&&e.push(--jsx-factory=${L}),T&&e.push(--jsx-fragment=${T}),M&&e.push(--jsx-import-source=${M}),C&&e.push("--jsx-dev"),m&&e.push("--jsx-side-effects"),h)for(let k in h){if(k.indexOf("=")>=0)throw new Error(Invalid define: ${k});e.push(--define:${k}=${ee(hk,"define",k)})}if(R)for(let k in R){if(k.indexOf("=")>=0)throw new Error(Invalid log override: ${k});e.push(--log-override:${k}=${ee(Rk,"log override",k)})}if($)for(let k in $){if(k.indexOf("=")>=0)throw new Error(Invalid supported: ${k});let O=$[k];if(typeof O!="boolean")throw new Error(Expected value for supported ${Q(k)} to be a boolean, got ${typeof O} instead);e.push(--supported:${k}=${O})}if(I)for(let k of I)e.push(--pure:${ee(k,"pure")});A&&e.push("--keep-names")}function hi(e,t,r,n,o){let s=[],a=[],i=Object.create(null),l=null,u=null;Je(s,t,i,r,n),pn(s,t,i);let p=c(t,i,"sourcemap",sn),f=c(t,i,"bundle",W),w=c(t,i,"splitting",W),E=c(t,i,"preserveSymlinks",W),U=c(t,i,"metafile",W),D=c(t,i,"outfile",b),S=c(t,i,"outdir",b),H=c(t,i,"outbase",b),K=c(t,i,"tsconfig",b),v=c(t,i,"resolveExtensions",Y),x=c(t,i,"nodePaths",Y),g=c(t,i,"mainFields",Y),d=c(t,i,"conditions",Y),L=c(t,i,"external",Y),T=c(t,i,"packages",b),M=c(t,i,"alias",se),C=c(t,i,"loader",se),m=c(t,i,"outExtension",se),h=c(t,i,"publicPath",b),R=c(t,i,"entryNames",b),$=c(t,i,"chunkNames",b),I=c(t,i,"assetNames",b),A=c(t,i,"inject",Y),P=c(t,i,"banner",se),N=c(t,i,"footer",se),k=c(t,i,"entryPoints",ui),O=c(t,i,"absWorkingDir",b),_=c(t,i,"stdin",se),B=c(t,i,"write",W)??o,j=c(t,i,"allowOverwrite",W),ne=c(t,i,"mangleCache",se);if(i.plugins=!0,X(t,i,in ${e}() call),p&&s.push(--sourcemap${p===!0?"":=${p}}),f&&s.push("--bundle"),j&&s.push("--allow-overwrite"),w&&s.push("--splitting"),E&&s.push("--preserve-symlinks"),U&&s.push("--metafile"),D&&s.push(--outfile=${D}),S&&s.push(--outdir=${S}),H&&s.push(--outbase=${H}),K&&s.push(--tsconfig=${K}),T&&s.push(--packages=${T}),v){let y=[];for(let G of v){if(ee(G,"resolve extension"),G.indexOf(",")>=0)throw new Error(Invalid resolve extension: ${G});y.push(G)}s.push(--resolve-extensions=${y.join(",")})}if(h&&s.push(--public-path=${h}),R&&s.push(--entry-names=${R}),$&&s.push(--chunk-names=${$}),I&&s.push(--asset-names=${I}),g){let y=[];for(let G of g){if(ee(G,"main field"),G.indexOf(",")>=0)throw new Error(Invalid main field: ${G});y.push(G)}s.push(--main-fields=${y.join(",")})}if(d){let y=[];for(let G of d){if(ee(G,"condition"),G.indexOf(",")>=0)throw new Error(Invalid condition: ${G});y.push(G)}s.push(--conditions=${y.join(",")})}if(L)for(let y of L)s.push(--external:${ee(y,"external")});if(M)for(let y in M){if(y.indexOf("=")>=0)throw new Error(Invalid package name in alias: ${y});s.push(--alias:${y}=${ee(My,"alias",y)})}if(P)for(let y in P){if(y.indexOf("=")>=0)throw new Error(Invalid banner file type: ${y});s.push(--banner:${y}=${ee(Py,"banner",y)})}if(N)for(let y in N){if(y.indexOf("=")>=0)throw new Error(Invalid footer file type: ${y});s.push(--footer:${y}=${ee(Ny,"footer",y)})}if(A)for(let y of A)s.push(--inject:${ee(y,"inject")});if(C)for(let y in C){if(y.indexOf("=")>=0)throw new Error(Invalid loader extension: ${y});s.push(--loader:${y}=${ee(Cy,"loader",y)})}if(m)for(let y in m){if(y.indexOf("=")>=0)throw new Error(Invalid out extension: ${y});s.push(--out-extension:${y}=${ee(my,"out extension",y)})}if(k)if(Array.isArray(k))for(let y=0,G=k.length;y<G;y++){let oe=k[y];if(typeof oe=="object"&&oe!==null){let ue=Object.create(null),fe=c(oe,ue,"in",b),le=c(oe,ue,"out",b);if(X(oe,ue,"in entry point at index "+y),fe===void 0)throw new Error('Missing property "in" for entry point at index '+y);if(le===void 0)throw new Error('Missing property "out" for entry point at index '+y);a.push([le,fe])}else a.push(["",ee(oe,"entry point at index "+y)])}else for(let y in k)a.push([y,ee(k[y],"entry point",y)]);if(_){let y=Object.create(null),G=c(_,y,"contents",an),oe=c(_,y,"resolveDir",b),ue=c(_,y,"sourcefile",b),fe=c(_,y,"loader",b);X(_,y,'in "stdin" object'),ue&&s.push(--sourcefile=${ue}),fe&&s.push(--loader=${fe}),oe&&(u=oe),typeof G=="string"?l=ae(G):G instanceof Uint8Array&&(l=G)}let V=[];if(x)for(let y of x)y+="",V.push(y);return{entries:a,flags:s,write:B,stdinContents:l,stdinResolveDir:u,absWorkingDir:O,nodePaths:V,mangleCache:cn(ne)}}function xi(e,t,r,n){let o=[],s=Object.create(null);Je(o,t,s,r,n),pn(o,t,s);let a=c(t,s,"sourcemap",sn),i=c(t,s,"sourcefile",b),l=c(t,s,"loader",b),u=c(t,s,"banner",b),p=c(t,s,"footer",b),f=c(t,s,"mangleCache",se);return X(t,s,in ${e}() call),a&&o.push(--sourcemap=${a===!0?"external":a}),i&&o.push(--sourcefile=${i}),l&&o.push(--loader=${l}),u&&o.push(--banner=${u}),p&&o.push(--footer=${p}),{flags:o,mangleCache:cn(f)}}function un(e){let t={},r={didClose:!1,reason:""},n={},o=0,s=0,a=new Uint8Array(16*1024),i=0,l=v=>{let x=i+v.length;if(x>a.length){let d=new Uint8Array(x*2);d.set(a),a=d}a.set(v,i),i+=v.length;let g=0;for(;g+4<=i;){let d=Rt(a,g);if(g+4+d>i)break;g+=4,U(a.subarray(g,g+d)),g+=d}g>0&&(a.copyWithin(0,g,i),i-=g)},u=v=>{r.didClose=!0,v&&(r.reason=": "+(v.message||v));let x="The service was stopped"+r.reason;for(let g in n)n[g](x,null);n={}},p=(v,x,g)=>{if(r.didClose)return g("The service is no longer running"+r.reason,null);let d=o++;n[d]=(L,T)=>{try{g(L,T)}finally{v&&v.unref()}},v&&v.ref(),e.writeToStdin(vt({id:d,isRequest:!0,value:x}))},f=(v,x)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(vt({id:v,isRequest:!1,value:x}))},w=async(v,x)=>{try{if(x.command==="ping"){f(v,{});return}if(typeof x.key=="number"){let g=t[x.key];if(!g)return;let d=g[x.command];if(d){await d(v,x);return}}throw new Error("Invalid command: "+x.command)}catch(g){let d=[Le(g,e,null,void 0,"")];try{f(v,{errors:d})}catch{}}},E=!0,U=v=>{if(E){E=!1;let g=String.fromCharCode(...v);if(g!==_e)throw new Error(Cannot start service: Host version "${_e}" does not match binary version ${Q(g)});return}let x=Xr(v);if(x.isRequest)w(x.id,x.value);else{let g=n[x.id];delete n[x.id],x.value.error?g(x.value.error,{}):g(null,x.value)}};return{readFromStdout:l,afterClose:u,service:{buildOrContext:({callName:v,refs:x,options:g,isTTY:d,defaultWD:L,callback:T})=>{let M=0,C=s++,m={},h={ref(){++M===1&&x&&x.ref()},unref(){--M===0&&(delete t[C],x&&x.unref())}};t[C]=m,h.ref(),yi(v,C,p,f,h,e,m,g,d,L,(R,$)=>{try{T(R,$)}finally{h.unref()}})},transform:({callName:v,refs:x,input:g,options:d,isTTY:L,fs:T,callback:M})=>{let C=fn(),m=h=>{try{if(typeof g!="string"&&!(g instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:R,mangleCache:$}=xi(v,d,L,en),I={command:"transform",flags:R,inputFS:h!==null,input:h!==null?ae(h):typeof g=="string"?ae(g):g};$&&(I.mangleCache=$),p(x,I,(A,P)=>{if(A)return M(new Error(A),null);let N=Ae(P.errors,C),k=Ae(P.warnings,C),O=1,_=()=>{if(--O===0){let B={warnings:k,code:P.code,map:P.map,mangleCache:void 0,legalComments:void 0};"legalComments"in P&&(B.legalComments=P?.legalComments),P.mangleCache&&(B.mangleCache=P?.mangleCache),M(null,B)}};if(N.length>0)return M(Ue("Transform failed",N,k),null);P.codeFS&&(O++,T.readFile(P.code,(B,j)=>{B!==null?M(B,null):(P.code=j,_())})),P.mapFS&&(O++,T.readFile(P.map,(B,j)=>{B!==null?M(B,null):(P.map=j,_())})),_()})}catch(R){let $=[];try{Je($,d,{},L,en)}catch{}let I=Le(R,e,C,void 0,"");p(x,{command:"error",flags:$,error:I},()=>{I.detail=C.load(I.detail),M(Ue("Transform failed",[I],[]),null)})}};if((typeof g=="string"||g instanceof Uint8Array)&&g.length>1024*1024){let h=m;m=()=>T.writeFile(g,h)}m(null)},formatMessages:({callName:v,refs:x,messages:g,options:d,callback:L})=>{if(!d)throw new Error(Missing second argument in ${v}() call);let T={},M=c(d,T,"kind",b),C=c(d,T,"color",W),m=c(d,T,"terminalWidth",Te);if(X(d,T,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 h={command:"format-msgs",messages:xe(g,"messages",null,"",m),isWarning:M==="warning"};C!==void 0&&(h.color=C),m!==void 0&&(h.terminalWidth=m),p(x,h,(R,$)=>{if(R)return L(new Error(R),null);L(null,$.messages)})},analyzeMetafile:({callName:v,refs:x,metafile:g,options:d,callback:L})=>{d===void 0&&(d={});let T={},M=c(d,T,"color",W),C=c(d,T,"verbose",W);X(d,T,in ${v}() call);let m={command:"analyze-metafile",metafile:g};M!==void 0&&(m.color=M),C!==void 0&&(m.verbose=C),p(x,m,(h,R)=>{if(h)return L(new Error(h),null);L(null,R.result)})}}}}function yi(e,t,r,n,o,s,a,i,l,u,p){let f=fn(),w=e==="context",E=(S,H)=>{let K=[];try{Je(K,i,{},l,Zr)}catch{}let v=Le(S,s,f,void 0,H);r(o,{command:"error",flags:K,error:v},()=>{v.detail=f.load(v.detail),p(Ue(w?"Context failed":"Build failed",[v],[]),null)})},U;if(typeof i=="object"){let S=i.plugins;if(S!==void 0){if(!Array.isArray(S))return E(new Error('"plugins" must be an array'),"");U=S}}if(U&&U.length>0){if(s.isSync)return E(new Error("Cannot use plugins in synchronous API calls"),"");bi(t,r,n,o,s,a,i,U,f).then(S=>{if(!S.ok)return E(S.error,S.pluginName);try{D(S.requestPlugins,S.runOnEndCallbacks,S.scheduleOnDisposeCallbacks)}catch(H){E(H,"")}},S=>E(S,""));return}try{D(null,(S,H)=>H([],[]),()=>{})}catch(S){E(S,"")}function D(S,H,K){let v=s.hasFS,{entries:x,flags:g,write:d,stdinContents:L,stdinResolveDir:T,absWorkingDir:M,nodePaths:C,mangleCache:m}=hi(e,i,l,Zr,v);if(d&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let h={command:"build",key:t,entries:x,flags:g,write:d,stdinContents:L,stdinResolveDir:T,absWorkingDir:M||u,nodePaths:C,context:w};S&&(h.plugins=S),m&&(h.mangleCache=m);let R=(A,P)=>{let N={errors:Ae(A.errors,f),warnings:Ae(A.warnings,f),outputFiles:void 0,metafile:void 0,mangleCache:void 0},k=N.errors.slice(),O=N.warnings.slice();A.outputFiles&&(N.outputFiles=A.outputFiles.map(Ei)),A.metafile&&(N.metafile=JSON.parse(A.metafile)),A.mangleCache&&(N.mangleCache=A.mangleCache),A.writeToStdout!==void 0&&console.log(Oe(A.writeToStdout).replace(/\n$/,"")),H(N,(_,B)=>{if(k.length>0||_.length>0){let j=Ue("Build failed",k.concat(_),O.concat(B));return P(j,null,_,B)}P(null,N,_,B)})},$,I;w&&(a["on-end"]=(A,P)=>new Promise(N=>{R(P,(k,O,_,B)=>{let j={errors:_,warnings:B};I&&I(k,O),$=void 0,I=void 0,n(A,j),N()})})),r(o,h,(A,P)=>{if(A)return p(new Error(A),null);if(!w)return R(P,(O,_)=>(K(),p(O,_)));if(P.errors.length>0)return p(Ue("Context failed",P.errors,P.warnings),null);let N=!1,k={rebuild:()=>($||($=new Promise((O,_)=>{let B;I=(ne,V)=>{B||(B=()=>ne?_(ne):O(V))};let j=()=>{r(o,{command:"rebuild",key:t},(V,y)=>{V?_(new Error(V)):B?B():j()})};j()})),$),watch:(O={})=>new Promise((_,B)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');X(O,{},"in watch() call"),r(o,{command:"watch",key:t},V=>{V?B(new Error(V)):_(void 0)})}),serve:(O={})=>new Promise((_,B)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let j={},ne=c(O,j,"port",Te),V=c(O,j,"host",b),y=c(O,j,"servedir",b),G=c(O,j,"keyfile",b),oe=c(O,j,"certfile",b),ue=c(O,j,"fallback",b),fe=c(O,j,"onRequest",on);X(O,j,"in serve() call");let le={command:"serve",key:t,onRequest:!!fe};ne!==void 0&&(le.port=ne),V!==void 0&&(le.host=V),y!==void 0&&(le.servedir=y),G!==void 0&&(le.keyfile=G),oe!==void 0&&(le.certfile=oe),ue!==void 0&&(le.fallback=ue),r(o,le,(Bt,to)=>{if(Bt)return B(new Error(Bt));fe&&(a["serve-request"]=(ro,no)=>{fe(no.args),n(ro,{})}),_(to)})}),cancel:()=>new Promise(O=>{if(N)return O();r(o,{command:"cancel",key:t},()=>{O()})}),dispose:()=>new Promise(O=>{if(N)return O();N=!0,r(o,{command:"dispose",key:t},()=>{O(),K(),o.unref()})})};o.ref(),p(null,k)})}}var bi=async(e,t,r,n,o,s,a,i,l)=>{let u=[],p=[],f={},w={},E=[],U=0,D=0,S=[],H=!1;i=[...i];for(let x of i){let g={};if(typeof x!="object")throw new Error(Plugin at index ${D} must be an object);let d=c(x,g,"name",b);if(typeof d!="string"||d==="")throw new Error(Plugin at index ${D} is missing a name);try{let L=c(x,g,"setup",on);if(typeof L!="function")throw new Error("Plugin is missing a setup function");X(x,g,on plugin ${Q(d)});let T={name:d,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};D++;let C=L({initialOptions:a,resolve:(m,h={})=>{if(!H)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof m!="string")throw new Error("The path to resolve must be a string");let R=Object.create(null),$=c(h,R,"pluginName",b),I=c(h,R,"importer",b),A=c(h,R,"namespace",b),P=c(h,R,"resolveDir",b),N=c(h,R,"kind",b),k=c(h,R,"pluginData",Qe),O=c(h,R,"with",se);return X(h,R,"in resolve() call"),new Promise((_,B)=>{let j={command:"resolve",path:m,key:e,pluginName:d};if($!=null&&(j.pluginName=$),I!=null&&(j.importer=I),A!=null&&(j.namespace=A),P!=null&&(j.resolveDir=P),N!=null)j.kind=N;else throw new Error('Must specify "kind" when calling "resolve"');k!=null&&(j.pluginData=l.store(k)),O!=null&&(j.with=wi(O,"with")),t(n,j,(ne,V)=>{ne!==null?B(new Error(ne)):_({errors:Ae(V.errors,l),warnings:Ae(V.warnings,l),path:V.path,external:V.external,sideEffects:V.sideEffects,namespace:V.namespace,suffix:V.suffix,pluginData:l.load(V.pluginData)})})})},onStart(m){let h='This error came from the "onStart" callback registered here:',R=Ve(new Error(h),o,"onStart");u.push({name:d,callback:m,note:R}),T.onStart=!0},onEnd(m){let h='This error came from the "onEnd" callback registered here:',R=Ve(new Error(h),o,"onEnd");p.push({name:d,callback:m,note:R}),T.onEnd=!0},onResolve(m,h){let R='This error came from the "onResolve" callback registered here:',$=Ve(new Error(R),o,"onResolve"),I={},A=c(m,I,"filter",Xe),P=c(m,I,"namespace",b);if(X(m,I,in onResolve() call for plugin ${Q(d)}),A==null)throw new Error("onResolve() call is missing a filter");let N=U++;f[N]={name:d,callback:h,note:$},T.onResolve.push({id:N,filter:A.source,namespace:P||""})},onLoad(m,h){let R='This error came from the "onLoad" callback registered here:',$=Ve(new Error(R),o,"onLoad"),I={},A=c(m,I,"filter",Xe),P=c(m,I,"namespace",b);if(X(m,I,in onLoad() call for plugin ${Q(d)}),A==null)throw new Error("onLoad() call is missing a filter");let N=U++;w[N]={name:d,callback:h,note:$},T.onLoad.push({id:N,filter:A.source,namespace:P||""})},onDispose(m){E.push(m)},esbuild:o.esbuild});C&&await C,S.push(T)}catch(L){return{ok:!1,error:L,pluginName:d}}}s["on-start"]=async(x,g)=>{let d={errors:[],warnings:[]};await Promise.all(u.map(async({name:L,callback:T,note:M})=>{try{let C=await T();if(C!=null){if(typeof C!="object")throw new Error(Expected onStart() callback in plugin ${Q(L)} to return an object);let m={},h=c(C,m,"errors",Y),R=c(C,m,"warnings",Y);X(C,m,from onStart() callback in plugin ${Q(L)}),h!=null&&d.errors.push(...xe(h,"errors",l,L,void 0)),R!=null&&d.warnings.push(...xe(R,"warnings",l,L,void 0))}}catch(C){d.errors.push(Le(C,o,l,M&&M(),L))}})),r(x,d)},s["on-resolve"]=async(x,g)=>{let d={},L="",T,M;for(let C of g.ids)try{({name:L,callback:T,note:M}=f[C]);let m=await T({path:g.path,importer:g.importer,namespace:g.namespace,resolveDir:g.resolveDir,kind:g.kind,pluginData:l.load(g.pluginData),with:g.with});if(m!=null){if(typeof m!="object")throw new Error(Expected onResolve() callback in plugin ${Q(L)} to return an object);let h={},R=c(m,h,"pluginName",b),$=c(m,h,"path",b),I=c(m,h,"namespace",b),A=c(m,h,"suffix",b),P=c(m,h,"external",W),N=c(m,h,"sideEffects",W),k=c(m,h,"pluginData",Qe),O=c(m,h,"errors",Y),_=c(m,h,"warnings",Y),B=c(m,h,"watchFiles",Y),j=c(m,h,"watchDirs",Y);X(m,h,from onResolve() callback in plugin ${Q(L)}),d.id=C,R!=null&&(d.pluginName=R),$!=null&&(d.path=$),I!=null&&(d.namespace=I),A!=null&&(d.suffix=A),P!=null&&(d.external=P),N!=null&&(d.sideEffects=N),k!=null&&(d.pluginData=l.store(k)),O!=null&&(d.errors=xe(O,"errors",l,L,void 0)),_!=null&&(d.warnings=xe(_,"warnings",l,L,void 0)),B!=null&&(d.watchFiles=Ye(B,"watchFiles")),j!=null&&(d.watchDirs=Ye(j,"watchDirs"));break}}catch(m){d={id:C,errors:[Le(m,o,l,M&&M(),L)]};break}r(x,d)},s["on-load"]=async(x,g)=>{let d={},L="",T,M;for(let C of g.ids)try{({name:L,callback:T,note:M}=w[C]);let m=await T({path:g.path,namespace:g.namespace,suffix:g.suffix,pluginData:l.load(g.pluginData),with:g.with});if(m!=null){if(typeof m!="object")throw new Error(Expected onLoad() callback in plugin ${Q(L)} to return an object);let h={},R=c(m,h,"pluginName",b),$=c(m,h,"contents",an),I=c(m,h,"resolveDir",b),A=c(m,h,"pluginData",Qe),P=c(m,h,"loader",b),N=c(m,h,"errors",Y),k=c(m,h,"warnings",Y),O=c(m,h,"watchFiles",Y),_=c(m,h,"watchDirs",Y);X(m,h,from onLoad() callback in plugin ${Q(L)}),d.id=C,R!=null&&(d.pluginName=R),$ instanceof Uint8Array?d.contents=$:$!=null&&(d.contents=ae($)),I!=null&&(d.resolveDir=I),A!=null&&(d.pluginData=l.store(A)),P!=null&&(d.loader=P),N!=null&&(d.errors=xe(N,"errors",l,L,void 0)),k!=null&&(d.warnings=xe(k,"warnings",l,L,void 0)),O!=null&&(d.watchFiles=Ye(O,"watchFiles")),_!=null&&(d.watchDirs=Ye(_,"watchDirs"));break}}catch(m){d={id:C,errors:[Le(m,o,l,M&&M(),L)]};break}r(x,d)};let K=(x,g)=>g([],[]);p.length>0&&(K=(x,g)=>{(async()=>{let d=[],L=[];for(let{name:T,callback:M,note:C}of p){let m,h;try{let R=await M(x);if(R!=null){if(typeof R!="object")throw new Error(Expected onEnd() callback in plugin ${Q(T)} to return an object);let $={},I=c(R,$,"errors",Y),A=c(R,$,"warnings",Y);X(R,$,from onEnd() callback in plugin ${Q(T)}),I!=null&&(m=xe(I,"errors",l,T,void 0)),A!=null&&(h=xe(A,"warnings",l,T,void 0))}}catch(R){m=[Le(R,o,l,C&&C(),T)]}if(m){d.push(...m);try{x.errors.push(...m)}catch{}}if(h){L.push(...h);try{x.warnings.push(...h)}catch{}}}g(d,L)})()});let v=()=>{for(let x of E)setTimeout(()=>x(),0)};return H=!0,{ok:!0,requestPlugins:S,runOnEndCallbacks:K,scheduleOnDisposeCallbacks:v}};function fn(){let e=new Map,t=0;return{load(r){return e.get(r)},store(r){if(r===void 0)return-1;let n=t++;return e.set(n,r),n}}}function Ve(e,t,r){let n,o=!1;return()=>{if(o)return n;o=!0;try{let s=(e.stack+"").split( );s.splice(1,1);let a=dn(t,s,r);if(a)return n={text:e.message,location:a},n}catch{}}}function Le(e,t,r,n,o){let s="Internal error",a=null;try{s=(e&&e.message||e)+""}catch{}try{a=dn(t,(e.stack+"").split(
),"")}catch{}return{id:"",pluginName:o,text:s,location:a,notes:n?[n]:[],detail:r?r.store(e):-1}}function dn(e,t,r){let n=" at ";if(e.readFileSync&&!t[0].startsWith(n)&&t[1].startsWith(n))for(let o=1;o<t.length;o++){let s=t[o];if(s.startsWith(n))for(s=s.slice(n.length);;){let a=/^(?:new |async )?\S+ \((.*)\)$/.exec(s);if(a){s=a[1];continue}if(a=/^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(s),a){s=a[1];continue}if(a=/^(\S+):(\d+):(\d+)$/.exec(s),a){let i;try{i=e.readFileSync(a[1],"utf8")}catch{break}let l=i.split(/\r\n|\r|\n|\u2028|\u2029/)[+a[2]-1]||"",u=+a[3]-1,p=l.slice(u,u+r.length)===r?r.length:0;return{file:a[1],namespace:"file",line:+a[2],column:ae(l.slice(0,u)).length,length:ae(l.slice(u,u+p)).length,lineText:l+
+t.slice(1).join(
),suggestion:""}}break}}return null}function Ue(e,t,r){let n=5;e+=t.length<1?"": with ${t.length} error${t.length<2?"":"s"}:+t.slice(0,n+1).map((s,a)=>{if(a===n)return
...;if(!s.location)return
${i}:${l}:${u}: ERROR: ${p}${s.text}}).join("");let o=new Error(e);for(let[s,a]of[["errors",t],["warnings",r]])Object.defineProperty(o,s,{configurable:!0,enumerable:!0,get:()=>a,set:i=>Object.defineProperty(o,s,{configurable:!0,enumerable:!0,value:i})});return o}function Ae(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function nn(e,t,r){if(e==null)return null;let n={},o=c(e,n,"file",b),s=c(e,n,"namespace",b),a=c(e,n,"line",Te),i=c(e,n,"column",Te),l=c(e,n,"length",Te),u=c(e,n,"lineText",b),p=c(e,n,"suggestion",b);if(X(e,n,t),u){let f=u.slice(0,(i&&i>0?i:0)+(l&&l>0?l:0)+(r&&r>0?r:80));!/[\x7F-\uFFFF]/.test(f)&&!/\n/.test(u)&&(u=f)}return{file:o||"",namespace:s||"",line:a||0,column:i||0,length:l||0,lineText:u||"",suggestion:p||""}}function xe(e,t,r,n,o){let s=[],a=0;for(let i of e){let l={},u=c(i,l,"id",b),p=c(i,l,"pluginName",b),f=c(i,l,"text",b),w=c(i,l,"location",rn),E=c(i,l,"notes",Y),U=c(i,l,"detail",Qe),D=in element ${a} of "${t}";X(i,l,D);let S=[];if(E)for(let H of E){let K={},v=c(H,K,"text",b),x=c(H,K,"location",rn);X(H,K,D),S.push({text:v||"",location:nn(x,D,o)})}s.push({id:u||"",pluginName:p||n,text:f||"",location:nn(w,D,o),notes:S,detail:r?r.store(U):-1}),a++}return s}function Ye(e,t){let r=[];for(let n of e){if(typeof n!="string")throw new Error(${Q(t)} must be an array of strings);r.push(n)}return r}function wi(e,t){let r=Object.create(null);for(let n in e){let o=e[n];if(typeof o!="string")throw new Error(key ${Q(n)} in object ${Q(t)} must be a string);r[n]=o}return r}function Ei({path:e,contents:t,hash:r}){let n=null;return{path:e,contents:t,hash:r,get text(){let o=this.contents;return(n===null||o!==t)&&(t=o,n=Oe(o)),n}}}var Ri=_e,et=e=>tt().build(e),Li=(e,t)=>tt().transform(e,t),Ti=(e,t)=>tt().formatMessages(e,t),ki=(e,t)=>tt().analyzeMetafile(e,t);var ke,mn,Ze,tt=()=>{if(Ze)return Ze;throw ke?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')},rt=e=>{e=ln(e||{});let t=e.wasmModule,r=e.workerURL;if(!t)throw new Error('Must provide the "wasmModule" option');if(ke)throw new Error('Cannot call "initialize" more than once');return ke=Ci(t,r),ke.catch(()=>{ke=void 0}),ke},Ci=async(e,t)=>{let r=new Worker(t.toString(),{type:"module"}),n,o,s=new Promise((l,u)=>{n=l,o=u});r.onmessage=({data:l})=>{r.onmessage=({data:u})=>a(u),l?o(l):n()},r.postMessage(e);let{readFromStdout:a,service:i}=un({writeToStdin(l){r.postMessage(l)},isSync:!1,hasFS:!1,esbuild:{build:et,transform:Li,formatMessages:Ti,analyzeMetafile:ki,version:Ri,initialize:rt}});await s,mn=()=>{r.terminate(),ke=void 0,mn=void 0,Ze=void 0},Ze={build:l=>new Promise((u,p)=>i.buildOrContext({callName:"build",refs:null,options:l,isTTY:!1,defaultWD:"/",callback:(f,w)=>f?p(f):u(w)})),transform:(l,u)=>new Promise((p,f)=>i.transform({callName:"transform",refs:null,input:l,options:u||{},isTTY:!1,fs:{readFile(w,E){E(new Error("Internal error"),null)},writeFile(w,E){E(null)}},callback:(w,E)=>w?f(w):p(E)})),formatMessages:(l,u)=>new Promise((p,f)=>i.formatMessages({callName:"formatMessages",refs:null,messages:l,options:u,callback:(w,E)=>w?f(w):p(E)})),analyzeMetafile:(l,u)=>new Promise((p,f)=>i.analyzeMetafile({callName:"analyzeMetafile",refs:null,metafile:typeof l=="string"?l:JSON.stringify(l),options:u,callback:(w,E)=>w?f(w):p(E)}))}};var gn=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e),hn=e=>{switch(e){case"javascript":case"js":case"mjs":return"js";case"typescript":case"ts":return"ts";case"jsx":return"jsx";case"tsx":return"tsx"}};var xn=e=>!!(Pi.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),Pi=["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 nt(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function ot(e){let t={},r=Object.keys(e).sort((n,o)=>o.length-n.length);for(let n of r)t[n]=e[n];return t}function yn(e){return nt(e)&&(e.imports!==void 0?Lt(e.imports):!0)&&(e.scopes!==void 0?Tt(e.scopes):!0)}function Lt(e){return nt(e)}function Tt(e){return nt(e)&&Object.values(e).every(t=>kt(t))}function kt(e){return nt(e)}function st(e){try{return new URL(e),!0}catch{return!1}}function wn(e,t){let r={};for(let[n,o]of Object.entries(e)){let s=Oi(n,t);if(s===null)continue;if(typeof o!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let a=Ct(o,t);if(a===null){console.warn("the address was invalid."),r[s]=null;continue}if(n.endsWith("/")&&!ce(a).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]=ce(a)}return ot(r)}function ce(e){return e.href}function Mi(e,t){let r={};for(let[o,s]of Object.entries(e)){if(!kt(s))throw new TypeError("the value of the scope with prefix scopePrefix needs to be an object.");let a;try{a=new URL(o,t)}catch{console.warn("the scope prefix URL was not parseable.");continue}let i=ce(a);r[i]=wn(s,t)}let n={};for(let o of Object.keys(r))n[o]=ot(r[o]);return ot(n)}function Oi(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=Ct(e,t);return r!==null?ce(r):e}function Ct(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 Ai=["ftp","file","http","https","ws","wss"];function Si(e){return Ai.some(t=>ce(e).startsWith(t))}function bn(e,t,r){for(let[n,o]of Object.entries(r))if(n===e){if(o===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!st(o))throw new TypeError("resolutionResult must be an URL.");return o}else if(n.endsWith("/")&&e.startsWith(n)&&(t===null||Si(t))){if(o===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!st(o))throw new TypeError("resolutionResult must be an URL.");let s=e.slice(n.length);if(!o.endsWith("/"))throw new TypeError('resolutionResult does not end with "/"');try{let a=new URL(s,o);if(!st(a))throw new TypeError("url must be an URL.");if(!ce(a).startsWith(o))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return ce(a)}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 Pt(e,t){let r={};if(!yn(e))throw new TypeError("the top-level value needs to be a JSON object.");let{imports:n,scopes:o}=e;if(n!==void 0){if(!Lt(n))throw new TypeError('"imports" top-level key needs to be an object.');r=wn(n,t)}let s={};if(o!==void 0){if(!Tt(o))throw new TypeError('"scopes" top-level key needs to be an object.');s=Mi(o,t)}return Object.keys(e).find(a=>a!=="imports"&&a!=="scopes")&&console.warn("an invalid top-level key was present in the import map."),{imports:r,scopes:s}}function Mt(e,{imports:t={},scopes:r={}},n){let o=ce(n),s=Ct(e,n),a=s!==null?ce(s):e;for(let[l,u]of Object.entries(r))if(l===o||l.endsWith("/")&&o.startsWith(l)){let p=bn(a,s,u);if(p!==null)return p}let i=bn(a,s,t);if(i!==null)return i;if(s!==null)return ce(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}function te(e){if(typeof e!="string")throw new TypeError(Path must be a string. Received ${JSON.stringify(e)})}function Ot(e,t){if(t.length>=e.length)return e;let r=e.length-t.length;for(let n=t.length-1;n>=0;--n)if(e.charCodeAt(r+n)!==t.charCodeAt(n))return e;return e.slice(0,-t.length)}function At(e,t,r=0){let n=!1,o=e.length;for(let s=e.length-1;s>=r;--s)if(t(e.charCodeAt(s))){if(n){r=s+1;break}}else n||(n=!0,o=s+1);return e.slice(r,o)}function St(e,t){if(te(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(Suffix must be a string. Received ${JSON.stringify(t)})}function Se(e,t){if(e.length<=1)return e;let r=e.length;for(let n=e.length-1;n>0&&t(e.charCodeAt(n));n--)r=n;return e.slice(0,r)}function pe(e){return e===47||e===92}function ye(e){return e>=97&&e<=122||e>=65&&e<=90}function at(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError("Must be a file URL.");return e}function En(e){e=at(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 Nt(e){te(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return pe(r)?!0:!!(ye(r)&&t>2&&e.charCodeAt(1)===58&&pe(e.charCodeAt(2)))}var Hi={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function lt(e){return e.replaceAll(/[\s]/g,t=>Hi[t]??t)}function Ln(e){if(!Nt(e))throw new TypeError("Must be an absolute path.");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),n=new URL("file:///");if(n.pathname=lt(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(n.hostname=t,!n.hostname))throw new TypeError("Invalid hostname.");return n}function ie(e){return e===47}function _t(e,t=""){St(e,t);let r=At(e,ie),n=Se(r,ie);return t?Ot(n,t):n}function Ut(e){te(e);let t=-1,r=0,n=-1,o=!0,s=0;for(let a=e.length-1;a>=0;--a){let i=e.charCodeAt(a);if(ie(i)){if(!o){r=a+1;break}continue}n===-1&&(o=!1,n=a+1),i===46?t===-1?t=a:s!==1&&(s=1):t!==-1&&(s=-1)}return t===-1||n===-1||s===0||s===1&&t===n-1&&t===r+1?"":e.slice(t,n)}function kn(e){return e=at(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function jt(e){return te(e),e.length>0&&ie(e.charCodeAt(0))}function Cn(e){if(!jt(e))throw new TypeError("Must be an absolute path.");let t=new URL("file:///");return t.pathname=lt(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}var Zi=(()=>{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"})(),J=Zi==="windows";function Mn(e){return J?En(e):kn(e)}function ct(e){return J?Ln(e):Cn(e)}var On={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\","":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},ta=new RegExp([${Object.values(On).join("")}],"gu");function An(e){return e.replaceAll(ta,t=>Ont)}var Sn=e=>{if(e.protocol==="file:")return{path:Mn(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},$n=e=>e.namespace==="file"?ct(e.path):new URL(${e.namespace}:${e.path});function je(e){e.hash="",e.search=""}function Nn(e,t){return e=new URL(e),je(e),_t(e.href,t)}function In(e){return e=new URL(e),je(e),Ut(e.pathname)}var ra="base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx",_n=e=>ra.includes(e),Un=e=>{let t=e.url,r=Nn(t);if(_n(r))return r;if(r==="mjs")return"js";let n=In(t).slice(1);if(_n(n))return n;if(n==="mjs")return"js";let s=(e.headers.get("Content-Type")??"text/plain").split(";")0?.trim?.()??"text/plain";return na(s)},na=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"}};var Fn=e=>({name:"remote-resource",setup({onStart:t,onResolve:r,onLoad:n,initialOptions:o}){let{importMapURL:s,sources:a=[],progressCallback:i}=e??{},l={};t(async()=>{if(!s)return;let f=await jn(${s},e.fetch,a,e.reload,i);l=Pt(JSON.parse(f.contents),s)});let u=(o.external??[]).map(f=>new RegExp(An(f).replace(/\\\*/g,".*")));r({filter:/.*/},f=>{let w;if(f.importer!==""){if(f.namespace==="")throw new Error("assert namespace is empty");w=new URL(${f.namespace}:${f.importer})}else if(f.resolveDir!=="")w=new URL(${ct(f.resolveDir).href}/);else return;let E;if(l!==null){let D=Mt(f.path,l,new URL(w));E=new URL(D)}else E=new URL(f.path,w);let U={type:"resolve",external:!1,path:E.href};f.kind!=="entry-point"&&(U.parent=w.href);for(let D of u)if(D.test(E.href))return U.external=!0,i?.(U),U;return i?.(U),Sn(E)});let p=f=>jn($n(f).href,e.fetch,a,e.reload,i);n({filter:/.*/,namespace:"file"},p),n({filter:/.*/,namespace:"http"},p),n({filter:/.*/,namespace:"https"},p),n({filter:/.*/,namespace:"data"},p)}}),jn=async(e,t,r,n,o)=>{let s=r.find(u=>u.path===e);if(s!==void 0)return o?.({type:"load",path:e,done:Promise.resolve({size:new Blob(s.contents).size,isCache:!0})}),{contents:s.contents,loader:s.loader};let a=n?n===!0?!1:n.some(u=>u.test(e)):!0,i=t(new Request(e),a);o?.({type:"load",path:e,done:i.then((u,p)=>({size:parseInt(u.headers.get("Content-Length")??"0"),isCache:p}))});letl=await i;return{contents:await l.text(),loader:Un(l)}};var Bn,Dn=async(e,t)=>(Bn??=rt({wasmModule:e,workerURL:t}),await Bn,async(r,{extension:n,fileName:o,dirURL:s})=>{o??=codeblock-${Math.floor(16777214*Math.random()).toString(16)}.${hn(n)};let a=${s}${o},{outputFiles:i}=await et({entryPoints:a,format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[Fn({fetch:oa,reload:new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"}),sources:{path:a,contents:r}})],write:!1});return i0.text}),oa=async(e,t)=>{let r=xn(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let n=await mt(e);if(n)return n.url||Object.defineProperty(n,"url",{value:e.url}),n,!0}try{let n=await r(e);if(n.ok)return r===GM_fetch&&await zt(e,n),n,!1;throw new TypeError(${n.status} ${n.statusText})}catch(n){if(!(n instanceof TypeError))throw n;let o=await mt(e);if(o)return o.url||Object.defineProperty(o,"url",{value:e.url}),o,!0;throw n}};var Hn=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},qn=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},Kn=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},Gn=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var zn=()=>{let e;return{show:(n,{x:o,y:s})=>{e=sa(),e.append(ia(n)),e.style.visibility="hidden",document.body.append(e);let{height:a}=e.getBoundingClientRect();e.style.top=${s-a}px,e.style.left=${o}px,e.style.removeProperty("visibility")},hide:async()=>{e?.classList?.remove?.("in"),await new Promise(n=>setTimeout(n,150)),e?.remove?.()}}},sa=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},ia=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 Wn=()=>{let e=document.createElement("a");e.classList.add("tool-btn"),e.type="button",e.setAttribute("aria-haspopup","true");let t=!1,{show:r,hide:n}=zn();return{component:e,setStatus:async(s,a)=>{switch(e.textContent="",await n(),s){case"loading":e.append(Kn());break;case"pass":e.append(Hn());break;case"fail":e.append(qn());break;case"none":break}a!==void 0&&s!=="none"?(e.style.removeProperty("pointer-events"),e.onclick=async()=>{if(t)await n();else{let{top:i,left:l}=e.getBoundingClientRect();r(a,{y:i+globalThis.scrollY,x:l})}t=!t}):e.style.pointerEvents="none"}}};var Vn=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(Gn()),t.addEventListener("click",e),t};var Yn=e=>{let{component:t,setStatus:r}=Wn(),n=document.createElement("div");return n.style.position="absolute",n.style.left="-2em",n.style.zIndex="1",n.style.display="flex",n.style.flexFlow="column",n.append(Vn(e),t),{menu:n,setStatus:r}};function Qn(e){return new Promise(t=>setTimeout(t,e))}function Xn(e,t){let{trailing:r=!1,interval:n=0}=t??{},o,s=!1,a=u=>{o?.resolve?.({executed:!1}),o=u},i=()=>{let{...u}=o;return o=void 0,u},l=async()=>{if(s||!o)return;s=!0,n>0&&await Qn(n);let{parameters:u,resolve:p,reject:f}=i();try{let w=await e(...u);s=!1,p({result:w,executed:!0})}catch(w){s=!1,f(w)}finally{r?await l():(a(),await Promise.resolve())}};return(...u)=>new Promise((p,f)=>{a({parameters:u,resolve:p,reject:f}),l()})}var Jn=async(e,t)=>{let r=await Dn(e,t),n=[],s=Xn(async()=>{let a=Qr(scrapbox.Project.name,scrapbox.Page.title??"",ut());n.forEach(({menu:i,setStatus:l})=>{l("none"),i.remove()}),a.forEach(i=>{let l=i.lang.toLowerCase();gn(l)&&i.startIds.forEach(u=>{let p=document.getElementById(L${u}),{menu:f,setStatus:w}=Yn(async()=>{await w("loading");try{let E=await r(i.lines.join(` ),{extension:l,fileName:i.filename,dirURL:${i.dir}/});console.log("execute:",E),await Function(return (async()=>{${E}})()`)(),await w("pass")}catch(E){await w("fail",E.toString())}});n.push({menu:f,setStatus:w}),p?.insertBefore?.(f,p?.firstElementChild)})}),await Promise.resolve()},{interval:100,trailing:!0});return await s(),scrapbox.addListener("lines:changed",s),()=>{scrapbox.removeListener("lines:changed",s),n.forEach(({menu:a,setStatus:i})=>{i("none"),a.remove()})}};var Zn=async(e,t)=>{let r=await globalThis.caches.keys();for(let n of r.sort().reverse()){let s=await(await caches.open(n)).match(e,t);if(s)return s}},eo=async(e,t)=>{let n=(await globalThis.caches.keys()).filter(s=>s.startsWith("api")).sort().reverse().at(0);if(!n)return;await(await caches.open(n)).put(e,t.clone())};var aa="https://scrapbox.io/files/666e81c5c7e6f0001c6ab8db.wasm",la="https://scrapbox.io/api/code/yosider-scripts/esbuild-wasm-no-blob/worker.js";(async()=>{let e=new Request(aa),t=await Zn(e)||await ca(e);await Jn(await WebAssembly.compileStreaming(t),la)})();async function ca(e){let t=await fetch(e);return await eo(e,t),t} /** @license
* esbuild-wasm@v0.21.5
*
* 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.
*/