for-takker-memex
code:script.js
var Sx=Object.defineProperty;var mn=(e,t)=>{for(var r in t)Sx(e,r,{get:tr,enumerable:!0})};var Qc=e=>Px.includes(e.name),Px="SocketIOError","DuplicateTitleError","NotFastForwardError";var fn=async()=>{let t=(await _x())("https://scrapbox.io",{reconnectionDelay:5e3,transports:["websocket"]});return await new Promise((r,n)=>{let o=s=>n(s);t.once("connect",()=>{t.off("disconnect",o),r()}),t.once("disconnect",o)}),t},Rx="4.2.0",Zc=https://cdnjs.cloudflare.com/ajax/libs/socket.io/${Rx}/socket.io.min.js,li,_x=async()=>{if(li)throw li;if(!document.querySelector(script[src="${Zc}"])){let e=document.createElement("script");e.src=Zc,await new Promise((t,r)=>{e.onload=()=>t(),e.onerror=n=>{li=n,r(n)},document.head.append(e)})}return new Promise(e=>{let t=setInterval(()=>{io&&(clearInterval(t),e(io))},500)})};var pi=(e,t=9e4)=>{let r=(o,s)=>{let i;return new Promise((a,c)=>{let l=u=>{clearTimeout(i),c(new Error(u))};e.emit(o,s,u=>{switch(clearTimeout(i),e.off("disconnect",l),o){case"socket.io-request":"error"in u?typeof u.error=="object"&&u.error&&"name"in u.error&&typeof u.error.name=="string"&&Qc({name:u.error.name})?a({ok:!1,value:u.error}):a({ok:!1,value:{name:"UnexpectedError",value:u.error}}):"data"in u&&a({ok:!0,value:u.data});break;case"cursor":"error"in u?a({ok:!1,value:{name:"UnexpectedError",value:u.error}}):"data"in u&&a({ok:!0,value:u.data});break}c(new Error('Invalid response: missing "data" or "error" field'))}),i=setTimeout(()=>{e.off("disconnect",l),a({ok:!1,value:{name:"TimeoutError",message:Timeout: exceeded ${t}ms}})},t),e.once("disconnect",l)})};async function*n(...o){let s,i=()=>new Promise(c=>s=c),a=c=>{s?.(c)};for(let c of o)e.on(c,a);try{for(;;)yield await i()}finally{for(let c of o)e.off(c,a)}}return{request:r,response:n}};var Ne=()=>fn(),ui=async e=>{if(e.connected)return;let t=new Promise(r=>e.once("connect",()=>r()));e.connect(),await t},ve=async e=>{if(e.disconnected)return;let t=new Promise(r=>{let n=o=>{o==="io client disconnect"&&(r(),e.off("disconnect",n))};e.on("disconnect",n)});e.disconnect(),await t};var di=(e,t)=>{let r=e.length>t.length,n=r?t:e,o=r?e:t,s=n.length+1,i=n.length+o.length+3,a=new Array(i);a.fill(-1);let c=[];function l(h,x,v){let L=Math.max(x,v),S=L-h;for(;S<n.length&&L<o.length&&nS===oL;)++S,++L;return ah+s=c.length,c.push([{x:S,y:L},ah+(x>v?-1:1)+s]),L}let u=new Array(i);u.fill(-1);let p=-1,f=o.length-n.length;do{++p;for(let h=-p;h<=f-1;++h)uh+s=l(h,uh-1+s+1,uh+1+s);for(let h=f+p;h>=f+1;--h)uh+s=l(h,uh-1+s+1,uh+1+s);uf+s=l(f,uf-1+s+1,uf+1+s)}while(uf+s!==o.length);let d=[],g=af+s;for(;g!==-1;)d.push(cg0),g=cg1;return{from:e,to:t,editDistance:f+p*2,buildSES:function*(){let h=0,x=0;for(let{x:v,y:L}of Cx(d))for(;h<v||x<L;)L-v>x-h?(yield{value:ox,type:r?"deleted":"added"},++x):L-v<x-h?(yield{value:nh,type:r?"added":"deleted"},++h):(yield{value:nh,type:"common"},++h,++x)}}};function*mi(e){let t=[],r=[];function*n(){if(t.length>r.length){for(let o=0;o<r.length;o++)yield el(to,ro);for(let o=r.length;o<t.length;o++)yield to}else{for(let o=0;o<t.length;o++)yield el(to,ro);for(let o=t.length;o<r.length;o++)yield ro}t=[],r=[]}for(let o of e)switch(o.type){case"added":t.push(o);break;case"deleted":r.push(o);break;case"common":yield*n(),yield o;break}yield*n()}var el=(e,t)=>({value:e.value,oldValue:t.value,type:"replaced"});function*Cx(e){for(let t=e.length-1;t>=0;t--)yield et}var Y=e=>{let{fetch:t=globalThis.fetch,hostName:r="scrapbox.io",...n}=e;return{fetch:t,hostName:r,...n}};var tt=e=>e==null,Ir=e=>typeof e=="string",Pe=e=>typeof e=="number";var Mx=e=>typeof e=="object"&&e!==null,Dx=e=>Mx(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,tl=e=>{try{let t=typeof e=="string"?JSON.parse(e):e;return Dx(t)?t:!1}catch(t){if(t instanceof SyntaxError)return!1;throw t}};var St=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"},ae=async e=>{let t=e.clone(),r=await t.text(),n=tl(r);if(!n)throw new St(t);return{ok:!1,value:n}};var so=async e=>{let{sid:t,hostName:r,fetch:n}=Y(e??{}),o=new Request(https://${r}/api/users/me,t?{headers:{Cookie:Z(t)}}:void 0),s=await n(o);if(!s.ok)throw new St(s);return await s.json()};var Z=e=>connect.sid=${e},gt=async e=>globalThis._csrf?globalThis._csrf:(await so(e)).csrfToken;var rl=(e,t)=>{let{sid:r,hostName:n}=Y(t??{});return new Request(https://${n}/api/projects/${e},r?{headers:{Cookie:Z(r)}}:void 0)},nl=async e=>e.ok?{ok:!0,value:await e.json()}:ae(e),pt=async(e,t)=>{let{fetch:r}=Y(t??{}),n=rl(e,t),o=await r(n);return nl(o)};pt.toRequest=rl;pt.fromResponse=nl;var ol=(e,t)=>{let{sid:r,hostName:n}=Y(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:Z(r)}}:void 0)},sl=async e=>e.ok?{ok:!0,value:await e.json()}:ae(e),Nr=async(e,t)=>{let{fetch:r}=Y(t??{}),n=await r(ol(e,t));return sl(n)};Nr.toRequest=ol;Nr.fromResponse=sl;var ao,cl=async()=>{if(ao!==void 0)return ao;let e=await so();if(e.isGuest)throw new Error("this script can only be executed by Logged in users");return ao=e.id,ao},il=new Map,fi=async e=>{let t=il.get(e);if(t!==void 0)return t;let r=await pt(e);if(!r.ok){let{name:o,message:s}=r.value;throw new Error(${o} ${s})}let{id:n}=r.value;return il.set(e,n),n},al=e=>e.padStart(8,"0"),gi=e=>{let t=Math.floor(new Date().getTime()/1e3).toString(16),r=Math.floor(16777214*Math.random()).toString(16);return${al(t).slice(-8)}${e.slice(-6)}0000${al(r)}};function*hi(e,t,{userId:r}){let{buildSES:n}=di(e.map(({text:i})=>i),t),o=0,s=e0.id;for(let i of mi(n())){switch(i.type){case"added":yield{_insert:s,lines:{id:gi(r),text:i.value}};continue;case"deleted":yield{_delete:s,lines:-1};break;case"replaced":yield{_update:s,lines:{text:i.value}};break}o++,s=eo?.id??"_end"}}var Or={};mn(Or,{getTitle:()=>Jb,parse:()=>rt});var Ix=e=>({type:"title",text:e.rows0.text}),Nx=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(i=>i.text.substring(n+1)).join(` )}},Re=(e,{parseOnNested:t,parseOnQuoted:r,patterns:n})=>(o,s,i)=>{var a,c,l,u,p,f;if(!t&&s.nested)return(a=i?.())!==null&&a!==void 0?a:[];if(!r&&s.quoted)return(c=i?.())!==null&&c!==void 0?c:[];for(let d of n){let g=d.exec(o);if(g===null)continue;let h=o.substring(0,g.index),x=o.substring(g.index+((u=(l=g[0])===null||l===void 0?void 0:l.length)!==null&&u!==void 0?u:0)),v=e((p=g[0])!==null&&p!==void 0?p:"",s);return[...Ft(h,s),...v,...Ft(x,s)]}return(f=i?.())!==null&&f!==void 0?f:[]},Oe=e=>[{type:"plain",raw:e,text:e}],Ox=Re(Oe,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),$x=/^>.*$/,jx=(e,t)=>t.context==="table"?Oe(e,t):[{type:"quote",raw:e,nodes:Ft(e.substring(1),{...t,quoted:!0})}],Ax=Re(jx,{parseOnNested:!1,parseOnQuoted:!1,patterns:[$x]}),Fx=/^\? .+$/,Ux=(e,t)=>t.context==="table"?Oe(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],Bx=Re(Ux,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Fx]}),Hx=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,zx=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,qx=(e,t)=>{if(t.context==="table")return Oe(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}]},Wx=Re(qx,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Hx,zx]}),Kx=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function pl(e){return(t,r)=>{if(e==="strongIcon"&&r.context==="table")return Oe(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),i=s.startsWith("/")?"root":"relative",a=n.substring(o+5,n.length),c=a.startsWith("*")?parseInt(a.substring(1),10):1;return new Array(c).fill({}).map(()=>({path:s,pathType:i,type:e,raw:t}))}}var Gx=pl("icon"),Xx=Re(Gx,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Kx]}),Yx=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,Vx=pl("strongIcon"),Jx=Re(Vx,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Yx]}),Qx=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,Zx=(e,t)=>t.context==="table"?Oe(e,t):[{type:"strong",raw:e,nodes:Ft(e.substring(2,e.length-2),{...t,nested:!0})}],eb=Re(Zx,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Qx]}),tb=/\[\$ .+? \]/,rb=/\[\$ [^\]]+\]/,nb=(e,t)=>t.context==="table"?Oe(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],ob=Re(nb,{parseOnNested:!1,parseOnQuoted:!0,patterns:[tb,rb]}),sb=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,ib=(e,t)=>{if(t.context==="table")return Oe(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 i=n.split("*").length-1;s.delete("*"),s.add(*-${Math.min(i,10)})}return[{type:"decoration",raw:e,rawDecos:n,decos:Array.from(s),nodes:Ft(o,{...t,nested:!0})}]},ab=Re(ib,{parseOnNested:!1,parseOnQuoted:!0,patterns:[sb]}),cb=/.*?/,lb=(e,t)=>t.context==="table"?Oe(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],pb=Re(lb,{parseOnNested:!1,parseOnQuoted:!0,patterns:[cb]}),ub=/^[$%] .+$/,db=(e,t)=>{var r;if(t.context==="table")return Oe(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}]},mb=Re(db,{parseOnNested:!1,parseOnQuoted:!1,patterns:[ub]}),fb=/\[\s+\]/,gb=(e,t)=>t.context==="table"?Oe(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],hb=Re(gb,{parseOnNested:!1,parseOnQuoted:!0,patterns:[fb]}),xb=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,bb=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,yb=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,vb=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,wb=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||kb(e),kb=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),Eb=(e,t)=>{if(t.context==="table")return Oe(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,i]=wb(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:i}]},Tb=Re(Eb,{parseOnNested:!0,parseOnQuoted:!0,patterns:[xb,bb,yb,vb]}),Lb=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,Sb=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,Pb=/\[https?:\/\/[^\s\]]+\]/,Rb=/https?:\/\/[^\s]+/,_b=(e,t)=>{if(t.context==="table")return Oe(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()}]},Cb=Re(_b,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Lb,Sb,Pb,Rb]}),ul=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,dl=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,Mb=e=>{let[t="",r="",n=""]=e.split(","),o=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),i=/^Z\d+$/.test(n)?parseInt(n.replace(/^Z/,""),10):14;return{latitude:o,longitude:s,zoom:i}},Db=(e,t)=>{var r;if(t.context==="table")return Oe(e,t);let n=(r=e.match(ul))!==null&&r!==void 0?r:e.match(dl);if(n===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,s="",i=""]=o?n:[n[0],n[2],n[1]],{latitude:a,longitude:c,zoom:l}=Mb(s),u=i!==""?https://www.google.com/maps/place/${encodeURIComponent(i)}/@${a},${c},${l}z:https://www.google.com/maps/@${a},${c},${l}z;return[{type:"googleMap",raw:e,latitude:a,longitude:c,zoom:l,place:i,url:u}]},Ib=Re(Db,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ul,dl]}),Nb=/\[\/?[^[\]]+\]/,Ob=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},$b=Re(Ob,{parseOnNested:!0,parseOnQuoted:!0,patterns:[Nb]}),jb=/(?:^|\s)#\S+/,Ab=(e,t)=>{if(t.context==="table")return Oe(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[...Oe(r,t),{type:"hashTag",raw:n,href:n.substring(1)}]},Fb=Re(Ab,{parseOnNested:!0,parseOnQuoted:!0,patterns:[jb]}),Ub=/^[0-9]+\. .*$/,Bb=(e,t)=>{if(t.context==="table")return Oe(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:Ft(s,{...t,nested:!0})}]},Hb=Re(Bb,{parseOnNested:!1,parseOnQuoted:!1,patterns:[Ub]}),zb=(e,t,r)=>{var n;return e===""?[]:(n=r?.())!==null&&n!==void 0?n:[]},qb=(...e)=>(t,r)=>e.reduceRight((n,o)=>()=>o(t,r,n),()=>Ox(t,r))(),Ft=qb(zb,Ax,Bx,pb,mb,ob,hb,ab,Wx,Jx,eb,Tb,Cb,Xx,Ib,$b,Fb,Hb),Wb=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(i=>i.text.substring(n+1)).map(i=>i.split(" ").map(a=>Ft(a,{nested:!1,quoted:!1,context:"table"})))}},Kb=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:Ft(r.substring(t),{nested:!1,quoted:!1,context:"line"})}},Gb=e=>{switch(e.type){case"title":return Ix(e);case"codeBlock":return Nx(e);case"table":return Wb(e);case"line":return Kb(e)}},Xb=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}}),Yb=(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)},ll=(e,t)=>{let r=e[e.length-1];return r!==void 0&&Yb(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)},Vb=(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(ll,[])]}return e.reduce(ll,[])},rt=(e,t)=>{var r;let n=Xb(e);return Vb(n,{hasTitle:(r=t?.hasTitle)!==null&&r!==void 0?r:!0}).map(Gb)},Jb=e=>{var t,r;return(r=(t=/^\s*\S.*$/m.exec(e)?.[0])===null||t===void 0?void 0:t.trim())!==null&&r!==void 0?r:"Untitled"};var X=e=>e.replaceAll(" ","_").toLowerCase();var Q=e=>[...e].map((t,r)=>t===" "?"_":!Qb.includes(t)||r===e.length-1&&Zb.includes(t)?encodeURIComponent(t):t).join(""),Qb='@$&+=:;",',Zb=':;",';var ey=/https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/,ty=/https?:\/\/youtu\.be\/([a-zA-Z\d_-]+)(?:\?([^\s]{0,100})|)/,ry=/https?:\/\/(?:www\.|)youtube\.com\/shorts\/([a-zA-Z\d_-]+)(?:\?([^\s]+)|)/,ny=/https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:[^\s]+&|)list=([a-zA-Z\d_-]+)(?:&[^\s]+|))/,co=e=>{if(ey.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(ty);if(t){let[,r,n]=t;return{videoId:r,params:new URLSearchParams(n),pathType:"dotbe"}}}{let t=e.match(ry);if(t){let[,r,n]=t;return{videoId:r,params:new URLSearchParams(n),pathType:"short"}}}{let t=e.match(ny);if(t){let[,r,n]=t;return{listId:n,params:new URLSearchParams(r),pathType:"list"}}}};var fl=e=>{let t=rt(e,{hasTitle:!0}).flatMap(g=>{switch(g.type){case"codeBlock":case"title":return[];case"line":case"table":return g}}),r=new Map,n=[],o=new Set,s=[],i=new Set,a=[],c=null,l=new Set,u=new Set,p=new RegExp(${location?.origin??"https://scrapbox.io"}/files/([a-z0-9]{24})(?:|\\.[a-zA-Z0-9]+)(?:|\\?[^\\s]*)$),f=g=>{switch(g.type){case"hashTag":if(r.has(X(g.href)))return;r.set(X(g.href),!1),n.push(g.href);return;case"link":switch(g.pathType){case"relative":{let h=ml(g.href);if(r.get(X(h)))return;r.set(X(h),!0),n.push(h);return}case"root":{let h=ml(g.href);if(/^\/[\w\d-]+\/?$/.test(h)||o.has(X(h)))return;o.add(X(h)),s.push(h);return}case"absolute":{if(g.content)return;let h=co(g.href);if(h&&h.pathType!=="list"){c??=https://i.ytimg.com/vi/${h.videoId}/mqdefault.jpg;return}let x=g.href.match(p)?.[1];x&&l.add(x);return}default:return}case"icon":case"strongIcon":{if(g.pathType==="root"||i.has(X(g.path)))return;i.add(X(g.path)),a.push(g.path);return}case"image":case"strongImage":{c??=g.src.endsWith("/thumb/1000")?g.src.replace(/\/thumb\/1000$/,"/raw"):g.src;{let h=g.src.match(p)?.[1];h&&l.add(h)}if(g.type==="image"){let h=g.link.match(p)?.[1];h&&l.add(h)}return}case"helpfeel":u.add(g.text);return;case"numberList":case"strong":case"quote":case"decoration":{for(let h of g.nodes)f(h);return}default:return}},d=[];for(let g of t)switch(g.type){case"line":for(let h of g.nodes)f(h);continue;case"table":{for(let h of g.cells)for(let x of h)for(let v of x)f(v);if(!["infobox","cosense"].includes(g.fileName))continue;d.push(...g.cells.map(h=>h.map(x=>x.map(v=>v.raw).join("")).join(" ").trim()));continue}}return[n,s,a,c,[...l],[...u],d]},ml=e=>e.replace(/#[a-f\d]{24,32}$/,""),gl=e=>e.flatMap(({text:t})=>/^\s*\? .*$/.test(t)?[t.trimStart().slice(2)]:[]);var Zt=(e,t)=>e.length===t.length&&e.every(r=>t.includes(r));function*hl(e,t,r){let n=t.flatMap(d=>d.split( ));for(let d of hi(e.lines,n,{userId:r}))yield d;(e.lines[0].text!==n[0]||!e.persistent)&&(yield{title:n[0]});let o=e.lines.slice(1,6).map(d=>d.text),s=n.slice(1,6);o.join("")!==s.join("")&&(yield{descriptions:s});let[i,a,c,l,u,p,f]=fl(n.join(
));Zt(e.links,i)||(yield{links:i}),Zt(e.projectLinks,a)||(yield{projectLinks:a}),Zt(e.icons,c)||(yield{icons:c}),e.image!==l&&(yield{image:l}),Zt(e.files,u)||(yield{files:u}),Zt(gl(e.lines),p)||(yield{helpfeels:p}),Zt(e.infoboxDefinition,f)||(yield{infoboxDefinition:f})}var xl=(e,t,r)=>{let{sid:n,hostName:o,followRename:s,projects:i}=Y(r??{}),a=new URLSearchParams;a.append("followRename",${s??!0});for(let l of i??[])a.append("projects",l);let c=https://${o}/api/pages/${e}/${Q(t)}?${a.toString()};return new Request(c,n?{headers:{Cookie:Z(n)}}:void 0)},bl=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."}}:ae(e),Ge=async(e,t,r)=>{let{fetch:n}=Y(r??{}),o=xl(e,t,r),s=await n(o);return await bl(s)};Ge.toRequest=xl;Ge.fromResponse=bl;var yl=(e,t)=>{let{sid:r,hostName:n,sort:o,limit:s,skip:i}=Y(t??{}),a=new URLSearchParams;o!==void 0&&a.append("sort",o),s!==void 0&&a.append("limit",${s}),i!==void 0&&a.append("skip",${i});let c=https://${n}/api/pages/${e}?${a.toString()};return new Request(c,r?{headers:{Cookie:Z(r)}}:void 0)},vl=async e=>e.ok?{ok:!0,value:await e.json()}:ae(e),wl=async(e,t)=>{let{fetch:r}=Y(t??{}),n=await r(yl(e,t));return await vl(n)};wl.toRequest=yl;wl.fromResponse=vl;var lo=async(e,t)=>{let r=await Ge(e,t);if(!r.ok)throw new Error(You have no privilege of editing "/${e}/${t}".);return r.value};var ie=e=>new Promise(t=>setTimeout(()=>t(),e));var er=async(e,t,r,n)=>{let o=n?.socket,s=o??await fn();await ui(s);try{let i=await Promise.all([lo(e,t),fi(e),cl()]).then(([p,f,d])=>({...p,projectId:f,userId:d})),{request:a}=pi(s),c=0,l=[],u;for(;n?.maxAttempts===void 0||c<n.maxAttempts;){let p=r(i,c,l,u);if(l=p instanceof Promise?await p:p,c++,l.length===0)return{ok:!0,value:i.commitId};let f={kind:"page",projectId:i.projectId,pageId:i.id,parentId:i.commitId,userId:i.userId,changes:l,cursor:null,freeze:!0};for(;;){let d=await a("socket.io-request",{method:"commit",data:f});if(d.ok)return i.commitId=d.value.commitId,{ok:!0,value:i.commitId};let g=d.value.name;if(g==="UnexpectedError"){let h=new Error;throw h.name=d.value.name,h.message=JSON.stringify(d.value),h}if(g==="TimeoutError"||g==="SocketIOError"){await ie(3e3);continue}g==="NotFastForwardError"&&(await ie(1e3),i={...await lo(e,t),projectId:i.projectId,userId:i.userId}),u=g;break}}return{ok:!1,value:{name:"RetryError",attempts:c,message:Retrying exceeded the maxAttempts (${c}).}}}finally{o||await ve(s)}};var kl=e=>{let t=e.match(/(.+?)(?:_(\d+))?$/),r=t?.[1]??e,n=t?.[2]?parseInt(t[2])+1:2;return${r}_${n}};var re=(e,t,r,n)=>er(e,t,async(o,s,i,a)=>{if(a==="DuplicateTitleError"){let u=kl(t);return i.map(p=>("title"in p&&(p.title=u),p))}let c=r(o.lines,{...o,attempts:s}),l=c instanceof Promise?await c:c;return l===void 0?[]:l.length===0?[{deleted:!0}]:[...hl(o,l,o.userId)]},n);var El=(e,t,r)=>er(e,t,n=>n.persistent?[{deleted:!0}]:[],r);var Tl=(e,t,r,n)=>{let{sid:o,hostName:s}=Y(n??{}),i=https://${s}/api/table/${e}/${Q(t)}/${encodeURIComponent(r)}.csv;return new Request(i,o?{headers:{Cookie:Z(o)}}:void 0)},Ll=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:ae(e),Sl=async(e,t,r,n)=>{let{fetch:o}=Y(n??{}),s=Tl(e,t,r,n),i=await o(s);return await Ll(i)};Sl.toRequest=Tl;Sl.fromResponse=Ll;var po=async(e,t,r,n)=>{let{sid:o,hostName:s,fetch:i,csrf:a}=Y(n??{}),c=new Request(https://${s}/api/pages/${e}/replace/links,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":a??await gt(n),...o?{Cookie:Z(o)}:{}},body:JSON.stringify({from:t,to:r})}),l=await i(c);if(!l.ok)return ae(l);let{message:u}=await l.json();return{ok:!0,value:parseInt(u.match(/\d+/)?.[0]??"0")}};var Pl=async(e,t)=>{let{sid:r,hostName:n,fetch:o,followingId:s}=Y(t??{}),i=new Request(https://${n}/api/pages/${e}/search/titles${s??followingId=${s}:""},r?{headers:{Cookie:Z(r)}}:void 0),a=await o(i);return a.ok?{ok:!0,value:{pages:await a.json(),followingId:a.headers.get("X-following-id")??""}}:a.status===422?{ok:!1,value:{name:"InvalidFollowingIdError",message:await a.text()}}:ae(a)};var Rl=async(e,t,r)=>{let{sid:n,hostName:o,fetch:s}=Y(r??{}),i=new Request(https://${o}/api/pages/${t}/search/query?q=${encodeURIComponent(e)},n?{headers:{Cookie:Z(n)}}:void 0),a=await s(i);return a.ok?{ok:!0,value:await a.json()}:a.status===422?{ok:!1,value:{name:"NoQueryError",message:(await a.json()).message}}:ae(a)};var _l=async(e,t)=>{let{sid:r,hostName:n,fetch:o,csrf:s}=Y(t??{}),i=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 gt(t),...r?{Cookie:Z(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await o(i);if(!a.ok)return a.status===422?{ok:!1,value:{name:"InvalidURLError",message:(await a.json()).message}}:ae(a);let{title:c}=await a.json();return{ok:!0,value:c}};var Cl=async(e,t)=>{let{sid:r,hostName:n,fetch:o,csrf:s}=Y(t??{}),i=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 gt(t),...r?{Cookie:Z(r)}:{}},body:JSON.stringify({timeout:3e3})}),a=await o(i);return a.ok?{ok:!0,value:await a.json()}:a.status===422?{ok:!1,value:{name:"InvalidURLError",message:(await a.json()).message}}:ae(a)};var Ml=async e=>{let{sid:t,hostName:r,gyazoTeamsName:n}=Y(e??{}),o=new Request(https://${r}/api/login/gyazo/oauth-upload/token${n??gyazoTeamsName=${n}:""},t?{headers:{Cookie:Z(t)}}:void 0),s=await fetch(o);if(!s.ok)return ae(s);let{token:i}=await s.json();return{ok:!0,value:i}};var Dl=(e,t,r,n)=>{let{sid:o,hostName:s}=Y(n??{}),i=https://${s}/api/code/${e}/${Q(t)}/${Q(r)};return new Request(i,o?{headers:{Cookie:Z(o)}}:void 0)},Il=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"}}:ae(e),$r=async(e,t,r,n)=>{let{fetch:o}=Y(n??{}),s=Dl(e,t,r,n),i=await o(s);return await Il(i)};$r.toRequest=Dl;$r.fromResponse=Il;var Nl=new TextEncoder().encode("0123456789abcdef");function Ol(e){let t=new Uint8Array(e.length*2);for(let r=0;r<t.length;r++){let n=e[r];t[r*2]=Nl[n>>4],t[r*2+1]=Nl[n&15]}return t}var $l="md5: data is invalid type",tr=64,gn=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(tr),this.#i=0,this.#s=0,this.#a=0}#l(t){let r=this.#s;r+=t,r>4294967295&&(this.#a+=1),this.#s=r>>>0}#c(t){let r=this.#e,n=this.#t,o=this.#r,s=this.#n,i=M=>t[M]|t[M+1]<<8|t[M+2]<<16|t[M+3]<<24,a=(M,B)=>M<<B|M>>>32-B,c=i(0),l=i(4),u=i(8),p=i(12),f=i(16),d=i(20),g=i(24),h=i(28),x=i(32),v=i(36),L=i(40),S=i(44),b=i(48),k=i(52),w=i(56),C=i(60);r=n+a(((o^s)&n^s)+r+c+3614090360,7),s=r+a(((n^o)&r^o)+s+l+3905402710,12),o=s+a(((r^n)&s^n)+o+u+606105819,17),n=o+a(((s^r)&o^r)+n+p+3250441966,22),r=n+a(((o^s)&n^s)+r+f+4118548399,7),s=r+a(((n^o)&r^o)+s+d+1200080426,12),o=s+a(((r^n)&s^n)+o+g+2821735955,17),n=o+a(((s^r)&o^r)+n+h+4249261313,22),r=n+a(((o^s)&n^s)+r+x+1770035416,7),s=r+a(((n^o)&r^o)+s+v+2336552879,12),o=s+a(((r^n)&s^n)+o+L+4294925233,17),n=o+a(((s^r)&o^r)+n+S+2304563134,22),r=n+a(((o^s)&n^s)+r+b+1804603682,7),s=r+a(((n^o)&r^o)+s+k+4254626195,12),o=s+a(((r^n)&s^n)+o+w+2792965006,17),n=o+a(((s^r)&o^r)+n+C+1236535329,22),r=n+a(((n^o)&s^o)+r+l+4129170786,5),s=r+a(((r^n)&o^n)+s+g+3225465664,9),o=s+a(((s^r)&n^r)+o+S+643717713,14),n=o+a(((o^s)&r^s)+n+c+3921069994,20),r=n+a(((n^o)&s^o)+r+d+3593408605,5),s=r+a(((r^n)&o^n)+s+L+38016083,9),o=s+a(((s^r)&n^r)+o+C+3634488961,14),n=o+a(((o^s)&r^s)+n+f+3889429448,20),r=n+a(((n^o)&s^o)+r+v+568446438,5),s=r+a(((r^n)&o^n)+s+w+3275163606,9),o=s+a(((s^r)&n^r)+o+p+4107603335,14),n=o+a(((o^s)&r^s)+n+x+1163531501,20),r=n+a(((n^o)&s^o)+r+k+2850285829,5),s=r+a(((r^n)&o^n)+s+u+4243563512,9),o=s+a(((s^r)&n^r)+o+h+1735328473,14),n=o+a(((o^s)&r^s)+n+b+2368359562,20),r=n+a((n^o^s)+r+d+4294588738,4),s=r+a((r^n^o)+s+x+2272392833,11),o=s+a((s^r^n)+o+S+1839030562,16),n=o+a((o^s^r)+n+w+4259657740,23),r=n+a((n^o^s)+r+l+2763975236,4),s=r+a((r^n^o)+s+f+1272893353,11),o=s+a((s^r^n)+o+h+4139469664,16),n=o+a((o^s^r)+n+L+3200236656,23),r=n+a((n^o^s)+r+k+681279174,4),s=r+a((r^n^o)+s+c+3936430074,11),o=s+a((s^r^n)+o+p+3572445317,16),n=o+a((o^s^r)+n+g+76029189,23),r=n+a((n^o^s)+r+v+3654602809,4),s=r+a((r^n^o)+s+b+3873151461,11),o=s+a((s^r^n)+o+C+530742520,16),n=o+a((o^s^r)+n+u+3299628645,23),r=n+a((o^(n|~s))+r+c+4096336452,6),s=r+a((n^(r|~o))+s+h+1126891415,10),o=s+a((r^(s|~n))+o+w+2878612391,15),n=o+a((s^(o|~r))+n+d+4237533241,21),r=n+a((o^(n|~s))+r+b+1700485571,6),s=r+a((n^(r|~o))+s+p+2399980690,10),o=s+a((r^(s|~n))+o+L+4293915773,15),n=o+a((s^(o|~r))+n+l+2240044497,21),r=n+a((o^(n|~s))+r+x+1873313359,6),s=r+a((n^(r|~o))+s+C+4264355552,10),o=s+a((r^(s|~n))+o+g+2734768916,15),n=o+a((s^(o|~r))+n+k+1309151649,21),r=n+a((o^(n|~s))+r+f+4149444226,6),s=r+a((n^(r|~o))+s+S+3174756917,10),o=s+a((r^(s|~n))+o+u+718787259,15),n=o+a((s^(o|~r))+n+v+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($l);else throw new TypeError($l);let n=this.#i,o=tr-n;if(r.length<o)this.#o.set(r,n),n+=r.length;else{this.#o.set(r.slice(0,o),n),this.#c(this.#o);let s=o;for(;s+tr<=r.length;)this.#c(r.slice(s,s+tr)),s+=tr;this.#o.fill(0).set(r.slice(s),0),n=r.length-s}return this.#i=n,this.#l(r.length),this}digest(){let t=tr-this.#i;t<9&&(t+=tr);let r=new Uint8Array(t);r[0]=128;let n=this.#s<<3,o=this.#a<<3|this.#s>>>29;r[r.length-8]=n&255,r[r.length-7]=n>>>8&255,r[r.length-6]=n>>>16&255,r[r.length-5]=n>>>24&255,r[r.length-4]=o&255,r[r.length-3]=o>>>8&255,r[r.length-2]=o>>>16&255,r[r.length-1]=o>>>24&255,this.update(r.buffer);let s=new ArrayBuffer(16),i=new DataView(s);return i.setUint32(0,this.#e,!0),i.setUint32(4,this.#t,!0),i.setUint32(8,this.#r,!0),i.setUint32(12,this.#n,!0),s}toString(t="hex"){let r=this.digest();switch(t){case"hex":return new TextDecoder().decode(Ol(new Uint8Array(r)));case"base64":{let n=new Uint8Array(r),o="";for(let s=0;s<n.length;++s)o+=String.fromCharCode(n[s]);return btoa(o)}default:throw new Error("md5: invalid format")}}};var jl=async(e,t,r)=>{let n=new gn().update(await e.arrayBuffer()).toString(),o=await ay(e,t,n,r);if(!o.ok)return o;if("embedUrl"in o.value)return{ok:!0,value:o.value};let s=await cy(o.value.signedUrl,e,r);return s.ok?ly(t,o.value.fileId,n,r):s},ay=async(e,t,r,n)=>{let{sid:o,hostName:s,fetch:i,csrf:a}=Y(n??{}),c={md5:r,size:e.size,contentType:e.type,name:e.name},l=a??await gt(),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":l,...o?{Cookie:Z(o)}:{}}}),p=await i(u);return p.ok?{ok:!0,value:await p.json()}:ae(p)},cy=async(e,t,r)=>{let{sid:n,fetch:o}=Y(r??{}),s=await o(e,{method:"PUT",body:t,headers:{"Content-Type":t.type,...n?{Cookie:Z(n)}:{}}});if(!s.ok){if(s.headers.get("Content-Type")?.includes?.("/xml"))return{ok:!1,value:{name:"GCSError",message:await s.text()}};throw new St(s)}return{ok:!0,value:void 0}},ly=async(e,t,r,n)=>{let{sid:o,hostName:s,fetch:i,csrf:a}=Y(n??{}),c=a??await gt(),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":c,...o?{Cookie:Z(o)}:{}}}),u=await i(l);if(!u.ok){try{if(u.status===404)return{ok:!1,value:{name:"NotFoundError",message:(await u.json()).message}}}catch{throw new St(u)}throw new St(u)}return{ok:!0,value:await u.json()}};var Al=async e=>{let t=e.title??".watchlistrc",r="projectsLastAccessed.json",n=await $r(e.project,t,r),o=n.ok?JSON.parse(n.value):{},s=JSON.parse(localStorage.getItem("projectsLastAccessed")??"{}"),i=new Set([...Object.keys(o),...Object.keys(s)]),a=Object.fromEntries([...i].map(l=>[l,Math.max(o[l]??0,s[l]??0)]).sort((l,u)=>u[1]-l[1])),c=JSON.stringify(a);localStorage.setItem("projectsLastAccessed",c),await re(e.project,t,()=>[t,"This page is automatically generated. DO NOT EDIT ANYTHING, WHITCH WILL BE OVERWRITTEN.","",code:${r}, ${c},""])};scrapbox.PageMenu.addMenu({title:"Gyazo",image:"https://i.gyazo.com/503a911fea542532aa5aba0a88eb7b60.png",onClick:()=>window.open("https://gyazo.com/captures")});var ho,pe,Hl,py,rr,Fl,zl,xi,ki,bi,yi,ql,hn={},Wl=[],uy=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ei=Array.isArray;function Ut(e,t){for(var r in t)e[r]=t[r];return e}function Kl(e){var t=e.parentNode;t&&t.removeChild(e)}function m(e,t,r){var n,o,s,i={};for(s in t)s=="key"?n=t[s]:s=="ref"?o=t[s]:i[s]=t[s];if(arguments.length>2&&(i.children=arguments.length>3?ho.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 mo(e,i,n,o,null)}function mo(e,t,r,n,o){var s={type:e,props:t,key:r,ref:n,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,constructor:void 0,__v:o??++Hl,__i:-1,__u:0};return o==null&&pe.vnode!=null&&pe.vnode(s),s}function W(e){return e.children}function fo(e,t){this.props=e,this.context=t}function nr(e,t){if(t==null)return e.__?nr(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"?nr(e):null}function Gl(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 Gl(e)}}function vi(e){(!e.__d&&(e.__d=!0)&&rr.push(e)&&!go.__r++||Fl!==pe.debounceRendering)&&((Fl=pe.debounceRendering)||zl)(go)}function go(){var e,t,r,n,o,s,i,a;for(rr.sort(xi);e=rr.shift();)e.__d&&(t=rr.length,n=void 0,s=(o=(r=e).__v).__e,i=[],a=[],r.__P&&((n=Ut({},o)).__v=o.__v+1,pe.vnode&&pe.vnode(n),Ti(r.__P,n,o,r.__n,r.__P.namespaceURI,32&o.__u?[s]:null,i,s??nr(o),!!(32&o.__u),a),n.__v=o.__v,n.__.__k[n.__i]=n,Vl(i,n,a),n.__e!=s&&Gl(n)),rr.length>t&&rr.sort(xi));go.__r=0}function Xl(e,t,r,n,o,s,i,a,c,l,u){var p,f,d,g,h,x=n&&n.__k||Wl,v=t.length;for(r.__d=c,dy(r,t,x),c=r.__d,p=0;p<v;p++)(d=r.__k[p])!=null&&typeof d!="boolean"&&typeof d!="function"&&(f=d.__i===-1?hn:x[d.__i]||hn,d.__i=p,Ti(e,d,f,o,s,i,a,c,l,u),g=d.__e,d.ref&&f.ref!=d.ref&&(f.ref&&Li(f.ref,null,d),u.push(d.ref,d.__c||g,d)),h==null&&g!=null&&(h=g),65536&d.__u||f.__k===d.__k?(c&&typeof d.type=="string"&&!e.contains(c)&&(c=nr(f)),c=Yl(d,c,e)):typeof d.type=="function"&&d.__d!==void 0?c=d.__d:g&&(c=g.nextSibling),d.__d=void 0,d.__u&=-196609);r.__d=c,r.__e=h}function dy(e,t,r){var n,o,s,i,a,c=t.length,l=r.length,u=l,p=0;for(e.__k=[],n=0;n<c;n++)i=n+p,(o=e.__k[n]=(o=t[n])==null||typeof o=="boolean"||typeof o=="function"?null:typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?mo(null,o,null,null,null):Ei(o)?mo(W,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?mo(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o)!=null?(o.__=e,o.__b=e.__b+1,a=my(o,r,i,u),o.__i=a,s=null,a!==-1&&(u--,(s=r[a])&&(s.__u|=131072)),s==null||s.__v===null?(a==-1&&p--,typeof o.type!="function"&&(o.__u|=65536)):a!==i&&(a==i-1?p=a-i:a==i+1?p++:a>i?u>c-i?p+=a-i:p--:a<i&&p++,a!==n+p&&(o.__u|=65536))):(s=r[i])&&s.key==null&&s.__e&&!(131072&s.__u)&&(s.__e==e.__d&&(e.__d=nr(s)),wi(s,s,!1),r[i]=null,u--);if(u)for(n=0;n<l;n++)(s=r[n])!=null&&!(131072&s.__u)&&(s.__e==e.__d&&(e.__d=nr(s)),wi(s,s))}function Yl(e,t,r){var n,o;if(typeof e.type=="function"){for(n=e.__k,o=0;n&&o<n.length;o++)n[o]&&(n[o].__=e,t=Yl(n[o],t,r));return t}e.__e!=t&&(r.insertBefore(e.__e,t||null),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType===8);return t}function my(e,t,r,n){var o=e.key,s=e.type,i=r-1,a=r+1,c=t[r];if(c===null||c&&o==c.key&&s===c.type&&!(131072&c.__u))return r;if(n>(c!=null&&!(131072&c.__u)?1:0))for(;i>=0||a<t.length;){if(i>=0){if((c=t[i])&&!(131072&c.__u)&&o==c.key&&s===c.type)return i;i--}if(a<t.length){if((c=t[a])&&!(131072&c.__u)&&o==c.key&&s===c.type)return a;a++}}return-1}function Ul(e,t,r){t[0]==="-"?e.setProperty(t,r??""):e[t]=r==null?"":typeof r!="number"||uy.test(t)?r:r+"px"}function uo(e,t,r,n,o){var s;e:if(t==="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof n=="string"&&(e.style.cssText=n=""),n)for(t in n)r&&t in r||Ul(e.style,t,"");if(r)for(t in r)n&&r[t]===n[t]||Ul(e.style,t,r[t])}else if(t[0]==="o"&&t[1]==="n")s=t!==(t=t.replace(/(PointerCapture)$|Capture$/i,"$1")),t=t.toLowerCase()in e||t==="onFocusOut"||t==="onFocusIn"?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=r,r?n?r.u=n.u:(r.u=ki,e.addEventListener(t,s?yi:bi,s)):e.removeEventListener(t,s?yi:bi,s);else{if(o=="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 Bl(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t.t==null)t.t=ki++;else if(t.t<r.u)return;return r(pe.event?pe.event(t):t)}}}function Ti(e,t,r,n,o,s,i,a,c,l){var u,p,f,d,g,h,x,v,L,S,b,k,w,C,M,B,P=t.type;if(t.constructor!==void 0)return null;128&r.__u&&(c=!!(32&r.__u),s=[a=t.__e=r.__e]),(u=pe.__b)&&u(t);e:if(typeof P=="function")try{if(v=t.props,L="prototype"in P&&P.prototype.render,S=(u=P.contextType)&&n[u.__c],b=u?S?S.props.value:u.__:n,r.__c?x=(p=t.__c=r.__c).__=p.__E:(L?t.__c=p=new P(v,b):(t.__c=p=new fo(v,b),p.constructor=P,p.render=gy),S&&S.sub(p),p.props=v,p.state||(p.state={}),p.context=b,p.__n=n,f=p.__d=!0,p.__h=[],p._sb=[]),L&&p.__s==null&&(p.__s=p.state),L&&P.getDerivedStateFromProps!=null&&(p.__s==p.state&&(p.__s=Ut({},p.__s)),Ut(p.__s,P.getDerivedStateFromProps(v,p.__s))),d=p.props,g=p.state,p.__v=t,f)L&&P.getDerivedStateFromProps==null&&p.componentWillMount!=null&&p.componentWillMount(),L&&p.componentDidMount!=null&&p.__h.push(p.componentDidMount);else{if(L&&P.getDerivedStateFromProps==null&&v!==d&&p.componentWillReceiveProps!=null&&p.componentWillReceiveProps(v,b),!p.__e&&(p.shouldComponentUpdate!=null&&p.shouldComponentUpdate(v,p.__s,b)===!1||t.__v===r.__v)){for(t.__v!==r.__v&&(p.props=v,p.state=p.__s,p.__d=!1),t.__e=r.__e,t.__k=r.__k,t.__k.forEach(function(T){T&&(T.__=t)}),k=0;k<p._sb.length;k++)p.__h.push(p._sb[k]);p._sb=[],p.__h.length&&i.push(p);break e}p.componentWillUpdate!=null&&p.componentWillUpdate(v,p.__s,b),L&&p.componentDidUpdate!=null&&p.__h.push(function(){p.componentDidUpdate(d,g,h)})}if(p.context=b,p.props=v,p.__P=e,p.__e=!1,w=pe.__r,C=0,L){for(p.state=p.__s,p.__d=!1,w&&w(t),u=p.render(p.props,p.state,p.context),M=0;M<p._sb.length;M++)p.__h.push(p._sb[M]);p._sb=[]}else do p.__d=!1,w&&w(t),u=p.render(p.props,p.state,p.context),p.state=p.__s;while(p.__d&&++C<25);p.state=p.__s,p.getChildContext!=null&&(n=Ut(Ut({},n),p.getChildContext())),L&&!f&&p.getSnapshotBeforeUpdate!=null&&(h=p.getSnapshotBeforeUpdate(d,g)),Xl(e,Ei(B=u!=null&&u.type===W&&u.key==null?u.props.children:u)?B:[B],t,r,n,o,s,i,a,c,l),p.base=t.__e,t.__u&=-161,p.__h.length&&i.push(p),x&&(p.__E=p.__=null)}catch(T){t.__v=null,c||s!=null?(t.__e=a,t.__u|=c?160:32,s[s.indexOf(a)]=null):(t.__e=r.__e,t.__k=r.__k),pe.__e(T,t,r)}else s==null&&t.__v===r.__v?(t.__k=r.__k,t.__e=r.__e):t.__e=fy(r.__e,t,r,n,o,s,i,c,l);(u=pe.diffed)&&u(t)}function Vl(e,t,r){t.__d=void 0;for(var n=0;n<r.length;n++)Li(r[n],r[++n],r[++n]);pe.__c&&pe.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(s){s.call(o)})}catch(s){pe.__e(s,o.__v)}})}function fy(e,t,r,n,o,s,i,a,c){var l,u,p,f,d,g,h,x=r.props,v=t.props,L=t.type;if(L==="svg"?o="http://www.w3.org/2000/svg":L==="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((d=s[l])&&"setAttribute"in d==!!L&&(L?d.localName===L:d.nodeType===3)){e=d,s[l]=null;break}}if(e==null){if(L===null)return document.createTextNode(v);e=document.createElementNS(o,L,v.is&&v),s=null,a=!1}if(L===null)x===v||a&&e.data===v||(e.data=v);else{if(s=s&&ho.call(e.childNodes),x=r.props||hn,!a&&s!=null)for(x={},l=0;l<e.attributes.length;l++)x[(d=e.attributes[l]).name]=d.value;for(l in x)if(d=x[l],l!="children"){if(l=="dangerouslySetInnerHTML")p=d;else if(l!=="key"&&!(l in v)){if(l=="value"&&"defaultValue"in v||l=="checked"&&"defaultChecked"in v)continue;uo(e,l,null,d,o)}}for(l in v)d=v[l],l=="children"?f=d:l=="dangerouslySetInnerHTML"?u=d:l=="value"?g=d:l=="checked"?h=d:l==="key"||a&&typeof d!="function"||x[l]===d||uo(e,l,d,x[l],o);if(u)a||p&&(u.__html===p.__html||u.__html===e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(p&&(e.innerHTML=""),Xl(e,Ei(f)?f:[f],t,r,n,L==="foreignObject"?"http://www.w3.org/1999/xhtml":o,s,i,s?s[0]:r.__k&&nr(r,0),a,c),s!=null)for(l=s.length;l--;)s[l]!=null&&Kl(s[l]);a||(l="value",g!==void 0&&(g!==e[l]||L==="progress"&&!g||L==="option"&&g!==x[l])&&uo(e,l,g,x[l],o),l="checked",h!==void 0&&h!==e[l]&&uo(e,l,h,x[l],o))}return e}function Li(e,t,r){try{typeof e=="function"?e(t):e.current=t}catch(n){pe.__e(n,r)}}function wi(e,t,r){var n,o;if(pe.unmount&&pe.unmount(e),(n=e.ref)&&(n.current&&n.current!==e.__e||Li(n,null,t)),(n=e.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(s){pe.__e(s,t)}n.base=n.__P=null}if(n=e.__k)for(o=0;o<n.length;o++)n[o]&&wi(n[o],t,r||typeof e.type!="function");r||e.__e==null||Kl(e.__e),e.__c=e.__=e.__e=e.__d=void 0}function gy(e,t,r){return this.constructor(e,r)}function we(e,t,r){var n,o,s,i;pe.__&&pe.__(e,t),o=(n=typeof r=="function")?null:r&&r.__k||t.__k,s=[],i=[],Ti(t,e=(!n&&r||t).__k=m(W,null,[e]),o||hn,hn,t.namespaceURI,!n&&r?[r]:o?null:t.firstChild?ho.call(t.childNodes):null,s,!n&&r?r:o?o.__e:t.firstChild,n,i),Vl(s,e,i)}function Si(e,t){var r={__c:t="__cC"+ql++,__:e,Consumer:function(n,o){return n.children(o)},Provider:function(n){var o,s;return this.getChildContext||(o=[],(s={})[t]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){o=null},this.shouldComponentUpdate=function(i){this.props.value!==i.value&&o.some(function(a){a.__e=!0,vi(a)})},this.sub=function(i){o.push(i);var a=i.componentWillUnmount;i.componentWillUnmount=function(){o&&o.splice(o.indexOf(i),1),a&&a.call(i)}}),n.children}};return r.Provider.__=r.Consumer.contextType=r}ho=Wl.slice,pe={__e:function(e,t,r,n){for(var o,s,i;t=t.__;)if((o=t.__c)&&!o.__)try{if((s=o.constructor)&&s.getDerivedStateFromError!=null&&(o.setState(s.getDerivedStateFromError(e)),i=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,n||{}),i=o.__d),i)return o.__E=o}catch(a){e=a}throw e}},Hl=0,py=function(e){return e!=null&&e.constructor==null},fo.prototype.setState=function(e,t){var r;r=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=Ut({},this.state),typeof e=="function"&&(e=e(Ut({},r),this.props)),e&&Ut(r,e),e!=null&&this.__v&&(t&&this._sb.push(t),vi(this))},fo.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),vi(this))},fo.prototype.render=W,rr=[],zl=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,xi=function(e,t){return e.__v.__b-t.__v.__b},go.__r=0,ki=0,bi=Bl(!1),yi=Bl(!0),ql=0;var or,ue,Pi,Jl,xn=0,sp=[],ge=pe,Ql=ge.__b,Zl=ge.__r,ep=ge.diffed,tp=ge.__c,rp=ge.unmount,np=ge.__;function bn(e,t){ge.__h&&ge.__h(ue,e,xn||t),xn=0;var r=ue.__H||(ue.__H={__:[],__h:[]});return e>=r.__.length&&r.__.push({}),r.__[e]}function F(e){return xn=1,sr(ap,e)}function sr(e,t,r){var n=bn(or++,2);if(n.t=e,!n.__c&&(n.__=[r?r(t):ap(void 0,t),function(a){var c=n.__N?n.__N[0]:n.__[0],l=n.t(c,a);c!==l&&(n.__N=[l,n.__[1]],n.__c.setState({}))}],n.__c=ue,!ue.u)){var o=function(a,c,l){if(!n.__c.__H)return!0;var u=n.__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=!1;return u.forEach(function(f){if(f.__N){var d=f.__[0];f.__=f.__N,f.__N=void 0,d!==f.__[0]&&(p=!0)}}),!(!p&&n.__c.props===a)&&(!s||s.call(this,a,c,l))};ue.u=!0;var s=ue.shouldComponentUpdate,i=ue.componentWillUpdate;ue.componentWillUpdate=function(a,c,l){if(this.__e){var u=s;s=void 0,o(a,c,l),s=u}i&&i.call(this,a,c,l)},ue.shouldComponentUpdate=o}return n.__N||n.__}function K(e,t){var r=bn(or++,3);!ge.__s&&_i(r.__H,t)&&(r.__=e,r.i=t,ue.__H.__h.push(r))}function ip(e,t){var r=bn(or++,4);!ge.__s&&_i(r.__H,t)&&(r.__=e,r.i=t,ue.__h.push(r))}function ke(e){return xn=5,$(function(){return{current:e}},[])}function $(e,t){var r=bn(or++,7);return _i(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function _(e,t){return xn=8,$(function(){return e},t)}function Bt(e){var t=ue.context[e.__c],r=bn(or++,9);return r.c=e,t?(r.__==null&&(r.__=!0,t.sub(ue)),t.props.value):e.__}function hy(){for(var e;e=sp.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(xo),e.__H.__h.forEach(Ri),e.__H.__h=[]}catch(t){e.__H.__h=[],ge.__e(t,e.__v)}}ge.__b=function(e){ue=null,Ql&&Ql(e)},ge.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),np&&np(e,t)},ge.__r=function(e){Zl&&Zl(e),or=0;var t=(ue=e.__c).__H;t&&(Pi===ue?(t.__h=[],ue.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.i=r.__N=void 0})):(t.__h.forEach(xo),t.__h.forEach(Ri),t.__h=[],or=0)),Pi=ue},ge.diffed=function(e){ep&&ep(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(sp.push(t)!==1&&Jl===ge.requestAnimationFrame||((Jl=ge.requestAnimationFrame)||xy)(hy)),t.__H.__.forEach(function(r){r.i&&(r.__H=r.i),r.i=void 0})),Pi=ue=null},ge.__c=function(e,t){t.some(function(r){try{r.__h.forEach(xo),r.__h=r.__h.filter(function(n){return!n.__||Ri(n)})}catch(n){t.some(function(o){o.__h&&(o.__h=[])}),t=[],ge.__e(n,r.__v)}}),tp&&tp(e,t)},ge.unmount=function(e){rp&&rp(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{xo(n)}catch(o){t=o}}),r.__H=void 0,t&&ge.__e(t,r.__v))};var op=typeof requestAnimationFrame=="function";function xy(e){var t,r=function(){clearTimeout(n),op&&cancelAnimationFrame(t),setTimeout(e)},n=setTimeout(r,100);op&&(t=requestAnimationFrame(r))}function xo(e){var t=ue,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),ue=t}function Ri(e){var t=ue;e.__c=e.__(),ue=t}function _i(e,t){return!e||e.length!==t.length||t.some(function(r,n){return r!==e[n]})}function ap(e,t){return typeof t=="function"?t(e):t}var cp=(e,t)=>{if(!Array.isArray(e))throw new TypeError("${t}" must be an array but actual is "${e}")};var bo=!1,lp=null;scrapbox.addListener("lines:changed",()=>bo=!1);scrapbox.addListener("layout:changed",()=>bo=!1);var pp=()=>(bo||(lp=scrapbox.Page.lines,bo=!0),lp);var up=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var dp=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var mp=()=>yo(document.getElementById("editor"),"div#editor"),yn=()=>yo(document.getElementsByClassName("lines").item(0),"div.lines");var $e=()=>{let e=document.getElementById("text-input");if(e)return dp(e,"textarea#text-input"),e};var fp=()=>yo(document.getElementsByClassName("popup-menu")?.[0],"div.popup-menu");var gp=()=>yo(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),yo=(e,t)=>{if(e)return up(e,t),e};var Be=()=>{let e=yn();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 He=e=>e.match(/^(\s*)/)?.[1]?.length??0,Pt=(e,t)=>{let r=He(hp(e,t)),n=0;for(;e+n+1<t.length&&He(hp(e+n+1,t))>r;)n++;return n},hp=(e,t)=>{let r=t[e];return Ir(r)?r:r.text};var Mi=e=>{if(tt(e))return;if(Pe(e))return vo(e)?.id;if(Ir(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)},xp=e=>{if(tt(e))return;if(Pe(e))return e;let t=Mi(e);return t?Be().findIndex(r=>r.id===t):-1};var vo=e=>{if(tt(e))return;if(Pe(e))return Be()[e];let t=Mi(e);return t?Be().find(r=>r.id===t):void 0},ir=e=>{if(bp(e))return e;let t=Mi(e);if(tt(t))return t;let r=document.getElementById(L${t});if(!tt(r))return r},bp=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var nt=()=>{let e=pp();return cp(e,"scrapbox.Page.lines"),e},he=e=>{if(tt(e))return;if(Pe(e)||Ir(e))return vo(e)?.text;if(!(e instanceof HTMLElement))return;if(bp(e))return vo(e)?.text;if(e.classList.contains("char-index"))return e.textContent??void 0;if(e.classList.contains("line")||e.getElementsByClassName("lines")?.[0])return Be().map(({text:n})=>n).join( );let t=[],r=vo(e);if(!tt(r)){for(let n of yy(e))t.push(vy(n));return r.text.slice(Math.min(...t),Math.max(...t)+1)}};var yp=()=>{let e=yn()?.firstElementChild;if(!tt(e))return e},vp=()=>{let e=yn()?.lastElementChild;if(!tt(e))return e};var Di=e=>{let t=xp(e);if(!tt(t))return Pt(t,nt())};function*yy(e){let t=e.getElementsByClassName("char-index");for(let r=0;r<t.length;r++)yield t[0]}var Ii=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index"),vy=e=>{if(!Ii(e))throw Error("A char DOM is required.");let t=e.className.match(/c-(\d+)/)?.[1];if(tt(t))throw Error('.char-index must have ".c-{\\d}"');return parseInt(t)},wp=e=>{let t=e?.getElementsByClassName?.("c-0")?.[0];return Ii(t)?t:void 0};var Ni=(e,t)=>{let r=ir(e)?.getElementsByClassName?.(c-${t})?.[0];return Ii(r)?r:void 0};var xe=(e,t)=>{let{noModifiedKeys:r=!1,...n}=t??{},o={bubbles:!0,cancelable:!0,keyCode:wy[e],...r?{}:{...n}},s=$e();if(!s)throw Error("#text-input must exist.");s.dispatchEvent(new KeyboardEvent("keydown",o)),s.dispatchEvent(new KeyboardEvent("keyup",o))},wy={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 Oi=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 ie(10)};var de=()=>{let e=$e();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 $i=e=>{let{top:t,bottom:r}=e.getBoundingClientRect();return t>=0&&r<=globalThis.innerHeight};function*Ye(e,t){for(let r=e;r<t;r++)yield r}var ji=()=>{xe("Home"),xe("Home")};var kp=async()=>{let e=yp();if(!e)throw Error(".line:first-of-type can't be found.");$i(e)||e.scrollIntoView({block:"center"});let t=wp(e);if(!t)throw Error(".line:first-of-type .c-0 can't be found.");let{left:r,top:n}=t.getBoundingClientRect();await Oi(e,{X:r,Y:n})},Ep=async()=>{await Tp(vp())},Ai=async e=>{await Tp(ir(e))},Tp=async e=>{if(!e)throw Error("The target line DOM is failed to find.");$i(e)||e.scrollIntoView({block:"center"});let{right:t,top:r,height:n}=e.getElementsByClassName("text")0.getBoundingClientRect();await Oi(e,{X:t+1,Y:r+n/2})};var Lp=(e=1)=>{for(let t of Ye(0,e))xe("z",{ctrlKey:!0})},Sp=(e=1)=>{for(let t of Ye(0,e))xe("z",{shiftKey:!0,ctrlKey:!0})};var Fi=async(e,t)=>{await Ai(e),ji(),xe("Enter"),xe("ArrowUp"),await je(t)},_e=async(e,t,r)=>{await Ai(e),ji();for(let n of Ye(e,t))xe("ArrowDown",{shiftKey:!0});xe("End",{shiftKey:!0}),await je(r)};var wo=(e=1)=>{for(let t of Ye(0,e))xe("ArrowRight",{ctrlKey:!0})},ko=(e=1)=>{for(let t of Ye(0,e))xe("ArrowLeft",{ctrlKey:!0})};var Eo=(e=1)=>{for(let t of Ye(0,e))xe("ArrowUp",{ctrlKey:!0})},To=(e=1)=>{for(let t of Ye(0,e))xe("ArrowDown",{ctrlKey:!0})},Lo=(e=1)=>{for(let t of Ye(0,e))xe("ArrowRight",{altKey:!0})},So=(e=1)=>{for(let t of Ye(0,e))xe("ArrowLeft",{altKey:!0})};var Po=(e=1)=>{for(let t of Ye(0,e))xe("ArrowUp",{altKey:!0})},Ro=(e=1)=>{for(let t of Ye(0,e))xe("ArrowDown",{altKey:!0})},je=async e=>{let t=$e();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 ie(1)};var ce=()=>{let e=gp();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=Pp(...r);n&&t.append(n)},dispose:()=>t.remove()}},Pp=(...e)=>{let t=e.flatMap(n=>{switch(n.type){case"spinner":returnEy();case"check-circle":returnTy();case"exclamation-triangle":returnLy();case"text":return_o(n.text);case"group":{let o=Pp(...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},_o=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},Ey=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),_o(e)},Ty=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),_o(e)},Ly=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),_o(e)};var jr=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_${X(e.to.title)}]=r,localStorage.setItem("pageTransitionContext",JSON.stringify(t))};var Sy=(e,t,r)=>{let n=new URL(/${e}/${Q(t)},location.href);if(r?.body&&(n.search=?body=${encodeURIComponent(r.body)}),r?.id&&(n.hash=#${r.id}),r?.context&&jr({...r?.context,to:{project:e,title:t}}),r?.newTab!==!1&&(r?.newTab===!0||e!==scrapbox.Project.name)){globalThis.open(n);return}if(r?.reload!==!1&&(r?.reload===!0||e!==scrapbox.Project.name)){globalThis.open(n,"_self");return}let o=document.createElement("a");o.href=n.toString(),document.body.append(o),o.click(),o.remove()},Ar=(e,t,r)=>Sy(e,t,{newTab:!1,reload:!1,body:r});var ar=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}},Co=async(e,t)=>{let r=t.clone();return await(await caches.open(Py(new Date))).put(e,r)},Py=e=>api-${e.getFullYear()}-${${e.getMonth()+1}.padStart(2,"0")}-${${e.getDate()}.padStart(2,"0")};var ht=()=>{let e=$e();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,n=r.find(s=>s.constructor.name==="Cursor");if(!n)throw Error('#text-input must has a "Cursor" store.');let o=r.find(s=>s.constructor.name==="Selection");if(!o)throw Error('#text-input must has a "Selection" store.');return{cursor:n,selection:o}};var Fr=()=>ht().cursor;var Rp=()=>ht().selection;var vn=e=>e===void 0?0:typeof e=="boolean"?Number(e):(e.capture?1:0)|(e.once?2:0)|(e.passive?4:0),_p=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 Mo=new Map,Ui=new Map,Cp=(e,t,r)=>{let n=Mo.get(e)??new Map,o=n.get(t)??new Set;if(o.has(vn(r)))return;if(o.add(vn(r)),n.set(t,o),Mo.set(e,n),typeof r=="object"&&r?.once){let i=Ui.get(t)??new Map,a=vn(r),c=function(u){return Bi(e,t,r),i.delete(a),t.call(this,u)};i.set(a,c),Ui.set(t,i);let l=$e();if(!l)return;l.addEventListener(e,c,r)}let s=$e();s&&s.addEventListener(e,t,r)};scrapbox.on("layout:changed",()=>{let e=$e();if(e)for(lett,rof Mo)for(letn,oof r)for(let s of o)e.addEventListener(t,n,_p(s))});var Bi=(e,t,r)=>{let n=Mo.get(e);if(!n)return;let o=n.get(t);if(!o)return;let s=vn(r);if(o.delete(s),typeof r=="object"&&r?.once){let a=Ui.get(t);if(!a)return;let c=a.get(s);if(!c)return;let l=$e();if(!l)return;l.removeEventListener(e,c,r),a.delete(s);return}let i=$e();i&&i.removeEventListener(e,t,r)};var Mp=e=>e.replace(/[.*+?^=!:${}()|\\/\\]/g,"\\$&");var Dp=({project:e,title:t,words:r,lines:n,query:o,close:s})=>{let i=_(c=>{jr({type:"search",query:o,to:{project:e,title:t}}),!(c.metaKey||c.ctrlKey||c.altKey||c.shiftKey)&&s()},e,t,o,s),a=$(()=>{let c=new RegExp((${r.map(l=>Mp(l)).join("|")}),"i");return n.flatMap(l=>{let u=l.split(c);return m("span",null,u.map((p,f)=>f%2===0?p:m("strong",null,p)))})},n,r);return m("a",{href:/${e}/${Q(t)},target:${e===scrapbox.Project.name?"":"_blank"},rel:${e===scrapbox.Project.name?"route":"noopener noreferrer"},onClick:i},t,m("div",{className:"description"},a))};var Ip=e=>{lett,r=F(e),n=_(()=>r(!0),[]),o=_(()=>r(!1),[]),s=_(()=>r(i=>!i),[]);returnt,{open:n,close:o,toggle:s}};var Np=(e,t)=>{letr,n=F(),o,s=F(!1),i=ke(Promise.resolve());return K(()=>{if(t===""){n(void 0);return}let a=!1;return i.current=(async()=>{if(await i.current,!a){s(!0);try{let c=await Rl(t,e);if(a)return;n(c.ok?c.value:void 0)}finally{s(!1)}}})(),()=>a=!0},t,e),{loading:o,result:r}};var Op=()=>m("style",null,`.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 > * {
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 {
}
.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 Ry=()=>m("i",{className:"spinner"}),$p=({exportOps:e})=>{let[t,r]=F(""),n=scrapbox.Project.name,{loading:o,result:s}=Np(n,t),i=_(d=>{r(d.currentTarget.value)},[]),[a,{open:c,close:l,toggle:u}]=Ip(!1),p=ke({open:c,close:l,toggle:u});K(()=>{Object.assign(p.current,{open:c,close:l,toggle:u})},[]),K(()=>e(p.current),[e]);let f=_(d=>{d.target instanceof HTMLElement&&d.target.id==="background"&&l()},[]);return m(W,null,m(Op,null),m("div",{id:"background",className:modal${a?"":" closed"},onClick:f},m("div",{className:"controller"},m("input",{type:"text",value:t,onInput:i}),m("div",{className:"info"},o&&m(Ry,null),${s?.pages?.length??0} pages)),s?.pages&&s.pages.length>0&&m("ul",{className:"result"},s.pages.map(d=>m("li",{key:d.title},m(Dp,{...d,project:n,query:t,close:l}))))))};var jp=()=>{let e=document.createElement("div"),t=e.attachShadow({mode:"open"});return document.body.append(e),new Promise(r=>{we(m($p,{exportOps:r}),t)})};var Do=(e,t)=>Object.hasOwn(e,t),Ap={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:">"},Hp=e=>{let t=e.toLowerCase();return Do(Ap,t)?Ap[t]:e},Fp={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:"/","?"},_y=(e,t)=>{if(e.startsWith("Key")){let r=e.slice(3);return t||(r=r.toLowerCase()),r}return Do(Fp,e)?Fpet?1:0:e},Up={"<":"lt",">":"gt"},Cy=/^($|Unidentified$|Process$|Dead$|Alt|Control|Hyper|Meta|Shift|Super|OS)/,Hi=e=>{let t=e.shiftKey,r=e.key||"Unidentified";if(r==="Unidentified"?r=_y(e.code||"",t):(r=Hp(r),r===" "&&(r="Space")),Cy.test(r))return"";r.length===1?t=!1:r=r.toLowerCase();let n="";return e.altKey&&(n+="a-"),e.ctrlKey&&(n+="c-"),e.metaKey&&(n+="m-"),t&&(n+="s-"),Do(Up,r)&&(r=Upr),n||r.length>1?<${n}${r}>:r},Bp={a:"altKey",c:"ctrlKey",m:"metaKey",s:"shiftKey"},My=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,n=t,o={key:Hp(n)};for(let s of r.split("-").slice(0,-1)){let i=s.toLowerCase();if(!Do(Bp,i))return{ok:!1,value:{name:"UnknownModifierError",modifier:s,context:e,message:${e}: Unknown modifier: ${s}}};let a=Bpi;if(oa!==void 0)return{ok:!1,value:{name:"DuplicateModifierError",modifier:s,context:e,message:${e}: Duplicate modifier: ${s}}};if(oa=!0,o.key.length===1&&o.shiftKey)return{ok:!1,value:{name:"DisallowedModifierError",modifier:s,context:e,message:${e}: Unusable modifier with single-character keys: ${s}}}}return{ok:!0,value:o}},zp=e=>{let t=My(e);return t.ok?{ok:!0,value:Hi(t.value)}:t},qp=e=>e.match(/<^<>\s+>|\s\S|^$/g);var Ve=!1,zi=e=>{Ve=typeof e=="boolean"?e:new Set(e)},xt=e=>Object.fromEntries(...Object.entries(console).map((t,r)=>{if(typeof r!="function")returnt,r;switch(t){case"warn":case"error":return[t,(...n)=>r(%c${e},"color: gray",...n)];case"log":case"info":case"debug":return[t,(...n)=>{Ve!==!0&&(!Ve||!Ve.has(e))||r(%c${e},"color: gray",...n)}];case"assert":return[t,(n,...o)=>{Ve!==!0&&(!Ve||!Ve.has(e))||r(n,%c${e},"color: gray",...o)}];case"time":case"timeEnd":return[t,n=>{Ve!==!0&&(!Ve||!Ve.has(e))||r(${e} ${n})}];default:returnt,(...n)=>{if(!(Ve!==!0&&(!Ve||!Ve.has(e))))return r(...n)}}}));var cr=xt("ScrapBindings:mod.ts"),Io=class{constructor(t,r){this.target=t;this.onSequenceUpdate=r?.onSequenceUpdate,this.flushInterval=r?.flushInterval??1e3}bind(t,r){let n=new Map,o=[];for(lets,iof t instanceof Map?t.entries():typeof t=="string"?t,r:Object.entries(t)){let a=Wp(s);if(!a.ok){for(let l of a.value)cr.error(${s}: ${l.message});n.set(s,a.value);continue}let c=a.value;this.bindings.set(c,i),c.startsWith(this.currentSequence)&&this.filtered.add(c),o.push(c)}return cr.debug("Binded the following commands:",o),this.emitChange(),n}unbind(...t){for(let r of t){let n=Wp(r);if(!n.ok)continue;let o=n.value;this.bindings.delete(o),this.filtered.delete(o)}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()),cr.debug("reset the sequence")};handleKeydown=t=>{if(!t.isTrusted)return;let r=Hi(t);if(!r)return;if(clearTimeout(this.timer),t.isComposing){this.backToInitial();return}this.currentSequence+=r,cr.debug("sequence",this.currentSequence);let n;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}n=()=>{cr.debug(run ${s});try{i(t)}catch(a){cr.error(a)}finally{this.backToInitial()}}}let o=this.filtered.size;if(cr.debug(${o} candidates: ${[...this.filtered.keys()].join(", ")}),o>0&&(this.prevBestMatchCommand=n),this.prevBestMatchCommand&&o<2){if(this.prevBestMatchCommand(),o===0){this.handleKeydown(t);return}return}if(o===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)}},Dy={name:"InvalidSequenceError",message:"cannot parse the sequence"},Wp=e=>{let t=qp(e);if(!t)return{ok:!1,value:Dy};let r="",n=[];for(let o of t){let s=zp(o);if(!s.ok){n.push(s.value);continue}r+=s.value}return n.length>0?{ok:!1,value:n}:{ok:!0,value:r}};var Iy=/https?:\/\/vimeo\.com\/(0-9+)/i,Kp=e=>{let t=e.match(Iy);if(t)return t1};var Ny=/https?:\/\/open\.spotify\.com\/(track|artist|playlist|album|episode|show)\/(a-zA-Z\d_-+)(?:\?^\s{0,100}|)/,Gp=e=>{let t=e.match(Ny);if(!t)return;let,r,n=t;return{videoId:n,pathType:r}};var Oy=/https?:\/\/anchor\.fm\/a-zA-Z\d_-+\/episodes\/(a-zA-Z\d_-+(?:\/a-zA-Z\d_-+)?)(?:\?^\s{0,100}|)/,Xp=e=>{let t=e.match(Oy);if(!t)return;let,r=t;return r};var Yp=e=>{let{type:t,pathType:r,content:n,href:o,...s}=e;if(n===""){let i=co(o);if(i)return{type:"youtube",href:o,...i,...s};let a=Kp(o);if(a)return{type:"vimeo",videoId:a,href:o,...s};let c=Gp(o);if(c)return{type:"spotify",href:o,...c,...s};let l=Xp(o);if(l)return{type:"anchor-fm",videoId:l,href:o,...s};if(jy(o))return{type:"video",href:o,...s}}return $y(o)?{type:"audio",content:n,href:o,...s}:{type:"absoluteLink",content:n,href:o,...s}},$y=e=>/\.(?:mp3|ogg|wav|aac)$/.test(e),jy=e=>/\.(?:mp4|webm)$/.test(e);var Vp=()=>{if(scrapbox.Layout!=="page")return{selectionRange:{start:{line:0,char:0},end:{line:0,char:0}},selectedText:""};let{selectionRange:e,selectedText:t,position:r}=de();if(!t){let u=Di(r.line)??0,p={start:{line:r.line,char:0},end:{line:r.line+u,char:he(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:n,end:o}=e,s=n.line>o.line,i=s?o.line:n.line,a=s?o.char:n.char,c=s?n.line:o.line,l=s?n.char:o.char;return{selectedText:t,selectionRange:{start:{line:i,char:a},end:{line:c,char:l}}}};var qi=(e,{title:t,projectTo:r,mode:n})=>{let[o,...s]=e.split(
),i=o.replaceAll("[","").replaceAll("]","").trim(),a=Math.min(...[o,...s].map(l=>He(l))),c=[from ${t},o.slice(a),...s.map(l=>l.slice(a))];return{text:${i},pages:[{project:r,title:i,lines:c,mode:n}]}};qi.hookName="default-hook";var Rt=e=>{let{project:t=scrapbox.Project.name,mode:r="newtab"}=e??{},n=[...e?.hooks??[],qi],{selectionRange:{start:o,end:s},selectedText:i}=Vp();if(!i||scrapbox.Layout!=="page")return;let a=(()=>{for(let p of n){let f=p(i,{title:scrapbox.Page.title,projectFrom:scrapbox.Project.name,projectTo:t,lines:Be().slice(o.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:d,dispose:g}=ce();try{if(p.pages.length>0){let x=p.pages.length;d({type:"spinner"},{type:"text",text:Create new ${x} pages...}),f=await Ne();let v=0;await Promise.all(p.pages.map(async L=>{let S=Array.isArray(L.lines)?b=>[...b.map(k=>k.text),...L.lines]:L.lines;await re(L.project,L.title,S,{socket:f}),d({type:"spinner"},{type:"text",text:Create ${x-++v} pages...})}))}d({type:"spinner"},{type:"text",text:${p.pages.length>0?"Created. ":""}Removing cut text...});let h=p.text;if(i===h)return;await re(scrapbox.Project.name,scrapbox.Page.title,x=>{let v=x.map(L=>L.text);return[...v.slice(0,o.line),...${vo.line.slice(0,o.char)}${h}${v.slice(s.line).join(` ).slice(s.char)}.split(`
)]}),d({type:"check-circle"},{type:"text",text:"Removed."});for(let x of p.pages)switch(x.mode){case"self":x.project===scrapbox.Project.name?Ar(x.project,x.title):window.open(https://scrapbox.io/${x.project}/${Q(x.title)},"_self");break;case"newtab":window.open(https://scrapbox.io/${x.project}/${Q(x.title)});break}}catch(h){d({type:"exclamation-triangle"},{type:"text",text:"Failed to create new pages (see console)."}),console.error(h)}finally{let h=ie(1e3);f&&await ve(f),await h,g()}};return u.hookName=c,u};function Ay(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}var Fy={};function Uy(){return Fy}function No(e,t){let r=Uy(),n=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Ay(e),s=o.getDay(),i=(s<n?7:0)+s-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function By(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Jp(e){let t=By(e);return t.setHours(0,0,0,0),t}function Wi(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Oo(e,t){let r=Wi(e.start),n=Wi(e.end),o=+r>+n,s=o?+r:+n,i=o?n:r;i.setHours(0,0,0,0);let a=t?.step??1;if(!a)return[];a<0&&(a=-a,o=!o);let c=[];for(;+i<=s;)c.push(Wi(i)),i.setDate(i.getDate()+a),i.setHours(0,0,0,0);return o?c.reverse():c}function Hy(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function Qp(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function zy(e){if(!Hy(e)&&typeof e!="number")return!1;let t=Qp(e);return!isNaN(Number(t))}function Ht(e,t){let r=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return r+n}var qy={y(e,t){let r=e.getFullYear(),n=r>0?r:1-r;return Ht(t==="yy"?n%100:n,t.length)},M(e,t){let r=e.getMonth();return t==="M"?String(r+1):Ht(r+1,2)},d(e,t){return Ht(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 Ht(e.getHours()%12||12,t.length)},H(e,t){return Ht(e.getHours(),t.length)},m(e,t){return Ht(e.getMinutes(),t.length)},s(e,t){return Ht(e.getSeconds(),t.length)},S(e,t){let r=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,r-3));return Ht(o,t.length)}},Wy=/(\w)\1*|''|'(''|[^'])+('|$)|./g,Ky=/^'([^]*?)'?$/,Gy=/''/g,Xy=/[a-zA-Z]/;function V(e,t){let r=Qp(e);if(!zy(r))throw new RangeError("Invalid time value");let n=t.match(Wy);return n?n.map(o=>{if(o==="''")return"'";let s=o[0];if(s==="'")return Yy(o);let i=qy[s];if(i)return i(r,o);if(s.match(Xy))throw new RangeError("Format string contains an unescaped latin alphabet character "+s+"");return o}).join(""):""}function Yy(e){let t=e.match(Ky);return t?t[1].replace(Gy,"'"):e}function Vy(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Jy(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function ze(e,t){let r=Vy(e);return isNaN(t)?Jy(e,NaN):(t&&r.setDate(r.getDate()+t),r)}function Qy(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Zy(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function ev(e,t){let r=Qy(e);return isNaN(t)?Zy(e,NaN):(t&&r.setDate(r.getDate()+t),r)}function _t(e,t){return ev(e,-t)}function tv(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function rv(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function nv(e,t){let r=+tv(e);return rv(e,r+t)}function $o(e,t){return nv(e,t*1e3)}function ov(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function sv(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function iv(e,t){let r=ov(e);return isNaN(t)?sv(e,NaN):(t&&r.setDate(r.getDate()+t),r)}function Zp(e,t){let r=t*7;return iv(e,r)}function av(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function jo(e){return av(e).getDate()}var cv=Math.pow(10,8)*24*60*60*1e3,e$=-cv,lv=6048e5,pv=3600,eu=pv*24,t$=eu*7,uv=eu*365.2425,dv=uv/12,r$=dv*3;function Gi(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}var mv={};function Xi(){return mv}function Ao(e,t){let r=Xi(),n=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Gi(e),s=o.getDay(),i=(s<n?7:0)+s-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function Ki(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function fv(e,t){let r=Gi(e),n=r.getFullYear(),o=Xi(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,i=Ki(e,0);i.setFullYear(n+1,0,s),i.setHours(0,0,0,0);let a=Ao(i,t),c=Ki(e,0);c.setFullYear(n,0,s),c.setHours(0,0,0,0);let l=Ao(c,t);return r.getTime()>=a.getTime()?n+1:r.getTime()>=l.getTime()?n:n-1}function gv(e,t){let r=Xi(),n=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=fv(e,t),s=Ki(e,0);return s.setFullYear(o,0,n),s.setHours(0,0,0,0),Ao(s,t)}function wn(e,t){let r=Gi(e),n=+Ao(r,t)-+gv(r,t);return Math.round(n/lv)+1}function hv(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function tu(e){return hv(e).getMonth()}function xv(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function kn(e){return xv(e).getFullYear()}function bv(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function ru(e){let t=bv(e);return t.setHours(0,0,0,0),t}function qe(e,t){let r=ru(e),n=ru(t);return+r==+n}var nu=e=>{let t=new Map;for(let r of e){let n=${kn(r)}-${tu(r)}-${jo(r)},o=t.get(n);o&&o.getTime()>r.getTime()||t.set(n,r)}return[...t.values()]};function Yi(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Fo(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function yv(e,t){let r=Yi(e);return isNaN(t)?Fo(e,NaN):(t&&r.setDate(r.getDate()+t),r)}function vv(e,t){let r=Yi(e);if(isNaN(t))return Fo(e,NaN);if(!t)return r;let n=r.getDate(),o=Fo(e,r.getTime());o.setMonth(r.getMonth()+t+1,0);let s=o.getDate();return n>=s?o:(r.setFullYear(o.getFullYear(),o.getMonth(),n),r)}function ou(e,t){let{years:r=0,months:n=0,weeks:o=0,days:s=0,hours:i=0,minutes:a=0,seconds:c=0}=t,l=Yi(e),u=n||r?vv(l,n+r*12):l,p=s||o?yv(u,s+o*7):u,f=a+i*60,d=(c+f*60)*1e3;return Fo(e,p.getTime()+d)}function wv(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function kv(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function Ev(e,t){let r=+wv(e);return kv(e,r+t)}var Tv=Math.pow(10,8)*24*60*60*1e3,ej=-Tv,Lv=36e5,Sv=3600,su=Sv*24,tj=su*7,Pv=su*365.2425,Rv=Pv/12,rj=Rv*3;function iu(e,t){return Ev(e,t*Lv)}function _v(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Cv(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function Mv(e,t){let r=+_v(e);return Cv(e,r+t)}var Dv=Math.pow(10,8)*24*60*60*1e3,cj=-Dv,Iv=6e4,Nv=3600,au=Nv*24,lj=au*7,Ov=au*365.2425,$v=Ov/12,pj=$v*3;function zt(e,t){return Mv(e,t*Iv)}function cu(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function lu(e,t){let r=cu(e),n=cu(t),o=r.getTime()-n.getTime();return o<0?-1:o>0?1:o}var jv=Math.pow(10,8)*24*60*60*1e3,$j=-jv,Av=864e5,Fv=3600,du=Fv*24,jj=du*7,Uv=du*365.2425,Bv=Uv/12,Aj=Bv*3;function mu(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function pu(e){let t=mu(e);return t.setHours(0,0,0,0),t}function uu(e){let t=mu(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 fu(e,t){let r=pu(e),n=pu(t),o=+r-uu(r),s=+n-uu(n);return Math.round((o-s)/Av)}function gu(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function hu(e,t){let r=gu(e),n=gu(t),o=r.getFullYear()-n.getFullYear(),s=r.getMonth()-n.getMonth();return o*12+s}function Hv(e){return t=>{let r=(e?Math[e]:Math.trunc)(t);return r===0?0:r}}var zv=Math.pow(10,8)*24*60*60*1e3,Yj=-zv,qv=6e4,Wv=3600,bu=Wv*24,Vj=bu*7,Kv=bu*365.2425,Gv=Kv/12,Jj=Gv*3;function xu(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Xv(e,t){return+xu(e)-+xu(t)}function Vi(e,t,r){let n=Xv(e,t)/qv;return Hv(r?.roundingMethod)(n)}function En(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Yv(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function Vv(e,t){let r=En(e);return isNaN(t)?Yv(e,NaN):(t&&r.setDate(r.getDate()+t),r)}function Jv(e,t){let r=t*7;return Vv(e,r)}var Qv={};function Zv(){return Qv}function Uo(e,t){let r=Zv(),n=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=En(e),s=o.getDay(),i=(s<n?7:0)+s-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function yu(e,t){let r=En(e.start),n=En(e.end),o=+r>+n,s=Uo(o?n:r,t),i=Uo(o?r:n,t);s.setHours(15),i.setHours(15);let a=+i.getTime(),c=s,l=t?.step??1;if(!l)return[];l<0&&(l=-l,o=!o);let u=[];for(;+c<=a;)c.setHours(0),u.push(En(c)),c=Jv(c,l),c.setHours(15);return o?u.reverse():u}function ew(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function vu(e){let t=ew(e);return t.setHours(23,59,59,999),t}function tw(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function wu(e){return tw(e).getHours()}function rw(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function ku(e){return rw(e).getMinutes()}function Eu(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function Lu(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}var nw={};function Su(){return nw}function Tu(e,t){let r=Su(),n=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Lu(e),s=o.getDay(),i=(s<n?7:0)+s-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function Pu(e,t){let r=Lu(e),n=r.getFullYear(),o=Su(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,i=Eu(e,0);i.setFullYear(n+1,0,s),i.setHours(0,0,0,0);let a=Tu(i,t),c=Eu(e,0);c.setFullYear(n,0,s),c.setHours(0,0,0,0);let l=Tu(c,t);return r.getTime()>=a.getTime()?n+1:r.getTime()>=l.getTime()?n:n-1}var ow=Math.pow(10,8)*24*60*60*1e3,AA=-ow;var sw=3600,Ru=sw*24,FA=Ru*7,iw=Ru*365.2425,aw=iw/12,UA=aw*3;function _u(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function lr(e,t){let r=_u(e),n=_u(t);return r.getTime()>n.getTime()}function cw(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function lw(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Ur(e){if(!cw(e)&&typeof e!="number")return!1;let t=lw(e);return!isNaN(Number(t))}function Ji(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function Qi(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function pw(e){let t=Qi(e),r=t.getFullYear(),n=t.getMonth(),o=Ji(e,0);return o.setFullYear(r,n+1,0),o.setHours(0,0,0,0),o.getDate()}function uw(e,t){let r=Qi(e),n=r.getFullYear(),o=r.getDate(),s=Ji(e,0);s.setFullYear(n,t,15),s.setHours(0,0,0,0);let i=pw(s);return r.setMonth(t,Math.min(o,i)),r}function Cu(e,t){let r=Qi(e);return isNaN(+r)?Ji(e,NaN):(t.year!=null&&r.setFullYear(t.year),t.month!=null&&(r=uw(r,t.month)),t.date!=null&&r.setDate(t.date),t.hours!=null&&r.setHours(t.hours),t.minutes!=null&&r.setMinutes(t.minutes),t.seconds!=null&&r.setSeconds(t.seconds),t.milliseconds!=null&&r.setMilliseconds(t.milliseconds),r)}var dw=Math.pow(10,8)*24*60*60*1e3,k2=-dw,mw=6048e5,fw=3600,Mu=fw*24,E2=Mu*7,gw=Mu*365.2425,hw=gw/12,T2=hw*3;function Ho(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}var xw={};function ea(){return xw}function Bo(e,t){let r=ea(),n=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,o=Ho(e),s=o.getDay(),i=(s<n?7:0)+s-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function Zi(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function bw(e,t){let r=Ho(e),n=r.getFullYear(),o=ea(),s=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,i=Zi(e,0);i.setFullYear(n+1,0,s),i.setHours(0,0,0,0);let a=Bo(i,t),c=Zi(e,0);c.setFullYear(n,0,s),c.setHours(0,0,0,0);let l=Bo(c,t);return r.getTime()>=a.getTime()?n+1:r.getTime()>=l.getTime()?n:n-1}function yw(e,t){let r=ea(),n=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,o=bw(e,t),s=Zi(e,0);return s.setFullYear(o,0,n),s.setHours(0,0,0,0),Bo(s,t)}function vw(e,t){let r=Ho(e),n=+Bo(r,t)-+yw(r,t);return Math.round(n/mw)+1}function Du(e,t,r){let n=Ho(e),o=vw(n,r)-t;return n.setDate(n.getDate()-o*7),n}var ww=Math.pow(10,8)*24*60*60*1e3,C2=-ww;var kw=3600,Iu=kw*24,M2=Iu*7,Ew=Iu*365.2425,Tw=Ew/12,D2=Tw*3;function Lw(e){let t=Object.prototype.toString.call(e);return e instanceof Date||typeof e=="object"&&t==="[object Date]"?new e.constructor(+e):typeof e=="number"||t==="[object Number]"||typeof e=="string"||t==="[object String]"?new Date(e):new Date(NaN)}function Sw(e,t){return e instanceof Date?new e.constructor(t):new Date(t)}function Pw(e,t){let r=Lw(e);return isNaN(t)?Sw(e,NaN):(t&&r.setDate(r.getDate()+t),r)}function Rw(e,t){let r=t*7;return Pw(e,r)}function Nu(e,t){return Rw(e,-t)}var Ou=e=>e==null,qt=e=>typeof e=="string";async function*$u(e){let t=[],r,n=i=>{if(!r){t.push(i);return}r(i),r=void 0},o=()=>t.length>0?Promise.resolve(t.pop()):new Promise(i=>r=i),s=0;for(let i of e)i.then(a=>n({state:"fulfilled",value:a})).catch(a=>n({state:"rejected",reason:a})),s++;for(let i=0;i<s;i++)yield await o()}var Ue=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,n,o,s,i,a,c,l,u,p,f,d,g]=t,h={title:g,base:new Date(parseInt(r),parseInt(n)-1,parseInt(o)),plan:{},record:{}};if(s){let x=new Date(h.base);x.setHours(parseInt(s)),x.setMinutes(parseInt(i)),h.plan.start=x}if(a&&(h.plan.duration=parseInt(a)*60),c){let x=new Date(h.base);x.setHours(parseInt(c)),x.setMinutes(parseInt(l)),x.setSeconds(parseInt(u)),h.record.start=x}if(p){let x=new Date(h.base);x.setHours(parseInt(p)),x.setMinutes(parseInt(f)),x.setSeconds(parseInt(d)),h.record.start&&lr(h.record.start,x)&&x.setDate(x.getDate()+1),h.record.end=x}return h};var Br=e=>e.record?.start??e.plan?.start??e.base,ju=e=>e.record?.end??(Ou(e.plan?.duration)?e.base:$o(Br(e),e.plan.duration));var ne=({title:e,base:t,plan:r,record:n})=>["",V(t,"yyyy-MM-dd")," ",r?.start?V(r.start,"HH:mm"):" ".repeat(5)," ",r?.duration?${r.duration/60}.padStart(4,"0"):" ".repeat(4)," ",n?.start?V(n?.start,"HH:mm:ss"):" ".repeat(8)," ",n?.end?V(n?.end,"HH:mm:ss"):" ".repeat(8),"",e].join("");function*Au(e){for(let t of pr(e))qt(t)||(yield t)}function*pr(e){for(let t=0;t<e.length;t++){let r=e[t],n=qt(r)?r:r.text,o=Pt(t,e),s=Ue(n);if(!s){yield n;continue}yield{...s,lines:e.slice(t+1,t+1+o).map(i=>qt(i)?i:i.text)},t+=o}}var _w=5*60,Tn=async()=>{let e=de().position.line,t=Ue(he(e)??""),r=t?.base??new Date,n={start:t?.plan?.start?$o(t.plan.start,_w+(t.plan.duration??0)):void 0,duration:t?.plan?.duration};await Fi(e+1,ne({title:"",base:r,plan:n,record:{}}))};var ur=async()=>{let e=de().position.line,t=Ue(he(e)??"");if(!t)return;let{record:{start:r,end:n},...o}=t;n||await _e(e,e,ne({record:{start:r?void 0:new Date},...o}))};var Ct=async()=>{let e=de().position.line,t=Ue(he(e)??"");if(!t)return;let{record:{start:r,end:n},...o}=t;r&&await _e(e,e,ne({record:{start:r,end:n?void 0:new Date},...o}))};var ta=async()=>{let e=de().position.line,t=Ue(he(e)??"");if(!t)return;let{record:{start:r,end:n},...o}=t;if(!r){await ur();return}if(!n){await Ct();return}await _e(e,e,ne({record:{},...o}))};var Ln=async()=>{let e=de().position.line,t=Ue(he(e)??"");if(!t)return;let{record:{start:r,end:n},...o}=t;if(r){if(n)return;await Ct();return}if(n)return;let s;for(let{text:a}of nt().slice(0,(e??0)+1).reverse()){let{record:c}=Ue(a)??{};if(c?.end){s=c.end;break}}let i=new Date;await _e(e,e,ne({record:{start:s??i,end:i},...o}))};var dr=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:n}=de();return r===""?[n.line,n.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var ra=(e,t=7)=>new Date((e+2592e3*((t+1)**1.5-1)/5221.154823442138)*1e3);var na=(e,t)=>{let r,n,o,s,i=null;if(i=e.match(/^(.*?)(s|e):([^\s]+)\s+d:(\d+)/))[,n,s,o,r]=i;else if(i=e.match(/^(.*?)d:(\d+)\s+(s|e):([^\s]+)/))[,n,r,s,o]=i;else if(i=e.match(/^(.*?)(s|e):([^\s]+)/))[,n,s,o]=i;else return(i=e.match(/^(.*?)d:(\d+)/))?([,n,r]=i,{name:n.trimEnd(),duration:parseInt(r)*60}):void 0;for(let{test:a,parse:c}of Cw){let l=o.match(a);if(!l)continue;let u=c(l),p=u.isDuration?ou(t,u):Cu(t,u);return s==="s"?{name:n.trimEnd(),start:p,...r!==void 0?{duration:parseInt(r)*60}:{}}:{name:n.trimEnd(),start:ra(t.getTime()/1e3,(p.getTime()-t.getTime())/(24*60*60*1e3)),...r!==void 0?{duration:parseInt(r)*60}:{}}}},Cw=[{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 mr=async()=>{let e=new Date,[t,r]=dr(),n=nt().slice(t,r+1).map(s=>s.text),o=n.flatMap(s=>{let i=s.trimEnd();if(i==="")return s;let{name:a,start:c,duration:l}=na(i,e)??{};return!a||!c&&!l?s:[ne({title:a.trim(),base:c??e,plan:{start:c,duration:l},record:{}})]}).join( );n.join(
)!==o&&await _e(t,r,o)};var zo=async(e,t,r)=>{let n=[];for(let o=e;o<=t;o++){let s=he(o)??"",i=Ue(s);if(!i){n.push(s);continue}n.push(ne(r(i,o)))}await _e(e,t,n.join(
))};var Sn=async(e=1)=>{let[t,r]=dr();await zo(t,r,n=>(n.base=ze(n.base,e),n))};var Pn=async()=>{let[e,t]=dr(),r=new Date;await zo(e,t,n=>(qe(n.base,r)||(n.base=r),n))};var Mw="日刊記録sheet",Dw=/日刊記録sheet (\d{4})-(\d{2})-(\d{2})/,Rn=["[** 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 oa=e=>{let t=e.match(Dw);if(!t)return;let[,r,n,o]=t,s=new Date(parseInt(r),parseInt(n)-1,parseInt(o));return Ur(s)?s:void 0},Wt=e=>V(e,'${Mw}' yyyy-MM-dd),fr=e=>{let t=oa(e[0]);if(!t)return e;let r=Iw(t),n=[],o=[];for(let a of pr(e.slice(1))){if(typeof a=="string"){if(Rn.includes(a)||r!==""&&r===a)continue;o.push(a);continue}n.push(a)}let s=n.sort((a,c)=>lu(Br(a),Br(c)));if(s.length===0)return[e[0],r,...Rn,...o];let i=[0,0,0,0,0,0,0,0];for(let a=1;a<Rn.length;a++){let c=iu(new Date(t.getFullYear(),t.getMonth(),t.getDate()),3*a),l=s.findIndex(d=>lr(Br(d),c));if(l<0){i[a]=-1;continue}if(l===0)continue;let u=s[l-1],p=Br(u),f=ju(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?[Rn[u]]:[]),ne(a),...a.lines]),...i.flatMap((a,c)=>a===-1?[Rn[c]]:[]),...o]},Iw=e=>yesterday: ${Wt(_t(e,1))};var _n=async(e,t)=>{let r=()=>{},n=setTimeout(()=>{let{render:o,dispose:s}=ce();r=s,o({type:"spinner"},{type:"text",text:"formatting..."})},500);await re(e,t,o=>fr(o.map(s=>s.text))),clearTimeout(n),r()};async function*sa(e,t,r){let n=[...t],o=[];for(;n.length>0;){let s=n.shift();if(!s)break;let i=s.base,a=[s];for(let c=0;c<n.length;c++)qe(n[c].base,i)&&(a.push(...n.splice(c,1)),c--);o.push((async()=>(await re(e,Wt(i),c=>fr([...c.map(l=>l.text),...a.flatMap(l=>[ne(l),...l.lines??[]])]),r),{date:i,size:a.length}))())}yield*$u(o)}var gr=async({from:{project:e,title:t},to:r})=>{let n=await Ge(e,t);if(!n.ok)throw n.value;let o=oa(t),{lines:s}=n.value,i=[];for(let u of Au(s))o&&qe(u.base,o)||i.push(u);let{render:a,dispose:c}=ce();a({type:"spinner"},{type:"text",text:copying ${i.length} tasks...});let l=await Ne();try{let u=0,p=!1;for await(let f of sa(r,i,{socket:l})){if(f.state!=="fulfilled"){console.error(f.reason),p=!0;continue}u+=f.value.size,a({type:"spinner"},{type:"text",text:copying ${i.length-u} tasks...})}if(p){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 re(e,t,f=>{let d=[];for(let g of pr(f)){if(qt(g)){d.push(g);continue}o&&qe(g.base,o)&&d.push(ne(g),...g.lines)}return d},{socket:l}),a({type:"check-circle"},{type:"text",text:"Moved"})}finally{await ve(l),await ie(1e3),c()}};var ut=e=>${e}.padStart(2,"0");var hr=e=>"hours"in e,ot=(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,bt=e=>${${e.year}.padStart(4,"0")}-${ut(e.month)}-${ut(e.date)}${"hours"in e?T${ut(e.hours)}:${ut(e.minutes)}:""},ee=e=>{let t=bt(e);return new Date(t.includes("T")?t:${t}T00:00)},We=e=>({year:e.getFullYear(),month:e.getMonth()+1,date:e.getDate(),hours:e.getHours(),minutes:e.getMinutes()});var Fu=e=>{switch(e.toLowerCase()){case"y":return"yearly";case"m":return"monthly";case"w":return"weekly";case"d":return"daily";default:return}};var Uu=e=>{switch(e){case"+":return"todo";case"-":return"note";case"!":return"deadline";case".":return"done";case"~":return"up-down";default:return}},Bu=e=>{switch(e){case"todo":return"+";case"note":return"-";case"deadline":return"!";case"done":return".";case"up-down":return"~"}};var st=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,n,o,s,i,a,c,l,u,p,f,d,g,h,x,v,L,S,b,k,w,C,M,B,P,T,E,R,D,N,j,I,H]=t,A=${e.slice(0,t.index).trim()}${e.slice((t.index??0)+r.length).trim()},z=Hu(s,i,a,c,l);if(!Ur(ee(z)))return{ok:!1,value:{name:"InvalidDateError",message:The reference point of the task "${bt(z)}" is an invalid date.}};let q=zu(z,f,d,g,u||h,p||x,v);if(q!==void 0){if(Pe(q)&&isNaN(q)||!Pe(q)&&!Ur(ee(q)))return{ok:!1,value:{name:"InvalidDateError",message:The estimated end of the task${Pe(q)?"": "${bt(q)}"} is an invalid date.}};if(Pe(q)&&q<0||!Pe(q)&&ot(q,z))return{ok:!1,value:{name:"TaskRangeError",message:The reference point of an task cannot be after its estimated end. reference point:${bt(z)}
estimated end:${bt(Pe(q)?We(zt(ee(z),q)):q)}}}}let J=/^[\uFE00-\uFE0F]*[✅❌]/.test(e)?"done":Uu(n),G=J?{status:J,refDate:z}:void 0;G&&o&&(G.speed=parseInt(o));let Se=Hu(w||s,C||i,M||a,b||B||c,k||P||l);if(!Ur(ee(Se)))return{ok:!1,value:{name:"InvalidDateError",message:The start of the task/event "${bt(Se)}" is an invalid date.}};let le=zu(Se,R||f,D||d,N||g,T||j||u||h,E||I||p||x,H||v),O=hr(Se)&&Pe(le)?{start:Se,duration:le}:void 0;if(O){let Fe={name:A,executed:O,generated:!1,raw:e};return G&&(Fe.freshness=G),(L||S)&&(Fe.recurrence={frequency:Fu(L??"D")??"daily",count:S?parseInt(S):1}),{ok:!0,value:Fe}}if(!G)return{ok:!1,value:{name:"InvalidDateError",message:"Task requires freshness to be spec"}};let se={name:A,freshness:G,generated:!1,raw:e};return q&&(se.estimated=q),{ok:!0,value:O?{...se,executed:O}:se}},yt=e=>!("executed"in e),Kt=e=>"recurrence"in e,qu=e=>!("executed"in e||"freshness"in e&&hr(e.freshness.refDate)&&e.estimated&&(Pe(e.estimated)||hr(e.estimated))),Cn=e=>"executed"in e?e.executed.duration:Pe(e.estimated)?e.estimated:void 0,vt=e=>yt(e)?e.freshness.refDate:e.executed.start,Wu=e=>{if(!yt(e)){let r=ee(e.executed.start);return We(zt(r,e.executed.duration))}if(Pe(e.estimated)&&hr(e.freshness.refDate)){let r=ee(e.freshness.refDate);return We(zt(r,e.estimated))}let t=ee(Pe(e.estimated)?e.freshness.refDate:e.estimated??e.freshness.refDate);return t.setHours(0),t.setMinutes(0),We(ze(t,1))},Nw=e=>{let t=e.freshness?${Bu(e.freshness.status)}${e.freshness.speed??""}:"",r=${bt(vt(e))},n=Cn(e);return${t}@${r}${n===void 0?"":D${n}}${e.name}},qo=(e,t)=>{let r=We(t),{recurrence:n,executed:o}=e;switch(n.frequency){case"yearly":{if(Math.abs(r.year-o.start.year)%(n.count??1)!==0||o.start.month!==r.month||o.start.date!==r.date)return;break}case"monthly":{if(hu(ee(r),ee(o.start))%(n.count??1)!==0)return;break}case"weekly":case"daily":{let a=n.frequency==="weekly"?7:1;if(fu(ee(r),ee(o.start))%((n.count??1)*a)!==0)return;break}}let s={...o.start};s.year=r.year,s.month=r.month,s.date=r.date;let i={name:e.name,executed:{start:s,duration:o.duration},generated:!0,raw:e.raw};return e.freshness&&(i.freshness=e.freshness),i},Wo=e=>e.freshness?e.generated?Nw(e):e.raw:e.generated?void 0:e.raw,Hu=(e,t,r,n,o)=>{let s=parseInt(e),i=parseInt(t),a=parseInt(r),c=n?parseInt(n):void 0,l=o?parseInt(o):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}},zu=(e,t,r,n,o,s,i)=>{if(!t&&!r&&!n&&!o&&!s&&!i)return;if(i)return parseInt(i);let a=t?parseInt(t):e.year,c=r?parseInt(r):e.month,l=n?parseInt(n):e.date,u=o?parseInt(o):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!hr(e)||!hr(f)?f:Math.round((ee(f).getTime()-ee(e).getTime())/(60*1e3))};var xr=(e,t)=>{if(!e.generated&&Kt(e)){let s=qo(e,t);return s?xr(s,t):void 0}let r=ee(yt(e)?e.freshness.refDate:e.executed.start),n=Cn(e),o=Wo(e);return{title:o!==void 0?${o}:e.name,base:r,plan:{start:qu(e)?void 0:r,duration:n!==void 0?n*60:void 0},record:{}}};var ia={あさごはん:"#log-breakfast",ひるごはん:"#log-lunch",よるごはん:"#log-dinner"},br=(e,{title:t,projectTo:r,mode:n})=>{let[o,...s]=e.split( ),i=Ue(o);if(!i)return;if(s.length===0)return{text:e,pages:[]};let{title:a,base:c,record:l,...u}=i,p=Ow(a,c,l),f=ne({title:${p},base:c,record:l,...u}),d=Math.min(...s.map(h=>He(h))),g=[.../[\[\]]/.test(a)&&a!==${p}?[a]:[],...t in ia?[...s.map(h=>h.slice(d)),"",ia[t],"#log-eatenfood"]:[...s.map(h=> ${h.slice(d)}),""]];return{text:f,pages:[{project:r,title:p,lines:Ku(t,g,[l.start??c]),mode:n}]}};br.hookName="task-hook";var Ow=(e,t,r)=>{let n=V(r.start??t,"yyyy-MM-dd");if(e in ia)return${n} ${e};if(st(e.slice(1,-1)))return e.slice(1,-1);let o=e.replace(/[\[\]]/g,"").trim();return${o}${o.endsWith(n)?"": ${n}}},yr=(e,{title:t,projectTo:r,mode:n,lines:o})=>{let[s,...i]=e.split( );if(i.length===0)return;let a=s.replace(/[\[\]]/g,"").trim(),c=Math.min(...i.map(p=>He(p))),l=r.startsWith("takker")?nu([new Date,...o.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(He(s))}${a},pages:[{project:r,title:a,lines:Ku(t,u,l),mode:n}]}};yr.hookName="new-page-hook";var vr=(e,{projectTo:t,mode:r})=>{if(e.includes( )||!/\[[^\]]+\]/.test(e))return;let[n,o]=e.match(/^(\s*)(.*)$/)?.slice?.(1)??["",e],s=[...o.matchAll(/\[([^\]])\]/g)].map(a=>X(a[1])),i=o.replaceAll("[","").replaceAll("]","");return{text:${n}${i},pages:[{project:t,title:i,lines:(a,{links:c})=>{let l=c.map(u=>X(u));if(!s.every(u=>l.includes(u)))return[...a.map(u=>u.text),o]},mode:r}]}};vr.hookName="splitted-link-hook";var Ku=(e,t,r)=>(n,{links:o})=>{let s=o.map(p=>X(p)),i=s.includes(X(e))?[]:[from ${e}],a=r.flatMap(p=>{let f=V(p,"yyyy-MM-dd");if(s.includes(f))return[];let d=V(p,"HH:mm:ss");return[#${f} ${d}]}),c=n.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 Gu=e=>e.preventDefault(),Xu=e=>e.stopPropagation(),Yu={"<A-a><A-c>":async e=>{Gu(e),Xu(e);let[t,r]=$w(),n=nt().slice(t,r+1).map(o=>{let s=o.text,i=o.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=st(i);if(!a||!a.ok)return s;let c=a.value;if(c.freshness?.status==="done")return s;let l=xr(c,new Date);return l?(l.title=${i},ne(l)):s}).join( );await _e(t,r,n),await mr()},"<A-a><A-m>":e=>{scrapbox.Layout==="page"&&(Gu(e),Xu(e),gr({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"}))}},$w=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:n}=de();return r===""?[n.line,n.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var wr=e=>e.preventDefault(),kr=e=>e.stopPropagation(),aa={"<A-a><A-a>":e=>{wr(e),kr(e),Tn()},"<A-a><A-s>":e=>{wr(e),kr(e),ur()},"<A-a><A-e>":e=>{wr(e),kr(e),Ct()},"<A-a><A-0>":e=>{wr(e),kr(e),Ln()},"<A-a><A-1>":e=>{wr(e),kr(e),Sn(1)},"<A-a><A-t>":e=>{wr(e),kr(e),Pn()},"<A-a><A-S>":e=>{scrapbox.Layout==="page"&&(wr(e),kr(e),_n(scrapbox.Project.name,scrapbox.Page.title))}};var Ee=e=>e.preventDefault(),Te=e=>e.stopPropagation(),Er=(e,t)=>{let r=fp()?.getElementsByClassName?.("button");if(!r)return;let n=[...r].find(o=>t instanceof RegExp?t.test(o.textContent??""):o.textContent===t);n instanceof HTMLDivElement&&e.target===document.activeElement&&(Ee(e),Te(e),n.click())},jw={"-":e=>Er(e,""),"]":e=>Er(e,""),c:e=>Er(e,"Copy plain"),$:e=>Er(e,""),"{":e=>Er(e,/{{c\d+}}/),"}":e=>Er(e,"reset cloze"),n:e=>Er(e,"make note")},Aw={"<C-]>":e=>{let{position:{line:t,char:r}}=de(),n=Ni(t,r)?.closest("a.page-link")??ir(t)?.querySelector?.("a.page-link");n instanceof HTMLAnchorElement&&(Ee(e),Te(e),n.click())},"<C-o>":e=>{Ee(e),Te(e),history.back()}},Fw={"<C-home>":e=>{Ee(e),Te(e),kp()},"<C-end>":e=>{Ee(e),Te(e),Ep()}},Vu=[br,yr,vr],Uw={"<C-X>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Ee(e),Te(e),Rt({project:t,mode:"self",hooks:Vu})?.())},"<C-D>":e=>{let t=window.prompt("Create a new page at",scrapbox.Project.name);t&&(Ee(e),Te(e),Rt({project:t,mode:"noopen",hooks:Vu})?.())},"<C-h>":e=>{Ee(e),Te(e),ko()},"<C-j>":e=>{Ee(e),Te(e),To()},"<C-k>":e=>{Ee(e),Te(e),Eo()},"<C-l>":e=>{Ee(e),Te(e),wo()},"<A-h>":e=>{Ee(e),Te(e),So()},"<A-j>":e=>{Ee(e),Te(e),Ro()},"<A-k>":e=>{Ee(e),Te(e),Po()},"<A-l>":e=>{Ee(e),Te(e),Lo()}};scrapbox.TimeStamp.removeAllFormats();var Bw={"<A-t><A-t>":e=>{Ee(e),Te(e),je(V(new Date,"#yyyy-MM-dd HH:mm:ss "))},"<A-t><A-j>":e=>{Ee(e),Te(e),je(V(new Date,"yyyy-MM-dd HH:mm:ss "))},"<A-t><A-k>":e=>{Ee(e),Te(e),je(V(new Date,"HH:mm:ss "))},"<A-t><A-l>":e=>{Ee(e),Te(e),je(V(new Date,"yyyy-MM-dd"))}},Ju={...jw,...Aw,...Fw,...Uw,...Bw,...Yu};var{render:Hw}=ce(),ca,zw=e=>{ca!==void 0&&cancelAnimationFrame(ca),ca=requestAnimationFrame(()=>Hw({type:"text",text:e}))},la=new Io({addEventListener:Cp,removeEventListener:Bi},{onSequenceUpdate:zw}),Qu=la.bind({...Ju,...scrapbox.Project.name==="takker-memex"?aa:{}});Qu.size>0&&alert([...Qu.entries()].map(([e,t])=>${e}:
${t.map(r=>- ${r}).join(`
)}).join(`
));var Zu=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),n=await Nr([]);if(!n.ok)return r;let o=n.value.projects.map(s=>s.id);return r.filter(s=>!o.includes(s))}catch(t){if(!(t instanceof SyntaxError))throw t;return[]}};var qw;(e=>{})(qw||={});var Ww="0.13.3",ed,td=async(e=Ww)=>{let t=https://cdnjs.cloudflare.com/ajax/libs/KaTeX/${e}/katex.min.js;if(document.querySelector(scriptsrc="${t}"))return window.katex!==void 0?Promise.resolve(window.katex):await new Promise(n=>{let o=setInterval(()=>{window.katex!==void 0&&(clearInterval(o),n(window.katex))},500)});let r=document.createElement("script");return r.src=t,ed??=new Promise((n,o)=>{r.onload=()=>n(window.katex),r.onerror=s=>o(s),document.head.append(r)}),ed};var Mn=(e,t={})=>{let r=ke(null),[n,o]=F(e),[s,i]=F("");return K(()=>{(async()=>{let{render:a}=await td();if(r.current)try{a(n,r.current,t),i("")}catch(c){if(c instanceof Error&&c.name==="ParseError")i(c.message.slice(19));else throw c}})()},[n]),{ref:r,error:s,setFormula:o}};var rd=e=>{let t=[],r=new Set,n=o=>{r.delete(o);let s=t.pop();if(!s)return;let i=s[0]().finally(()=>n(i)).then(a=>s[1](a)).catch(a=>s[2](a));r.add(i)};return o=>{if(r.size<e){let s=o().finally(()=>n(s));return r.add(s),s}return new Promise((s,i)=>{t.push([o,s,i])})}};var Kw="0.6.5",sd=ScrapBubble-${Kw},nd=await globalThis.caches.open(sd);(async()=>{for(let e of await globalThis.caches.keys())e.startsWith("ScrapBubble-")&&e!==sd&&(await globalThis.caches.delete(e),console.log(ScrapBubble deleted old cache :"${e}"))})();var od=rd(3);async function*Ko(e,t){let r=((t?.saveFailedResponse?nd.match(e):void 0)??ar(e,t)).then(i=>["cache",i]);{let i=ie(1e3).then(()=>"timeout"),a=await Promise.race([r,i]);if(a!=="timeout"){a[1]&&(yield["cache",a[1]]);let c=await od(()=>fetch(e));!c.ok&&t?.saveFailedResponse&&await nd.put(e,c.clone()),yield["network",c]}}let n=od(()=>fetch(e)).then(i=>["network",i]),[o,s]=await Promise.race([r,n]);if(o==="network"){yield[o,s];return}s&&(yield[o,s]),yield await n}var id=(e,t)=>new Date(e.headers.get("Date")??0).getTime()/1e3+t<new Date().getTime()/1e3;var Go=()=>{let e=new Map;return{dispatch:(t,r)=>{let n=e.get(t);if(n)for(let o of n)o(r)},on:(t,r)=>{let n=e.get(t)??new Set;n.add(r),e.set(t,n)},off:(t,r)=>{let n=e.get(t);n&&n.delete(r)}}};var Je=!1,ad=e=>{Je=typeof e=="boolean"?e:new Set(e)},Gt=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...n)=>r(%c${e},"color: gray",...n)];case"log":case"info":case"debug":return[t,(...n)=>{Je!==!0&&(!Je||!Je.has(e))||r(%c${e},"color: gray",...n)}];case"assert":return[t,(n,...o)=>{Je!==!0&&(!Je||!Je.has(e))||r(n,%c${e},"color: gray",...o)}];case"time":case"timeEnd":return[t,n=>{Je!==!0&&(!Je||!Je.has(e))||r(${e} ${n})}];default:return[t,(...n)=>{if(!(Je!==!0&&(!Je||!Je.has(e))))return r(...n)}]}}));var pa=Go(),Xo=new Map,Gw=Gt("ScrapBubble:useProject.ts"),cd=e=>{let[t,r]=F();return K(()=>{pa.on(e,r);let n=Xo.get(e);return n?r(n.loading?void 0:n.value):(Xo.set(e,{loading:!0}),r(void 0),(async()=>{try{let o=pt.toRequest(e);for await(let[,s]of Ko(o)){let i=await pt.fromResponse(s);Xo.set(e,{loading:!1,value:i}),pa.dispatch(e,i);break}}catch(o){Gw.error(o),Xo.delete(e)}})()),()=>pa.off(e,r)},[e]),t};var Xw=["default-light","default-dark","default-minimal"],Yw=["paper-light","paper-dark-dark","paper-dark"],ld=["blue","purple","green","orange","red"],Vw=["hacker1","hacker2"],pd=["winter","spring","summer","automn"],ud=["tropical"],dd=["kyoto","newyork","paris"],md=["mred","lgreen"],E3=["default-light","default-minimal","paper-light",...ld,...pd,...ud,...dd,...md];var Jw=[...Xw,...Yw,...ld,...Vw,...pd,...ud,...dd,...md];function fd(e){return Jw.includes(e)}var gd="default-light",Tr=e=>{let t=cd(e);return $(()=>{if(!t||!t.ok)return gd;let r=t.value.theme;return fd(r)?r:gd},[t])};var Hr=(e,t)=>new Promise(r=>{let n=!1,o=()=>{n=!0,r(!1)};e.addEventListener("click",o),e.addEventListener("pointerleave",o),setTimeout(()=>{n||r(!0),e.removeEventListener("click",o),e.removeEventListener("pointerleave",o),r(!1)},t)});var zr=e=>{let{top:t,right:r,left:n,bottom:o}=e.getBoundingClientRect(),s=document.body.getBoundingClientRect(),i=(n-s.left)/s.width>.5;return{top:Math.round(o-s.top),bottom:Math.round(globalThis.innerHeight-globalThis.scrollY-t),...i?{right:Math.round(s.right-r)}:{left:Math.round(n-s.left)},maxWidth:i?r-10:document.documentElement.clientWidth-n-10}};var hd=({project:e,title:t,descriptions:r,thumbnail:n,linkTo:o,bubble:s,delay:i,prefetch:a})=>{let c=$(()=>n?[]:rt(r.join( ),{hasTitle:!1}),[n,r]),l=Tr(e),u=_(async({currentTarget:f})=>{a(e,t),await Hr(f,i)&&s({project:e,title:t,linkTo:o,type:"link",position:zr(f)})},[e,t,i,o?.project,o?.titleLc]),p=$(()=>o?()=>{jr({type:"page",from:{project:o.project??e,title:o.titleLc},to:{project:e,title:t}})}:()=>{},[e,t,o?.project,o?.titleLc]);return m("a",{className:"related-page-card page-link",type:"link","data-theme":l,href:/${e}/${Q(t)},rel:e===scrapbox.Project.name?"route":"noopner noreferrer",target:e!==scrapbox.Project.name?"_blank":"",onPointerEnter:u,onClick:p},m("div",{class:"hover"}),m("div",{class:"content"},m("div",{class:"header"},m("div",{class:"title"},t)),n?m("div",{class:"thumbnail"},m("img",{src:n})):m("div",{class:"description"},c.flatMap((f,d)=>f.type==="line"?[m("p",{key:d},f.nodes.map(g=>m(xd,{node:g,project:e})))]:[]))))},xd=({node:e,project:t})=>{switch(e.type){case"code":return m("code",null,e.text);case"formula":return m(Qw,{node:e});case"commandLine":return m("code",null,e.symbol," $",e.text);case"helpfeel":return m("code",null,"? ",e.text);case"quote":case"strong":case"decoration":return m(W,null,e.nodes.map(r=>m(xd,{node:r,project:t})));case"icon":case"strongIcon":return m(Zw,{node:e,project:t});case"hashTag":return m(ek,{node:e});case"link":return m(tk,{node:e});case"plain":case"blank":return m(W,null,e.text);default:return m(W,null)}},Qw=({node:{formula:e}})=>{let{ref:t,error:r,setFormula:n}=Mn("");return n(e),m("span",{className:formula ${r?" error":""}},r?m("code",null,e):m("span",{className:"katex-display",ref:t}))},Zw=({node:{pathType:e,path:t},project:r})=>{let[n,o]=e==="relative"?[r,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[r,t];return m("img",{class:"icon",src:/api/pages/${n}/${Q(o)}/icon})},ek=({node:{href:e}})=>m("span",{class:"page-link"},"#",e),tk=({node:{pathType:e,href:t,content:r}})=>e!=="absolute"?m("span",{class:"page-link"},t):m("span",{class:"link"},r||t);var oe=(e,t)=>/${e}/${X(t)},Yo=e=>{let t=e.match("/([^/]+)/(.+)");if(!t)throw SyntaxError("${e}" cannnot match "/(^/+)/(.+)");return{project:t[1],titleLc:t[2]}};var Ed=Symbol.for("immer-nothing"),bd=Symbol.for("immer-draftable"),te=Symbol.for("immer-state");function it(e,...t){throw new Error(Immer minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf)}var qr=Object.getPrototypeOf;function Wr(e){return!!e&&!!e[te]}function Dt(e){return e?Td(e)||Array.isArray(e)||!!e[bd]||!!e.constructor?.[bd]||es(e)||ts(e):!1}var rk=Object.prototype.constructor.toString();function Td(e){if(!e||typeof e!="object")return!1;let t=qr(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)===rk}function Dn(e,t){Zo(e)===0?Reflect.ownKeys(e).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function Zo(e){let t=e[te];return t?t.type_:Array.isArray(e)?1:es(e)?2:ts(e)?3:0}function ma(e,t){return Zo(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ld(e,t,r){let n=Zo(e);n===2?e.set(t,r):n===3?e.add(r):e[t]=r}function nk(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function es(e){return e instanceof Map}function ts(e){return e instanceof Set}function Ce(e){return e.copy_||e.base_}function fa(e,t){if(es(e))return new Map(e);if(ts(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=Td(e);if(t===!0||t==="class_only"&&!r){let n=Object.getOwnPropertyDescriptors(e);delete n[te];let o=Reflect.ownKeys(n);for(let s=0;s<o.length;s++){let i=o[s],a=n[i];a.writable===!1&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(n[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(qr(e),n)}else{let n=qr(e);if(n!==null&&r)return{...e};let o=Object.create(n);return Object.assign(o,e)}}function ba(e,t=!1){return rs(e)||Wr(e)||!Dt(e)||(Zo(e)>1&&(e.set=e.add=e.clear=e.delete=ok),Object.freeze(e),t&&Object.entries(e).forEach(([r,n])=>ba(n,!0))),e}function ok(){it(2)}function rs(e){return Object.isFrozen(e)}var ga={};function Lr(e){let t=ga[e];return t||it(0,e),t}function sk(e,t){ga[e]||(ga[e]=t)}var In;function Vo(){return In}function ik(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function yd(e,t){t&&(Lr("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ha(e){xa(e),e.drafts_.forEach(ak),e.drafts_=null}function xa(e){e===In&&(In=e.parent_)}function vd(e){return In=ik(In,e)}function ak(e){let t=e[te];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function wd(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return e!==void 0&&e!==r?(r[te].modified_&&(ha(t),it(4)),Dt(e)&&(e=Jo(t,e),t.parent_||Qo(t,e)),t.patches_&&Lr("Patches").generateReplacementPatches_(r[te].base_,e,t.patches_,t.inversePatches_)):e=Jo(t,r,[]),ha(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Ed?e:void 0}function Jo(e,t,r){if(rs(t))return t;let n=t[te];if(!n)return Dn(t,(o,s)=>kd(e,n,t,o,s,r)),t;if(n.scope_!==e)return t;if(!n.modified_)return Qo(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;let o=n.copy_,s=o,i=!1;n.type_===3&&(s=new Set(o),o.clear(),i=!0),Dn(s,(a,c)=>kd(e,n,o,a,c,r,i)),Qo(e,o,!1),r&&e.patches_&&Lr("Patches").generatePatches_(n,r,e.patches_,e.inversePatches_)}return n.copy_}function kd(e,t,r,n,o,s,i){if(Wr(o)){let a=s&&t&&t.type_!==3&&!ma(t.assigned_,n)?s.concat(n):void 0,c=Jo(e,o,a);if(Ld(r,n,c),Wr(c))e.canAutoFreeze_=!1;else return}else i&&r.add(o);if(Dt(o)&&!rs(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Jo(e,o),(!t||!t.scope_.parent_)&&typeof n!="symbol"&&Object.prototype.propertyIsEnumerable.call(r,n)&&Qo(e,o)}}function Qo(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ba(t,r)}function ck(e,t){let r=Array.isArray(e),n={type_:r?1:0,scope_:t?t.scope_:Vo(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},o=n,s=ya;r&&(o=[n],s=Nn);let{revoke:i,proxy:a}=Proxy.revocable(o,s);return n.draft_=a,n.revoke_=i,a}var ya={get(e,t){if(t===te)return e;let r=Ce(e);if(!ma(r,t))return lk(e,r,t);let n=r[t];return e.finalized_||!Dt(n)?n:n===ua(e.base_,t)?(da(e),e.copy_[t]=On(n,e)):n},has(e,t){return t in Ce(e)},ownKeys(e){return Reflect.ownKeys(Ce(e))},set(e,t,r){let n=Sd(Ce(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let o=ua(Ce(e),t),s=o?.[te];if(s&&s.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if(nk(r,o)&&(r!==void 0||ma(e.base_,t)))return!0;da(e),Mt(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 ua(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,da(e),Mt(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let r=Ce(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:n.enumerable,value:r[t]}},defineProperty(){it(11)},getPrototypeOf(e){return qr(e.base_)},setPrototypeOf(){it(12)}},Nn={};Dn(ya,(e,t)=>{Nn[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});Nn.deleteProperty=function(e,t){return Nn.set.call(this,e,t,void 0)};Nn.set=function(e,t,r){return ya.set.call(this,e[0],t,r,e[0])};function ua(e,t){let r=e[te];return(r?Ce(r):e)[t]}function lk(e,t,r){let n=Sd(t,r);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}function Sd(e,t){if(!(t in e))return;let r=qr(e);for(;r;){let n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=qr(r)}}function Mt(e){e.modified_||(e.modified_=!0,e.parent_&&Mt(e.parent_))}function da(e){e.copy_||(e.copy_=fa(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var pk=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,r,n)=>{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"&&it(6),n!==void 0&&typeof n!="function"&&it(7);let o;if(Dt(t)){let s=vd(this),i=On(t,void 0),a=!0;try{o=r(i),a=!1}finally{a?ha(s):xa(s)}return yd(s,n),wd(o,s)}else if(!t||typeof t!="object"){if(o=r(t),o===void 0&&(o=t),o===Ed&&(o=void 0),this.autoFreeze_&&ba(o,!0),n){let s=[],i=[];Lr("Patches").generateReplacementPatches_(t,o,s,i),n(s,i)}return o}else it(1,t)},this.produceWithPatches=(t,r)=>{if(typeof t=="function")return(s,...i)=>this.produceWithPatches(s,a=>t(a,...i));let n,o;return[this.produce(t,r,(s,i)=>{n=s,o=i}),n,o]},typeof e?.autoFreeze=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof e?.useStrictShallowCopy=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Dt(e)||it(8),Wr(e)&&(e=uk(e));let t=vd(this),r=On(e,void 0);return r[te].isManual_=!0,xa(t),r}finishDraft(e,t){let r=e&&e[te];(!r||!r.isManual_)&&it(9);let{scope_:n}=r;return yd(n,t),wd(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let o=t[r];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}r>-1&&(t=t.slice(r+1));let n=Lr("Patches").applyPatches_;return Wr(e)?n(e,t):this.produce(e,o=>n(o,t))}};function On(e,t){let r=es(e)?Lr("MapSet").proxyMap_(e,t):ts(e)?Lr("MapSet").proxySet_(e,t):ck(e,t);return(t?t.scope_:Vo()).drafts_.push(r),r}function uk(e){return Wr(e)||it(10,e),Pd(e)}function Pd(e){if(!Dt(e)||rs(e))return e;let t=e[te],r;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=fa(e,t.scope_.immer_.useStrictShallowCopy_)}else r=fa(e,!0);return Dn(r,(n,o)=>{Ld(r,n,Pd(o))}),t&&(t.finalized_=!1),r}function Rd(){class e extends Map{constructor(c,l){super(),this[te]={type_:2,parent_:l,scope_:l?l.scope_:Vo(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:c,draft_:this,isManual_:!1,revoked_:!1}}get size(){return Ce(this[te]).size}has(c){return Ce(this[te]).has(c)}set(c,l){let u=this[te];return i(u),(!Ce(u).has(c)||Ce(u).get(c)!==l)&&(r(u),Mt(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[te];return i(l),r(l),Mt(l),l.base_.has(c)?l.assigned_.set(c,!1):l.assigned_.delete(c),l.copy_.delete(c),!0}clear(){let c=this[te];i(c),Ce(c).size&&(r(c),Mt(c),c.assigned_=new Map,Dn(c.base_,l=>{c.assigned_.set(l,!1)}),c.copy_.clear())}forEach(c,l){let u=this[te];Ce(u).forEach((p,f,d)=>{c.call(l,this.get(f),f,this)})}get(c){let l=this[te];i(l);let u=Ce(l).get(c);if(l.finalized_||!Dt(u)||u!==l.base_.get(c))return u;let p=On(u,l);return r(l),l.copy_.set(c,p),p}keys(){return Ce(this[te]).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 n extends Set{constructor(c,l){super(),this[te]={type_:3,parent_:l,scope_:l?l.scope_:Vo(),modified_:!1,finalized_:!1,copy_:void 0,base_:c,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return Ce(this[te]).size}has(c){let l=this[te];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[te];return i(l),this.has(c)||(s(l),Mt(l),l.copy_.add(c)),this}delete(c){if(!this.has(c))return!1;let l=this[te];return i(l),s(l),Mt(l),l.copy_.delete(c)||(l.drafts_.has(c)?l.copy_.delete(l.drafts_.get(c)):!1)}clear(){let c=this[te];i(c),Ce(c).size&&(s(c),Mt(c),c.copy_.clear())}values(){let c=this[te];return i(c),s(c),c.copy_.values()}entries(){let c=this[te];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 o(a,c){return new n(a,c)}function s(a){a.copy_||(a.copy_=new Set,a.base_.forEach(c=>{if(Dt(c)){let l=On(c,a);a.drafts_.set(c,l),a.copy_.add(l)}else a.copy_.add(c)}))}function i(a){a.revoked_&&it(3,JSON.stringify(Ce(a)))}sk("MapSet",{proxyMap_:t,proxySet_:o})}var Qe=new pk,ns=Qe.produce,z3=Qe.produceWithPatches.bind(Qe),q3=Qe.setAutoFreeze.bind(Qe),W3=Qe.setUseStrictShallowCopy.bind(Qe),K3=Qe.applyPatches.bind(Qe),G3=Qe.createDraft.bind(Qe),X3=Qe.finishDraft.bind(Qe);Rd();var _d=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},Cd=(e,t)=>ns(e,r=>{if(!r)return t;if(r.updated<t.updated){let{lines:n,linked:o,projectLinked:s,...i}=t;Object.assign(r,i),va(t)||(r.lines=n),o&&(r.linked??=o),s&&(r.projectLinked??=s);return}va(r)&&!va(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)}),va=e=>e.lines[0].id==="dummy";var Md=(e,t)=>{let r=new Map,n=X(t.title);for(let c of t.links){let l=dk(e,c);l.linked=[n],r.set(oe(e,c),l)}let o=oe(e,n),s=t.projectLinks.map(c=>{let l=Yo(c);return oe(l.project,l.titleLc)}),i={...os(e,t),linked:[],projectLinked:[]};r.set(o,i);let a=t.links.map(c=>X(c));for(let c of t.relatedPages.links1hop){c.linksLc.includes(n)&&i.linked.push(c.titleLc);for(let f of c.linksLc.filter(d=>a.includes(d))){let d=oe(e,f),g=r.get(d);if(!g)throw Error(storage already must have "${d}");if(!g.linked){g.linked=[c.titleLc];continue}g.linked.push(c.titleLc)}let l=oe(e,c.titleLc),u=os(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}for(let c of t.relatedPages.projectLinks1hop){let l=oe(c.projectName,c.titleLc);s.includes(l)||i.projectLinked.push(l);let u=os(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 d=oe(e,f),g=r.get(d);if(!g)throw Error(storage already must have "${d}");if(!g.linked){g.linked=[c.titleLc];continue}g.linked.push(c.titleLc)}let l=oe(e,c.titleLc),u=os(e,c),p=r.get(l)?.linked;p&&(u.linked=p),r.set(l,u)}return r},os=(e,t)=>({project:e,titleLc:"titleLc"in t?t.titleLc:X(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}),dk=(e,t)=>({project:e,titleLc:X(t),exists:!1,descriptions:[],image:null,lines:[{text:t,id:"dummy",userId:"dummy",updated:0,created:0}],updated:0,isLinkedCorrect:!1});var ss=Gt("ScrapBubble:bubble.ts"),wa=new Map,is=new Set,ka=Go();function*Id(e){for(let t of e)yield wa.get(t)}var Nd=(e,t)=>ka.on(e,t),Od=(e,t)=>ka.off(e,t),$d=async(e,t,r,n)=>{let o=[];for(let s of[...t].reverse()){let i=oe(s,e);is.has(i)||o.push(mk(s,e,r,n))}await Promise.all(o)},Dd=0,mk=async(e,t,r,n)=>{let o=oe(e,t);if(is.has(o))return;is.add(o);let s=Dd++,i=${s} Check update ${o};ss.time(i);try{let a=Ge.toRequest(e,t,{followRename:!0,projects:[...r]});for await(let[c,l]of Ko(a,{ignoreSearch:!0,saveFailedResponse:!0})){ss.debug(${s}${c} ${o});let u=await Ge.fromResponse(l);if(u.ok){let p=Md(e,u.value);for(let[f,d]of p){let g=wa.get(f),h=Cd(g,d);h&&g!==h&&(wa.set(f,h),ka.dispatch(f,d))}}if(n?.ignoreFetch===!0||c==="cache"&&!id(l,n?.maxAge??60))break}}catch(a){ss.error(a)}finally{is.delete(o),ss.timeEnd(i),Dd--}};var jd=Gt("ScrapBubble:useBubbleData.ts"),Kr=e=>{let[t,r]=F(Ea(e));return K(()=>{r(Ea(e));let n,o=()=>{clearTimeout(n),n=setTimeout(()=>{jd.debug(Update ${e.length} pages),r(Ea(e))},10)};return e.forEach(s=>Nd(s,o)),()=>e.forEach(s=>Od(s,o))},e),t},Ea=e=>{let t=[...Id(e)].flatMap(r=>r?[r]:[]);return jd.debug(Required: ${e.length} pages, ${t.length} found,t),t};var Ad=({source:e,linked:t,externalLinked:r,projectsForSort:n,...o})=>{let s=$(()=>[...t.keys(),...r.keys()],[t,r]),i=Kr(s),a=$(()=>[...n],[n]),c=$(()=>{let u=(p,f)=>{let d=a.indexOf(p.project),g=a.indexOf(f.project);return d===g?f.updated-p.updated:d<0?1:g<0?-1:d-g};return[...i].sort(u)},[i,a]),l=$(()=>({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 m("ul",{className:"card-bubble",style:l,onClick:o.onClick},c.map(({project:u,titleLc:p,lines:[{text:f}],descriptions:d,image:g})=>{let h=oe(u,p),x=t.get(h)??r.get(h);return m("li",{key:h},m(hd,{project:u,title:f,linkTo:x,descriptions:d,thumbnail:g??"",...o}))}))};var Gr=e=>{if(e.pathType==="root"){let[,t="",r=""]=e.href.match(/\/([\w\-]+)(?:\/?|\/(.*))$/)??["","",""];if(t==="")throw SyntaxError(Failed to get a project name from "${e.href}");let[,n]=r?.match?.(/#([a-f\d]{24,32})$/)??["",""];return r===""?{project:t}:n===""?{project:t,title:r}:{project:t,title:r.slice(0,-1-n.length),hash:n}}else{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 Ta=(e,t)=>t.some(r=>{let n=!e.project;switch(r.type){case"hashTag":return n&&X(r.href)===e.titleLc;case"link":{if(r.pathType=="absolute"||r.pathType==="relative"!==n)return!1;let{project:o,title:s=""}=Gr({pathType:r.pathType,href:r.href});return n?!o&&X(s)===e.titleLc:o===e.project&&X(s)===e.titleLc}case"quote":case"strong":case"decoration":return Ta(e,r.nodes)}});var Xt=Si({title:"",project:"",whiteList:new Set,bubble:()=>{},hide:()=>{},delay:0,prefetch:()=>{}}),Ud=({lines:e,project:t,title:r,whiteList:n,noIndent:o,hash:s,linkTo:i,...a})=>{let c=$(()=>e.flatMap(d=>typeof d=="string"?[]:[d.id]),[e]),l=$(()=>{let d=0;return rt(e.map(g=>typeof g=="string"?g:g.text).join( ),{hasTitle:!0}).map(g=>{switch(g.type){case"title":case"line":return{...g,id:c[d++]};case"codeBlock":{let h=d;return d+=g.content.split(
).length+1,{...g,ids:c.slice(h,d)}}case"table":{let h=d;return d+=g.cells.length+1,{...g,ids:c.slice(h,d)}}}})},[e,c]),u=$(()=>{if(s&&c.includes(s))return s;if(i)return l.find(d=>d.type!=="line"?!1:Ta(i,d.nodes))?.id},[l,c,s,i?.project,i?.titleLc]),p=ke(null);K(()=>{if(!u)return;let d=p.current?.querySelector(data-id="${u}"),g=globalThis.scrollY;d?.scrollIntoView?.({block:"center"}),globalThis.scroll(0,g)},[u]);let f=Tr(t);return m("div",{className:"lines","data-theme":f,ref:p},m(Xt.Provider,{value:{project:t,title:r,whiteList:n,...a}},l.map(d=>{switch(d.type){case"title":return m(W,null,m(Yr,{key:d.id,index:d.id,indent:0,noIndent:o,permalink:d.id===u},m("a",{className:"page-link",type:"link",href:/${t}/${Q(d.text)},rel:t===scrapbox.Project.name?"route":"noopener noreferrer",target:t===scrapbox.Project.name?"":"_blank"},d.text)),m("hr",null));case"codeBlock":return m(fk,{key:d.ids[0],block:d,noIndent:o,ids:d.ids,scrollId:u});case"table":return m(gk,{key:d.ids[0],block:d,noIndent:o,ids:d.ids,scrollId:u});case"line":return m(Yr,{key:d.id,index:d.id,indent:d.indent,noIndent:o,permalink:d.id===u},d.nodes.length>0?d.nodes.map(g=>m(Xr,{node:g})):m("br",null))}})))},Yr=({index:e,indent:t,noIndent:r,children:n,permalink:o})=>m("div",{className:line${o?" permalink":""},"data-id":e,"data-indent":t,style:{"margin-left":r?"":${1*t}em}},n),fk=({block:{fileName:e,content:t,indent:r},ids:n,scrollId:o})=>{let{project:s,title:i}=Bt(Xt),[a,c]=F(""),l=_(async u=>{u.preventDefault(),u.stopPropagation();try{await navigator.clipboard.writeText(t),c("Copied"),await ie(1e3),c("")}catch(p){alert(Failed to copy the code block Error:${p.message})}},[t]);return m(W,null,m(Yr,{index:n[0],indent:r,permalink:n[0]===o},m("span",{className:"code-block"},m("span",{className:"code-block-start"},m("a",{href:/api/code/${s}/${Q(i)}/${e},target:"_blank"},e)),m("span",{className:"copy",title:"Copy",onClick:l},a))),m(W,null,t.split(
).map((u,p)=>m(Yr,{index:n[p+1],indent:r,permalink:n[p+1]===o},m("code",{className:"code-block"},u)))))},gk=({block:{fileName:e,cells:t,indent:r},ids:n,scrollId:o})=>{let{project:s,title:i}=Bt(Xt);return m(W,null,m(Yr,{index:n[0],indent:r,permalink:n[0]===o},m("span",{className:"table-block"},m("span",{className:"table-block-start"},m("a",{href:/api/table/${s}/${Q(i)}/${e}.csv,target:"_blank"},e)))),m(W,null,t.map((a,c)=>m(Yr,{index:n[c+1],indent:r,permalink:n[c+1]===o},m("span",{className:"table-block table-block-row"},a.map((l,u)=>m("span",{className:cell col-${u}},l.map(p=>m(Xr,{node:p})))))))))},Xr=({node:e})=>{switch(e.type){case"code":return m("code",{className:"code"},e.text);case"formula":return m(hk,{node:e});case"commandLine":return m(bk,{node:e});case"helpfeel":return m("code",{className:"helpfeel"},m("span",{className:"prefix"},"?")," ",m("span",{className:"entry"},e.text));case"quote":return m("blockquote",{className:"quote"},e.nodes.map(t=>m(Xr,{node:t})));case"strong":return m("strong",null,e.nodes.map(t=>m(Xr,{node:t})));case"decoration":return m(xk,{node:e});case"plain":case"blank":return m(W,null,e.text);case"hashTag":return m(wk,{node:e});case"link":return m(kk,{node:e});case"googleMap":return m(yk,{node:e});case"icon":return m(Fd,{node:e});case"strongIcon":return m(Fd,{node:e,strong:!0});case"image":return m(vk,{node:e});case"strongImage":return m("img",{className:"image strong-image",src:e.src});case"numberList":return m(W,null,${e.number}. ,e.nodes.map(t=>m(Xr,{node:t})))}},hk=({node:{formula:e}})=>{let{ref:t,error:r,setFormula:n}=Mn("");return n(e),m("span",{className:formula ${r?" error":""}},r?m("code",null,e):m("span",{className:"katex-display",ref:t}))},xk=({node:{decos:e,nodes:t}})=>m("span",{className:e.map(r=>deco-${r}).join(" ")},t.map(r=>m(Xr,{node:r}))),bk=({node:e})=>{let[t,r]=F(""),n=_(async o=>{o.preventDefault(),o.stopPropagation();try{await navigator.clipboard.writeText(e.text),r("Copied"),await ie(1e3),r("")}catch(s){alert(Failed to copy the code block
Error:${s.message})}},[e.text]);return m(W,null,m("code",{className:"cli"},m("span",{className:"prefix"},e.symbol)," ",m("span",{className:"command"},e.text)),m("span",{className:"tool-buttons"},m("span",{title:"Copy",className:"copy",onClick:n},t)))},yk=({node:{place:e,latitude:t,longitude:r,zoom:n}})=>m("span",{className:"pointing-device-map"},m("a",{href:https://www.google.com/maps/search/${e}/@${t},${r},${n}z,rel:"noopner noreferrer",target:"_blank"},m("img",{className:"google-map",src:/api/google-map/static-map?center=${t}%2C${r}&markers=${e}&zoom=${n}&_csrf=${globalThis._csrf}}))),Fd=({node:{pathType:e,path:t},strong:r})=>{let{project:n}=Bt(Xt),[o,s]=e==="relative"?[n,t]:t.match(/\/([\w\-]+)\/(.+)$/)?.slice?.(1)??[n,t],i=Q(s);return m("a",{href:/${o}/${i},rel:o===scrapbox.Project.name?"route":"noopener noreferrer",target:o===scrapbox.Project.name?"":"_blank"},m("img",{className:r?"icon strong-icon":"icon",alt:s,src:/api/pages/${o}/${i}/icon},s))},vk=({node:{link:e,src:t}})=>{let r=e||(/https:\/\/gyazo\.com\/[^\/]+\/thumb\/1000/.test(t)?t.slice(0,-11):t);return m("a",{className:e?"link":"",href:r,rel:"noopner noreferrer",target:"_blank"},m("img",{className:"image",src:t}))},wk=({node:{href:e}})=>{let{project:t}=Bt(Xt),r=Bd(t,e),n=Hd(t,e,"hashtag");return m("a",{href:/${t}/${Q(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:n},"#",e)},kk=({node:{pathType:e,...t}})=>{switch(e){case"relative":case"root":return m(Ek,{pathType:e,href:t.href});case"absolute":{let r=Yp({pathType:e,...t});switch(r.type){case"youtube":return m(Tk,{...r});case"vimeo":return m(Lk,{...r});case"spotify":return m(Sk,{...r});case"anchor-fm":return m(Pk,{...r});case"audio":return m(Rk,{...r});case"video":return m(Ck,{...r});case"absoluteLink":return m("a",{className:"link",href:r.href,rel:"noopener noreferrer",target:"_blank"},r.content||r.href)}}}},Ek=({pathType:e,href:t})=>{let{project:r}=Bt(Xt),{project:n=r,title:o,hash:s=""}=Gr({pathType:e,href:t}),i=Hd(n,o,"link",s),a=Bd(n,o??"");return m("a",{className:page-link${o!==void 0&&a?" empty-page-link":""},type:"link",href:/${n}${o===void 0?"":/${Q(o)}${s===""?"":#${s}}},rel:n===scrapbox.Project.name?"route":"noopener noreferrer",target:n===scrapbox.Project.name?"":"_blank",onPointerEnter:i},t)},Tk=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 m("div",{className:"iframe-video-player"},m("iframe",{src:t,allowFullScreen:!0,type:"text/html"}))},Lk=({videoId:e})=>m("div",{className:"iframe-video-player"},m("iframe",{src:https://player.vimeo.com/video/${e},allowFullScreen:!0,type:"text/html"})),Sk=e=>m("div",{className:"iframe-video-player"},m("iframe",{className:spotify type-${e.pathType},src:https://open.spotify.com/embed/${e.pathType}/${e.videoId},allowFullScreen:!0,type:"text/html",scrolling:"no"})),Pk=e=>m("div",{className:"iframe-video-player"},m("iframe",{className:"anchor-fm",src:e.href.replace("/episodes/","/embed/episodes/"),allowFullScreen:!0,type:"text/html",scrolling:"no"})),Rk=e=>e.content===""?m("audio",{className:"audio-player",preload:"none",controls:!0,src:e.href}):m(_k,{...e}),_k=({href:e,content:t})=>{let r=ke(null),n=_(()=>{r.current?.paused?(r.current.currentTime=0,r.current.play()):r.current?.pause?.()},[]);return m("span",{className:"audio-link"},m("a",{href:e,rel:"noopener noreferrer",target:"_blank"},t),m("span",{className:"play",onClick:n},"♬"),m("audio",{preload:"none",src:e,ref:r}))},Ck=({href:e})=>m("div",{className:"video-player"},m("video",{class:"video",style:{display:"inline-block"},controls:!0,loop:!0,src:e})),Bd=(e,t)=>{let{whiteList:r}=Bt(Xt),n=$(()=>(r.has(e)?[...r]:[e,...r]).map(s=>oe(s,t)),[r,e]),o=Kr(n);return $(()=>_d(o),o)},Hd=(e,t,r,n)=>{let{delay:o,bubble:s,prefetch:i}=Bt(Xt);return _(async({currentTarget:a})=>{t&&(i(e,t),await Hr(a,o)&&s({project:e,title:t,hash:n,type:r,position:zr(a)}))},[e,t,n,r,o,i,s])};var zd=({pages:e,onClick:t,source:r,whiteList:n,...o})=>{let[s,i]=F(oe(e[0].project,e[0].titleLc)),a=$(()=>({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 m("div",{className:"text-bubble",style:a,onClick:t},e.length>1&&m("div",{role:"tablist"},e.map(c=>m(Mk,{key:oe(c.project,c.titleLc),project:c.project,titleLc:c.titleLc,selected:s===oe(c.project,c.titleLc),tabSelector:i}))),e.map(c=>m(Dk,{key:oe(c.project,c.titleLc),selected:s===oe(c.project,c.titleLc),...c,title:c.lines[0].text,hash:r.hash,linkTo:r.linkTo,whiteList:n,...o})))},Mk=({project:e,titleLc:t,tabSelector:r,selected:n})=>{let o=_(()=>r(oe(e,t)),[e,t]),s=Tr(e);return m("button",{role:"tab","aria-selected":n,"data-theme":s,tabIndex:-1,onClick:o},e)},Dk=({selected:e,...t})=>{let r=Tr(t.project);return m("div",{role:"tabpanel","data-theme":r,hidden:!e},m(Ud,{...t}))};var qd=Gt("ScrapBubble:Bubble.tsx"),Wd=({source:e,parentTitles:t,whiteList:r,...n})=>{let o=$(()=>r.has(e.project)?new Set([e.project,...r]):new Set([e.project]),[r,e.project]),[s,i,a]=Nk(e,o,r,t);return m(W,null,Ik(a)&&m(zd,{pages:a,source:e,whiteList:r,onClick:n.hide,...n}),m(Ad,{linked:s,externalLinked:i,onClick:n.hide,source:e,projectsForSort:o,...n}))},Ik=e=>e.length>0,Nk=(e,t,r,n)=>{let[[o,s,i],a]=F([new Map,new Map,[]]),c=$(()=>{let p=[...t].map(f=>oe(f,e.title));return qd.debug("projects",p),p},[t,e.title]),l=Kr(c),u=$(()=>n.map(p=>X(p)),[n]);return ip(()=>{let p=new Map,f=new Map,d=[];for(let g of l){let h={project:g.project,titleLc:g.titleLc};for(let v of g.projectLinked??[]){let{project:L,titleLc:S}=Yo(v);u.includes(S)&&r.has(L)||f.has(v)||f.set(v,h)}if(!r.has(g.project))continue;let x={titleLc:g.titleLc};for(let v of g.linked??[]){if(u.includes(v))continue;let L=oe(g.project,v);p.has(L)||p.set(L,x)}u.includes(g.titleLc)||g.exists&&d.push(g)}a(ns(g=>{qd.debug(depth: ${u.length}, bubbled from ${oe(e.project,e.title)}, bubbles,,l,"before",g[0],"internal cards,",p,"external cards",f);for(let h of g[0].keys())p.has(h)||g[0].delete(h);for(let[h,x]of p)g[0].set(h,x);for(let h of g[1].keys())f.has(h)||g[1].delete(h);for(let[h,x]of f)g[1].set(h,x);g[2]=d}))},[l,r,u]),[o,s,i]};var Kd=(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(n){if(!(n instanceof TypeError))throw n;return e}}};var Gd=e=>{let t=$(()=>Kd(e.style,import.meta.url),[e.style]);return m(W,null,t!==""&&(t instanceof URL?m("link",{rel:"stylesheet",href:t.href}):m("style",null,t)))};var Xd=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 Yd=()=>{let[e,t]=F([{bubble:n=>r(0,n),hide:()=>r(0)}]),r=_((n,o)=>{t(([s,...i])=>[s,...o?[...i.slice(0,n),o===i.at(n)?.source?i.at(n):{source:o,parentTitles:[scrapbox.Page.title??"",...i.slice(0,n).map(a=>a.source.title)],bubble:a=>r(n+1,a),hide:()=>r(n+1)}]:[...i.slice(0,n)]])},[]);return e};var La=(e,t,r,n,o)=>{K(()=>(e.addEventListener(t,r,n),()=>e.removeEventListener(t,r,n)),[e,t,n,...o??[]])};var Vd=e=>e instanceof HTMLSpanElement&&e.matches(".line-title .text"),as=e=>e instanceof HTMLAnchorElement&&e.classList.contains("page-link");var Sa="scrap-bubble",Jd=({delay:e,whiteList:t,watchList:r,style:n})=>{let[{bubble:o,hide:s},...i]=Yd(),a=_((c,l)=>$d(l,t.has(c)?t:new Set([c]),r),[t,r]);return La(document,"pointerenter",async c=>{let l=c.target;if(!as(l)&&!Vd(l))return;let{project:u=scrapbox.Project.name,title:p,hash:f=""}=as(l)?Gr({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 d=decodeURIComponent(p??"");a(u,d),await Hr(l,e)&&o({project:u,title:d,hash:f,position:zr(l),type:Ok(l)})},{capture:!0},[e,t,r]),La(document,"click",c=>{c.target.dataset.userscriptName!==Sa&&s()},{capture:!0},[s]),K(()=>(scrapbox.addListener("page:changed",s),()=>scrapbox.removeListener("page:changed",s)),[s]),m(W,null,m("link",{rel:"stylesheet",href:"https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.12.0/katex.min.css"}),m("style",null,Xd),m(Gd,{style:n}),i.map(c=>m(Wd,{key:oe(c.source.project,c.source.title),...c,whiteList:t,delay:e,prefetch:a})))},Ok=e=>as(e)?e.type==="link"?"link":"hashtag":"title";var Qd=async e=>{let{delay:t=500,whiteList:r=[],watchList:n=(await Zu()).slice(0,100),style:o="",debug:s=!1}=e??{};ad(s);let i=document.createElement("div");i.dataset.userscriptName=Sa,document.body.append(i);let a=i.attachShadow({mode:"open"});we(m(Jd,{delay:t,whiteList:new Set([scrapbox.Project.name,...r]),watchList:new Set(n),style:o}),a)};var $k=["takker-memex","takker-private","takker","takker-books","villagepump"],$n=[];switch(scrapbox.Project.name){case"hub":case"villagepump":case"verbalizing-community":$n.push("villagepump","hub","verbalizing-community");break;case"programming-notes":case"customize":case"scrapboxlab":$n.push("programming-notes","customize","scrapboxlab");break;case"sta":$n.push("sta-taskmanagement");break;case"sta-taskmanagement":case"taskmanagement":$n.push("sta-taskmanagement","taskmanagement");break}Qd({delay:/mobile/i.test(navigator.userAgent)?300:500,whiteList:[...$k,...$n],style:@import "/api/code/takker/kakeruの背景を白にするUserCSS/style.css";
@import "/api/code/takker/アイコン記法を画像記法っぽくするUserCSS/style2.css";});var Zd=(e,t,r)=>{if(r.length===0)return[];let n=r.map(a=>a.text).join(
),o=rt(n,{hasTitle:!0}),s=new Map,i=0;for(let a of o)switch(a.type){case"title":case"line":{i++;break}case"table":i+=a.cells.length+1;break;case"codeBlock":{let c=s.get(a.fileName);s.set(a.fileName,{dir:c?.dir??https://scrapbox.io/api/code/${e}/${Q(t)},lang:c?.lang??a.fileName.split(".").pop()??"text",startIds:[...c?.startIds??[],r[i].id],lines:[...c?.lines??[],...a.content.split( )]}),i+=a.content.split(
).length+1;break}}return[...s.entries()].map(([a,c])=>({filename:a,...c}))};function Ra(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(dt(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(dt(s)),t(n[s])}},r=new cs;return r.write32(0),r.write32(e.id<<1|+!e.isRequest),t(e.value),Pa(r.buf,r.len-4,0),r.buf.subarray(0,r.len)}function em(e){let t=()=>{switch(r.read8()){case 0:return null;case 1:return!!r.read8();case 2:return r.read32();case 3:return Vr(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[Vr(r.read())]=t();return a}default:throw new Error("Invalid packet")}},r=new cs(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 cs=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);Pa(this.buf,t,r)}write(t){let r=this._write(4+t.length);Pa(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 _a(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}},dt,Vr,tm;if(typeof TextEncoder<"u"&&typeof TextDecoder<"u"){let e=new TextEncoder,t=new TextDecoder;dt=r=>e.encode(r),Vr=r=>t.decode(r),tm='new TextEncoder().encode("")'}else throw new Error("No UTF-8 codec found");if(!(dt("")instanceof Uint8Array))throw new Error(Invariant violation: "${tm} 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 _a(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function Pa(e,t,r){e[r++]=t,e[r++]=t>>8,e[r++]=t>>16,e[r++]=t>>24}var jn="0.21.5";var be=JSON.stringify,rm="warning",nm="silent";function om(e){if(Me(e,"target"),e.indexOf(",")>=0)throw new Error(Invalid target: ${e});return e}var us=()=>null,me=e=>typeof e=="boolean"?null:"a boolean",U=e=>typeof e=="string"?null:"a string",ds=e=>e instanceof RegExp?null:"a RegExp object",Pr=e=>typeof e=="number"&&e===(e|0)?null:"an integer",am=e=>typeof e=="function"?null:"a function",fe=e=>Array.isArray(e)?null:"an array",at=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"an object",Ak=e=>typeof e=="object"&&e!==null?null:"an array or an object",Fk=e=>e instanceof WebAssembly.Module?null:"a WebAssembly.Module",sm=e=>typeof e=="object"&&!Array.isArray(e)?null:"an object or null",cm=e=>typeof e=="string"||typeof e=="boolean"?null:"a string or a boolean",Uk=e=>typeof e=="string"||typeof e=="object"&&e!==null&&!Array.isArray(e)?null:"a string or an object",Bk=e=>typeof e=="string"||Array.isArray(e)?null:"a string or an array",lm=e=>typeof e=="string"||e instanceof Uint8Array?null:"a string or a Uint8Array",Hk=e=>typeof e=="string"||e instanceof URL?null:"a string or a URL";function y(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(${be(r)} must be ${s});return o}function ye(e,t,r){for(let n in e)if(!(n in t))throw new Error(Invalid option ${r}: ${be(n)})}function pm(e){let t=Object.create(null),r=y(e,t,"wasmModule",Fk),n=y(e,t,"workerURL",Hk);return ye(e,t,"in initialize() call"),{wasmModule:r,workerURL:n}}function um(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 ${be(r)} in mangle cache to map to either a string or false)}}return t}function ms(e,t,r,n,o){let s=y(t,r,"color",me),i=y(t,r,"logLevel",U),a=y(t,r,"logLimit",Pr);s!==void 0?e.push(--color=${s}):n&&e.push("--color=true"),e.push(--log-level=${i||o}),e.push(--log-limit=${a||0})}function Me(e,t,r){if(typeof e!="string")throw new Error(Expected value for ${t}${r!==void 0?" "+be(r):""} to be a string, got ${typeof e} instead);return e}function dm(e,t,r){let n=y(t,r,"legalComments",U),o=y(t,r,"sourceRoot",U),s=y(t,r,"sourcesContent",me),i=y(t,r,"target",Bk),a=y(t,r,"format",U),c=y(t,r,"globalName",U),l=y(t,r,"mangleProps",ds),u=y(t,r,"reserveProps",ds),p=y(t,r,"mangleQuoted",me),f=y(t,r,"minify",me),d=y(t,r,"minifySyntax",me),g=y(t,r,"minifyWhitespace",me),h=y(t,r,"minifyIdentifiers",me),x=y(t,r,"lineLimit",Pr),v=y(t,r,"drop",fe),L=y(t,r,"dropLabels",fe),S=y(t,r,"charset",U),b=y(t,r,"treeShaking",me),k=y(t,r,"ignoreAnnotations",me),w=y(t,r,"jsx",U),C=y(t,r,"jsxFactory",U),M=y(t,r,"jsxFragment",U),B=y(t,r,"jsxImportSource",U),P=y(t,r,"jsxDev",me),T=y(t,r,"jsxSideEffects",me),E=y(t,r,"define",at),R=y(t,r,"logOverride",at),D=y(t,r,"supported",at),N=y(t,r,"pure",fe),j=y(t,r,"keepNames",me),I=y(t,r,"platform",U),H=y(t,r,"tsconfigRaw",Uk);if(n&&e.push(--legal-comments=${n}),o!==void 0&&e.push(--source-root=${o}),s!==void 0&&e.push(--sources-content=${s}),i&&(Array.isArray(i)?e.push(--target=${Array.from(i).map(om).join(",")}):e.push(--target=${om(i)})),a&&e.push(--format=${a}),c&&e.push(--global-name=${c}),I&&e.push(--platform=${I}),H&&e.push(--tsconfig-raw=${typeof H=="string"?H:JSON.stringify(H)}),f&&e.push("--minify"),d&&e.push("--minify-syntax"),g&&e.push("--minify-whitespace"),h&&e.push("--minify-identifiers"),x&&e.push(--line-limit=${x}),S&&e.push(--charset=${S}),b!==void 0&&e.push(--tree-shaking=${b}),k&&e.push("--ignore-annotations"),v)for(let A of v)e.push(--drop:${Me(A,"drop")});if(L&&e.push(--drop-labels=${Array.from(L).map(A=>Me(A,"dropLabels")).join(",")}),l&&e.push(--mangle-props=${l.source}),u&&e.push(--reserve-props=${u.source}),p!==void 0&&e.push(--mangle-quoted=${p}),w&&e.push(--jsx=${w}),C&&e.push(--jsx-factory=${C}),M&&e.push(--jsx-fragment=${M}),B&&e.push(--jsx-import-source=${B}),P&&e.push("--jsx-dev"),T&&e.push("--jsx-side-effects"),E)for(let A in E){if(A.indexOf("=")>=0)throw new Error(Invalid define: ${A});e.push(--define:${A}=${Me(EA,"define",A)})}if(R)for(let A in R){if(A.indexOf("=")>=0)throw new Error(Invalid log override: ${A});e.push(--log-override:${A}=${Me(RA,"log override",A)})}if(D)for(let A in D){if(A.indexOf("=")>=0)throw new Error(Invalid supported: ${A});let z=D[A];if(typeof z!="boolean")throw new Error(Expected value for supported ${be(A)} to be a boolean, got ${typeof z} instead);e.push(--supported:${A}=${z})}if(N)for(let A of N)e.push(--pure:${Me(A,"pure")});j&&e.push("--keep-names")}function zk(e,t,r,n,o){let s=[],i=[],a=Object.create(null),c=null,l=null;ms(s,t,a,r,n),dm(s,t,a);let u=y(t,a,"sourcemap",cm),p=y(t,a,"bundle",me),f=y(t,a,"splitting",me),d=y(t,a,"preserveSymlinks",me),g=y(t,a,"metafile",me),h=y(t,a,"outfile",U),x=y(t,a,"outdir",U),v=y(t,a,"outbase",U),L=y(t,a,"tsconfig",U),S=y(t,a,"resolveExtensions",fe),b=y(t,a,"nodePaths",fe),k=y(t,a,"mainFields",fe),w=y(t,a,"conditions",fe),C=y(t,a,"external",fe),M=y(t,a,"packages",U),B=y(t,a,"alias",at),P=y(t,a,"loader",at),T=y(t,a,"outExtension",at),E=y(t,a,"publicPath",U),R=y(t,a,"entryNames",U),D=y(t,a,"chunkNames",U),N=y(t,a,"assetNames",U),j=y(t,a,"inject",fe),I=y(t,a,"banner",at),H=y(t,a,"footer",at),A=y(t,a,"entryPoints",Ak),z=y(t,a,"absWorkingDir",U),q=y(t,a,"stdin",at),J=y(t,a,"write",me)??o,G=y(t,a,"allowOverwrite",me),Se=y(t,a,"mangleCache",at);if(a.plugins=!0,ye(t,a,in ${e}() call),u&&s.push(--sourcemap${u===!0?"":=${u}}),p&&s.push("--bundle"),G&&s.push("--allow-overwrite"),f&&s.push("--splitting"),d&&s.push("--preserve-symlinks"),g&&s.push("--metafile"),h&&s.push(--outfile=${h}),x&&s.push(--outdir=${x}),v&&s.push(--outbase=${v}),L&&s.push(--tsconfig=${L}),M&&s.push(--packages=${M}),S){let O=[];for(let se of S){if(Me(se,"resolve extension"),se.indexOf(",")>=0)throw new Error(Invalid resolve extension: ${se});O.push(se)}s.push(--resolve-extensions=${O.join(",")})}if(E&&s.push(--public-path=${E}),R&&s.push(--entry-names=${R}),D&&s.push(--chunk-names=${D}),N&&s.push(--asset-names=${N}),k){let O=[];for(let se of k){if(Me(se,"main field"),se.indexOf(",")>=0)throw new Error(Invalid main field: ${se});O.push(se)}s.push(--main-fields=${O.join(",")})}if(w){let O=[];for(let se of w){if(Me(se,"condition"),se.indexOf(",")>=0)throw new Error(Invalid condition: ${se});O.push(se)}s.push(--conditions=${O.join(",")})}if(C)for(let O of C)s.push(--external:${Me(O,"external")});if(B)for(let O in B){if(O.indexOf("=")>=0)throw new Error(Invalid package name in alias: ${O});s.push(--alias:${O}=${Me(BO,"alias",O)})}if(I)for(let O in I){if(O.indexOf("=")>=0)throw new Error(Invalid banner file type: ${O});s.push(--banner:${O}=${Me(IO,"banner",O)})}if(H)for(let O in H){if(O.indexOf("=")>=0)throw new Error(Invalid footer file type: ${O});s.push(--footer:${O}=${Me(HO,"footer",O)})}if(j)for(let O of j)s.push(--inject:${Me(O,"inject")});if(P)for(let O in P){if(O.indexOf("=")>=0)throw new Error(Invalid loader extension: ${O});s.push(--loader:${O}=${Me(PO,"loader",O)})}if(T)for(let O in T){if(O.indexOf("=")>=0)throw new Error(Invalid out extension: ${O});s.push(--out-extension:${O}=${Me(TO,"out extension",O)})}if(A)if(Array.isArray(A))for(let O=0,se=A.length;O<se;O++){let Fe=A[O];if(typeof Fe=="object"&&Fe!==null){let Tt=Object.create(null),Lt=y(Fe,Tt,"in",U),ft=y(Fe,Tt,"out",U);if(ye(Fe,Tt,"in entry point at index "+O),Lt===void 0)throw new Error('Missing property "in" for entry point at index '+O);if(ft===void 0)throw new Error('Missing property "out" for entry point at index '+O);i.push([ft,Lt])}else i.push(["",Me(Fe,"entry point at index "+O)])}else for(let O in A)i.push([O,Me(A[O],"entry point",O)]);if(q){let O=Object.create(null),se=y(q,O,"contents",lm),Fe=y(q,O,"resolveDir",U),Tt=y(q,O,"sourcefile",U),Lt=y(q,O,"loader",U);ye(q,O,'in "stdin" object'),Tt&&s.push(--sourcefile=${Tt}),Lt&&s.push(--loader=${Lt}),Fe&&(l=Fe),typeof se=="string"?c=dt(se):se instanceof Uint8Array&&(c=se)}let le=[];if(b)for(let O of b)O+="",le.push(O);return{entries:i,flags:s,write:J,stdinContents:c,stdinResolveDir:l,absWorkingDir:z,nodePaths:le,mangleCache:um(Se)}}function qk(e,t,r,n){let o=[],s=Object.create(null);ms(o,t,s,r,n),dm(o,t,s);let i=y(t,s,"sourcemap",cm),a=y(t,s,"sourcefile",U),c=y(t,s,"loader",U),l=y(t,s,"banner",U),u=y(t,s,"footer",U),p=y(t,s,"mangleCache",at);return ye(t,s,in ${e}() call),i&&o.push(--sourcemap=${i===!0?"external":i}),a&&o.push(--sourcefile=${a}),c&&o.push(--loader=${c}),l&&o.push(--banner=${l}),u&&o.push(--footer=${u}),{flags:o,mangleCache:um(p)}}function mm(e){let t={},r={didClose:!1,reason:""},n={},o=0,s=0,i=new Uint8Array(16*1024),a=0,c=S=>{let b=a+S.length;if(b>i.length){let w=new Uint8Array(b*2);w.set(i),i=w}i.set(S,a),a+=S.length;let k=0;for(;k+4<=a;){let w=_a(i,k);if(k+4+w>a)break;k+=4,g(i.subarray(k,k+w)),k+=w}k>0&&(i.copyWithin(0,k,a),a-=k)},l=S=>{r.didClose=!0,S&&(r.reason=": "+(S.message||S));let b="The service was stopped"+r.reason;for(let k in n)n[k](b,null);n={}},u=(S,b,k)=>{if(r.didClose)return k("The service is no longer running"+r.reason,null);let w=o++;n[w]=(C,M)=>{try{k(C,M)}finally{S&&S.unref()}},S&&S.ref(),e.writeToStdin(Ra({id:w,isRequest:!0,value:b}))},p=(S,b)=>{if(r.didClose)throw new Error("The service is no longer running"+r.reason);e.writeToStdin(Ra({id:S,isRequest:!1,value:b}))},f=async(S,b)=>{try{if(b.command==="ping"){p(S,{});return}if(typeof b.key=="number"){let k=t[b.key];if(!k)return;let w=k[b.command];if(w){await w(S,b);return}}throw new Error("Invalid command: "+b.command)}catch(k){let w=[Sr(k,e,null,void 0,"")];try{p(S,{errors:w})}catch{}}},d=!0,g=S=>{if(d){d=!1;let k=String.fromCharCode(...S);if(k!==jn)throw new Error(Cannot start service: Host version "${jn}" does not match binary version ${be(k)});return}let b=em(S);if(b.isRequest)f(b.id,b.value);else{let k=n[b.id];delete n[b.id],b.value.error?k(b.value.error,{}):k(null,b.value)}};return{readFromStdout:c,afterClose:l,service:{buildOrContext:({callName:S,refs:b,options:k,isTTY:w,defaultWD:C,callback:M})=>{let B=0,P=s++,T={},E={ref(){++B===1&&b&&b.ref()},unref(){--B===0&&(delete t[P],b&&b.unref())}};t[P]=T,E.ref(),Wk(S,P,u,p,E,e,T,k,w,C,(R,D)=>{try{M(R,D)}finally{E.unref()}})},transform:({callName:S,refs:b,input:k,options:w,isTTY:C,fs:M,callback:B})=>{let P=fm(),T=E=>{try{if(typeof k!="string"&&!(k instanceof Uint8Array))throw new Error('The input to "transform" must be a string or a Uint8Array');let{flags:R,mangleCache:D}=qk(S,w,C,nm),N={command:"transform",flags:R,inputFS:E!==null,input:E!==null?dt(E):typeof k=="string"?dt(k):k};D&&(N.mangleCache=D),u(b,N,(j,I)=>{if(j)return B(new Error(j),null);let H=Jr(I.errors,P),A=Jr(I.warnings,P),z=1,q=()=>{if(--z===0){let J={warnings:A,code:I.code,map:I.map,mangleCache:void 0,legalComments:void 0};"legalComments"in I&&(J.legalComments=I?.legalComments),I.mangleCache&&(J.mangleCache=I?.mangleCache),B(null,J)}};if(H.length>0)return B(An("Transform failed",H,A),null);I.codeFS&&(z++,M.readFile(I.code,(J,G)=>{J!==null?B(J,null):(I.code=G,q())})),I.mapFS&&(z++,M.readFile(I.map,(J,G)=>{J!==null?B(J,null):(I.map=G,q())})),q()})}catch(R){let D=[];try{ms(D,w,{},C,nm)}catch{}let N=Sr(R,e,P,void 0,"");u(b,{command:"error",flags:D,error:N},()=>{N.detail=P.load(N.detail),B(An("Transform failed",[N],[]),null)})}};if((typeof k=="string"||k instanceof Uint8Array)&&k.length>1024*1024){let E=T;T=()=>M.writeFile(k,E)}T(null)},formatMessages:({callName:S,refs:b,messages:k,options:w,callback:C})=>{if(!w)throw new Error(Missing second argument in ${S}() call);let M={},B=y(w,M,"kind",U),P=y(w,M,"color",me),T=y(w,M,"terminalWidth",Pr);if(ye(w,M,in ${S}() call),B===void 0)throw new Error(Missing "kind" in ${S}() call);if(B!=="error"&&B!=="warning")throw new Error(Expected "kind" to be "error" or "warning" in ${S}() call);let E={command:"format-msgs",messages:It(k,"messages",null,"",T),isWarning:B==="warning"};P!==void 0&&(E.color=P),T!==void 0&&(E.terminalWidth=T),u(b,E,(R,D)=>{if(R)return C(new Error(R),null);C(null,D.messages)})},analyzeMetafile:({callName:S,refs:b,metafile:k,options:w,callback:C})=>{w===void 0&&(w={});let M={},B=y(w,M,"color",me),P=y(w,M,"verbose",me);ye(w,M,in ${S}() call);let T={command:"analyze-metafile",metafile:k};B!==void 0&&(T.color=B),P!==void 0&&(T.verbose=P),u(b,T,(E,R)=>{if(E)return C(new Error(E),null);C(null,R.result)})}}}}function Wk(e,t,r,n,o,s,i,a,c,l,u){let p=fm(),f=e==="context",d=(x,v)=>{let L=[];try{ms(L,a,{},c,rm)}catch{}let S=Sr(x,s,p,void 0,v);r(o,{command:"error",flags:L,error:S},()=>{S.detail=p.load(S.detail),u(An(f?"Context failed":"Build failed",[S],[]),null)})},g;if(typeof a=="object"){let x=a.plugins;if(x!==void 0){if(!Array.isArray(x))return d(new Error('"plugins" must be an array'),"");g=x}}if(g&&g.length>0){if(s.isSync)return d(new Error("Cannot use plugins in synchronous API calls"),"");Kk(t,r,n,o,s,i,a,g,p).then(x=>{if(!x.ok)return d(x.error,x.pluginName);try{h(x.requestPlugins,x.runOnEndCallbacks,x.scheduleOnDisposeCallbacks)}catch(v){d(v,"")}},x=>d(x,""));return}try{h(null,(x,v)=>v([],[]),()=>{})}catch(x){d(x,"")}function h(x,v,L){let S=s.hasFS,{entries:b,flags:k,write:w,stdinContents:C,stdinResolveDir:M,absWorkingDir:B,nodePaths:P,mangleCache:T}=zk(e,a,c,rm,S);if(w&&!s.hasFS)throw new Error('The "write" option is unavailable in this environment');let E={command:"build",key:t,entries:b,flags:k,write:w,stdinContents:C,stdinResolveDir:M,absWorkingDir:B||l,nodePaths:P,context:f};x&&(E.plugins=x),T&&(E.mangleCache=T);let R=(j,I)=>{let H={errors:Jr(j.errors,p),warnings:Jr(j.warnings,p),outputFiles:void 0,metafile:void 0,mangleCache:void 0},A=H.errors.slice(),z=H.warnings.slice();j.outputFiles&&(H.outputFiles=j.outputFiles.map(Xk)),j.metafile&&(H.metafile=JSON.parse(j.metafile)),j.mangleCache&&(H.mangleCache=j.mangleCache),j.writeToStdout!==void 0&&console.log(Vr(j.writeToStdout).replace(/\n$/,"")),v(H,(q,J)=>{if(A.length>0||q.length>0){let G=An("Build failed",A.concat(q),z.concat(J));return I(G,null,q,J)}I(null,H,q,J)})},D,N;f&&(i["on-end"]=(j,I)=>new Promise(H=>{R(I,(A,z,q,J)=>{let G={errors:q,warnings:J};N&&N(A,z),D=void 0,N=void 0,n(j,G),H()})})),r(o,E,(j,I)=>{if(j)return u(new Error(j),null);if(!f)return R(I,(z,q)=>(L(),u(z,q)));if(I.errors.length>0)return u(An("Context failed",I.errors,I.warnings),null);let H=!1,A={rebuild:()=>(D||(D=new Promise((z,q)=>{let J;N=(Se,le)=>{J||(J=()=>Se?q(Se):z(le))};let G=()=>{r(o,{command:"rebuild",key:t},(le,O)=>{le?q(new Error(le)):J?J():G()})};G()})),D),watch:(z={})=>new Promise((q,J)=>{if(!s.hasFS)throw new Error('Cannot use the "watch" API in this environment');ye(z,{},"in watch() call"),r(o,{command:"watch",key:t},le=>{le?J(new Error(le)):q(void 0)})}),serve:(z={})=>new Promise((q,J)=>{if(!s.hasFS)throw new Error('Cannot use the "serve" API in this environment');let G={},Se=y(z,G,"port",Pr),le=y(z,G,"host",U),O=y(z,G,"servedir",U),se=y(z,G,"keyfile",U),Fe=y(z,G,"certfile",U),Tt=y(z,G,"fallback",U),Lt=y(z,G,"onRequest",am);ye(z,G,"in serve() call");let ft={command:"serve",key:t,onRequest:!!Lt};Se!==void 0&&(ft.port=Se),le!==void 0&&(ft.host=le),O!==void 0&&(ft.servedir=O),se!==void 0&&(ft.keyfile=se),Fe!==void 0&&(ft.certfile=Fe),Tt!==void 0&&(ft.fallback=Tt),r(o,ft,(Jc,Ex)=>{if(Jc)return J(new Error(Jc));Lt&&(i["serve-request"]=(Tx,Lx)=>{Lt(Lx.args),n(Tx,{})}),q(Ex)})}),cancel:()=>new Promise(z=>{if(H)return z();r(o,{command:"cancel",key:t},()=>{z()})}),dispose:()=>new Promise(z=>{if(H)return z();H=!0,r(o,{command:"dispose",key:t},()=>{z(),L(),o.unref()})})};o.ref(),u(null,A)})}}var Kk=async(e,t,r,n,o,s,i,a,c)=>{let l=[],u=[],p={},f={},d=[],g=0,h=0,x=[],v=!1;a=[...a];for(let b of a){let k={};if(typeof b!="object")throw new Error(Plugin at index ${h} must be an object);let w=y(b,k,"name",U);if(typeof w!="string"||w==="")throw new Error(Plugin at index ${h} is missing a name);try{let C=y(b,k,"setup",am);if(typeof C!="function")throw new Error("Plugin is missing a setup function");ye(b,k,on plugin ${be(w)});let M={name:w,onStart:!1,onEnd:!1,onResolve:[],onLoad:[]};h++;let P=C({initialOptions:i,resolve:(T,E={})=>{if(!v)throw new Error('Cannot call "resolve" before plugin setup has completed');if(typeof T!="string")throw new Error("The path to resolve must be a string");let R=Object.create(null),D=y(E,R,"pluginName",U),N=y(E,R,"importer",U),j=y(E,R,"namespace",U),I=y(E,R,"resolveDir",U),H=y(E,R,"kind",U),A=y(E,R,"pluginData",us),z=y(E,R,"with",at);return ye(E,R,"in resolve() call"),new Promise((q,J)=>{let G={command:"resolve",path:T,key:e,pluginName:w};if(D!=null&&(G.pluginName=D),N!=null&&(G.importer=N),j!=null&&(G.namespace=j),I!=null&&(G.resolveDir=I),H!=null)G.kind=H;else throw new Error('Must specify "kind" when calling "resolve"');A!=null&&(G.pluginData=c.store(A)),z!=null&&(G.with=Gk(z,"with")),t(n,G,(Se,le)=>{Se!==null?J(new Error(Se)):q({errors:Jr(le.errors,c),warnings:Jr(le.warnings,c),path:le.path,external:le.external,sideEffects:le.sideEffects,namespace:le.namespace,suffix:le.suffix,pluginData:c.load(le.pluginData)})})})},onStart(T){let E='This error came from the "onStart" callback registered here:',R=ls(new Error(E),o,"onStart");l.push({name:w,callback:T,note:R}),M.onStart=!0},onEnd(T){let E='This error came from the "onEnd" callback registered here:',R=ls(new Error(E),o,"onEnd");u.push({name:w,callback:T,note:R}),M.onEnd=!0},onResolve(T,E){let R='This error came from the "onResolve" callback registered here:',D=ls(new Error(R),o,"onResolve"),N={},j=y(T,N,"filter",ds),I=y(T,N,"namespace",U);if(ye(T,N,in onResolve() call for plugin ${be(w)}),j==null)throw new Error("onResolve() call is missing a filter");let H=g++;p[H]={name:w,callback:E,note:D},M.onResolve.push({id:H,filter:j.source,namespace:I||""})},onLoad(T,E){let R='This error came from the "onLoad" callback registered here:',D=ls(new Error(R),o,"onLoad"),N={},j=y(T,N,"filter",ds),I=y(T,N,"namespace",U);if(ye(T,N,in onLoad() call for plugin ${be(w)}),j==null)throw new Error("onLoad() call is missing a filter");let H=g++;f[H]={name:w,callback:E,note:D},M.onLoad.push({id:H,filter:j.source,namespace:I||""})},onDispose(T){d.push(T)},esbuild:o.esbuild});P&&await P,x.push(M)}catch(C){return{ok:!1,error:C,pluginName:w}}}s["on-start"]=async(b,k)=>{let w={errors:[],warnings:[]};await Promise.all(l.map(async({name:C,callback:M,note:B})=>{try{let P=await M();if(P!=null){if(typeof P!="object")throw new Error(Expected onStart() callback in plugin ${be(C)} to return an object);let T={},E=y(P,T,"errors",fe),R=y(P,T,"warnings",fe);ye(P,T,from onStart() callback in plugin ${be(C)}),E!=null&&w.errors.push(...It(E,"errors",c,C,void 0)),R!=null&&w.warnings.push(...It(R,"warnings",c,C,void 0))}}catch(P){w.errors.push(Sr(P,o,c,B&&B(),C))}})),r(b,w)},s["on-resolve"]=async(b,k)=>{let w={},C="",M,B;for(let P of k.ids)try{({name:C,callback:M,note:B}=p[P]);let T=await M({path:k.path,importer:k.importer,namespace:k.namespace,resolveDir:k.resolveDir,kind:k.kind,pluginData:c.load(k.pluginData),with:k.with});if(T!=null){if(typeof T!="object")throw new Error(Expected onResolve() callback in plugin ${be(C)} to return an object);let E={},R=y(T,E,"pluginName",U),D=y(T,E,"path",U),N=y(T,E,"namespace",U),j=y(T,E,"suffix",U),I=y(T,E,"external",me),H=y(T,E,"sideEffects",me),A=y(T,E,"pluginData",us),z=y(T,E,"errors",fe),q=y(T,E,"warnings",fe),J=y(T,E,"watchFiles",fe),G=y(T,E,"watchDirs",fe);ye(T,E,from onResolve() callback in plugin ${be(C)}),w.id=P,R!=null&&(w.pluginName=R),D!=null&&(w.path=D),N!=null&&(w.namespace=N),j!=null&&(w.suffix=j),I!=null&&(w.external=I),H!=null&&(w.sideEffects=H),A!=null&&(w.pluginData=c.store(A)),z!=null&&(w.errors=It(z,"errors",c,C,void 0)),q!=null&&(w.warnings=It(q,"warnings",c,C,void 0)),J!=null&&(w.watchFiles=ps(J,"watchFiles")),G!=null&&(w.watchDirs=ps(G,"watchDirs"));break}}catch(T){w={id:P,errors:[Sr(T,o,c,B&&B(),C)]};break}r(b,w)},s["on-load"]=async(b,k)=>{let w={},C="",M,B;for(let P of k.ids)try{({name:C,callback:M,note:B}=f[P]);let T=await M({path:k.path,namespace:k.namespace,suffix:k.suffix,pluginData:c.load(k.pluginData),with:k.with});if(T!=null){if(typeof T!="object")throw new Error(Expected onLoad() callback in plugin ${be(C)} to return an object);let E={},R=y(T,E,"pluginName",U),D=y(T,E,"contents",lm),N=y(T,E,"resolveDir",U),j=y(T,E,"pluginData",us),I=y(T,E,"loader",U),H=y(T,E,"errors",fe),A=y(T,E,"warnings",fe),z=y(T,E,"watchFiles",fe),q=y(T,E,"watchDirs",fe);ye(T,E,from onLoad() callback in plugin ${be(C)}),w.id=P,R!=null&&(w.pluginName=R),D instanceof Uint8Array?w.contents=D:D!=null&&(w.contents=dt(D)),N!=null&&(w.resolveDir=N),j!=null&&(w.pluginData=c.store(j)),I!=null&&(w.loader=I),H!=null&&(w.errors=It(H,"errors",c,C,void 0)),A!=null&&(w.warnings=It(A,"warnings",c,C,void 0)),z!=null&&(w.watchFiles=ps(z,"watchFiles")),q!=null&&(w.watchDirs=ps(q,"watchDirs"));break}}catch(T){w={id:P,errors:[Sr(T,o,c,B&&B(),C)]};break}r(b,w)};let L=(b,k)=>k([],[]);u.length>0&&(L=(b,k)=>{(async()=>{let w=[],C=[];for(let{name:M,callback:B,note:P}of u){let T,E;try{let R=await B(b);if(R!=null){if(typeof R!="object")throw new Error(Expected onEnd() callback in plugin ${be(M)} to return an object);let D={},N=y(R,D,"errors",fe),j=y(R,D,"warnings",fe);ye(R,D,from onEnd() callback in plugin ${be(M)}),N!=null&&(T=It(N,"errors",c,M,void 0)),j!=null&&(E=It(j,"warnings",c,M,void 0))}}catch(R){T=[Sr(R,o,c,P&&P(),M)]}if(T){w.push(...T);try{b.errors.push(...T)}catch{}}if(E){C.push(...E);try{b.warnings.push(...E)}catch{}}}k(w,C)})()});let S=()=>{for(let b of d)setTimeout(()=>b(),0)};return v=!0,{ok:!0,requestPlugins:x,runOnEndCallbacks:L,scheduleOnDisposeCallbacks:S}};function fm(){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 ls(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 i=gm(t,s,r);if(i)return n={text:e.message,location:i},n}catch{}}}function Sr(e,t,r,n,o){let s="Internal error",i=null;try{s=(e&&e.message||e)+""}catch{}try{i=gm(t,(e.stack+"").split(
),"")}catch{}return{id:"",pluginName:o,text:s,location:i,notes:n?[n]:[],detail:r?r.store(e):-1}}function gm(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 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:dt(c.slice(0,l)).length,length:dt(c.slice(l,l+u)).length,lineText:c+
+t.slice(1).join(
),suggestion:""}}break}}return null}function An(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,i)=>{if(i===n)return
...;if(!s.location)return
${a}:${c}:${l}: ERROR: ${u}${s.text}}).join("");let o=new Error(e);for(let[s,i]of[["errors",t],["warnings",r]])Object.defineProperty(o,s,{configurable:!0,enumerable:!0,get:()=>i,set:a=>Object.defineProperty(o,s,{configurable:!0,enumerable:!0,value:a})});return o}function Jr(e,t){for(let r of e)r.detail=t.load(r.detail);return e}function im(e,t,r){if(e==null)return null;let n={},o=y(e,n,"file",U),s=y(e,n,"namespace",U),i=y(e,n,"line",Pr),a=y(e,n,"column",Pr),c=y(e,n,"length",Pr),l=y(e,n,"lineText",U),u=y(e,n,"suggestion",U);if(ye(e,n,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:o||"",namespace:s||"",line:i||0,column:a||0,length:c||0,lineText:l||"",suggestion:u||""}}function It(e,t,r,n,o){let s=[],i=0;for(let a of e){let c={},l=y(a,c,"id",U),u=y(a,c,"pluginName",U),p=y(a,c,"text",U),f=y(a,c,"location",sm),d=y(a,c,"notes",fe),g=y(a,c,"detail",us),h=in element ${i} of "${t}";ye(a,c,h);let x=[];if(d)for(let v of d){let L={},S=y(v,L,"text",U),b=y(v,L,"location",sm);ye(v,L,h),x.push({text:S||"",location:im(b,h,o)})}s.push({id:l||"",pluginName:u||n,text:p||"",location:im(f,h,o),notes:x,detail:r?r.store(g):-1}),i++}return s}function ps(e,t){let r=[];for(let n of e){if(typeof n!="string")throw new Error(${be(t)} must be an array of strings);r.push(n)}return r}function Gk(e,t){let r=Object.create(null);for(let n in e){let o=e[n];if(typeof o!="string")throw new Error(key ${be(n)} in object ${be(t)} must be a string);r[n]=o}return r}function Xk({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=Vr(o)),n}}}var Vk=jn,gs=e=>hs().build(e),Jk=(e,t)=>hs().transform(e,t),Qk=(e,t)=>hs().formatMessages(e,t),Zk=(e,t)=>hs().analyzeMetafile(e,t);var Rr,hm,fs,hs=()=>{if(fs)return fs;throw Rr?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')},xs=e=>{e=pm(e||{});let t=e.wasmModule,r=e.workerURL;if(!t)throw new Error('Must provide the "wasmModule" option');if(Rr)throw new Error('Cannot call "initialize" more than once');return Rr=e0(t,r),Rr.catch(()=>{Rr=void 0}),Rr},e0=async(e,t)=>{let r=new Worker(t.toString(),{type:"module"}),n,o,s=new Promise((c,l)=>{n=c,o=l});r.onmessage=({data:c})=>{r.onmessage=({data:l})=>i(l),c?o(c):n()},r.postMessage(e);let{readFromStdout:i,service:a}=mm({writeToStdin(c){r.postMessage(c)},isSync:!1,hasFS:!1,esbuild:{build:gs,transform:Jk,formatMessages:Qk,analyzeMetafile:Zk,version:Vk,initialize:xs}});await s,hm=()=>{r.terminate(),Rr=void 0,hm=void 0,fs=void 0},fs={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,d){d(new Error("Internal error"),null)},writeFile(f,d){d(null)}},callback:(f,d)=>f?p(f):u(d)})),formatMessages:(c,l)=>new Promise((u,p)=>a.formatMessages({callName:"formatMessages",refs:null,messages:c,options:l,callback:(f,d)=>f?p(f):u(d)})),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,d)=>f?p(f):u(d)}))}};var bs=e=>["ts","js","tsx","jsx","mjs","javascript","typescript"].includes(e),ys=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 xm=e=>!!(t0.includes(e.hostname)||e.hostname.endsWith(".openai.azure.com")),t0=["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 vs(e){return typeof e=="object"&&e!==null&&e.constructor===Object}function ws(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 bm(e){return vs(e)&&(e.imports!==void 0?Ca(e.imports):!0)&&(e.scopes!==void 0?Ma(e.scopes):!0)}function Ca(e){return vs(e)}function Ma(e){return vs(e)&&Object.values(e).every(t=>Da(t))}function Da(e){return vs(e)}function ks(e){try{return new URL(e),!0}catch{return!1}}function vm(e,t){let r={};for(let[n,o]of Object.entries(e)){let s=n0(n,t);if(s===null)continue;if(typeof o!="string"){console.warn("addresses need to be strings."),r[s]=null;continue}let i=Ia(o,t);if(i===null){console.warn("the address was invalid."),r[s]=null;continue}if(n.endsWith("/")&&!wt(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]=wt(i)}return ws(r)}function wt(e){return e.href}function r0(e,t){let r={};for(let[o,s]of Object.entries(e)){if(!Da(s))throw new TypeError("the value of the scope with prefix scopePrefix needs to be an object.");let i;try{i=new URL(o,t)}catch{console.warn("the scope prefix URL was not parseable.");continue}let a=wt(i);r[a]=vm(s,t)}let n={};for(let o of Object.keys(r))n[o]=ws(r[o]);return ws(n)}function n0(e,t){if(!e.length)return console.warn("specifier key cannot be an empty string."),null;let r=Ia(e,t);return r!==null?wt(r):e}function Ia(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 o0=["ftp","file","http","https","ws","wss"];function s0(e){return o0.some(t=>wt(e).startsWith(t))}function ym(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(!ks(o))throw new TypeError("resolutionResult must be an URL.");return o}else if(n.endsWith("/")&&e.startsWith(n)&&(t===null||s0(t))){if(o===null)throw new TypeError("resolution of specifierKey was blocked by a null entry.");if(!ks(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 i=new URL(s,o);if(!ks(i))throw new TypeError("url must be an URL.");if(!wt(i).startsWith(o))throw new TypeError("resolution of normalizedSpecifier was blocked due to it backtracking above its prefix specifierKey.");return wt(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 Na(e,t){let r={};if(!bm(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(!Ca(n))throw new TypeError('"imports" top-level key needs to be an object.');r=vm(n,t)}let s={};if(o!==void 0){if(!Ma(o))throw new TypeError('"scopes" top-level key needs to be an object.');s=r0(o,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 Oa(e,{imports:t={},scopes:r={}},n){let o=wt(n),s=Ia(e,n),i=s!==null?wt(s):e;for(let[c,l]of Object.entries(r))if(c===o||c.endsWith("/")&&o.startsWith(c)){let u=ym(i,s,l);if(u!==null)return u}let a=ym(i,s,t);if(a!==null)return a;if(s!==null)return wt(s);throw new TypeError("specifier was a bare specifier, but was not remapped to anything by importMap.")}function De(e){if(typeof e!="string")throw new TypeError(Path must be a string. Received ${JSON.stringify(e)})}function $a(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 ja(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 Aa(e,t){if(De(e),e.length===0)return e;if(typeof t!="string")throw new TypeError(Suffix must be a string. Received ${JSON.stringify(t)})}function Qr(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 kt(e){return e===47||e===92}function Nt(e){return e>=97&&e<=122||e>=65&&e<=90}function Ts(e){if(e=e instanceof URL?e:new URL(e),e.protocol!=="file:")throw new TypeError("Must be a file URL.");return e}function wm(e){e=Ts(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 Ua(e){De(e);let t=e.length;if(t===0)return!1;let r=e.charCodeAt(0);return kt(r)?!0:!!(Nt(r)&&t>2&&e.charCodeAt(1)===58&&kt(e.charCodeAt(2)))}var h0={" ":"%09","\n":"%0A","\v":"%0B","\f":"%0C","\r":"%0D"," ":"%20"};function Ls(e){return e.replaceAll(/[\s]/g,t=>h0[t]??t)}function Tm(e){if(!Ua(e))throw new TypeError("Must be an absolute path.");let[,t,r]=e.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/),n=new URL("file:///");if(n.pathname=Ls(r.replace(/%/g,"%25")),t!==void 0&&t!=="localhost"&&(n.hostname=t,!n.hostname))throw new TypeError("Invalid hostname.");return n}function ct(e){return e===47}function Ha(e,t=""){Aa(e,t);let r=ja(e,ct),n=Qr(r,ct);return t?$a(n,t):n}function za(e){De(e);let t=-1,r=0,n=-1,o=!0,s=0;for(let i=e.length-1;i>=0;--i){let a=e.charCodeAt(i);if(ct(a)){if(!o){r=i+1;break}continue}n===-1&&(o=!1,n=i+1),a===46?t===-1?t=i: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 Sm(e){return e=Ts(e),decodeURIComponent(e.pathname.replace(/%(?![0-9A-Fa-f]{2})/g,"%25"))}function qa(e){return De(e),e.length>0&&ct(e.charCodeAt(0))}function Pm(e){if(!qa(e))throw new TypeError("Must be an absolute path.");let t=new URL("file:///");return t.pathname=Ls(e.replace(/%/g,"%25").replace(/\\/g,"%5C")),t}var P0=(()=>{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"})(),Le=P0==="windows";function _m(e){return Le?wm(e):Sm(e)}function Ss(e){return Le?Tm(e):Pm(e)}var Cm={"&":"\\x26","!":"\\x21","#":"\\x23",$:"\\$","%":"\\x25","*":"\\*","+":"\\+",",":"\\x2c",".":"\\.",":":"\\x3a",";":"\\x3b","<":"\\x3c","=":"\\x3d",">":"\\x3e","?":"\\?","@":"\\x40","^":"\\^","":"\\x60","~":"\\x7e","(":"\\(",")":"\\)","[":"\\","":"\\]","{":"\\{","}":"\\}","/":"\\/","-":"\\x2d","\\":"\\\\","|":"\\|"},_0=new RegExp([${Object.values(Cm).join("")}],"gu");function Mm(e){return e.replaceAll(_0,t=>Cmt)}function Fn(e){e.hash="",e.search=""}function Ps(e,t){return e=new URL(e),Fn(e),Ha(e.href,t)}function Rs(e){return e=new URL(e),Fn(e),za(e.pathname)}var Dm=e=>{if(e.protocol==="file:")return{path:_m(e),namespace:"file"};let t=e.protocol.slice(0,-1);return{path:e.href.slice(t.length+1),namespace:t}},Im=e=>e.namespace==="file"?Ss(e.path):new URL(${e.namespace}:${e.path});var C0="base64","binary","copy","css","dataurl","default","empty","file","js","json","jsx","local-css","text","ts","tsx",Nm=e=>C0.includes(e),Om=e=>{let t=e.url,r=Ps(t);if(Nm(r))return r;if(r==="mjs")return"js";let n=Rs(t).slice(1);if(Nm(n))return n;if(n==="mjs")return"js";let s=(e.headers.get("Content-Type")??"text/plain").split(";")0?.trim?.()??"text/plain";return M0(s)},M0=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 jm=e=>({name:"remote-resource",setup({onStart:t,onResolve:r,onLoad:n,initialOptions:o}){let{importMapURL:s,sources:i=[],progressCallback:a}=e??{},c={};t(async()=>{if(!s)return;let p=await $m(${s},e.fetch,i,e.reload,a);c=Na(JSON.parse(p.contents instanceof Uint8Array?new TextDecoder().decode(p.contents):p.contents??""),s)});let l=(o.external??[]).map(p=>new RegExp(Mm(p).replace(/\\\*/g,".*")));r({filter:/.*/},p=>{let f;if(p.importer!==""){if(p.namespace==="")throw new Error("assert namespace is empty");f=new URL(${p.namespace}:${p.importer})}else if(p.resolveDir!=="")f=new URL(${Ss(p.resolveDir).href}/);else return;let d;if(c!==null){let h=Oa(p.path,c,new URL(f));d=new URL(h)}else d=new URL(p.path,f);let g={type:"resolve",external:!1,path:d.href};p.kind!=="entry-point"&&(g.parent=f.href);for(let h of l)if(h.test(d.href))return g.external=!0,a?.(g),{path:g.path,external:g.external};return a?.(g),Dm(d)});let u=p=>$m(Im(p).href,e.fetch,i,e.reload,a);n({filter:/.*/,namespace:"file"},u),n({filter:/.*/,namespace:"http"},u),n({filter:/.*/,namespace:"https"},u),n({filter:/.*/,namespace:"data"},u)}}),$m=async(e,t,r,n,o)=>{let s=r.find(u=>u.path===e);if(s!==void 0){let u=Rs(e).slice(1)||Ps(e),p=s.loader??(bs(u)?ys(u):"text");return o?.({type:"load",path:e,done:Promise.resolve({size:new Blob(s.contents).size,loader:p,isCache:!0})}),{contents:s.contents,loader:p}}let i=n?n===!0?!1:!n.some(u=>u.test(e)):!0,a=t(new Request(e),i).then((u,p)=>{let f=Om(u);return u.blob().then(d=>d,f,p)});o?.({type:"load",path:e,done:a.then((u,p,f)=>({size:u.size,loader:p,isCache:f}))});letc,l=await a;return{contents:new Uint8Array(await c.arrayBuffer()),loader:l}};var Am,Fm=async(e,t)=>(Am??=xs({wasmModule:e,workerURL:t}),await Am,async(r,{extension:n,fileName:o,dirURL:s})=>{o??=codeblock-${Math.floor(16777214*Math.random()).toString(16)}.${ys(n)};let i=${s}${o},a=new Map,{outputFiles:c}=await gs({entryPoints:i,format:"esm",bundle:!0,minify:!0,charset:"utf8",plugins:[jm({fetch:D0,reload:new URLPattern({hostname:location.hostname}),new URLPattern({hostname:"scrapbox.io"}),sources:{path:i,contents:r},progressCallback:l=>{if(l.type==="resolve"){if(!l.parent)return;let u=a.get(l.parent)??{path:l.parent,isCache:!1,children:[]},p=a.get(l.path)??{path:l.path,isCache:!1,children:[]};u.children.push(p),a.set(l.parent,u),a.set(l.path,p);return}l.done.then(({isCache:u})=>{let p=a.get(l.path)??{path:l.path,isCache:u,children:[]};p.isCache=u,a.set(l.path,p)})}})],write:!1});return{contents:c0.text,graph:a.get(new URL(i).href)}}),D0=async(e,t)=>{let r=xm(new URL(e.url))||!GM_fetch?globalThis.fetch:GM_fetch;if(t){let n=await ar(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 Co(e,n),n,!1;throw new TypeError(${n.status} ${n.statusText})}catch(n){if(!(n instanceof TypeError))throw n;let o=await ar(e);if(o)return o.url||Object.defineProperty(o,"url",{value:e.url}),o,!0;throw n}};var Um=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle-fill"),e.style.color="hsl(133, 46.1%, 47.3%)",e},Bm=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-cross-circle"),e.style.color="hsl(1.7, 64.5%, 58%)",e},Hm=()=>{let e=document.createElement("i");return e.classList.add("i","fa","fa-spinner"),e},zm=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-play"),e};var qm=()=>{let e;return{show:(n,{x:o,y:s})=>{e=I0(),e.append(N0(n)),e.style.visibility="hidden",document.body.append(e);let{height:i}=e.getBoundingClientRect();e.style.top=${s-i}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?.()}}},I0=()=>{let e=document.createElement("div");return e.setAttribute("role","tooltip"),e.classList.add("fade","in","tooltip","top"),e},N0=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 Wm=()=>{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}=qm();return{component:e,setStatus:async(s,i)=>{switch(e.textContent="",await n(),s){case"loading":e.append(Hm());break;case"pass":e.append(Um());break;case"fail":e.append(Bm());break;case"none":break}i!==void 0&&s!=="none"?(e.style.removeProperty("pointer-events"),e.onclick=async()=>{if(t)await n();else{let{top:a,left:c}=e.getBoundingClientRect();r(i,{y:a+globalThis.scrollY,x:c})}t=!t}):e.style.pointerEvents="none"}}};var Km=e=>{let t=document.createElement("a");return t.classList.add("tool-btn"),t.type="button",t.setAttribute("aria-haspopup","true"),t.append(zm()),t.addEventListener("click",e),t};var Gm=e=>{let{component:t,setStatus:r}=Wm(),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(Km(e),t),{menu:n,setStatus:r}};function Xm(e){return new Promise(t=>setTimeout(t,e))}function Ym(e,t){let{trailing:r=!1,interval:n=0}=t??{},o,s=!1,i=l=>{o?.resolve?.({executed:!1}),o=l},a=()=>{let{...l}=o;return o=void 0,l},c=async()=>{if(s||!o)return;s=!0,n>0&&await Xm(n);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 Vm,Jm=async(e,t)=>{let r=[],o=Ym(async()=>{let s=Zd(scrapbox.Project.name,scrapbox.Page.title??"",Be());r.forEach(({menu:i,setStatus:a})=>{a("none"),i.remove()}),s.forEach(i=>{let a=i.lang.toLowerCase();bs(a)&&i.startIds.forEach(c=>{let l=document.getElementById(L${c}),{menu:u,setStatus:p}=Gm(async()=>{await p("loading");try{Vm??=await Fm(e,t);let{contents:f}=await Vm(i.lines.join(` ),{extension:a,fileName:i.filename,dirURL:${i.dir}/});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 o(),scrapbox.addListener("lines:changed",o),()=>{scrapbox.removeListener("lines:changed",o),r.forEach(({menu:s,setStatus:i})=>{i("none"),s.remove()})}};var Un=e=>e==null,_s=e=>typeof e=="string",Cs=e=>typeof e=="number";var Qm=!1;scrapbox.addListener("lines:changed",()=>Qm=!1);scrapbox.addListener("layout:changed",()=>Qm=!1);var Zm=(e,t)=>{if(!(e instanceof HTMLDivElement))throw new TypeError("${t}" must be HTMLDivElememt but actual is "${e}")};var ef=(e,t)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError("${t}" must be HTMLTextAreaElement but actual is "${e}")};var Ka=()=>O0(document.getElementsByClassName("lines").item(0),"div.lines");var Et=()=>{let e=document.getElementById("text-input");if(e)return ef(e,"textarea#text-input"),e};var O0=(e,t)=>{if(e)return Zm(e,t),e};var Ga=()=>{let e=Ka();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 tf=e=>{if(Un(e))return;if(Cs(e))return j0(e)?.id;if(_s(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 j0=e=>{if(Un(e))return;if(Cs(e))return Ga()[e];let t=tf(e);return t?Ga().find(r=>r.id===t):void 0},rf=e=>{if(A0(e))return e;let t=tf(e);if(Un(t))return t;let r=document.getElementById(L${t});if(!Un(r))return r},A0=e=>e instanceof HTMLDivElement&&e.classList.contains("line");var F0=e=>e instanceof HTMLSpanElement&&e.classList.contains("char-index");var Xa=(e,t)=>{let r=rf(e)?.getElementsByClassName?.(c-${t})?.[0];return F0(r)?r:void 0};var Ya=e=>new Promise(t=>setTimeout(()=>t(),e));var nf=async e=>{let t=Et();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 Ya(1)};var Va=e=>e.replaceAll(" ","_").toLowerCase(),of=e=>e.replaceAll("_"," "),Bn=e=>[...e].map((t,r)=>t===" "?"_":!z0.includes(t)||r===e.length-1&&q0.includes(t)?encodeURIComponent(t):t).join(""),z0='@$&+=:;",',q0=':;",';var _r=()=>{let e=Et();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=e[t].return.return.stateNode._stores,n=r.find(s=>s.constructor.name==="Cursor");if(!n)throw Error('#text-input must has a "Cursor" store.');let o=r.find(s=>s.constructor.name==="Selection");if(!o)throw Error('#text-input must has a "Selection" store.');return{cursor:n,selection:o}};var sf=()=>_r().cursor;var af=()=>_r().selection;var cf=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 W0=new Map;scrapbox.on("layout:changed",()=>{let e=Et();if(e)for(let[t,r]of W0)for(let[n,o]of r)for(let s of o)e.addEventListener(t,n,cf(s))});var lf=({title:e,projects:t,selected:r,confirm:n})=>m("div",{className:candidate${r?" selected":""}},m(K0,{title:e,confirm:n}),t.map(o=>m(G0,{project:o.name,title:e,mark:o.mark,confirm:o.confirm}))),K0=({title:e,confirm:t})=>m("a",{className:"button",tabIndex:0,role:"menuitem",href:./${Bn(e)},onClick:pf(t)},e),G0=({project:e,title:t,mark:r,confirm:n})=>r===""?m(W,null):m("a",{className:"mark",tabIndex:0,href:../${e}/${Bn(t)},onClick:pf(n),title:/${e}/${Bn(t)}},r instanceof URL?m("img",{src:r.href}):${r}),pf=e=>_(t=>{t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||(t.preventDefault(),t.stopPropagation(),e())},[e]);var uf=(e,t)=>{let[r,n]=F(null),o=_(c=>n(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=_(c=>n(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=_(()=>n(e.length===0?null:t(e[0])),[e,t]),a=_(()=>n(e.length===0?null:t(e[e.length-1])),[e,t]);return{selectedId:r,next:o,prev:s,selectFirst:i,selectLast:a}};var df=e=>{let[t,r]=F(null),n=$(()=>{let o=t?.getBoundingClientRect?.(),i=Xa(e.line,e.char)?.getBoundingClientRect?.();return!i||!o?{}:{top:${i.bottom-o.top}px,left:${i?.left??0-o.left}px,right:${o.right-(i?.left??0)}px}},[t,e.line,e.char]);return{updateStandardElement:r,...n}};var Qa="enableProjectsOnSuggestion",mf=(e,t)=>{let[r,n]=F(Ms([...e],t)),o=_((s,i)=>{X0(s,i,e,t),n(Ms([...e],t))},[e,t.enableSelfProjectOnStart]);return K(()=>{let s=i=>{i.key===Qa&&n(Ms([...e],t))};return addEventListener("storage",s),()=>removeEventListener("storage",s)},[e,t.enableSelfProjectOnStart]),{projects:r,set:o}},Ja=!0,Ms=(e,t)=>{try{let r=localStorage.getItem(Qa);if(r===null)return Ds(e),e;let n=JSON.parse(r);return Array.isArray(n)&&n.every(o=>typeof o=="string")?!t.enableSelfProjectOnStart||!e.includes(scrapbox.Project.name)?n:n.includes(scrapbox.Project.name)?Ja?n:n.filter(o=>o!==scrapbox.Project.name):Ja?[...n,scrapbox.Project.name]:n:(Ds(e),e)}catch(r){if(!(r instanceof TypeError))throw r;return Ds(e),e}},X0=(e,t,r,n)=>{let o=Ms([...r],n);n.enableSelfProjectOnStart&&e===scrapbox.Project.name&&(Ja=t),Ds(t?[...o,e]:o.filter(s=>s!==e))},Ds=e=>localStorage.setItem(Qa,JSON.stringify(e));var ff=()=>$(()=>document.documentElement.dataset.os??"",[]);var Hn=(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(n){if(!(n instanceof TypeError))throw n;return e}}};var gf=({progress:e})=>m("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 xf=({position:e,start:t,enableSelfProjectOnStart:r,projects:n,...o})=>{let{projects:s,set:i}=mf(n,{enableSelfProjectOnStart:r}),{updateStandardElement:a,top:c,left:l,right:u}=df({line:e.line,char:t}),p=ff();return m(W,null,m(V0,{itemCount:o.items.length,enableProjects:s,projects:n,top:c,right:u,set:i,os:p,...o}),m(Y0,{updateStandardElement:a,start:t,enableProjects:s,projects:n,top:c,left:l,os:p,...o}))},Y0=({start:e,updateStandardElement:t,confirmAfter:r,cancel:n,query:o,enableProjects:s,projects:i,items:a,top:c,left:l,progress:u,callback:p,limit:f,mark:d,os:g})=>{let h=_((P,T)=>{let E=T?/${T}/${P}:${P};r((R,{line:D})=>[${...R.slice(0,e).join("")}${E}${...R.slice(e+...o.length).join("")},{line:D,char:e+[...E].length}])},[e,o]),x=$(()=>i.size>1||!i.has(scrapbox.Project.name),[i]),v=$(()=>{let P=[];for(let T of a){if(P.length===f)break;T.projects.some(E=>s.includes(E))&&P.push({title:T.title,projects:T.projects.flatMap(E=>s.includes(E)?[{name:E,mark:x?Hn(d[E]??"",import.meta.url)||E[0]:"",confirm:()=>h(T.title,E)}]:[]),confirm:()=>h(T.title)})}return P},[s,x,a,f,d,h]),{selectedId:L,next:S,prev:b,selectLast:k,selectFirst:w}=uf(v,hf),C=_(()=>L===null?!1:(v.find(P=>hf(P)===L)?.confirm?.(),!0),[L,v]);K(()=>p(v.length===0?void 0:{selectNext:P=>(S(P),!0),selectPrev:P=>(b(P),!0),selectFirst:()=>(w(),!0),selectLast:()=>(k(),!0),confirm:C,cancel:()=>(n(),!0)}),[p,v.length,S,b,w,k,C]);let M=$(()=>v.length>0&&c!=null&&l!=null?{top:c,left:l}:{display:"none"},[v.length,c,l]),B=_(P=>{if(!P){t(P);return}let T=P.parentNode;if(!(T instanceof ShadowRoot))throw Error('The parent of "div.container" must be ShadowRoot');t(T.host.parentElement)},[t]);return m("div",{ref:B,className:"container candidates","data-os":g,style:M},v.map(P=>m(lf,{key:P.title,...P,selected:L===P.title})),a.length>f&&m("div",{className:"counter"},${a.length-f} more links),m(gf,{progress:u}))},V0=({enableProjects:e,projects:t,projectScore:r,mark:n,itemCount:o,top:s,right:i,set:a,os:c,freezeUntil:l})=>{let u=$(()=>[...t].sort((f,d)=>(r.get(d)??0)-(r.get(f)??0)).flatMap(f=>r.has(f)?[{name:f,enable:e.includes(f),mark:Hn(n[f]??"",import.meta.url)||f[0],score:r.get(f),onClick:()=>l(()=>{a(f,!e.includes(f)),Et().focus()})}]:[]),[t,r,e,n]),p=$(()=>o>0&&s!=null&&i!=null&&t.size>1?{top:s,right:i}:{display:"none"},[s,i,o,t.size]);return m("div",{className:"container projects","data-os":c,style:p},u.map(f=>m(J0,{key:f.name,...f})))},J0=e=>m("div",{className:e.enable?"mark":"mark disabled","data-score":e.score.toPrecision(3),onClick:e.onClick,title:e.name},e.mark instanceof URL?m("img",{src:e.mark.href}):${e.mark}),hf=e=>e.title;var Ze=!1,Za=e=>{Ze=typeof e=="boolean"?e:new Set(e)},en=e=>Object.fromEntries([...Object.entries(console)].map(([t,r])=>{if(typeof r!="function")return[t,r];switch(t){case"warn":case"error":return[t,(...n)=>r(%c${e},"color: gray",...n)];case"log":case"info":case"debug":return[t,(...n)=>{Ze!==!0&&(!Ze||!Ze.has(e))||r(%c${e},"color: gray",...n)}];case"assert":return[t,(n,...o)=>{Ze!==!0&&(!Ze||!Ze.has(e))||r(n,%c${e},"color: gray",...o)}];case"time":case"timeEnd":return[t,n=>{Ze!==!0&&(!Ze||!Ze.has(e))||r(${e} ${n})}];default:return[t,(...n)=>{if(!(Ze!==!0&&(!Ze||!Ze.has(e))))return r(...n)}]}}));var tn=e=>{let[t,r,n,...o]=e;return{title:t,links:o,image:r,exists:n>=0,updated:Math.min(0,n)}},bf=e=>[e.title,e.image,e.exists?e.updated:-1,...e.links];var yf=e=>{let t=new Map;for(let r of e){let n=X(r.title);t.set(n,{title:r.title,image:r.image,updated:r.updated,links:r.links,exists:!0});for(let o of r.links){let s=X(o);t.has(s)||t.set(s,{title:o,updated:0,links:[],exists:!1})}}return[...t.values()].map(r=>bf(r))};var vf=en("scrapbox-storage:remote.ts"),wf=async e=>{let t,r=[],n=download and create Links of "${e}";vf.time(n);do{let s=await Pl(e,{followingId:t});if(!s.ok)return s;t=s.value.followingId,r.push(...s.value.pages)}while(t);let o=yf(r);return vf.timeEnd(n),{ok:!0,value:o}};async function*kf(e){let t=[],r=[],n=new Map;for(let s of e)s.id?t.push(s.id):r.push(s.project),n.set(s.project,s.checked);let o=await Nr(t);if(!o.ok)r=e.map(s=>s.project);else for(let s of o.value.projects)n.has(s.name)&&(yield{ok:!0,value:{...s,checked:n.get(s.name)??0}});for(let s of r){let i=await pt(s);yield i.ok?{ok:!0,value:{...i.value,checked:n.get(s)??0}}:{ok:!1,value:{...i.value,project:s}}}}var rc=(e,t)=>t.some(r=>e instanceof r),Ef,Tf;function Q0(){return Ef||(Ef=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Z0(){return Tf||(Tf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var nc=new WeakMap,ec=new WeakMap,Is=new WeakMap;function eE(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{r(Vt(e.result)),o()},i=()=>{n(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",i)});return Is.set(t,e),t}function tE(e){if(nc.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{r(),o()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});nc.set(e,t)}var oc={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return nc.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Vt(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 Rf(e){oc=e(oc)}function rE(e){return Z0().includes(e)?function(...t){return e.apply(sc(this),t),Vt(this.request)}:function(...t){return Vt(e.apply(sc(this),t))}}function nE(e){return typeof e=="function"?rE(e):(e instanceof IDBTransaction&&tE(e),rc(e,Q0())?new Proxy(e,oc):e)}function Vt(e){if(e instanceof IDBRequest)return eE(e);if(ec.has(e))return ec.get(e);let t=nE(e);return t!==e&&(ec.set(e,t),Is.set(t,e)),t}var sc=e=>Is.get(e);function _f(e,t,{blocked:r,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(e,t),a=Vt(i);return n&&i.addEventListener("upgradeneeded",c=>{n(Vt(i.result),c.oldVersion,c.newVersion,Vt(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function Cf(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",n=>t(n.oldVersion,n)),Vt(r).then(()=>{})}var oE=["get","getKey","getAll","getAllKeys","count"],sE=["put","add","delete","clear"],tc=new Map;function Lf(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(tc.get(t))return tc.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=sE.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||oE.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,o?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),o&&c.done]))[0]};return tc.set(t,s),s}Rf(e=>({...e,get:(t,r,n)=>Lf(t,r)||e.get(t,r,n),has:(t,r)=>!!Lf(t,r)||e.has(t,r)}));var iE=["continue","continuePrimaryKey","advance"],Sf={},ic=new WeakMap,Mf=new WeakMap,aE={get(e,t){if(!iE.includes(t))return e[t];let r=Sf[t];return r||(r=Sf[t]=function(...n){ic.set(this,Mf.get(this)[t](...n))}),r}};async function*cE(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;t=t;let r=new Proxy(t,aE);for(Mf.set(r,t),Is.set(r,sc(t));t;)yield r,t=await(ic.get(r)||t.continue()),ic.delete(r)}function Pf(e,t){return t===Symbol.asyncIterator&&rc(e,[IDBIndex,IDBObjectStore,IDBCursor])||t==="iterate"&&rc(e,[IDBIndex,IDBObjectStore])}Rf(e=>({...e,get(t,r,n){return Pf(t,r)?cE:e.get(t,r,n)},has(t,r){return Pf(t,r)||e.has(t,r)}}));var Df=en("scrapbox-storage:db.ts"),If,Ns=async()=>(If??=await _f("scrapbox-storage",1,{upgrade(e){Df.time("update DB");for(let t of e.objectStoreNames)e.deleteObjectStore(t);e.createObjectStore("links",{keyPath:"project"}),e.createObjectStore("status",{keyPath:"project"}),Df.timeEnd("update DB")}}),If),Nf=async e=>(await Ns()).put("links",e);var Os=new Map,Of=e=>{let t={type:"update",projects:e};$f(t);let r=new BroadcastChannel(jf);r.postMessage(t),r.close()},$f=e=>{for(let t of new Set(e.projects.flatMap(r=>[...Os.get(r)??[]])))t?.(e)},jf="scrapbox-storage-notify",lE=new BroadcastChannel(jf);lE.addEventListener("message",e=>$f(e.data));var zn=(e,t)=>{for(let r of e){let n=Os.get(r)??new Set;n.add(t),Os.set(r,n)}return()=>{for(let r of e)Os.get(r)?.delete?.(t)}};var Ot=en("scrapbox-storage:mod.ts"),$s=async(e,t)=>{let r=await Ns(),n=[],o=[];try{{Ot.debug("check updates of links...");let a=r.transaction("status","readwrite");await Promise.all(e.map(async c=>{let l=await a.store.get(c);if(l?.isValid===!1)return;let u=l?.checked??0,p=new Date().getTime()/1e3;if(u+t>p||l?.updating&&u+600>p)return;let f={project:c,id:l?.id,isValid:!0,checked:u,updated:l?.updated??0,updating:!0};n.push(f),a.store.put(f)})),await a.done,Ot.debug(checked. ${n.length} projects maybe need upgrade.)}if(n.length===0)return[];let s=[],i=[];for await(let a of kf(n)){if(!a.ok)switch(o.push({project:a.value.project,isValid:!1}),a.value.name){case"NotFoundError":Ot.warn("${a.value.project}" is not found.);continue;case"NotMemberError":Ot.warn(You are not a member of "${a.value.project}".);continue;case"NotLoggedInError":Ot.warn(You are not a member of "${a.value.project}" or You are not logged in yet.);continue}if(a.value.updated<a.value.checked)Ot.debug(no updates in "${a.value.name}");else{let c=await wf(a.value.name);if(!c.ok)throw Error(${c.value.name} ${c.value.message});let l={project:a.value.name,links:c.value};i.push(l),Ot.time(write data of "${a.value.name}"),await Nf(l),s.push(a.value.name),Ot.timeEnd(write data of "${a.value.name}")}o.push({project:a.value.name,isValid:!0,id:a.value.id,checked:new Date().getTime()/1e3,updated:a.value.updated,updating:!1})}return s.length>0&&Of(s),i}finally{let s=r.transaction("status","readwrite"),i=s.store;await Promise.all(o.map(a=>i.put(a))),await s.done}},rn=async e=>{let t=[],r=new Date;{let o=(await Ns()).transaction("links","readonly");await Promise.all(e.map(async s=>{let i=await o.store.get(s);t.push(i??{project:s,links:[]})})),await o.done}let n=new Date().getTime()-r.getTime();return Ot.debug(Read links of ${e.length} projects in ${n}ms),t};Cf("userscript-links").catch(e=>console.error(e));var ac=xt("scrapbox-select-suggestion:useSource.ts"),Af=e=>{let[t,r]=F([]),n=_(o=>{let s=new Date,i=new Map;for(let{project:l,links:u}of o)for(let p of u){let{title:f,updated:d,image:g}=tn(p),h=Va(f),x=i.get(h);i.set(h,{title:x?.title??f,updated:Math.max(x?.updated??0,d),metadata:[...x?.metadata??[],{project:l,image:g}]})}let a=[...i.entries()].map(([l,u])=>({titleLc:l,...u})),c=new Date().getTime()-s.getTime();ac.debug(Compiled ${a.length} source in ${c}ms),ac.debug("Detect changes!"),r(a)},[]);return K(()=>{let o=!1,s=async()=>{let l=await rn([...e]);o||n(l)};s();let i=zn([...e],({projects:l})=>{ac.debug(Detect ${l.length} projects' update:,l),s()}),a=()=>$s([...e],600);a();let c=setInterval(a,600*1e3);return()=>{o=!0,clearInterval(c),i()}},[e]),t};var Ff=e=>{let t=$(()=>Hn(e.style,import.meta.url),[e.style]);return m(W,null,t!==""&&(t instanceof URL?m("link",{rel:"stylesheet",href:t.href}):m("style",null,t)))};var Uf=()=>m("style",null,.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;
}
font-size:11px;
}
.projects {
margin-right: 4px;
display: grid;
grid-template-rows: repeat(4, min-content);
grid-auto-flow: column;
direction: rtl;
}
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;
}
padding: unset;
border: unset;
height: 0.5px;
transition: background 0.1s;
});function*Bf(e){if(!("nodes"in e))return;let t=0;function*r(n){for(let o of Array.isArray(n)?n:[n]){if(typeof o=="string"){t+=[...o].length;continue}switch(o.type){case"link":yield{whole:o.unit.whole,start:t},t+=[...o.unit.whole].length;break;case"indent":case"quote":t+=[...o.unit.tag].length,yield*r(o.children);break;case"deco":t+=[...o.unit.deco].length+2,yield*r(o.children),t++;break;case"strong":t+=2,yield*r(o.children),t+=2;break;default:t+=[...o.unit.whole].length;break}}}yield*r(e.nodes)}var Hf=(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),n=Math.max(t.range.start.char,t.range.end.char),o=t.lines?t.range.start.line!==t.range.end.line?
:[...t.lines[t.range.start.line].text].slice(r,n).join(""):"";if(uE(t.lines[t.position.line],o)&&e.type!=="cancelled")return{type:"completion",context:"selection",query:o,start:r,position:t.position};if(o!=="")return e.type==="completion"?{type:"ready"}:e;let s=pE(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"}},pE=(e,t)=>{for(let{whole:r,start:n}of Bf(e))if(!(t<=n||n+[...r].length<=t))return{whole:r,start:n}},uE=(e,t)=>!(t.trim()===""||t.includes(
)||"codeBlock"in e||"title"in e||"tableBlock"in e&&e.tableBlock.start);var zf=()=>{let e=ke(scrapbox.Page.lines),t=ke(!1);return K(()=>{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)}},[]),_(()=>(t.current&&(e.current=scrapbox.Page.lines,t.current=!1),e.current??void 0),[])};var dE=xt("scrapbox-select-suggestion:useLifecycle.ts"),qf=()=>{let[e,t]=sr(Hf,{type:"ready"}),r=zf(),n=$(()=>{let i;return a=>{i!==void 0&&clearTimeout(i),i=setTimeout(()=>{let{cursor:c,selection:l}=_r();t({type:a,lines:r(),range:l.getRange({normalizeOrder:!0}),position:c.getPosition()})},a==="cursor:changed"?100:void 0)}},[]);K(()=>{let i=()=>{n("lines:changed")};scrapbox.addListener("lines:changed",i),scrapbox.addListener("layout:changed",i);let a=()=>{n("selection:changed")},c=af();return c.addChangeListener(a),()=>{scrapbox.removeListener("lines:changed",i),scrapbox.removeListener("layout:changed",i),c.removeChangeListener(a)}},[]),K(()=>{if(e.context!=="input")return;let i=()=>{n("cursor:changed")},a=sf();return a.addChangeListener(i),()=>a.removeChangeListener(i)},[e.context]);let[o,s]=F(e);return o!==e&&(s(e),dE.debug("Detect changes",e)),{state:e,setEnable:_(i=>t({type:i?"enable":"disable"}),[]),cancel:_(()=>t({type:"cancel"}),[]),freezeUntil:_(i=>{t({type:"lock"});let a=i();if(a instanceof Promise)return a.then(()=>{t({type:"unlock"})});t({type:"unlock"})},[]),confirmAfter:_(async i=>{let a=r();if(!a)return;t({type:"lock"});let{cursor:c,selection:l}=_r(),u=c.getPosition().line,p=a[u].text,[f,d]=i(p,c.getPosition());l.setRange({start:{line:u,char:0},end:{line:u,char:[...p].length}}),await nf(f),c.setPosition(d),c.focus(),t({type:"unlock"}),t({type:"cancel"})},[])}};var Wf=(e,t)=>{let r=e.dist-t.dist;if(r!==0)return r;let n=e.matches.map(([i])=>i).sort(),o=t.matches.map(([i])=>i).sort();for(let i=0;i<n.length;i++){let a=n[i]-(o[i]??o.length);if(a!==0)return a}let s=e.title.length-t.title.length;return s!==0?s:t.updated-e.updated};var Kf=e=>{let t=new Map,r=[...e].reverse();{let i=1;for(let a of r){t.set(a,(t.get(a)??0)|i);let c=a.toLowerCase();t.set(c,(t.get(c)??0)|i);let l=a.toUpperCase();t.set(l,(t.get(l)??0)|i),i<<=1}}let n=r.length,o=~(-1<<n),s=1<<n-1;return i=>{let a=0,c=o,l=[...i].reverse(),u=[],p=l.length;u[p]=n;for(let f of l){let d=t.get(f)??0,g=d|a,h=(d&c)+c^c|d,x=a|~(h|c),v=c&h;u[p-1]=u[p]+(x&s?1:v&s?-1:0),c=v<<1|~(g|x<<1),a=x<<1&g,p--}return u}};var mE=[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],Gf=e=>{let t=of(e.trim()).split(/\s+/).sort((r,n)=>n.length-r.length);if(!(t.length===0||t.every(r=>r==="")))return r=>{let n=[...r];for(let o of t)n=fE(o,n);return n}},fE=(e,t)=>{let r=[...e].length,n=mE[r],o=Kf(e);return t.flatMap(({title:s,dist:i,matches:a,...c})=>{a??=[],i??=0;let l=o(s).flatMap((p,f)=>p<=n&&a.every(([d,g])=>f+r<=d||g<f)?[[f,p]]:[]);if(l.length===0)return[];let u=l.reduce((p,[f,d])=>(p.dist<=d||(p.dist=d,p.start=f),p),{dist:r,start:0});return a.push([u.start,u.start+r-1]),[{title:s,dist:u.dist+i,matches:a,...c}]})};var gE=xt("scrapbox-select-suggestion:cancelableSearch.ts");async function*Xf(e,t,r){let n=Gf(e);if(!n)return;let o=r?.chunk??1e3,s=Math.floor(t.length/o)+1,i=0,a=new Date;try{for(;i<s;i++)await new Promise(c=>requestAnimationFrame(c)),yield[n(t.slice(i*o,(i+1)*o)),(i+1)/s]}finally{let l=new Date().getTime()-a.getTime();gE.debug(search ${(i/s*100).toPrecision(3)}% of the source for "${e}" in ${l}ms)}}function Yf(e,t){let r=null,n=null,o=(...s)=>{o.clear(),n=()=>{o.clear(),e.call(o,...s)},r=setTimeout(n,t)};return o.clear=()=>{typeof r=="number"&&(clearTimeout(r),r=null,n=null)},o.flush=()=>{n?.()},Object.defineProperty(o,"pending",{get:()=>typeof r=="number"}),o}var hE=xt("scrapbox-select-suggestion:useSearch.ts"),Vf=e=>{let t=_((o,s,i)=>{let a=!1,c=Xf(o,s,{chunk:5e3});return{run:async()=>{if(i){let f=[];for await(let[d]of c){if(a)return;f.push(...d)}n({progress:1,candidates:f});return}let l=Yf(n,500),u=!1,p=[];for await(let[f,d]of c){if(a){l.clear();return}p=[...p,...f],n({progress:d}),f.length!==0&&(l({progress:d,candidates:p}),u||(l.flush(),u=!0))}l({progress:1,candidates:p}),l.flush()},abort:()=>a=!0}},[]),[r,n]=sr($(()=>xE(t),[t]),{source:e});return[$(()=>{if(!nn(r))return;let[o,s]=bE(r.candidates);return hE.debug("Detect changes",{progress:r.progress,items:s}),{progress:r.progress,projectScore:o,items:s}},[r]),{search:_(o=>n({query:o}),[]),update:_(o=>n({source:o}),[])}]},nn=e=>"query"in e,xE=e=>(t,r)=>{if("query"in r){let i=nn(t)?t.query:"";if(r.query===i)return t;let a=nn(t)?t.job:void 0;if(!r.query)return a?.abort?.(),{source:t.source};let{run:c,abort:l}=e(r.query,t.source,!1),u=a?.abort?.()?.then?.(c)??c();return{query:r.query,source:t.source,job:{done:u,abort:()=>(l(),u)},progress:0,candidates:!i||!nn(t)?[]:t.candidates}}if("source"in r){if(!nn(t))return r.source===t.source?t:r;let{source:i,job:a,...c}=t;if(r.source===i)return t;let{run:l,abort:u}=e(t.query,i,!1),p=a.done.then(l);return{source:r.source,job:{done:p,abort:()=>a.abort().then(()=>(u(),p))},...c}}if(!nn(t))return t;if(!r.candidates){let{progress:i,...a}=t;return i===r.progress?t:{progress:r.progress,...a}}let{candidates:n,progress:o,...s}=t;return n===r.candidates&&o===r.progress?t:{candidates:r.candidates??n,progress:r.progress,...s}},bE=e=>{let t=new Map,r=[];for(let n of e.sort(Wf)){let o=n.metadata.map(({project:s})=>s);for(let s of o)t.set(s,(t.get(s)??0)+.5**n.dist);r.push({title:n.title,dist:n.dist,projects:o})}return[t,r]};var Jf=(e,t)=>{let r=ke({...t});K(()=>(Object.assign(r.current,t),()=>{for(let n of Object.keys(t))delete r.current[n]}),[...Object.keys(t)].sort().map(n=>t[n])),K(()=>{e(r.current)},[e])};var yE={selectNext:()=>!1,selectPrev:()=>!1,selectFirst:()=>!1,selectLast:()=>!1,confirm:()=>!1,cancel:()=>!1},Qf=e=>{let t=Af(e.projects),[r,{update:n,search:o}]=Vf(t),{state:s,setEnable:i,...a}=qf();n(t),o(s.type==="completion"?s.context==="input"?s.query.slice(1,-1):s.query:"");let[c,l]=F(),{callback:u,style:p,...f}=e;return Jf(u,{enable:_(()=>i(!0),[]),disable:_(()=>i(!1),[]),...s.type!=="completion"||!c?yE:c}),m(W,null,m(Uf,null),m(Ff,{style:p}),s.type==="completion"&&r&&m(xf,{callback:l,...r,...s,...a,...f}))};var Zf=e=>{let t=document.createElement("div");t.dataset.userscriptName="scrapbox-select-suggestion";let r=t.attachShadow({mode:"open"});document.body.append(t);let{limit:n=5,debug:o=!1,mark:s={},style:i="",enableSelfProjectOnStart:a=!0}=e??{},c=new Set([...a?[scrapbox.Project.name]:[],...e?.projects??[scrapbox.Project.name]]);return zi(o),Za(o),new Promise(l=>we(m(Qf,{limit:n,projects:c,mark:s,style:i,callback:l,enableSelfProjectOnStart:a}),r))};var et=e=>e.flatMap(t=>{let r=t.slice(1),n=Math.min(...r.map(o=>o.text.length-o.text.trimStart().length));return r.map(o=>o.text.slice(n))}).join(
).trim();function*eg(e,t){for(let[r,n]of t.entries()){let o=e.get(r);if(o&&et(o.blocks)===et(n)){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 tg=e=>{let t=new Map;if(e.length===0)return t;let r=rt(e.map(o=>o.text).join(
),{hasTitle:!0}),n=0;for(let o of r)switch(o.type){case"title":case"line":n++;break;case"table":n+=o.cells.length+1;break;case"codeBlock":{let s=t.get(o.fileName)??[],i=o.content.split(
).length+1;s.push(e.slice(n,n+i)),t.set(o.fileName,s),n+=i;break}}return t};var rg=e=>{let t,r,n=async()=>{for(;t;){let[o,s]=t;t=void 0;try{let i=await e(...o);s({type:"resolve",value:i})}catch(i){s({type:"reject",value:i})}}r=void 0};return(...o)=>{let{resolve:s,promise:i}=Promise.withResolvers();return t?.[1]?.({type:"cancel"}),t=[o,s],r??=n(),i}};var js=class{constructor(t,r){this._filename=t;this._preview=rg(async(n,o,s)=>(this._dispose=await r(s?{filename:this.filename,before:n,after:o,render:(...i)=>{s.textContent="",s.append(...i)}}:{filename:this.filename,before:n}),!1))}get filename(){return this._filename}get blocks(){return this._blocks??[]}async update(t){if(await this._dispose?.(),!t||et(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 n=this.makeArea(),o=t.at(0)?.at?.(-1)?.id,s=ir(o);if(!s)throw new Error("div.lines#L${o}" could not be found.);s.insertAdjacentElement("afterend",n);let i=()=>{let a=s.getElementsByClassName("indent")[0];a instanceof HTMLElement&&(n.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,n)}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(n=>n.slice(1).map(({id:o})=>#L${o})),r=this.blocks.flatMap(n=>n.map(({id:o})=>#L${o}));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 ng=({previewers:e})=>{let t=new Map,r=()=>{let s=tg(Be());for(let{changed:i,filename:a}of eg(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 js(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}})}},n=()=>{if(scrapbox.Layout!=="page"){scrapbox.off("lines:changed",r);return}r(),scrapbox.on("lines:changed",r)};n(),scrapbox.on("page:changed",n);let o=document.createElement("style");return o.textContent=".scrap-run{display:block;width:95%}",document.head.append(o),()=>{scrapbox.off("page:changed",n),o.remove()}};var qn=e=>{let t=new FileReader,r=new Promise(n=>t.onload=()=>n(t.result));return t.readAsDataURL(e),r};var og=async e=>{if(!("after"in e))return;let t=et(e.after),n=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("parsererror");if(n){let i=document.createElement("pre"),a=document.createElement("code");a.innerText=n.innerHTML,i.append(a),e.render(i);return}let o=await qn(new Blob([t],{type:"image/svg+xml"})),s=document.createElement("img");s.src=o,e.render(s)};var pc={};mn(pc,{default:()=>pg});var sg=globalThis||(typeof window<"u"?window:self),YE=Object.create,lc=Object.defineProperty,VE=Object.getOwnPropertyDescriptor,JE=Object.getOwnPropertyNames,QE=Object.getPrototypeOf,ZE=Object.prototype.hasOwnProperty,eT=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tT=(e,t)=>{for(var r in t)lc(e,r,{get:t[r],enumerable:!0})},cc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of JE(t))!ZE.call(e,o)&&o!==r&&lc(e,o,{get:()=>t[o],enumerable:!(n=VE(t,o))||n.enumerable});return e},rT=(e,t,r)=>(cc(e,t,"default"),r&&cc(r,t,"default")),ag=(e,t,r)=>(r=e!=null?YE(QE(e)):{},cc(t||!e||!e.__esModule?lc(r,"default",{value:e,enumerable:!0}):r,e)),cg=eT((e,t)=>{var r;typeof window<"u"?r=window:typeof sg<"u"?r=sg:typeof self<"u"?r=self:r={},t.exports=r}),lg={};tT(lg,{default:()=>pg});var nT=ag(cg());rT(lg,ag(cg()));var{default:ig,...oT}=nT,pg=ig!==void 0?ig:oT;var mc={};mn(mc,{default:()=>gg});var sT=Object.create,dc=Object.defineProperty,iT=Object.getOwnPropertyDescriptor,aT=Object.getOwnPropertyNames,cT=Object.getPrototypeOf,lT=Object.prototype.hasOwnProperty,pT=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),uT=(e,t)=>{for(var r in t)dc(e,r,{get:t[r],enumerable:!0})},uc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of aT(t))!lT.call(e,o)&&o!==r&&dc(e,o,{get:()=>t[o],enumerable:!(n=iT(t,o))||n.enumerable});return e},dT=(e,t,r)=>(uc(e,t,"default"),r&&uc(r,t,"default")),dg=(e,t,r)=>(r=e!=null?sT(cT(e)):{},uc(t||!e||!e.__esModule?dc(r,"default",{value:e,enumerable:!0}):r,e)),mg=pT((e,t)=>{t.exports=n;var r=Object.prototype.toString;function n(o){if(!o)return!1;var s=r.call(o);return s==="[object Function]"||typeof o=="function"&&s!=="[object RegExp]"||typeof window<"u"&&(o===window.setTimeout||o===window.alert||o===window.confirm||o===window.prompt)}}),fg={};uT(fg,{default:()=>gg});var mT=dg(mg());dT(fg,dg(mg()));var{default:ug,...fT}=mT,gg=ug!==void 0?ug:fT;var hc={};mn(hc,{default:()=>vg});var gT=Object.create,gc=Object.defineProperty,hT=Object.getOwnPropertyDescriptor,xT=Object.getOwnPropertyNames,bT=Object.getPrototypeOf,yT=Object.prototype.hasOwnProperty,vT=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),wT=(e,t)=>{for(var r in t)gc(e,r,{get:t[r],enumerable:!0})},fc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xT(t))!yT.call(e,o)&&o!==r&&gc(e,o,{get:()=>t[o],enumerable:!(n=hT(t,o))||n.enumerable});return e},kT=(e,t,r)=>(fc(e,t,"default"),r&&fc(r,t,"default")),xg=(e,t,r)=>(r=e!=null?gT(bT(e)):{},fc(t||!e||!e.__esModule?gc(r,"default",{value:e,enumerable:!0}):r,e)),bg=vT((e,t)=>{var r=function(o){return o.replace(/^\s+|\s+$/g,"")},n=function(o){return Object.prototype.toString.call(o)==="[object Array]"};t.exports=function(o){if(!o)return{};for(var s={},i=r(o).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:n(s[u])?s[u].push(p):s[u]=[s[u],p]}return s}}),yg={};wT(yg,{default:()=>vg});var ET=xg(bg());kT(yg,xg(bg()));var{default:hg,...TT}=ET,vg=hg!==void 0?hg:TT;var yc={};mn(yc,{default:()=>Lg});var LT=Object.create,bc=Object.defineProperty,ST=Object.getOwnPropertyDescriptor,PT=Object.getOwnPropertyNames,RT=Object.getPrototypeOf,_T=Object.prototype.hasOwnProperty,CT=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),MT=(e,t)=>{for(var r in t)bc(e,r,{get:t[r],enumerable:!0})},xc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of PT(t))!_T.call(e,o)&&o!==r&&bc(e,o,{get:()=>t[o],enumerable:!(n=ST(t,o))||n.enumerable});return e},DT=(e,t,r)=>(xc(e,t,"default"),r&&xc(r,t,"default")),kg=(e,t,r)=>(r=e!=null?LT(RT(e)):{},xc(t||!e||!e.__esModule?bc(r,"default",{value:e,enumerable:!0}):r,e)),Eg=CT((e,t)=>{t.exports=n;var r=Object.prototype.hasOwnProperty;function n(){for(var o={},s=0;s<arguments.length;s++){var i=arguments[s];for(var a in i)r.call(i,a)&&(o[a]=i[a])}return o}}),Tg={};MT(Tg,{default:()=>Lg});var IT=kg(Eg());DT(Tg,kg(Eg()));var{default:wg,...NT}=IT,Lg=wg!==void 0?wg:NT;var on=e=>{let t=n=>typeof n.default<"u"?n.default:n,r=n=>Object.assign({},n);switch(e){case"global/window":return t(pc);case"is-function":return t(mc);case"parse-headers":return t(hc);case"xtend":return t(yc);default:throw new Error('module "'+e+'" not found')}},OT=Object.create,wc=Object.defineProperty,$T=Object.getOwnPropertyDescriptor,jT=Object.getOwnPropertyNames,AT=Object.getPrototypeOf,FT=Object.prototype.hasOwnProperty,As=(e=>typeof on<"u"?on:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof on<"u"?on:t)[r]}):e)(function(e){if(typeof on<"u")return on.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),UT=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),BT=(e,t)=>{for(var r in t)wc(e,r,{get:t[r],enumerable:!0})},vc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of jT(t))!FT.call(e,o)&&o!==r&&wc(e,o,{get:()=>t[o],enumerable:!(n=$T(t,o))||n.enumerable});return e},HT=(e,t,r)=>(vc(e,t,"default"),r&&vc(r,t,"default")),Pg=(e,t,r)=>(r=e!=null?OT(AT(e)):{},vc(t||!e||!e.__esModule?wc(r,"default",{value:e,enumerable:!0}):r,e)),Rg=UT((e,t)=>{"use strict";var r=As("global/window"),n=As("is-function"),o=As("parse-headers"),s=As("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(d){l[d==="delete"?"del":d]=function(g,h,x){return h=c(g,h,x),h.method=d.toUpperCase(),u(h)}});function i(d,g){for(var h=0;h<d.length;h++)g(d[h])}function a(d){for(var g in d)if(d.hasOwnProperty(g))return!1;return!0}function c(d,g,h){var x=d;return n(g)?(h=g,typeof d=="string"&&(x={uri:d})):x=s(g,{uri:d}),x.callback=h,x}function l(d,g,h){return g=c(d,g,h),u(g)}function u(d){if(typeof d.callback>"u")throw new Error("callback argument missing");var g=!1,h=function(N,j,I){g||(g=!0,d.callback(N,j,I))};function x(){b.readyState===4&&setTimeout(S,0)}function v(){var N=void 0;if(b.response?N=b.response:N=b.responseText||p(b),E)try{N=JSON.parse(N)}catch{}return N}function L(N){return clearTimeout(R),N instanceof Error||(N=new Error(""+(N||"Unknown XMLHttpRequest Error"))),N.statusCode=0,h(N,D)}function S(){if(!w){var N;clearTimeout(R),d.useXDR&&b.status===void 0?N=200:N=b.status===1223?204:b.status;var j=D,I=null;return N!==0?(j={body:v(),statusCode:N,method:M,headers:{},url:C,rawRequest:b},b.getAllResponseHeaders&&(j.headers=o(b.getAllResponseHeaders()))):I=new Error("Internal XMLHttpRequest Error"),h(I,j,j.body)}}var b=d.xhr||null;b||(d.cors||d.useXDR?b=new l.XDomainRequest:b=new l.XMLHttpRequest);var k,w,C=b.url=d.uri||d.url,M=b.method=d.method||"GET",B=d.body||d.data,P=b.headers=d.headers||{},T=!!d.sync,E=!1,R,D={body:void 0,headers:{},statusCode:0,method:M,url:C,rawRequest:b};if("json"in d&&d.json!==!1&&(E=!0,P.accept||P.Accept||(P.Accept="application/json"),M!=="GET"&&M!=="HEAD"&&(P["content-type"]||P["Content-Type"]||(P["Content-Type"]="application/json"),B=JSON.stringify(d.json===!0?B:d.json))),b.onreadystatechange=x,b.onload=S,b.onerror=L,b.onprogress=function(){},b.onabort=function(){w=!0},b.ontimeout=L,b.open(M,C,!T,d.username,d.password),T||(b.withCredentials=!!d.withCredentials),!T&&d.timeout>0&&(R=setTimeout(function(){if(!w){w=!0,b.abort("timeout");var N=new Error("XMLHttpRequest timeout");N.code="ETIMEDOUT",L(N)}},d.timeout)),b.setRequestHeader)for(k in P)P.hasOwnProperty(k)&&b.setRequestHeader(k,P[k]);else if(d.headers&&!a(d.headers))throw new Error("Headers cannot be set on an XDomainRequest object");return"responseType"in d&&(b.responseType=d.responseType),"beforeSend"in d&&typeof d.beforeSend=="function"&&d.beforeSend(b),b.send(B||null),b}function p(d){try{if(d.responseType==="document")return d.responseXML;var g=d.responseXML&&d.responseXML.documentElement.nodeName==="parsererror";if(d.responseType===""&&!g)return d.responseXML}catch{}return null}function f(){}}),_g={};BT(_g,{default:()=>Fs});var zT=Pg(Rg());HT(_g,Pg(Rg()));var{default:Sg,...qT}=zT,Fs=Sg!==void 0?Sg:qT;var Us=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},IZ=function(){function e(r){this.value=r}function t(r){var n,o;function s(c,l){return new Promise(function(u,p){var f={key:c,arg:l,resolve:u,reject:p,next:null};o?o=o.next=f:(n=o=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":n.resolve({value:l,done:!0});break;case"throw":n.reject(l);break;default:n.resolve({value:l,done:!1});break}n=n.next,n?i(n.key,n.arg):o=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)}}}(),Dg=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},Ig=function(){function e(t,r){for(var n=0;n<r.length;n++){var o=r[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),kc=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)},Wn="";function WT(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 KT=
This page requires a browser that supports WebGL.<br/>
,GT=
It does not appear your computer can support WebGL.<br/>
,XT=1,YT=2;function VT(e,t,r){function n(i){var a=e.parentNode;a&&(a.innerHTML=WT(i))}function o(i,a){typeof r=="function"?r(i):n(a)}if(!window.WebGLRenderingContext)return o(XT,KT),null;var s=JT(e,t);return s?s.getExtension("OES_standard_derivatives"):o(YT,GT),s}function JT(e,t){for(var r=["webgl","experimental-webgl"],n=null,o=0;o<r.length;++o)try{n=e.getContext(r[o],t)}catch{if(n)break}return n}function sn(e,t,r,n){var o=e.gl,s=o.createShader(r);o.shaderSource(s,t),o.compileShader(s);var i=o.getShaderParameter(s,o.COMPILE_STATUS);return i?s:(Wn=o.getShaderInfoLog(s),console.error("*** Error compiling shader "+s+":"+Wn),e.trigger("error",{shader:s,source:t,type:r,error:Wn,offset:n||0}),o.deleteShader(s),null)}function Cg(e,t,r,n){for(var o=e.gl,s=o.createProgram(),i=0;i<t.length;++i)o.attachShader(s,t[i]);if(r)for(var a=0;a<r.length;++a)o.bindAttribLocation(s,n?n[a]:a,r[a]);o.linkProgram(s);var c=o.getProgramParameter(s,o.LINK_STATUS);return c?s:(Wn=o.getProgramInfoLog(s),console.log("Error in program linking:"+Wn),o.deleteProgram(s),null)}function Ec(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=[];for(var n in e){var o=e[n],s=void 0;if(t&&(n=t+"."+n),typeof o=="number")r.push({type:"float",method:"1f",name:n,value:o});else if(Array.isArray(o)){if(typeof o[0]=="number")o.length===1?r.push({type:"float",method:"1f",name:n,value:o}):o.length>=2&&o.length<=4?r.push({type:"vec"+o.length,method:o.length+"fv",name:n,value:o}):o.length>4&&r.push({type:"float[]",method:"1fv",name:n+"[0]",value:o});else if(typeof o[0]=="string")r.push({type:"sampler2D",method:"1i",name:n,value:o});else if(Array.isArray(o[0])&&typeof o[0][0]=="number"){if(o[0].length>=2&&o[0].length<=4)for(s=0;s<o.length;s++)r.push({type:"vec"+o[0].length,method:o[s].length+"fv",name:n+"["+s+"]",value:o[s]})}else if(Us(o[0])==="object")for(s=0;s<o.length;s++)r.push.apply(r,kc(Ec(o[s],n+"["+s+"]")))}else typeof o=="boolean"?r.push({type:"bool",method:"1i",name:n,value:o}):typeof o=="string"?r.push({type:"sampler2D",method:"1i",name:n,value:o}):(typeof o>"u"?"undefined":Us(o))==="object"&&r.push.apply(r,kc(Ec(o,n)))}return r}function QT(e){var t=e.getBoundingClientRect();return t.top+t.height>0&&t.top<(window.innerHeight||document.documentElement.clientHeight)}function Mg(e){return(e&e-1)===0}function ZT(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function eL(e,t){return e&&t?e.toString()!==t.toString():!1}function tL(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(),t.status==200?t.responseText:""}function Ng(e){var t=new Set;return Object.assign(e,{on:function(r,n){var o={};o[r]=n,t.add(o)},off:function(r,n){if(n){var o={};o[r]=n,t.delete(o)}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,d=void 0;try{for(var g=Object.keys(u)[Symbol.iterator](),h;!(p=(h=g.next()).done);p=!0){var x=h.value;if(x===r){t.delete(u);return}}}catch(v){f=!0,d=v}finally{try{!p&&g.return&&g.return()}finally{if(f)throw d}}}}catch(v){i=!0,a=v}finally{try{!s&&c.return&&c.return()}finally{if(i)throw a}}}},listSubscriptions:function(){var r=!0,n=!1,o=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){n=!0,o=c}finally{try{!r&&s.return&&s.return()}finally{if(n)throw o}}},subscribe:function(r){t.add(r)},unsubscribe:function(r){t.delete(r)},unsubscribeAll:function(){t.clear()},trigger:function(r){for(var n=arguments.length,o=Array(n>1?n-1:0),s=1;s<n;s++)o[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,kc(o))}}catch(f){a=!0,c=f}finally{try{!i&&l.return&&l.return()}finally{if(a)throw c}}}})}var Tc=function(){function e(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};Dg(this,e),Ng(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(n.filtering),this.load(n)}return Ig(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,n=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(o,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),n.filtering="nearest"):c=new Image,c.onload=function(){try{r.setElement(c,n)}catch(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,n)}o(r)},c.onerror=function(l){console.log("Texture '"+r.name+"': failed to load url: '"+r.source+"'",l,n),o(r)},ZT()&&r.source.slice(0,5)==="data:"||(c.crossOrigin="anonymous"),c.src=r.source,a&&r.setElement(c,n)}),this.loading}},{key:"setData",value:function(t,r,n){var o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.width=t,this.height=r,this.source=n,this.sourceType="data",this.update(o),this.setFiltering(o),this.loading=Promise.resolve(this),this.loading}},{key:"setElement",value:function(t,r){var n=this,o=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(){n.intervalID=setInterval(function(){n.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(o)+") 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=Mg(this.width)&&Mg(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}();Tc.getMaxTextureSize=function(e){return e.getParameter(e.MAX_TEXTURE_SIZE)};Tc.activeUnit=-1;var Og=function(){function e(t,r,n){var o=this;Dg(this,e),Ng(this),r=r||{},n=n||{},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||
precision mediump float;
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||
precision mediump float;
varying vec2 v_texcoord;
void main(){
gl_FragColor = vec4(0.0);
}
;var s=VT(t,r,n.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");Fs.get(i,function(h,x,v){o.load(v,o.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");Fs.get(a,function(h,x,v){o.load(o.fragmentString,v)})}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(h){f.x=h.clientX||h.pageX,f.y=h.clientY||h.pageY},!1);var d=this;function g(){d.nMouse>1&&d.setMouse(f),d.resize()&&(d.forceRender=!0),d.render(),d.animationFrameRequest=window.requestAnimationFrame(g)}return this.setMouse({x:0,y:0}),g(),this}return Ig(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 n in this.buffers){var o=this.buffers[n];this.gl.deleteProgram(o.program)}this.program=null,this.gl=null}},{key:"load",value:function(t,r){var n=this;r&&(this.vertexString=r),t&&(this.fragmentString=t);var o=this.fragmentString.split(/\r?\n/);this.fragmentString=#define PLATFORM_WEBGL ,o.forEach(function(h,x){var v=h.trim();if(v.startsWith('#include "lygia')){var L=v.substring(15).replace(/\'|\"|\;|\s/g,"");if(L.endsWith("glsl")){if(n.deps[L]===void 0){var S="https://lygia.xyz"+L;n.deps[L]=tL(S)}n.fragmentString+=n.deps[L]+
}}else n.fragmentString+=h+
}),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=sn(this,this.vertexString,this.gl.VERTEX_SHADER),f=sn(this,this.fragmentString,this.gl.FRAGMENT_SHADER);f?this.isValid=!0:(f=sn(this,void main(){
gl_FragColor = vec4(1.0);
},this.gl.FRAGMENT_SHADER),this.isValid=!1);var d=Cg(this,[p,f]);this.gl.useProgram(d),this.gl.deleteShader(p),this.gl.deleteShader(f),this.program=d,this.change=!0,this.BUFFER_COUNT=0;var g=this.getBuffers(this.fragmentString);Object.keys(g).length&&this.loadPrograms(g),this.buffers=g,this.texureIndex=this.BUFFER_COUNT,this.trigger("load",{}),this.forceRender=!0,this.render()}},{key:"test",value:function(t,r,n){var o=this.vertexString,s=this.fragmentString,i=this.paused,a=this.gl.getExtension("EXT_disjoint_timer_query"),c=a.createQueryEXT(),l=this.isValid;(r||n)&&(this.load(r,n),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||n)&&u.load(s,o)}function f(){u.forceRender=!0,u.render();var d=a.getQueryObjectEXT(c,a.QUERY_RESULT_AVAILABLE_EXT),g=u.gl.getParameter(a.GPU_DISJOINT_EXT);if(d&&!g){var h={wasValid:l,frag:r||u.fragmentString,vert:n||u.vertexString,timeElapsedMs:a.getQueryObjectEXT(c,a.QUERY_RESULT_EXT)/1e6};p(),t(h)}else window.requestAnimationFrame(f)}f()}},{key:"loadTexture",value:function(t,r,n){var o=this;n||(n={}),typeof r=="string"?n.url=r:(typeof r>"u"?"undefined":Us(r))==="object"&&r.data&&r.width&&r.height?(n.data=r.data,n.width=r.width,n.height=r.height):(typeof r>"u"?"undefined":Us(r))==="object"&&(n.element=r),this.textures[t]?this.textures[t]&&(this.textures[t].load(n),this.textures[t].on("loaded",function(s){o.forceRender=!0})):(this.textures[t]=new Tc(this.gl,t,n),this.textures[t].on("loaded",function(s){o.forceRender=!0}))}},{key:"refreshUniforms",value:function(){this.uniforms={}}},{key:"setUniform",value:function(t){for(var r={},n=arguments.length,o=Array(n>1?n-1:0),s=1;s<n;s++)o[s-1]=arguments[s];r[t]=o,this.setUniforms(r)}},{key:"setUniforms",value:function(t){var r=Ec(t);for(var n in r)r[n].type==="sampler2D"?this.loadTexture(r[n].name,r[n].value[0]):this.uniform(r[n].method,r[n].type,r[n].name,r[n].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 n=(t.x-r.left)*this.realToCSSPixels,o=this.canvas.height-(t.y-r.top)*this.realToCSSPixels;this.uniform("2f","vec2","u_mouse",n,o)}}},{key:"uniform",value:function(t,r,n){this.uniforms[n]=this.uniforms[n]||{};for(var o=this.uniforms[n],s=arguments.length,i=Array(s>3?s-3:0),a=3;a<s;a++)i[a-3]=arguments[a];var c=eL(o.value,i);if(c||this.change||!o.location||!o.value){o.name=n,o.type=r,o.value=i,o.method="uniform"+t,this.gl.useProgram(this.program),o.location=this.gl.getUniformLocation(this.program,n),this.gl[o.method].apply(this.gl,[o.location].concat(o.value));for(var l in this.buffers){var u=this.buffers[l];this.gl.useProgram(u.program);var p=this.gl.getUniformLocation(u.program,n);this.gl[o.method].apply(this.gl,[p].concat(o.value))}}}},{key:"uniformTexture",value:function(t,r,n){if(this.textures[t]===void 0)this.loadTexture(t,r,n);else{this.uniform("1i","sampler2D",t,this.texureIndex);for(var o in this.buffers){var s=this.buffers[o];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=QT(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 n in this.buffers){var o=this.buffers[n];this.uniform("1i","sampler2D",o.name,o.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,n=t.canvas.height;t.viewport(0,0,r,n);for(var o in this.buffers){var s=this.buffers[o];s.bundle.render(r,n,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 n=arguments[3]||arguments[4];r["u_buffer"+n]={fragment:"#define BUFFER_"+n+
+t}}),r}},{key:"loadPrograms",value:function(t){var r=this,n=this.gl,o=sn(r,r.vertexString,n.VERTEX_SHADER);for(var s in t){var i=t[s],a=sn(r,i.fragment,n.FRAGMENT_SHADER,1);a?r.isValid=!0:(a=sn(r,void main(){
gl_FragColor = vec4(1.0);
},n.FRAGMENT_SHADER),r.isValid=!1);var c=Cg(r,[o,a]);i.name=s,i.program=c,i.bundle=r.createSwappableBuffer(r.canvas.width,r.canvas.height,c),n.deleteShader(a)}n.deleteShader(o)}},{key:"createSwappableBuffer",value:function(t,r,n){var o=this.createBuffer(t,r,n),s=this.createBuffer(t,r,n),i=this.gl;return{input:o,output:s,swap:function(){var a=o;o=s,s=a,this.input=o,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,n){var o=this.gl,s=this.BUFFER_COUNT;this.BUFFER_COUNT+=2,o.getExtension("OES_texture_float");var i=o.createTexture();o.activeTexture(o.TEXTURE0+s),o.bindTexture(o.TEXTURE_2D,i),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,t,r,0,o.RGBA,o.FLOAT,null),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);var a=o.createFramebuffer();return{index:s,texture:i,buffer:a,W:t,H:r,resize:function(c,l){o.bindFramebuffer(o.FRAMEBUFFER,a);var u=Math.min(c,this.W),p=Math.min(l,this.H),f=new Float32Array(u*p*4);o.readPixels(0,0,u,p,o.RGBA,o.FLOAT,f),o.bindFramebuffer(o.FRAMEBUFFER,null);var d=s+1,g=o.createTexture();o.activeTexture(o.TEXTURE0+d),o.bindTexture(o.TEXTURE_2D,g),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,c,l,0,o.RGBA,o.FLOAT,null),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.NEAREST),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texSubImage2D(o.TEXTURE_2D,0,0,0,u,p,o.RGBA,o.FLOAT,f);var h=o.createFramebuffer();o.bindFramebuffer(o.FRAMEBUFFER,null),o.deleteTexture(i),o.activeTexture(o.TEXTURE0+s),o.bindTexture(o.TEXTURE_2D,g),s=this.index=s,i=this.texture=g,a=this.buffer=h,this.W=c,this.H=l}}}},{key:"resizeSwappableBuffers",value:function(){var t=this.gl,r=t.canvas.width,n=t.canvas.height;t.viewport(0,0,r,n);for(var o in this.buffers){var s=this.buffers[o];s.bundle.resize(r,n,s.program,s.name)}t.useProgram(this.program)}},{key:"version",value:function(){return"0.1.7"}}]),e}();function rL(){var e=document.getElementsByClassName("glslCanvas");if(e.length>0){window.glslCanvases=[];for(var t=0;t<e.length;t++){var r=new Og(e[t]);r.isValid&&window.glslCanvases.push(r)}}}window.addEventListener("load",function(){rL()});var Bs=Og;var $g=e=>{if(!("after"in e))return Promise.resolve(void 0);let t=document.createElement("canvas");return new Bs(t).load(et(e.after)),e.render(t),Promise.resolve(void 0)};var jg=e=>{let t="";for(let r=0;r<e.length;r+=3)r+2===e.length?t+=Lc(e[r],e[r+1],0):r+1===e.length?t+=Lc(e[r],0,0):t+=Lc(e[r],e[r+1],e[r+2]);return t},Hs=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?"_":"?"))),Lc=(e,t,r)=>{let n=e>>2,o=(e&3)<<4|t>>4,s=(t&15)<<2|r>>6,i=r&63;return Hs(n&63)+Hs(o&63)+Hs(s&63)+Hs(i&63)};var Ag=async(e,t="svg")=>{let r=new Blob([new TextEncoder().encode(e)]).stream().pipeThrough(new CompressionStream("deflate")),n=new Uint8Array(await new Response(r).arrayBuffer());returnhttps://www.plantuml.com/plantuml/${t}/~1${jg(n)}};var Fg=async e=>{if(!("after"in e))return;let t=document.createElement("img"),r=await Ag(et(e.after));t.src=r,e.render(t)};var Sc=Promise.resolve({log:new Uint8Array(0)}),zs,Ug=(e,t,r,n)=>(Sc=(async()=>{await Sc,zs??=await nL(t,r);let o=new Promise(i=>{let a=c=>{if(c.data.type==="stdout"){n(c.data.message);return}c.data.type==="compile"&&(i(c.data),zs.removeEventListener("message",a))};zs.addEventListener("message",a)}),s={type:"compile",input:e};return zs.postMessage(s),o})(),Sc),nL=async(e,t)=>{let r=new Worker(e,{type:"module"}),n=new Promise(s=>{let i=a=>{a.data.type==="asset-url"&&(s(),r.removeEventListener("message",i))};r.addEventListener("message",i)}),o={type:"asset-url",url:${t}};return r.postMessage(o),await n,r};var Bg=(e,t)=>async r=>{if(!("after"in r))return;let n=oL(),o="Compile is not started yet. Please wait...",s=l=>{o=[...o.split( ),l].join(
),n.log(o)},i=document.createElement("img"),a=setTimeout(()=>{r.render(n.div),n.log(o)},2e3),{svg:c}=await Ug(et(r.after),e,t,s);if(clearTimeout(a),!c){r.render(n.div),n.log(o);return}i.src=await qn(new Blob([c],{type:"image/svg+xml"})),r.render(i)},oL=()=>{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 n=document.createElement("pre"),o=document.createElement("code");return n.append(o),t.append(n),{div:e,log:s=>{o.textContent=s,n.scroll(0,n.scrollHeight)}}};var Hg=(e,t,r=0,n=[])=>{let[o,s]=F("uninitialized"),[i,a]=F({ok:!0,value:t}),c=_(e,n);return K(()=>{(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,...n]),i.ok?{result:i.value,state:o}:{result:i.value,state:"rejected"}};var zg=e=>{let t=e.flatMap(({changes:o,created:s,userId:i})=>o.flatMap(a=>{let c=sL(a,i,s);return c?[c]:[]})),r=[...new Set(t.map(({created:o})=>o))].sort();return{history:t.reduce((o,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[...o,c];let l=o.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),[...o,c]):[...o.slice(0,l),c,...o.slice(l)]}let i=o.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),o):(o[i].snapshots.set(s.created,{text:s.type==="update"?s.text:void 0,type:s.type,userId:s.userId}),o)},[]),range:r}},sL=(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 qg=async(e,t)=>{let r=await fetch(/api/commits/${e}/${t}),{commits:n}=await r.json();return zg(n)},Wg=async(e,t)=>{let r=await fetch(/api/page-snapshots/${e}/${t}),{snapshots:n}=await r.json(),o=new Map(n.map(({lines:i,created:a})=>[a,i])),s=n.map(({created:i})=>i).sort();return{pages:o,range:s}};var Kg=e=>{let t=document.createElement("div");t.dataset.userscriptName="takker99/scrapbox-history-slider";let r=t.attachShadow({mode:"open"});return document.body.append(t),new Promise(n=>we(m(iL,{getController:o=>n(o)}),r))},iL=({getController:e})=>{let[t,r]=F(!0),n=_(()=>r(!1),[]),o=_(()=>r(!0),[]),s=_(()=>r(g=>!g),[]);K(()=>e({open:n,close:o,toggle:s}),[e]);let i=_(g=>{g.target instanceof HTMLElement&&g.target.id==="background"&&o()},[]),{state:a,result:c}=Hg(async()=>{if(t||scrapbox.Layout!=="page")return;let[g,h]=await Promise.all([qg(scrapbox.Project.name,scrapbox.Page.id),Wg(scrapbox.Project.name,scrapbox.Page.id)]);return{range:[...h.range,...g.range],getSnapshot:x=>g.range.includes(x)?g.history.flatMap(({snapshots:v})=>{let L=v.get(x);if(L)return L.text===void 0?[]:[L.text];let S=Math.max(...[...v.keys()].filter(k=>k<x));if(S===x)return[];let b=v.get(S)?.text;return b===void 0?[]:[b]}):h.pages.get(x)?.map?.(v=>v.text)??[]}},{range:[],getSnapshot:()=>[]},1e3,[t]),[l,u]=F(0),[p,f]=F(0);K(()=>{if(a!=="resolved")return;let g=Math.max(0,c.range.length-1);u(g),f(g)},[c]);let d=_(g=>f(parseInt(g.currentTarget.value)),[]);return m(W,null,m("style",null,'.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}'),m("div",{id:"background",className:modal${t?" closed":""},onClick:i},m("div",{className:"controller"},m("button",{className:"close-button",onClick:o},"x"),a==="resolved"&&c.range.length===0&&m("span",{className:"not-found"},"no history found."),a!=="rejected"&&c.range.length>0&&m(W,null,m("input",{type:"range",max:l,min:"0",step:"1",value:p,title:V(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss"),onInput:d}),m("time",{dateTime:V(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss")},V(new Date(c.range[p]*1e3),"yyyy-MM-dd HH:mm:ss")))),a!=="rejected"?m("div",{className:"viewer"},m("pre",null,c.getSnapshot(c.range[p]).join(
))):m("div",{className:"error viewer"},Error: ${JSON.stringify(c)})))};var $t=()=>/mobile/i.test(navigator.userAgent);function*Pc(e,t,r){let n=0,o=[],s=async()=>(n++,n<=e?n-1:await new Promise(i=>o.push(i)));for(let i of t)yield(async()=>{let a=await s();try{return{success:!0,value:await r(i,a)}}catch(c){return{success:!1,reason:c}}finally{n--,o.shift()?.(a)}})()}var Gg=async(e,t,r)=>{if(e.length===0||e.every(({before:o,after:s})=>o===s))return;let n=await Ne();try{let o=Pc(5,e,async s=>{let i=0,a=0;s.before===s.after&&r({link:s,projectCount:0,replaced:0,done:!0});let c=Pc(2,[...new Set(t)],async l=>{let u=await aL(s,l,n);if(!u.ok)throw cL(u.value);i++,a+=u.value,r({link:s,projectCount:i,replaced:a,done:!1})});await Promise.all([...c]),r({link:s,projectCount:i,replaced:a,done:!0})});await Promise.all([...o])}finally{await ve(n)}},aL=async(e,t,r)=>{let[n]=await Promise.all([po(t,e.before,e.after),re(t,e.before,(o,{persistent:s})=>{if(s)return[e.after,...o.map(i=>i.text).slice(1)]},{socket:r})]);return n},jt=e=>e.split(
).flatMap(t=>[...t.matchAll(/\[((?:[^\[!"#%&'()\*\+,\-\.\/\{\|\}<>_~] |.[^ ]*)[^\[\]]*)\]/g)]).map(([,t])=>t),cL=e=>{let t=new Error;return t.name=e.name,t.message=e.message,t};var lL=e=>({type:"title",text:e.rows[0].text}),pL=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(i=>i.text.substring(n+1)).join(
)}},Ie=(e,{parseOnNested:t,parseOnQuoted:r,patterns:n})=>(o,s,i)=>{var a,c,l,u,p,f;if(!t&&s.nested)return(a=i?.())!==null&&a!==void 0?a:[];if(!r&&s.quoted)return(c=i?.())!==null&&c!==void 0?c:[];for(let d of n){let g=d.exec(o);if(g===null)continue;let h=o.substring(0,g.index),x=o.substring(g.index+((u=(l=g[0])===null||l===void 0?void 0:l.length)!==null&&u!==void 0?u:0)),v=e((p=g[0])!==null&&p!==void 0?p:"",s);return[...Jt(h,s),...v,...Jt(x,s)]}return(f=i?.())!==null&&f!==void 0?f:[]},Ae=e=>[{type:"plain",raw:e,text:e}],uL=Ie(Ae,{parseOnNested:!0,parseOnQuoted:!0,patterns:[/^()(.*)()$/]}),dL=/^>.*$/,mL=(e,t)=>t.context==="table"?Ae(e,t):[{type:"quote",raw:e,nodes:Jt(e.substring(1),{...t,quoted:!0})}],fL=Ie(mL,{parseOnNested:!1,parseOnQuoted:!1,patterns:[dL]}),gL=/^\? .+$/,hL=(e,t)=>t.context==="table"?Ae(e,t):[{type:"helpfeel",raw:e,text:e.substring(2)}],xL=Ie(hL,{parseOnNested:!1,parseOnQuoted:!1,patterns:[gL]}),bL=/\[\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)\]\]/i,yL=/\[\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}\]\]/,vL=(e,t)=>{if(t.context==="table")return Ae(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}]},wL=Ie(vL,{parseOnNested:!1,parseOnQuoted:!0,patterns:[bL,yL]}),kL=/\[[^[\]]*\.icon(?:\*[1-9]\d*)?\]/;function Yg(e){return(t,r)=>{if(e==="strongIcon"&&r.context==="table")return Ae(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),i=s.startsWith("/")?"root":"relative",a=n.substring(o+5,n.length),c=a.startsWith("*")?parseInt(a.substring(1),10):1;return new Array(c).fill({}).map(()=>({path:s,pathType:i,type:e,raw:t}))}}var EL=Yg("icon"),TL=Ie(EL,{parseOnNested:!0,parseOnQuoted:!0,patterns:[kL]}),LL=/\[\[[^[\]]*\.icon(?:\*\d+)?\]\]/,SL=Yg("strongIcon"),PL=Ie(SL,{parseOnNested:!1,parseOnQuoted:!0,patterns:[LL]}),RL=/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/,_L=(e,t)=>t.context==="table"?Ae(e,t):[{type:"strong",raw:e,nodes:Jt(e.substring(2,e.length-2),{...t,nested:!0})}],CL=Ie(_L,{parseOnNested:!1,parseOnQuoted:!0,patterns:[RL]}),ML=/\[\$ .+? \]/,DL=/\[\$ [^\]]+\]/,IL=(e,t)=>t.context==="table"?Ae(e,t):[{type:"formula",raw:e,formula:e.substring(3,e.length-(e.endsWith(" ]")?2:1))}],NL=Ie(IL,{parseOnNested:!1,parseOnQuoted:!0,patterns:[ML,DL]}),OL=/\[[!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\]]+\]|[^\]])+\]/,$L=(e,t)=>{if(t.context==="table")return Ae(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 i=n.split("*").length-1;s.delete("*"),s.add(*-${Math.min(i,10)})}return[{type:"decoration",raw:e,rawDecos:n,decos:Array.from(s),nodes:Jt(o,{...t,nested:!0})}]},jL=Ie($L,{parseOnNested:!1,parseOnQuoted:!0,patterns:[OL]}),AL=/.*?/,FL=(e,t)=>t.context==="table"?Ae(e,t):[{type:"code",raw:e,text:e.substring(1,e.length-1)}],UL=Ie(FL,{parseOnNested:!1,parseOnQuoted:!0,patterns:[AL]}),BL=/^[$%] .+$/,HL=(e,t)=>{var r;if(t.context==="table")return Ae(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}]},zL=Ie(HL,{parseOnNested:!1,parseOnQuoted:!1,patterns:[BL]}),qL=/\[\s+\]/,WL=(e,t)=>t.context==="table"?Ae(e,t):[{type:"blank",raw:e,text:e.substring(1,e.length-1)}],KL=Ie(WL,{parseOnNested:!1,parseOnQuoted:!0,patterns:[qL]}),GL=/\[https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?(?:\s+https?:\/\/[^\s\]]+)?\]/i,XL=/\[https?:\/\/[^\s\]]+\s+https?:\/\/[^\s\]]+\.(?:png|jpe?g|gif|svg)(?:\?[^\]\s]+)?\]/i,YL=/\[https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?(?:\s+https?:\/\/[^\s\]]+)?\]/,VL=/\[https?:\/\/[^\s\]]+\s+https?:\/\/(?:[0-9a-z-]+\.)?gyazo\.com\/[0-9a-f]{32}(?:\/raw)?\]/,JL=e=>/^https?:\/\/[^\s\]]+\.(png|jpe?g|gif|svg)(\?[^\]\s]+)?$/i.test(e)||QL(e),QL=e=>/^https?:\/\/([0-9a-z-]\.)?gyazo\.com\/[0-9a-f]{32}(\/raw)?$/.test(e),ZL=(e,t)=>{if(t.context==="table")return Ae(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,i]=JL(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:i}]},eS=Ie(ZL,{parseOnNested:!0,parseOnQuoted:!0,patterns:[GL,XL,YL,VL]}),tS=/\[https?:\/\/[^\s\]]+\s+[^\]]*[^\s]\]/,rS=/\[[^[\]]*[^\s]\s+https?:\/\/[^\s\]]+\]/,nS=/\[https?:\/\/[^\s\]]+\]/,oS=/https?:\/\/[^\s]+/,sS=(e,t)=>{if(t.context==="table")return Ae(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()}]},iS=Ie(sS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[tS,rS,nS,oS]}),Vg=/\[([^\]]*[^\s])\s+([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)\]/,Jg=/\[([NS]\d+(?:\.\d+)?,[EW]\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+([^\]]*[^\s]))?\]/,aS=e=>{let[t="",r="",n=""]=e.split(","),o=parseFloat(t.replace(/^N/,"").replace(/^S/,"-")),s=parseFloat(r.replace(/^E/,"").replace(/^W/,"-")),i=/^Z\d+$/.test(n)?parseInt(n.replace(/^Z/,""),10):14;return{latitude:o,longitude:s,zoom:i}},cS=(e,t)=>{var r;if(t.context==="table")return Ae(e,t);let n=(r=e.match(Vg))!==null&&r!==void 0?r:e.match(Jg);if(n===null)return[];let o=e.startsWith("[N")||e.startsWith("[S"),[,s="",i=""]=o?n:[n[0],n[2],n[1]],{latitude:a,longitude:c,zoom:l}=aS(s),u=i!==""?https://www.google.com/maps/place/${encodeURIComponent(i)}/@${a},${c},${l}z:https://www.google.com/maps/@${a},${c},${l}z;return[{type:"googleMap",raw:e,latitude:a,longitude:c,zoom:l,place:i,url:u}]},lS=Ie(cS,{parseOnNested:!1,parseOnQuoted:!0,patterns:[Vg,Jg]}),pS=/\[\/?[^[\]]+\]/,uS=e=>{let t=e.substring(1,e.length-1);return[{type:"link",raw:e,pathType:t.startsWith("/")?"root":"relative",href:t,content:""}]},dS=Ie(uS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[pS]}),mS=/(?:^|\s)#\S+/,fS=(e,t)=>{if(t.context==="table")return Ae(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[...Ae(r,t),{type:"hashTag",raw:n,href:n.substring(1)}]},gS=Ie(fS,{parseOnNested:!0,parseOnQuoted:!0,patterns:[mS]}),hS=/^[0-9]+\. .*$/,xS=(e,t)=>{if(t.context==="table")return Ae(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:Jt(s,{...t,nested:!0})}]},bS=Ie(xS,{parseOnNested:!1,parseOnQuoted:!1,patterns:[hS]}),yS=(e,t,r)=>{var n;return e===""?[]:(n=r?.())!==null&&n!==void 0?n:[]},vS=(...e)=>(t,r)=>e.reduceRight((n,o)=>()=>o(t,r,n),()=>uL(t,r))(),Jt=vS(yS,fL,xL,UL,zL,NL,KL,jL,wL,PL,CL,eS,iS,TL,lS,dS,gS,bS),wS=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(i=>i.text.substring(n+1)).map(i=>i.split(" ").map(a=>Jt(a,{nested:!1,quoted:!1,context:"table"})))}},kS=e=>{let{indent:t,text:r}=e.rows[0];return{indent:t,type:"line",nodes:Jt(r.substring(t),{nested:!1,quoted:!1,context:"line"})}},ES=e=>{switch(e.type){case"title":return lL(e);case"codeBlock":return pL(e);case"table":return wS(e);case"line":return kS(e)}},TS=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}}),LS=(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)},Xg=(e,t)=>{let r=e[e.length-1];return r!==void 0&&LS(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)},SS=(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(Xg,[])]}return e.reduce(Xg,[])},Qt=(e,t)=>{var r;let n=TS(e);return SS(n,{hasTitle:(r=t?.hasTitle)!==null&&r!==void 0?r:!0}).map(ES)};var Qg=e=>Qt(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return PS(r);case"table":return RS(r);case"line":return _S(r)}}).map(r=>r).join(
),PS=({fileName:e,content:t,indent:r})=>{let n=" ".repeat(r);return[${n}code:${e},...t.split(
).map(o=>${n} ${o})]},RS=({fileName:e,cells:t,indent:r})=>{let n=" ".repeat(r);return[${n}table:${e},...t.map(o=>${n} ${o.map(s=>s.map(i=>Kn(i)).join("")).join(" ")})]},_S=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${Kn(r)}).join("")}],Kn=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Kn(t)).join("")};case"strong":return${e.nodes.map(t=>Kn(t)).join("")};case"decoration":{let t=e.decos.map(r=>{let n=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return n>0?"*".repeat(n):r}).join("");return[${t?${t} :""}${e.nodes.map(r=>Kn(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=>jt(e).length>0?"":"",onClick:e=>{let t=Qg(e);if(e!=t)return t}});var Zg=e=>!e.includes(
)&&/\[[^\]]+\]/.test(e);scrapbox.PopupMenu.addButton({title:e=>Zg(e)?"[][]":"",onClick:e=>{if(!Zg(e))return;let t=e.replaceAll("[","").replaceAll("]","");return(async()=>{let{render:r,dispose:n}=ce();try{let o=scrapbox.Project.name;r({type:"spinner"},{type:"text",text:create /${o}/${t}}),await re(o,t,([{text:s}],{persistent:i})=>{if(!i)return[s,e]}),r({type:"check-circle"},{type:"text",text:create /${o}/${t}})}catch(o){if(console.error(o),!(o instanceof Error))throw o;r({type:"exclamation-triangle"},{type:"text",text:${o.name} ${o.message}})}finally{await ie(2e3),n()}})(),${t}}});var eh=(e,t)=>{switch(e.type){case"title":return"";case"codeBlock":return[e.fileName, \\`\`${NS(e.fileName)},e.content,"\n"].join(
);case"table":return CS(e);case"line":return DS(e,t)}},CS=e=>{let t=[e.fileName],r=Math.max(...e.cells.map(n=>n.length));return e.cells.forEach((n,o)=>{t.push(| ${n.map(s=>s.map(i=>an(i)).join("")).join(" | ")} |),o===0&&t.push(|${" -- |".repeat(r)})}),t.join(
)},MS=" ",DS=(e,t)=>{let r=e.nodes.map(o=>an(o,{section:e.indent===t})).join("").trim();if(r==="")return"";if(e.indent===t)return r;let n=MS.repeat(e.indent-t-1);return/^\d+\. /.test(r)||(n+="- "),n+r},an=(e,t)=>{let{section:r=!1}=t??{};switch(e.type){case"quote":return> ${e.nodes.map(n=>an(n)).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(n=>an(n)).join("")}**;case"formula":return$${e.formula}$;case"decoration":{let n=e.nodes.map(o=>an(o)).join("");return e.decos.includes("/")&&(n=*${n}*),r?(e.decos.includes("*-3")&&(n=`# ${n} ),e.decos.includes("*-2")&&(n=## ${n}
),e.decos.includes("*-1")&&(n=### ${n}
)):e.decos.some(o=>/\*-/.test(o[0]))&&(n=**${n}**),e.decos.includes("~")&&(n=~~${n}~~),n}case"code":return\${e.text}\`;case"commandLine":return\`${e.symbol} ${e.text}\`;case"link":switch(e.pathType){case"root":return[${e.href}](https://scrapbox.io${e.href});case"relative":return[${e.href}](https://scrapbox.io/${scrapbox.Project.name}/${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(n=>an(n)).join("")};case"blank":case"plain":return e.text}},IS=[{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"}],NS=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return IS.find(r=>r.extensions.includes(t))?.fileType??""};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{(async()=>{try{let t=Or.parse(e,{hasTitle:!1}),r=Math.min(...t.map(n=>n.indent));await navigator.clipboard.writeText(t.map(n=>eh(n,r)).join(` ))}catch(t){alert(Failed to copy:
${JSON.stringify(t)})}})()}});var At=e=>typeof e=="string";var Rc=(e,...t)=>{let r=e;for(let n of t){let o=r instanceof Promise?r.then(s=>At(s)?s:n(s)):n(r);if(At(o))return o;r=o instanceof URL?new URL(o):o.then(s=>At(s)?s:new URL(s))}return r instanceof Promise?r.then(n=>${n}):${e}};var cn=e=>e.ok?void 0:{name:"HTTPError",message:${e.status} ${e.statusText},response:e};var th=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=cn(r);return n?{ok:!1,value:n}:{ok:!0,value:await r.json()}})()};var qs=e=>{let{fetch:t=globalThis.fetch,...r}=e;return{fetch:t,...r}},rh=e=>typeof e=="object"&&e!==null;var Gn=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 Ws=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(!rh(r)||typeof r.message!="string")throw new Gn({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 Gn({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)})}}catch(r){throw r instanceof SyntaxError?new Gn({status:e.status,statusText:e.statusText,body:t,path:new URL(e.url)}):r}};var nh=async(e,t)=>{let{title:r,description:n,metadataIsPublic:o,collectionId:s,refererURL:i,accessToken:a,created:c,app:l,fetch:u}=qs(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),n!=null&&p.append("desc",n),s&&p.append("collection_id",s),o&&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}),d=await Ws(f);return d.ok?{ok:!0,value:JSON.parse(d.value)}:d};var oh=(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 Ks="",sh=!1,Gs=new Map,ih=async(e,t,r,n)=>{let o=Gs.get(e.href);if(o)return o;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()],n||${t},{type:l});if(l==="video/mp4"){let d=await oh(u);if(d.ok){let g=new URL(await d.text());return Gs.set(e.href,g),g}}let p=await jl(u,r);if(!p.ok)throw Error(p.value.name);let f=new URL(p.value.embedUrl);return Gs.set(e.href,f),f}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(sh){if(!Ks)return}else{let c=await Ml();if(sh=!0,!c.ok){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(Ks=c.value||"",!Ks){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let i=await nh(await s.blob(),{accessToken:Ks,refererURL:t,description:n});if(!i.ok)throw Error(i.value.name);let a=new URL(i.value.permalink_url);return Gs.set(e.href,a),a};var OS={"<":"<",">":">","&":"&",""":'"',"'":"'","`":""},_c=e=>e.replace(/&(lt|gt|amp|quot|#x27|#x60);/g,t=>OSt);var Xs=e=>{let t={name:e.user.name,screenName:e.user.screen_name},r=new Date(e.created_at),n=[...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.indices0-a.indices0),o=[];{let i=0,a=e.text;for(let{indices:c,...l}of n){let u=...a.slice(0,c0-i).join("");o.push({type:"plain",text:_c(u)}),o.push(l),a=...a.slice(c1-i).join(""),i=c1}a&&o.push({type:"plain",text:_c(a)})}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=Xs(e.parent)),e.quoted_tweet&&(s.quote=Xs(e.quoted_tweet)),s};var $S="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",Ys=(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||$S.includes(n)?r:o?n===e?[${decodeURIComponent(o)}]:[/${n}/${decodeURIComponent(o)}]:[/${n}]};var ah=(e=jS)=>t=>{let,r=t.href.match(/^https:\/\/(?:(?:www\.|mobile\.|m\.)?twitter|x)\.com\/\w\d_+\/(?:status|statuses)\/(\d+)/)??[];return r?(async()=>{let n=await(th(r)??Cl(t.href));if(!n.ok)throw n.value;return e("images"in n.value?{...n.value,id:r}:n.value,t)})():t},jS=async e=>{if("images"in e)return Xn(e);let{quote:t,replyTo:r,...n}=Xs(e);return[...r?[...(await Xn(r)).split(` ).map(o=> > ${o}),...r.quote?(await Xn(r.quote)).split(
).map(o=> > ${o}):[]]:[],...(await Xn(n)).split(
).map(o=>> ${o}),...t?(await Xn(t)).split(
).map(o=>> > ${o}):[]].join(
)?.map?.(o=>> ${Mc(o)})??["> [/ no description provided]"],...e.images.length>0?[> ${e.images.map(o=>[${o}])}]:[]].join(
);let r=e.content,n=e.author.screenName;return[@${Mc(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=[],i=1;for(;i<o.media.length;i+=2)s.push([${await Cc(o.mediai-1,t)}] [${await Cc(o.mediai,t)}]);return i===o.media.length&&s.push([${await Cc(o.mediai-1,t)}]), ${s.join(`
`)}
}case"url":return${Ys()(o.url)} }}))).join("").split(
)].join(
)},Vs="",AS=async()=>{if(Vs)return Vs;let e=await pt(scrapbox.Project.name);if(!e.ok)throw new Error(e.value.name);return Vs=e.value.id,Vs},Cc=async(e,t)=>await ih(e.url,t,await AS(),"")??e.url,Mc=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]]\s*/g," ").trim();var ch=e=>{if(!window.GM_fetch)return;let t=window.GM_fetch;return(async()=>{let r=await t(https://t.co/${e}),n=cn(r);return n?{ok:!1,value:n}:{ok:!0,value:new DOMParser().parseFromString(await r.text(),"text/html").title}})()};var lh=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=ch(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 ph=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 uh=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 Dc=e=>{if(!e.hostname.startsWith("www.google."))return e;let t=e.searchParams.get("url");return t?new URL(decodeURIComponent(t)):e};var dh=/charset=(^;+)/,mh=e=>{if(!window.GM_fetch)return;let t=window.GM_fetch;return(async()=>{let r=await t(${e}),n=cn(r);if(n)return{ok:!1,value:n};let o=r.headers.get("content-type")?.match?.(dh)?.1??await FS(r.clone());return{ok:!0,value:new TextDecoder(o).decode(await r.arrayBuffer())}})()},FS=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?.(dh)?.1??"utf-8"};var fh=(e=US)=>async t=>e(await BS(t),t),US=(e,t)=>{let r=(At(e)?e:e.title).replace(/\s/g," ").replaceAll("","[").replaceAll("","]");return r?[${t.hash?${decodeURIComponent(t.hash.slice(1))} | :""}${r} ${t}]:${t}},BS=async e=>{let t=mh(e);if(!t){let n=await _l(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 gh=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 hh=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 xh=(e,...t)=>{if(e instanceof URL)return Rc(new URL(e),...t);let r=0,n=0,o=0,s=!1,i=e.split(/(https?:\/\/\S+)/g).map(u=>{if(!/^https?:\/\/\S+$/.test(u))return u;r++;try{let p=Rc(new URL(u),...t);return At(p)?(n++,p):(s=!0,p,u)}catch(p){return console.error(p),o++,u}});if(!s)return i.join("");let{render:a,dispose:c}=ce(),l=()=>a({type:"spinner"},{type:"text",text:URL: ${n}/${r} converted, ${o} failed});return l(),Promise.all(i.map(async u=>{if(At(u))return u;try{let p=await u0;return n++,p}catch(p){return console.error(p),o++,u1}finally{l()}})).then(u=>(a({type:"check-circle"},{type:"text",text:URL: ${n}/${r} converted, ${o} failed}),u.join(""))).finally(()=>{setTimeout(c,1e3)})};var bh=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 yh=e=>Qt(e,{hasTitle:!1}).flatMap(r=>{switch(r.type){case"title":return[];case"codeBlock":return HS(r);case"table":return zS(r);case"line":return qS(r)}}).map(r=>r).join(` ),HS=({fileName:e,content:t,indent:r})=>{let n=" ".repeat(r);return[${n}code:${e},...t.split(
).map(o=>${n} ${o})]},zS=({fileName:e,cells:t,indent:r})=>{let n=" ".repeat(r);return[${n}table:${e},...t.map(o=>${n} ${o.map(s=>s.map(i=>i.raw).join("")).join(" ")})]},qS=({nodes:e,indent:t})=>[${" ".repeat(t)}${e.map(r=>${Yn(r)}).join("")}],Yn=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Yn(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=>Yn(t)).join("")};case"decoration":{e.decos.includes("-")||e.decos.push("-");let t=e.decos.map(r=>{let n=parseInt(r.match(/\*-(\d)/)?.[1]??"0");return n>0?"*".repeat(n):r}).join("");return[${t?${t} :""}${e.nodes.map(r=>Yn(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=>Yn(t)).join("")};case"blank":case"plain":return${e.text}}};scrapbox.PopupMenu.addButton({title:"",onClick:e=>{let t=yh(e);if(e!==t)return t}});var Ic=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 n=e.slice(t+2).split(
);if(n.length===0)return;for(let[s,i]of r){let a=s.match(/^\/(.*?)\/([gimy]*)$/);if(a){let c=new RegExp(a[1],a[2]);n=n.map(l=>l.replace(c,i.replaceAll("\\n",
)))}else n=n.map(c=>c.replaceAll(s,i.replaceAll("\\n",
)))}let o=${e.slice(0,t+2)}${n.join(`
)};if(e!==o)return o};scrapbox.PopupMenu.addButton({title:e=>Ic(e)?"replace":"",onClick:e=>{let t=Ic(e);if(t!==void 0)return t}});var vh=e=>{let t=document.createElement("div"),r=t.attachShadow({mode:"open"}),n=document.createElement("style");n.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(n);let o=document.createElement("dialog");o.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(o);let s=o.querySelector(".editor");s.rows=e.length,s.value=e.join(
);let i=()=>{o.style.minWidth=${Math.max(...s.value.split(`
).map(u=>[...u].length))+6}em};i(),s.addEventListener("input",i);let a=o.querySelector(".cancel"),c=o.querySelector(".replace"),l=new Promise(u=>{let p=()=>{u({convert:!1}),t.remove()};o.addEventListener("close",p),o.addEventListener("click",p),a.addEventListener("click",p),c.addEventListener("click",()=>{let f=s.value.split(`
);u({convert:!0,links:e.flatMap((d,g)=>d===f[g]||d===""||!f[g]?[]:[{before:d,after:f[g]??d}])}),t.remove()}),o.querySelector(".container").addEventListener("click",f=>{f.stopPropagation()})});return document.body.append(t),o.showModal(),l};var wh=async(e,t)=>{let r=jt(e),n=await vh([...new Set(r)]);if(!n.convert||n.links.length===0)return;let o=new Map(n.links.map(s=>[s.before,ce()]));await Gg(n.links,t,s=>{let{link:i,projectCount:a,replaced:c,done:l}=s,u=o.get(i.before);if(u){if(l){u.render({type:"check-circle"},{type:"text",text:"${i.after}", ${c}l. ${a}p.}),setTimeout(()=>u.dispose(),1e3);return}u.render({type:"spinner"},{type:"text",text:"${i.after}", ${c}l. ${a}p.})}})};async function kh(e,t){let r=jt(e)[0];if(!r)return;let n=window.prompt(Replace "${r}" to this in ${t.map(a=>"/${a}").join(", ")},r)?.replace?.(/[\[\]\n]/g," ")??"";if(n==="")return;let{render:o,dispose:s}=ce(),i=await Ne();try{o({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([po(u,r,n),re(u,r,(f,{persistent:d})=>{if(d)return[n,...f.map(g=>g.text).slice(1)]},{socket:i})]);if(!p.ok)throw o({type:"exclamation-triangle"},{type:"text",text:${p.value.name} ${p.value.message}}),WS(p.value);return a++,o({type:"spinner"},{type:"text",text:Replacing links in ${t.length-a} projects...}),p.value}))).reduce((u,p)=>u+p,0);o({type:"check-circle"},{type:"text",text:Successfully replaced ${l} links.})}finally{await ve(i),setTimeout(s,1e3)}}function WS(e){let t=new Error;return t.name=e.name,t.message=e.message,t}var Eh=e=>{let t=[scrapbox.Project.name,...e];scrapbox.PopupMenu.addButton({title:r=>{let n=jt(r).length;return n>1?"update links":n===1?"update a link":""},onClick:r=>{let n=jt(r).length;n>1?wh(r,t):n===1&&kh(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 n=(await(await GM_fetch(https://gyazo.com/${t}.json)).json()).metadata?.ocr?.description;if(n)try{await navigator.clipboard.writeText(n)}catch(o){console.error(o),alert(${o.name} ${o.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 Th=e=>{let t="",r=0;for(let n of e)if(n.type!=="title"){if(n.indent>r)for(let o=r;o<n.indent;o++)t+=Vn(${o!==r?"\\item":""}\\begin{itemize},o*2)+ ;if(n.indent<r)for(let o=r;o>n.indent;o--)t+=Vn("\\end{itemize}",(o-1)*2)+
;r=n.indent,t+=Vn(${r>0?"\\item ":""}${KS(n)},r*2)+
}for(let n=r;n>0;n--)t+=Vn("\\end{itemize}",(n-1)*2)+
${e.content}
\\end{lstlisting},XS=e=>{let t=\\caption{${Xe(e.fileName)}}\\label{table:${Xe(e.fileName)}},r=Math.max(...e.cells.map(o=>o.length)),n=e.cells.map(o=> ${o.map(s=>s.map(i=>ln(i)).join("")).join(" & ")}\\\\);return\\begin{table}htbp ${t}
\\centering
\\begin{tabular}{${"c".repeat(r)}}
${n.length===0?"":n.length===1?` \\toprule
${n.join(`
`)}
\\bottomrule: \\toprule
\\midrule
${n.slice(1).join(`
`)}
\\bottomrule`}
\\end{tabular}
\\end{table}},YS=e=>e.nodes.map(t=>ln(t)).join(""),ln=e=>{switch(e.type){case"quote":return\\begin{quote}
${Vn(e.nodes.map(t=>ln(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{${Xe(e.path)}};case"strong":return\\textbf{${e.nodes.map(t=>ln(t)).join("")}};case"formula":return$${e.formula}$;case"decoration":{let t=e.nodes.map(r=>ln(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=>ln(t)).join("")};case"helpfeel":return\\lstinline!? ${Xe(e.text)}!;case"code":return\\lstinline!${Xe(e.text)}!;case"commandLine":return\\lstinline!${Xe(e.symbol)} ${Xe(e.text)}!;case"link":return e.pathType==="absolute"?e.content===""?\\url{${e.href}}:\\href{${e.href}}{${Xe(e.content)}}:Xe(e.href);case"googleMap":return\\href{${e.url}}{${Xe(e.place)}};case"hashTag":return Xe(#${e.href});case"blank":case"plain":return Xe(e.text)}},VS=[{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"}],JS=e=>{let t=e.replace(/^.*\.(\w+)$/,"$1");return VS.find(r=>r.extensions.includes(t))?.fileType??""},Xe=e=>e.replaceAll("\\","\\textbackslash ").replaceAll("#","\\#").replaceAll("%","\\%").replaceAll("$","\\$").replaceAll("&","\\&").replaceAll("~","\\textasciitilde ").replaceAll("^","\\textasciicircum ").replaceAll("_","\\_").replaceAll("{","\\{").replaceAll("}","\\}").replaceAll("|","\\textbar ").replaceAll("<","\\textless ").replaceAll(">","\\textgreater "),Vn=(e,t)=>e.split( ).map(r=>${" ".repeat(t)}${r}).join(
);scrapbox.PopupMenu.addButton({title:"TeX",onClick:e=>{navigator.clipboard.writeText(Th(Qt(e))).catch(t=>{console.error(t),alert(${t.name} ${t.message}
${t.stack})})}});var Js="https://keicho.herokuapp.com/api/";var Lh=async(e,t)=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let r=await window.GM_fetch(${Js}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 n=await r.json();return{ok:!0,value:{text:n.text,buttons:n.buttons,canInput:n.can_input}}};var Sh=()=>{let{popupMenu:e,render:t}=QS();mp()?.append?.(e);let r=Fr(),n=()=>{requestAnimationFrame(()=>{let o=document.getElementsByClassName("cursor")[0];e.style.top=${parseInt(o.style.top)+parseInt(o.style.height)+4}px})};return r.addChangeListener(n),{render:t,visible:()=>!e.hidden,open:()=>e.hidden=!1,close:()=>e.hidden=!0,toggle:()=>e.hidden=!e.hidden,dispose:()=>{e.remove(),r.removeChangeListener(n)}}},QS=()=>{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
}
max-width:90vw
}
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
}
font-size:13px;
padding:6px;
min-width:12vw
}
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:(...n)=>{r.textContent="",r.append(...n.map(({text:o,onClick:s})=>{let i=document.createElement("div");return i.classList.add("button"),i.textContent=o,s&&i.addEventListener("click",()=>s()),i}))}}};var Ph=async(e="normal")=>{if(!window.GM_fetch)return{ok:!1,value:{name:"GMFetchNotAvailableError"}};let t=await window.GM_fetch(${Js}web/create/?mode=${e},{mode:"cors"});return t.ok?{ok:!0,value:await t.text()}:{ok:!1,value:{name:"ResponseError",res:t}}};var Rh=e=>https://keicho.netlify.app/#talk=${e};var _h=e=>{let t=e.split( ),r=t[1]??t[0],n=e===t[0]?"":t[0];return n?[n.trim(),r].join(
):r};var Qs=async(e,t,r)=>{let n=Fr(),o=n.lines.findIndex(i=>i.id===t.id);o<0&&(o=n.lines.findIndex(i=>i.text===t.text)),o<0&&(o=Math.min(r,Math.max(0,n.lines.length-1)));let s=n.lines[o].text;return Rp().clear(),n.setPosition({line:o,char:[...s].length}),await je(
${e}),n.getPosition().line};var Ch=e=>Qt(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(n=>${r} ${n})].join(
).trimEnd();case"table":return[${r}${t.fileName},...t.cells.map(n=>${r} ${n.flatMap(o=>o.map(s=>Zs(s))).join(" ")})].join(
).trimEnd();case"line":return${r}${t.nodes.map(n=>Zs(n)).join("")}.trimEnd()}}).join(
),Zs=e=>{switch(e.type){case"quote":return> ${e.nodes.map(t=>Zs(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=>Zs(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 pn=e=>/^[((]/.test(e);var Dh=async e=>{let t=scrapbox.Page.lines;if(!t)return;let{cursor:r,selection:n}=ht(),o=e?.entire||n.hasSelectionAll(),s=o?t.map(E=>E.text).join(
):n.getSelectedText(),i=e?.botIcon??"[/nishio/nisbot.icon]",{render:a,visible:c,open:l,close:u,dispose:p}=Sh();u();let f=new Set,d=()=>{p();for(let E of f)E()},g=E=>f.add(E),h={text:"Exit",onClick:d},x=e?.talkId||Mh(s)||(o?"":Mh(t.slice(0,1+r.getPosition().line).map(E=>E.text).join(
))),v=!x;if(!x){let E=Ph(e?.mode),R=setTimeout(()=>{a({text:"Start talking..."}),l();let N=0;R=setInterval(()=>{a({text:Start talking${".".repeat(N%3)}}),N++},1e3)},1e3),D=await E;if(clearTimeout(R),!D.ok){if(D.value.name==="GMFetchNotAvailableError"){alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc.");return}if(D.value.name==="ResponseError"){a({text:Error: ${D.value.res.status} ${D.value.res.statusText}},h),l(),console.error(Error: ${D.value.res.status} ${D.value.res.statusText},await D.value.res.text());return}return}x=D.value}let L=x,S=n.normalizeOrder(n.getRange()),b=o?t.length-1:S.end.line,k=t[b],w=o?"":" ".repeat(Math.min(...t.slice(S.start.line,S.end.line+1).map(E=>He(E.text)))),C=async E=>{let R=await Lh(E,L);if(!R.ok)switch(R.value.name){case"ResponseError":return a({text:Error: ${R.value.res.status} ${R.value.res.statusText}},h),l(),console.error(Error: ${R.value.res.status} ${R.value.res.statusText},await R.value.res.text()),R;case"GMFetchNotAvailableError":return alert("GM_fetch is not available. Please use Tampermonkey and install GM_fethc."),R}return R},M="",B=async E=>{let R=Ch(E).split(
).map(I=>I.trim()).join(
).trim();R.startsWith(M)&&(R=R.slice(M.length));let D=R.split(
);if(D.length===0)return;if(D.every(I=>pn(I))&&(M=R),D.filter(I=>!pn(I)).length<2){let I,H;for(let A of D){if(H=await C(A),!H.ok)return H;pn(A)||(I=H)}return I??H}let j=0;{let I;for(;j<D.length&&pn(D[j]);j++)if(I=await C(D[j]),!I.ok)return I}{let I=await C("まず聞いて");if(!I.ok)return I}for(;j<D.length&&!pn(D[j]);j++){let I=await C(D[j]);if(!I.ok)return I}return await C("おしまい")},P=async E=>{if(scrapbox.Layout!=="page"||E==="")return;let R=B(E),D=setTimeout(()=>{a({text:"Asking..."}),l();let A=0;D=setInterval(()=>{a({text:Asking${".".repeat(A%3)}}),A++},1e3)},1e3),N=await R;if(clearTimeout(D),!N||!N.ok)return;let{text:j,buttons:I}=N.value,H=_h(j);if(H.trim()){let A=${w}${i}${H.includes(`
)?
${H.split(`
).map(z=> ${w}${z}).join(
)}:H}
${w};b=await Qs(A,k,b),k=t[b]}a({text:"Send",onClick:T},{text:"🙂",onClick:()=>je("🙂")},{text:"🙁",onClick:()=>je("🙁")},...I.map(A=>({text:A,onClick:async()=>{b=await Qs(A,k,b),k=t[b],await P(A)}})),h),l()},T=async()=>{if(scrapbox.Layout!=="page")return;let E=scrapbox.Page.lines,R=r.getPosition().line,[D,N,j]=ZS(E,R,i);D!==""&&(b=j,k=E[b],w=" ".repeat(Math.min(...E.slice(N,j+1).map(I=>He(I.text)))),await P(D))};return v&&(b=await Qs(Rh(L),k,b),k=t[b]),await P(s),{ask:T,open:l,close:u,visible:c,exit:d,onExit:g}},Mh=e=>{for(let t of e.split(
).reverse()){let r=t.match(/https?:\/\/keicho\.netlify\.app\/#talk=(\w+)/)?.[1];if(r)return r}},ZS=(e,t,r)=>{let n=Math.max(e.findLastIndex((s,i)=>i<t&&s.text.trim().startsWith(r)),1),o=n+Pt(n,e)+1;return[e.slice(o,t+1).map(s=>s.text.trim()).join(
).trim(),o,t]};scrapbox.PopupMenu.addButton({title:"",onClick:e=>${e}});scrapbox.PopupMenu.addButton({title:"",onClick:e=>$ ${e}});var Ih=[br,yr,vr];scrapbox.PopupMenu.addButton({title:e=>{let t=Rt({project:scrapbox.Project.name,mode:"noopen",hooks:Ih});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&&Rt({project:e,mode:"noopen",hooks:Ih})?.()}});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( );if(e!=t)return t}});var eP=[Dc,lh,Dc,uh,gh,Ys(),hh,ah(),ph,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"),n=e.searchParams.get("sr");return e.search="",t&&e.searchParams.append("dt",t),e.pathname.startsWith("/transit/route/")&&(r&&e.searchParams.append("tm",r),n&&e.searchParams.append("sr",n)),e},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,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}]},e=>e.hostname==="github.com"?${e}:e,bh,fh()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let t=xh(e,...eP);if(typeof t=="string")return e===t?void 0:t;t.then(r=>{if(e!==r)return je(r)})}});Eh(["takker","takker-memex","takker-private","takker-books"]);if(!/mobile/i.test(navigator.userAgent)){let e=(t,r)=>{t.trim()!==""&&Dh({mode:r}).then(n=>{if(!n)return;let{ask:o,visible:s,onExit:i}=n,a=c=>{!s()||c.key!=="Enter"||!c.ctrlKey||c.altKey||c.shiftKey||(c.preventDefault(),c.stopPropagation(),o())};$e().addEventListener("keydown",a),i(()=>$e().removeEventListener("keydown",a))})};scrapbox.PopupMenu.addButton({title:()=>"🤖",onClick:t=>e(t)})}var Jn=(e,t)=>t.map(r=>r.replace(/@yyyy-MM-dd HH:mm:ss@/g,V(e,"yyyy-MM-dd HH:mm:ss")).replace(/@yyyy-MM-dd@/g,V(e,"yyyy-MM-dd")).replace(/@yyyy-MM-dd(?:([+-])(\d+)(w?))?(?:\((Sun|Mon|Tue|Wed|Thu|Fri|Sat)\))?@/g,(n,o,s,i,a)=>{let c=o?o==="+"?ze(e,parseInt(s)*(i==="w"?7:1)):_t(e,parseInt(s)*(i==="w"?7:1)):e;return V(a?ze(No(c),tP(a)):c,"yyyy-MM-dd")}).replace(/@yyyy-ww@/g,${kn(e)}-w${${wn(e)}.padStart(2,"0")}).replace(/@yyyy-ww([+-])(\d+)(w?)@/g,(n,o,s,i)=>{let a=o==="+"?ze(e,parseInt(s)*(i==="w"?7:1)):_t(e,parseInt(s)*(i==="w"?7:1));return${kn(a)}-w${${wn(a)}.padStart(2,"0")}})),tP=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 Oh=async(e,t,r)=>{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 o=new Date(2023,1,3),s=async()=>{let l=new Date,u={start:o,end:ze(l,1)},{render:p,dispose:f}=ce(),d;try{let g=await Nh(t),h=await Nh(r),x=Oo(u).filter(S=>{let b=Jn(S,g)[0],k=n.find(w=>w.title===b);return!k||!k.exists}),v=yu(u).filter(S=>{let b=Jn(S,h)[0],k=n.find(w=>w.title===b);return!k||!k.exists});if(x.length===0&&v.length===0)return;let L=x.length+v.length;p({type:"spinner"},{type:"text",text:create ${L} review pages...}),d=await Ne();for(let S of[...x.map(b=>Jn(b,g)),...v.map(b=>Jn(b,h))])await re(e,S[0],(b,k)=>k.persistent?void 0:S,d?{socket:d}:{}),L--,p({type:"spinner"},{type:"text",text:create ${L} review pages...});p({type:"check-circle"},{type:"text",text:created ${x.length+v.length} review pages.}),o=l}catch(g){p({type:"exclamation-triangle"},{type:"text",text:g instanceof Error?${g.name} ${g.message}:"Unknown error! (see developper console)"}),console.error(g)}finally{d&&await ve(d),await ie(1e3),f()}},i=s(),a=new Date,c=setInterval(()=>{let l=new Date;qe(a,l)||(a=l,i.then(()=>i=s()))},1e4);return()=>(clearTimeout(c),i)},Nh=async e=>{let t=await $r(e[0],e[1],e[2]);if(!t.ok){let n=new Error;throw n.name=t.value.name,n.message=${t.value.message} at fetching /${e0}/${e1}/${e2},n}let r=t.value.split( );if(r.length===0)throw new Error(template "/${e0}/${e1}/${e2}" is empty!);return r};var Oc=(...e)=>{let t=e.flatMap(n=>{if(typeof n=="string")return[ei(n)];if(Array.isArray(n.type))return[$h(n.type)];switch(n.type){case"text":return[ei(n.text)];case"group":{let o=Oc(...n.items);return o?[o]:[]}default:return[$h(n.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},ei=e=>{let t=document.createElement("span");return t.classList.add("item"),t.append(e),t},$h=e=>{if(Array.isArray(e)){let t=document.createElement("span");t.classList.add("fa-stack");let r=Nc(e[0]);r.classList.add("fa-stack-1x");let n=Nc(e[1]);return n.classList.add("fa-stack-1x"),t.append(r,n),ei(t)}return ei(Nc(e))},Nc=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:$c,selection:jc}=ht(),Ah=e=>{let{className:t,display:r,onClick:n,context:o="page"}=e,s=document.createElement("div");t&&s.classList.add(t),jh(o)||(s.style.display="none");let i=(...l)=>{if(l.length===1&&l[0]===""){s.style.display="none";return}s.textContent="";let u=Oc(...l);u&&s.append(u)},a=typeof r=="function"?r({cursor:$c,selection:jc}):r;return i(...Array.isArray(a)?a:[a]),s.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),n({cursor:$c,selection:jc,setDisplay:i})}),{status:s,context:o,update:()=>{if(jh(o)?s.removeAttribute("style"):s.style.display="none",typeof r=="function"){let l=r({cursor:$c,selection:jc});i(...Array.isArray(l)?l:[l])}}}},jh=e=>e!=="stream"?scrapbox.Layout===e:scrapbox.Layout==="list"&&location.pathname.startsWith("/stream");var Fh=()=>{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 Ac=new Set,{cursor:rP,selection:nP}=ht(),oP=Fh();var lt=e=>{let t=Ah(e);return Ac.add(t),oP.append(t.status),()=>{t.status.remove(),Ac.delete(t)}},Fc=()=>{for(let{update:e}of Ac)e()};rP.addChangeListener(()=>Fc());nP.addChangeListener(()=>Fc());scrapbox.addListener("layout:changed",Fc);var Uh=async(e,t)=>{try{let r=t.getSelectedText()||he(e.getPosition().line);if(!r)return;await navigator.clipboard.writeText(r)}catch(r){console.error(r),alert(Faild to copy:
${JSON.stringify(r)})}},Bh=async(e,t)=>{try{let r=t.hasSelection(),n=r?t.getRange().start.line:e.getPosition().line,o=r?t.getSelectedText():he(n);if(!o)return;await navigator.clipboard.writeText(o),r||t.setRange({start:{line:n,char:0},end:{line:n,char:o.length}}),e.focus(),xe("Delete")}catch(r){console.error(r),alert(Faild to cut:
${JSON.stringify(r)})}},Hh=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)})}},zh=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=Fr();t.hasFocus||(e.preventDefault(),t.focus())});var Uc=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")}},qh=new Uc;var Wh=e=>new Promise(t=>setTimeout(t,e));async function mt(e,{wait:t=1}={}){let r=qh.textInput;r.focus(),r.value=e;let n=document.createEvent("UIEvent");n.initEvent("input",!0,!1),r.dispatchEvent(n),await Wh(t)}if($t()){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:()=>mt(V(new Date,"#yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD HH:mm:ss ",onClick:()=>mt(V(new Date,"yyyy-MM-dd HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"YYYY-MM-DD",onClick:()=>mt(V(new Date,"yyyy-MM-dd"))}),scrapbox.PageMenu(e).addItem({title:"HH:mm:ss ",onClick:()=>mt(V(new Date,"HH:mm:ss "))}),scrapbox.PageMenu(e).addItem({title:"⬜",onClick:()=>mt("⬜")}),scrapbox.PageMenu(e).addItem({title:"🚧",onClick:()=>mt("🚧")}),scrapbox.PageMenu(e).addItem({title:"⌛",onClick:()=>mt("⌛")}),scrapbox.PageMenu(e).addItem({title:"📝",onClick:()=>mt("📝")}),scrapbox.PageMenu(e).addItem({title:"✅",onClick:()=>mt("✅")}),scrapbox.PageMenu(e).addItem({title:"❌",onClick:()=>mt("❌")})}scrapbox.PageMenu.addItem({title:"Open kakeru",image:"https://i.kakeru.app/15c3b1a40b6b3c2ebd68f33f4c86b3f6-opaque.png",onClick:()=>window.open("https://kakeru.app")});async function Kh(e,{from:t,to:r,merge:n}){if(t===r)return{success:!0,dup:!1};let o=await Ge(t,e);if(!o.ok)return{success:!1,at:"from",name:o.value.name,message:o.value.message};let s=o.value;if(!s.persistent)return{success:!1,at:"from",name:"EmptyPageError",message:"The request page is empty."};let i=await Ge(r,e);if(!i.ok)return{success:!1,at:"to",name:i.value.name,message:i.value.message};let a=o.value;return a.persistent&&!n?{success:!1,at:"to",name:"NoEmptyPageError",message:The same page already exists in "/${r}"}:(await re(r,e,c=>[...c,...s.lines.slice(1)].map(l=>l.text)),await El(t,e),{success:!0,dup:a.persistent})}var Bc=async()=>{let e=scrapbox.Page.title,t=scrapbox.Project.name,r=window.prompt(Take "/${t}/${e}" from "${t}" to:,"takker");if(!r)return;let{render:n,dispose:o}=ce();n({type:"spinner"},{type:"text",text:/${t}/${e} → /${r}/${e}});try{let s=await Kh(e,{from:t,to:r,merge:!0});if(!s.success){n({type:"exclamation-triangle"},{type:"text",text:${s.name} ${s.message}});return}return n({type:"check-circle"},{type:"text",text:Moved ${s.dup?"and merged ":""}to "/${r}/${e}".}),https://scrapbox.io/${r}/${Q(e)}}catch(s){n({type:"exclamation-triangle"},{type:"text",text:s instanceof Error?${s.name} ${s.message}:"Unknown error! (see developper console)"}),console.error(s)}finally{setTimeout(()=>o(),1e3)}};scrapbox.PageMenu.addItem({title:"Transport",onClick:async()=>{await Bc()}});scrapbox.PageMenu.addItem({title:"Transport and Open",onClick:async()=>{let e=await Bc();e&&window.open(e)}});var Hc=e=>e.replace(/[\[\]]/g,"").replace(/\s/g," "),Cr=e=>${e}.padStart(2,"0"),Gh=e=>${e.getFullYear()}-${Cr(e.getMonth()+1)}-${Cr(e.getDate())} ${Cr(e.getHours())}:${Cr(e.getMinutes())}:${Cr(e.getSeconds())},zc=e=>${e.getFullYear()}-${Cr(e.getMonth()+1)}-${Cr(e.getDate())};async function Xh(e,t,r,n){let{render:o,dispose:s}=ce(),i=[],a=[];for(let l of sP(r)){if(l.type==="line"){i.push(${Hc(l.text)}~@${zc(new Date)});continue}let u=${Hc(l.lines0)}~@${zc(new Date)};a.push([u,...l.lines.slice(1),"",#${Gh(new Date)}]),i.push(${u})}let c=n?.socket;try{c??=await Ne(),o({type:"spinner"},{type:"text",text:Adding ${i.length} items...}),await re(e,t,l=>{let u=l.map(f=>f.text),p=u.flatMap((f,d)=>f.trim()==="[/icons/hr.icon]"?[d]:[]).pop()??-1;return p<0?[...u,...i]:[...u.slice(0,p),...i,...u.slice(p)]},{socket:c}),o({type:"spinner"},{type:"text",text:Create ${a.length} pages...}),await Promise.all(a.map(l=>re(e,l[0],u=>[u[0].text,...u.slice(1).map(p=>p.text),...l.slice(1)],{socket:c}))),o({type:"check-circle"},{type:"text",text:"Added to the inbox."})}catch(l){o({type:"exclamation-triangle"},{type:"text",text:"Failed to add (see console). Write directory instead."}),console.error(l),Ar(e,t,[...i,...a].join( ))}finally{let l=ie(1e3);c&&await ve(c),await l,s()}}function*sP(e){let t=0;for(;t<e.length;){let r=Pt(t,e);if(r===0){yield{type:"line",text:e[t].trim()},t++;continue}let n=He(e[t]);yield{type:"block",lines:e.slice(t,t+r+1).map(o=>o.slice(n))},t+=r+1}}var Yh=async(e,t)=>{let r=window.prompt("Type all you think of","");if(!r||r.trim()==="")return;let n=r.trim().split(/\s+/);await Xh(e,t,n)};var iP="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)}/${iP},{execute:n}=await import(r);n()}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}))}});var Qn=e=>{let[t,r]=F([]),[n,o]=F([]),[s,i]=F(!1),a=_(async()=>{let l=new Set;i(!0);let u=await rn(e),p=[],f=u.flatMap(({links:d,project:g})=>d.flatMap(h=>{let{title:x}=tn(h),v=st(x);if(!v)return[];if(!v.ok)return p.push({project:g,title:x,...v.value}),[];let L=X(x);return l.has(L)?[]:(l.add(L),[{project:g,title:x,...v.value}])}));r(f),o(p),i(!1)},[e]),c=_(async()=>{i(!0),await $s(e,60),i(!1)},[e]);return K(()=>(a(),zn(e,a)),[e,a]),{tasks:t,errors:n,load:c,loading:s}};var Vh=()=>_(e=>e.stopPropagation(),[]);var ti=()=>{let[e,t]=sr(aP,{isOpen:!1,prevOverflowY:""}),r=_(()=>t(!0),[]),n=_(()=>t(!1),[]),o=_(({children:s})=>{let i=Vh(),a=$(()=>{let c;return l=>{if(!l){c?.(),t(l);return}let u=new AbortController;l.addEventListener("cancel",()=>t(!1),{signal:u.signal}),c=()=>{u.abort()},t(l)}},[]);return m("dialog",{ref:a,onClick:n},s&&m("div",{className:"dialog-inner",onClick:i},s))},[]);return{isOpen:e.isOpen,open:r,close:n,Dialog:o}},aP=(e,t)=>{let r=e.dialog?.open??!1;if(t instanceof HTMLDialogElement||t===null)return r===e.isOpen&&t===e.dialog?e:{isOpen:r,dialog:t,prevOverflowY:e.prevOverflowY};if(t){e.dialog?.showModal?.();let n=e.isOpen?e.prevOverflowY:document.documentElement.style.overflowY;return document.documentElement.style.overflowY="hidden",e.isOpen&&r?e:{isOpen:!0,prevOverflowY:n,dialog:e.dialog}}return e.dialog?.close?.(),e.prevOverflowY===""?document.documentElement.style.removeProperty("overflow-y"):document.documentElement.style.overflowY=e.prevOverflowY,!e.isOpen&&!r?e:{isOpen:!1,prevOverflowY:"",dialog:e.dialog}};var Zn=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{&::backdrop{background-color:#000c}padding:10px;background:unset;margin-top:unset;margin-bottom:unset;border:unset;height:unset;overflow-y:hidden;&open>.dialog-inner{display:flex}>.dialog-inner{flex-direction:column;align-items:center;row-gap:10px;height:100%;>*{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 un=({text:e,title:t})=>{let[r,n]=F(""),o=_(async s=>{s.preventDefault(),s.stopPropagation();try{await navigator.clipboard.writeText(e),n("Copied"),await ie(1e3),n("")}catch(i){alert(Failed to copy the code block
Error:${i.message})}},[e]);return m("button",{className:"copy",title:t??"Copy",onClick:o},r)};var cP=60*60*24*1e3,Jh=(e,t)=>{let r=ee(e.refDate),n=(t.getTime()-r.getTime())/cP;switch(r.setHours(0),r.setMinutes(0),e.status){case"done":return-1/0;case"deadline":return n/(e.speed??1);case"todo":return Math.min(n/(e.speed??1),0);case"note":return t.getTime()<r.getTime()?-1/0:-n/(e.speed??1);case"up-down":{let o=e.speed??30;return o*(-1+Math.cos(Math.PI*2*n/o))}}};var Zh=(e,t)=>{if(t.score!==e.score)return t.score-e.score;let r=Qh(e.freshness),n=Qh(t.freshness);return r!==n?n-r:ot(vt(e),vt(t))?-1:1},Qh=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 Ke=e=>${e.getFullYear()}-${ut(e.getMonth()+1)}-${ut(e.getDate())},eo=e=>{let[t,r,n]=e.split("-").map(o=>parseInt(o,10));return{year:t,month:r,date:n}},to=e=>${Pu(e)}-w${ut(wn(e))},ri=e=>{let[t,r]=e.split("-w").map(n=>parseInt(n,10));return No(Du(new Date(t,0,1),r))};var ro=({loading:e,onClick:t})=>e?m("div",null,m("i",{className:"fa fa-spinner"})):m("button",{className:"navi reload",onClick:t},"");var dn=()=>{let[e,t]=F(new Date);return K(()=>{let r=setInterval(()=>t(new Date),6e4);return()=>{clearInterval(r)}},[]),e};var ex=e=>{switch(e){case"todo":return"ToDo";case"note":return"覚書";case"deadline":return"締切";case"up-down":return"浮遊";case"done":return"完了"}};var tx=(e,t)=>new URL(/${e.project}/${Q(e.title)},t??location.href);var ni=({children:e,project:t,title:r,className:n,...o})=>m("a",{...o,className:[n??"","page-link"].join(" "),type:"link",href:tx({project:t,title:r}).pathname,...t===scrapbox.Project.name?{rel:"route"}:{rel:"noopener noreferrer",target:"_blank"}},e);var rx=({action:e,pActions:t})=>{let r=$(()=>ex(e.freshness.status),[e.freshness.status]),n=$(()=>bt(vt(e)).slice(11)||" ",[vt(e)]),o=$(()=>Cn(e),[e]),s=Math.floor(Math.round(e.score)/7),i=dn(),a=$(()=>e.executed!==void 0&&lr(zt(ee(e.executed.start),e.executed.duration),i),[e.executed?.start,e.executed?.duration,i]),c=$(()=>[...t,e].map(l=>${l.raw}).join( ),[t,e]);return m("li",{"data-type":e.freshness.status,"data-freshness":e.score.toFixed(0),"data-level":s,...s<0?{style:{opacity:lP(e).toFixed(2)}}:{}},m(un,{text:c,title:"ここまでコピー"}),m("span",{className:"label type"},r),m("i",{className:label far fa-fw${a?" fa-bookmark":""}}),m("span",{className:"label freshness"},e.score.toFixed(0)),m("time",{className:"label start"},n),m("span",{className:"label duration"},o,"m"),m(ni,{project:e.project,title:e.raw},e.name))},lP=e=>Math.max(.8*Math.exp(Math.log(8/7)/7*e.score),.05);var nx=(e=Ke(new Date))=>{let[t,r]=F(e),n=_(()=>{r(s=>{switch(s){case"errors":return"expired";case"expired":return Ke(new Date);default:{let i=ee(eo(s));return i.setDate(i.getDate()+1),Ke(i)}}})},[]),o=_(()=>{r(s=>{let i=Ke(new Date);switch(s){case"errors":return"errors";case"expired":return"errors";case i:return"expired";default:{let a=ee(eo(s));return a.setDate(a.getDate()-1),Ke(a)}}})},[]);return{pageNo:t,next:n,prev:o}};var oi=(e,t)=>K(()=>(scrapbox.on(e,t),()=>scrapbox.off(e,t)),[]);var no=(e,t)=>{let r=ke({...t});K(()=>(Object.assign(r.current,t),()=>{for(let n of Object.keys(t))delete r.current[n]}),[...Object.keys(t)].sort().map(n=>t[n])),K(()=>{e(r.current)},[e])};var ox=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(n=>we(m(pP,{getController:n,projects:e}),r))},pP=({getController:e,projects:t})=>{let{tasks:r,errors:n,load:o,loading:s}=Qn(t),{pageNo:i,next:a,prev:c}=nx(),l=$(()=>{if(i==="errors")return n.map(h=>({name:${h.title}
name:${h.name}
message:${h.message},raw:h.title,freshness:{refDate:{year:9999,month:1,date:1},status:"todo"},project:h.project,generated:!0,score:0}));if(i==="expired"){let h=new Date;return r.flatMap(x=>!yt(x)&&ot(Wu(x),We(h))&&x.freshness===void 0&&x.recurrence===void 0?[{...x,score:0,freshness:{refDate:x.executed.start,status:"todo"}}]:[]).sort((x,v)=>ot(vt(x),vt(v))?-1:0)}let g=ee(eo(i));return r.flatMap(h=>{if(!h.freshness)return[];if(Kt(h))return[];let x=Jh(h.freshness,g);return x>-999?[{...h,score:x}]:[]}).sort(Zh)},[r,n,i]),{Dialog:u,open:p,close:f}=ti();no(e,{open:p,close:f});let d=$(()=>[i,...l.map(g=> ${g.raw})].join( ),[l,i]);return oi("page:changed",f),m(W,null,m("style",null,Zn),m(u,null,m("div",{className:"controller"},m(un,{text:d,title:"Copy All Tasks"}),m("span",null,i),m("button",{className:"navi left",onClick:c},""),m("button",{className:"navi right",onClick:a},""),m(ro,{loading:s,onClick:o}),m("button",{className:"close",onClick:f},"")),m("ul",{className:"result task-list","data-page-no":i},l.map((g,h)=>m(rx,{key:g.raw,action:g,pActions:l.slice(0,h)})))))};var ii=(e,t)=>/${e}/${X(t)},oo=new Map,qc=new Map,sx=(e,t)=>{oo.set(e,t);for(let r of qc.get(e)??[])r(t)},si=()=>{Mr!==void 0&&(clearInterval(Mr),Mr=void 0);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=ii(e,t);if(!oo.has(r))return;let n=Be().map(o=>o.text);Mr=setInterval(()=>{X(t)===X(n[0])&&(sx(r,n),Mr!==void 0&&(clearInterval(Mr),Mr=void 0))},1e3)},Mr;scrapbox.on("page:changed",()=>{scrapbox.off("lines:changed",si);let e=scrapbox.Project.name,t=scrapbox.Page.title??"",r=ii(e,t);oo.has(r)&&scrapbox.on("lines:changed",si)});var uP=(e,t)=>{let r=ii(e,t),n=oo.get(r);return n||(oo.set(r,[]),Ge(e,t).then(o=>{if(!o.ok)return[];let s=o.value.lines.map(i=>i.text);sx(r,s),t===scrapbox.Page.title&&!scrapbox.listeners("lines:changed").includes(si)&&scrapbox.on("lines:changed",si)})),n??[]},ix=(e,t)=>{let[r,n]=F(uP(e,t));return K(()=>{let o=ii(e,t),s=qc.get(o)??new Set;return s.add(n),qc.set(o,s),()=>{s.delete(n)}},[e,t]),r};var Wc=e=>e.duration===void 0?void 0:We(zt(ee(e.start),e.duration)),Kc=(e,t)=>{let r=ee(e.start),n=t.getTime(),o=Math.round((n-r.getTime())/(60*1e3));if(o<=0)return[void 0,e];if(e.duration<=o)return[e,void 0];let s={start:e.start,duration:o};return[s,{start:Wc(s),duration:e.duration-o}]};var Dr=e=>"title"in e,dP=e=>e.record?.duration!==void 0,ax=(e,t)=>Dr(e)&&e.status==="done"?e.status:dP(e)?Dr(e)&&e.executed?ot(We(t),e.executed.start)?"moved":"expired":"done":ot(Wc(e.plan),We(t))?Dr(e)?"expired":"done":"undone";var cx=(e,t)=>{let r=st(e.title.slice(1,-1));if(!e.plan.start)return;let n={name:r?.ok?r.value.name:e.title,plan:{start:We(e.plan.start),duration:(e.plan.duration??0)/60}};if(e.record.start&&(n.record={start:We(e.record.start)},e.record.end&&(n.record.duration=Vi(e.record.end,e.record.start))),!r?.ok)return n;let o={...n,title:r.value.raw,project:t};return r.value.freshness&&(o.status=r?.value.freshness.status),yt(r.value)||(o.executed=r.value.executed),o},Gc=(e,t)=>{let r=Wo(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 lx=(e,t,r)=>{let n=[Xc(e,_t(t,1),r),Xc(e,t,r),Xc(e,ze(t,1),r)],o=$(()=>n.flat(),n);return $(()=>{let s=Jp(t),i=vu(t);return o.flatMap(a=>{let[,c]=Kc(a.plan,s);if(!c)return[];let[l]=Kc(c,i);if(!l)return[];let{plan:u,...p}=a;return[{plan:l,...p}]}).sort((a,c)=>ot(a.plan.start,c.plan.start)?-1:0)},[o,t])},Xc=(e,t,r)=>{let n=ix(e,Wt(t)),o=$(()=>fP(n,e),[n,e]);return $(()=>o.length!==0?o:mP(t,r),[o,t,r])},mP=(e,t)=>t.flatMap(r=>{if(r.freshness?.status==="done")return[];if(yt(r))return[];if(Kt(r)){let o=qo(r,e);return o?[Gc(o,r.project)]:[]}let n=ee(r.executed.start);return qe(n,e)?[Gc(r,r.project)]:[]}),fP=(e,t)=>{let r=[];for(let n of pr(e)){if(qt(n))continue;let o=cx(n,t);o&&r.push(o)}return r};var px=({event:e})=>{let t=$(()=>e.plan.start.hours+e.plan.start.minutes/60,[e.plan.start]),r=$(()=>--start: ${t}; --duration: ${e.plan.duration};,[t,e.plan.duration]),n=dn(),o=$(()=>ax(e,n),[e,n]);return Dr(e)?m(ni,{className:"event","data-status":o,style:r,title:e.title,project:e.project},e.name):m("div",{className:"event","data-status":o,title:e.name,style:r},e.name)};var ux=({project:e,date:t,tasks:r})=>{let n=lx(e,t,r),o=$(()=>n.flatMap(a=>Dr(a)?[${a.title}]:[]).join( ),[n]),s=dn(),i=$(()=>qe(s,t)?m("div",{className:"indicator",style:--start: ${wu(s)+ku(s)/60}}):m(W,null),[s,t]);return m("div",{className:"timeline",role:"gridcell"},n.map(a=>m(px,{key:a.name,event:a})),i,m(un,{text:o}))};var Yc=({dateList:e,tasks:t,project:r,hasColumn:n})=>m("div",{className:"timeline-wrap",role:"grid"},(n??!0)&&m("div",{className:"column-header",role:"row"},e.map(o=>m("div",{key:Ke(o),className:"cell",role:"columnheader"},m("h2",null,jo(o))))),m("div",{className:"week-container",role:"presentation"},m("div",{className:"week",role:"presentation"},m("div",{className:"borders"},[...Array(24).keys()].map(o=>m("div",{key:o,className:"border","data-time":${ut(o)}:00}))),e.map(o=>m(ux,{key:Ke(o),project:r,date:o,tasks:t})))));var Vc=(e,t,r)=>{let[n,o]=F(e),s=_(()=>o(t),[t]),i=_(()=>o(r),[t]),a=_(c=>o(c),[]);return{pageNo:n,next:s,prev:i,jump:a}};var dx=e=>{let t=ke(new Set),[r,n]=F(e),o=_(()=>{for(let l of t.current)l()},[]),s=_(()=>{n(!0),o()},[]),i=_(()=>n(!1),[]),a=_(()=>n(l=>(l||o(),!l)),[]),c=_(l=>(t.current.add(l),()=>t.current.delete(l)),[]);return{isOpen:r,open:s,close:i,toggle:a,onOpen:c}};var gx=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(n=>we(m(gP,{getController:n,projects:e,mainProject:e[0]}),r))},hx=(e,t)=>{let r=document.createElement("div");r.dataset.userscriptName="takker-scheduler/timeline-wedget";let n=r.attachShadow({mode:"open"});return document.body.append(r),new Promise(o=>we(m(hP,{getController:o,projects:e,mainProject:e[0],open:t}),n))},mx=!1,gP=({getController:e,projects:t,mainProject:r})=>{let{tasks:n,load:o,loading:s}=Qn(t),{pageNo:i,next:a,prev:c,jump:l}=Vc(to(new Date),xP,bP),u=$(()=>{let x=ri(i);return[0,1,2,3,4,5,6].map(v=>ze(x,v))},[i]),{open:p,close:f,Dialog:d,isOpen:g}=ti();mx||=g,no(e,{open:p,close:f,isOpen:g}),oi("page:changed",f);let h=_(()=>l(to(new Date)),[l]);return m(W,null,m("style",null,Zn),m(d,null,m("div",{className:"controller"},m("span",null,i),m("button",{className:"navi left",onClick:c},""),m("button",{className:"navi right",onClick:a},""),m("button",{className:"today",onClick:h},""),m(ro,{loading:s,onClick:o}),m("button",{className:"close",onClick:f},"")),mx&&m("div",{ref:xx,className:"result scheduler","data-page-no":i},m(Yc,{dateList:u,tasks:n,project:r}))))},fx=!1,hP=({projects:e,mainProject:t,getController:r,open:n})=>{let{tasks:o,load:s,loading:i}=Qn(e),{pageNo:a,next:c,prev:l,jump:u}=Vc(new Date,yP,vP),p=$(()=>[a],[a]),f=_(()=>u(new Date),[u]),{isOpen:d,open:g,close:h}=dx(n);return fx||=d,no(r,{open:g,close:h,isOpen:d}),m(W,null,m("style",null,Zn),fx&&m("div",{className:wedget${d?" open":""},ref:xx},m("div",{className:"controller"},m("span",null,Ke(a)),m("button",{className:"navi left",onClick:l},""),m("button",{className:"navi right",onClick:c},""),m("button",{className:"today",onClick:f},""),m(ro,{loading:i,onClick:s})),m(Yc,{dateList:p,tasks:o,project:t,hasColumn:!1})))},xP=e=>to(Zp(ri(e),1)),bP=e=>to(Nu(ri(e),1)),yP=e=>ze(e,1),vP=e=>_t(e,1),xx=e=>{let t=e?.getElementsByClassName?.("indicator")?.[0];if(!t)return;let r=globalThis.scrollY;t.scrollIntoView({block:"center"}),globalThis.scroll(0,r)};Al({project:"takker-dist"});jp().then(e=>{scrapbox.PageMenu.addItem({title:"Fulltext Search",onClick:()=>{e.toggle()}})});var wP="https://scrapbox.io/files/666ac977264f7d001ce9d125.wasm",kP="/api/code/takker-dist/esbuild-wasm-no-blob/worker.js";(async()=>{let e=new Request(wP),t=await ar(e);t||(t=await fetch(e),await Co(e,t)),await Jm(await WebAssembly.compileStreaming(t),kP)})();(async()=>{let e=[scrapbox.Project.name,"takker","takker-memex","takker-books","takker-private","villagepump","hub","arpla","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"],t=await Zf({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","概要と参加方法"]].map(([o,s])=>[o,https://scrapbox.io/api/pages/${o}/${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":"⿻"},enableSelfProjectOnStart:!0}),r=o=>{o.preventDefault(),o.stopPropagation()},n=()=>document.querySelector(".line .popup-menu")!==null;la.bind({"<Tab>":o=>{n()||t.selectNext?.({cyclic:!0})&&r(o)},"<S-Tab>":o=>{n()||t.selectPrev?.({cyclic:!0})&&r(o)},"<Enter>":o=>{n()||t.confirm?.()&&r(o)},"<Esc>":o=>{n()||t.cancel?.()&&r(o)}})})();ng({previewers:[{when:/(?:^|\.)svg$/,preview:og},{when:/(?:^|\.)glsl$/,preview:$g},{when:/(?:^|\.)(?:plantuml|puml|pu)$/,preview:Fg},{when:/(?:^|\.)tikz\(tex\)$/,preview:Bg("https://scrapbox.io/api/code/takker-dist/scrapbox-tikz/mod.js","https://scrapbox.io/files/65d1645c19cd8e002433c3df")}]});(async()=>{let{toggle:e}=await Kg([]);scrapbox.PageMenu.addItem({title:"履歴スライダー",image:"https://1.bp.blogspot.com/-UZtkSEX0wh4/U5l5_dNcEsI/AAAAAAAAhWs/UzJGVzyiX8Y/s800/kaichu_dokei.png",onClick:e})})();Oh("takker",["takker","振り返り(takker-workflow@0.0.1)のtemplate","txt"],["takker","1週間の振り返り(takker-workflow@0.0.1)のtemplate","txt"]);$t()&&(lt({display:{type:"caret-left"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?So():ko()}}),lt({display:{type:"caret-right"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Lo():wo()}}),lt({display:{type:"caret-up"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Po():Eo()}}),lt({display:{type:"caret-down"},onClick:({cursor:e,selection:t})=>{e.focus(),t.getSelectedText()===""?Ro():To()}}),lt({display:{type:"copy"},onClick:async({cursor:e,selection:t})=>await Uh(e,t)}),lt({display:{type:"cut"},onClick:async({cursor:e,selection:t})=>await Bh(e,t)}),lt({display:{type:"clipboard"},onClick:async({cursor:e})=>await Hh(e)}),lt({display:{type:"undo"},onClick:()=>Lp()}),lt({display:{type:"redo"},onClick:()=>Sp()}),lt({display:({cursor:e})=>e.getVisible()&&e.hasFocus&&e.visiblePopupMenu?{type:["i-cursor","slash"]}:{type:"i-cursor"},onClick:({cursor:e})=>zh(e)}));if($t()&&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:mr}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>gr({from:{project:scrapbox.Project.name,title:scrapbox.Page.title},to:"takker-memex"})})}if($t()){let e="New Page",t=[br,yr,vr];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&&Rt({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&&Rt({project:r,mode:"self",hooks:t})?.()}})}scrapbox.PageMenu.addMenu({title:"Add to inbox",image:"https://img.icons8.com/ios/180/FFFFFF/inbox.png",onClick:()=>Yh("takker-memex","メモ帳")});(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= 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;
}
opacity: 0;
},document.head.append(r);let n=["takker-memex","takker"],{open:o}=await ox(n);scrapbox.PageMenu.addMenu({title:e,image:"/assets/img/favicon/apple-touch-icon.png",onClick:o});let s=await gx(n);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 hx(n,a[c]),u=()=>{a[c]=!l.isOpen,l.isOpen?l.close():l.open(),localStorage.setItem(i,JSON.stringify(a))};$t()?lt({display:{type:"calendar"},onClick:u}):scrapbox.PageMenu.addItem({title:"toggle wedget",onClick:u})}})();var bx=e=>String(e).padStart(2,"0"),yx=e=>${e.getFullYear()}-${bx(e.getMonth()+1)}-${bx(e.getDate())};for(let e of document.getElementsByClassName("new-button")){let t=#${yx(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=Or.parse(e,{hasTitle:!1});if(console.log("Parserd text:"),console.log(t),navigator.clipboard){let r=EP(t).join(`
);console.log(r),navigator.clipboard.writeText(r).catch(n=>console.log(n)),console.log("Copied.")}}});function EP(e){let t=Math.min(...e.map(o=>o.indent)),r=t,n=["<p>"];for(let o of e.filter(s=>s.type==="line")){let s=o.indent-r;s<0&&n.push(...[...Array(-s)].map(a=>"</ul>")),s>0&&n.push(...[...Array(s)].map(a=>'<ul style="margin-top: 5px;margin-bottom: 5px;">'));let i=o.nodes.map(a=>ai(a)).join("");o.indent>t?n.push(<li>${i}</li>):n.push(${i}<br/>),r=o.indent}return n.push(...[...Array(r-t)].map(o=>"</ul>")),n.push("</p>"),n}function ai(e){switch(e.type){case"quote":return<span style="
font-style: italic;
background-color: rgba(128,128,128,0.1);
display: block;
height: 1.3em;
vertical-align: top;" src="${t}" alt="${n}" /></a>;case"strongIcon":return"";case"formula":return\\( ${e.formula} \\);case"helpfeel":return"";case"decoration":let o=e.nodes.map(s=>ai(s)).join("");return e.decos.includes("*-4")&&(o=<h4>${o}</h4>),e.decos.includes("*-3")&&(o=<h5>${o}</h5>),e.decos.includes("*-2")&&(o=<h6>${o}</h6>),e.decos.includes("*-1")&&(o=<strong>${o}</strong>),e.decos.includes("/")&&(o=<i>${o}</i>),e.decos.includes("-")&&(o=<strike>${o}</strike>),e.decos.includes("!")&&(o=<pre>${o}</pre>),o;case"strong":return<strong>${e.nodes.map(s=>ai(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($t()){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:ta}),scrapbox.PageMenu(e).addItem({title:"Add task",image:"https://img.icons8.com/ios/180/FFFFFF/plus-math.png",onClick:Tn}),scrapbox.PageMenu(e).addItem({title:"Start task",image:"https://img.icons8.com/ios/180/FFFFFF/start--v1.png",onClick:ur}),scrapbox.PageMenu(e).addItem({title:"End task",image:"https://img.icons8.com/ios/180/FFFFFF/stop-squared.png",onClick:Ct}),scrapbox.PageMenu(e).addItem({title:"Posteriori end task",image:"https://img.icons8.com/ios/180/FFFFFF/end--v1.png",onClick:Ln}),scrapbox.PageMenu(e).addItem({title:"Book starting",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:async()=>{let[t,r]=TP(),n=nt().slice(t,r+1).map(o=>{let s=o.text,i=o.text.match(/\[([^\]]+)\]/)?.[1];if(!i)return s;let a=st(i);if(!a||!a.ok)return s;let c=a.value;if(c.freshness?.status==="done")return s;let l=xr(c);return l.title=${i},l?ne(l):s}).join( );await _e(t,r,n),await mr()}}),scrapbox.PageMenu(e).addItem({title:"Walk a day",image:"https://img.icons8.com/ios/180/FFFFFF/plus-1day.png",onClick:()=>Sn()}),scrapbox.PageMenu(e).addItem({title:"Move today",image:"https://img.icons8.com/ios/180/FFFFFF/date-to.png",onClick:()=>Pn()}),scrapbox.PageMenu(e).addItem({title:"Format",image:"https://img.icons8.com/ios/180/FFFFFF/sort-by-start-date.png",onClick:()=>_n(scrapbox.Project.name,scrapbox.Page.title)}),scrapbox.PageMenu(e).addItem({title:"Transport",onClick:()=>gr({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 TP=()=>{let{selectionRange:{start:e,end:t},selectedText:r,position:n}=de();return r===""?[n.line,n.line]:e.line>t.line?[t.line,e.line]:[e.line,t.line]};var vx="scrapbox-episopass",ci=!1;scrapbox.PopupMenu.addButton({title:e=>ci?"remove EP":/https:\/\/scrapbox\.io\/files\/\w+\.html/.test(e)?"run EP":"",onClick:async e=>{if(document.getElementById(vx)?.remove(),ci){ci=!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 n=await(await fetch(t)).text();if(!n.includes("<title>EpisoPass</title>"))return;let o=new Blob([n],{type:"text/html"}),s=URL.createObjectURL(o);document.getElementsByClassName("cursor-line")[0].insertAdjacentHTML("beforeend",<iframe id="${vx}" src="${s}" width="800" height="400"></iframe>),ci=!0;return}catch(r){console.error("Failed to load an EpisoPass html: ",r)}}});var wx="takker-memex",kx=async()=>{if(scrapbox.Project.name!==wx)return()=>{};let e=scrapbox.Project.pages;await new Promise(i=>{let a=setInterval(()=>{if(e.length===0){e=scrapbox.Project.pages;return}clearInterval(a),i()},2e3)});let t=new Date(2023,0,24),r=async()=>{let i=new Date,c=Oo({start:t,end:i}).filter(f=>{let d=Wt(f),g=e.find(h=>h.title===d);return!g||!g.exists});if(c.length===0)return;let{render:l,dispose:u}=ce(),p;try{l({type:"spinner"},{type:"text",text:load tasks for ${c.length} diary pages});let f=new Map,d=new Set,g=c.map(x=>Ke(x));for(let{links:x,project:v}of await rn(["takker","takker-memex"]))for(let L of x){let{title:S}=tn(L),b=st(S);if(!b)continue;if(!b.ok){console.error(/${v}/${S}: ${b.value.name} ${b.value.message});continue}let k=X(S);if(!d.has(k)&&(d.add(k),b.value.freshness?.status!=="done"))for(let w of c){let C=xr(b.value,w);if(!C)continue;let M=Ke(C.base);g.includes(M)&&(f.set(M,[...f.get(M)??[],C]),Kt(b.value))}}p=await Ne();let h=0;l({type:"spinner"},{type:"text",text:create 0/${c.length} diary pages...});for(let x of c){let v=Wt(x),L=f.get(Ke(x))?.map?.(k=>ne(k))??[],S=#${V(x,"yyyy-MM-dd")},b=#${V(x,"yyyy-MM-dd HH:mm:ss")};await re(wx,v,(k,{persistent:w})=>{if(w)return;let C=[...k.map(M=>M.text),...L];return C.some(M=>M.includes(S))?fr(C):fr([...C,b])},{socket:p}),h++,l({type:"spinner"},{type:"text",text:create ${h}/${c.length} diary pages...})}l({type:"check-circle"},{type:"text",text:created ${c.length} diary pages.}),t=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 ve(p),await ie(1e3),u()}},n=r(),o=new Date,s=setInterval(()=>{let i=new Date;qe(o,i)||(o=i,n.then(()=>n=r()))},1e4);return()=>(clearTimeout(s),n)};kx();export{lt as addButton,je as insertText,la as scrapBindings}; /** @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.
*/