script.jsfunction ce(e){return Array.isArray(e)}function M(e){return typeof e=="string"}var Ve=(e,r)=>{if(!(e instanceof HTMLDivElement))throw new TypeError(`"${r}" must be HTMLDivElememt but actual is "${e}"`)};var We=(e,r)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError(`"${r}" must be HTMLTextAreaElement but actual is "${e}"`)};var q=()=>{let e=document.getElementById("text-input");if(e)return We(e,"textarea#text-input"),e};var qe=()=>Kt(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),Kt=(e,r)=>{if(e)return Ve(e,r),e};function Fe(e,r={}){let{signal:t,persistent:o=!0}=r;return t?.aborted?Promise.reject(t.reason):new Promise((n,s)=>{let a=()=>{clearTimeout(i),s(t?.reason)},i=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e);if(t?.addEventListener("abort",a,{once:!0}),o===!1)try{Deno.unrefTimer(i)}catch(f){if(!(f instanceof ReferenceError))throw f;console.error("`persistent` option is only available in Deno")}})}var Ke=async e=>{let r=q();if(!r)throw Error("#text-input is not ditected.");r.focus(),r.value=e;let t=new InputEvent("input",{bubbles:!0});r.dispatchEvent(t),await Fe(1)};var ze=()=>{let e=qe();if(!e)throw new Error("div.status-bar can't be found");let r=document.createElement("div");return e.append(r),{render:(...t)=>{r.textContent="";let o=Ye(...t);o&&r.append(o)},dispose:()=>r.remove()}},Ye=(...e)=>{let r=e.flatMap(o=>{switch(o.type){case"spinner":return[er()];case"check-circle":return[tr()];case"exclamation-triangle":return[rr()];case"text":return[pe(o.text)];case"group":{let n=Ye(...o.items);return n?[n]:[]}}});if(r.length===0)return;if(r.length===1)return r[0];let t=document.createElement("span");return t.classList.add("item-group"),t.append(...r),t},pe=e=>{let r=document.createElement("span");return r.classList.add("item"),r.append(e),r},er=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),pe(e)},tr=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),pe(e)},rr=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),pe(e)};var Ae=(e,...r)=>{let t=r.reduce((o,n)=>M(o)?o:o instanceof Promise?o.then(s=>M(s)?s:n(s)):n(o),e);return t instanceof Promise?t.then(o=>`${o}`):`${e}`};function N(e){return e.val}function S(e){return e.err}var Xe=" must not return ",nr="`transformer`",sr="`recoverer`",ar="`defaultValue`",ue=nr+Xe,V="called with ",me=ar+" must not be ",le=sr+Xe;var ir="`Ok`",Je="`Err`",Qe=V+Je,Ze=V+ir,cr="Carrying `E` in "+Je+" instead of throwing it directly. See `.cause`",Pe="an instance of `Error` of the current realm.",us="The thrown value is not "+Pe,ms="The contained E should be "+Pe,pr="This `.cause` is not "+Pe;function _(e){return e.ok}function b(e){return{ok:!0,val:e,err:null}}function E(e){return!e.ok}function A(e){return{ok:!1,val:null,err:e}}function P(e){return et(e,Qe)}function v(e){return tt(e,Ze)}function et(e,r){if(E(e))throw new TypeError(r);return e.val}function tt(e,r){if(_(e))throw new TypeError(r);return e.err}async function W(e,r){if(E(e))return e;let t=N(e),o=await r(t);return b(o)}function Ie(e,r,t){if(_(e)){let n=N(e);return t(n)}let o=S(e);return r(o)}var fe="`null`",ga=ue+fe,lr=V+fe,ya=me+fe,ha=le+fe;var de="`undefined`",Oa=ue+de,fr=V+de,Na=me+de,ba=le+de;var K=e=>e.ok?b(e):A({name:"HTTPError",message:`${e.status} ${e.statusText}`,response:e});var ot=e=>window.GM_fetch?.(`https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x`)?.then?.(r=>W(K(r),t=>t.json()));var Ee=e=>{let{fetch:r=globalThis.fetch,...t}=e;return{fetch:r,...t}},nt=e=>typeof e=="object"&&e!==null;var Q=class e extends Error{name="UnexpectedResponseError";status;statusText;body;path;constructor(r){super(`${r.status} ${r.statusText} when fetching ${r.path.toString()}`),this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.path=r.path,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};var Re=async e=>{let r=await e.text();if(e.ok)return b(r);if(e.status===400)return A({name:"BadRequestError",message:r});try{let t=JSON.parse(r);if(!nt(t)||typeof t.message!="string")throw new Q({status:e.status,statusText:e.statusText,body:r,path:new URL(e.url)});switch(e.status){case 401:return A({name:"UnauthorizedError",message:t.message});case 403:return A({name:"NotPrivilegeError",message:t.message});case 404:return A({name:"NotFoundError",message:t.message});case 422:return A({name:"InvalidParameterError",message:t.message});case 429:return A({name:"RateLimitError",message:t.message});default:throw new Q({status:e.status,statusText:e.statusText,body:r,path:new URL(e.url)})}}catch(t){throw t instanceof SyntaxError?new Q({status:e.status,statusText:e.statusText,body:r,path:new URL(e.url)}):t}};var st=async(e,r)=>{let{title:t,description:o,metadataIsPublic:n,collectionId:s,refererURL:a,accessToken:p,created:i,app:f,fetch:m}=Ee(r),u=new FormData;u.append("imagedata",e),u.append("access_token",p),a&&u.append("referer_url",a.toString()),f!==void 0&&u.append("app",f),t!==void 0&&u.append("title",t),o!=null&&u.append("desc",o),s&&u.append("collection_id",s),n&&u.append("metadata_is_public","true"),i!==void 0&&u.append("created_at",`${i}`);let F=await m("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:u}),C=await Re(F);return E(C)?C:b(JSON.parse(P(C)))};function L(e){return e.val}function I(e){return e.err}var at=" must not return ",Er="`transformer`",Rr="`recoverer`",gr="`defaultValue`",z=Er+at,H="called with ",Y=gr+" must not be ",X=Rr+at;var yr="`Ok`",it="`Err`",ct=H+it,hr=H+yr,Tr="Carrying `E` in "+it+" instead of throwing it directly. See `.cause`",Se="an instance of `Error` of the current realm.",pp="The thrown value is not "+Se,up="The contained E should be "+Se,xr="This `.cause` is not "+Se;function w(e){return e.ok}function R(e){return{ok:!0,val:e,err:null}}function l(e){return!e.ok}function O(e){return{ok:!1,val:null,err:e}}function d(e){return pt(e,ct)}function pt(e,r){if(l(e))throw new TypeError(r);return e.val}function Z(e,r){if(l(e))return e;let t=L(e),o=r(t);return R(o)}async function y(e,r){if(l(e))return e;let t=L(e),o=await r(t);return R(o)}async function x(e,r){if(w(e))return e;let t=I(e),o=await r(t);return O(o)}async function ge(e,r){if(w(e))return e;let t=I(e);return await r(t)}var ye="`null`",Ru=z+ye,Or=H+ye,gu=Y+ye,yu=X+ye;var he="`undefined`",wu=z+he,Nr=H+he,Ou=Y+he,Nu=X+he;var h=e=>e.ok?R(e):O({name:"HTTPError",message:`${e.status} ${e.statusText}`,response:e});var mt=async(e,r)=>{let t=new Request(e,r);try{return R(await globalThis.fetch(t))}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return O({name:"AbortError",message:o.message,request:t});if(o instanceof TypeError)return O({name:"NetworkError",message:o.message,request:t});throw o}};var g=e=>{let{fetch:r=mt,hostName:t="scrapbox.io",...o}=e;return{fetch:r,hostName:t,...o}};var lt=e=>{let{sid:r,hostName:t}=g(e??{});return new Request(`https://${t}/api/users/me`,r?{headers:{Cookie:T(r)}}:void 0)},ft=e=>y(h(e),async r=>await r.json()),dt=(()=>{let e=async r=>{let{fetch:t,...o}=g(r??{}),n=await t(lt(o));return l(n)?n:ft(d(n))};return e.toRequest=lt,e.fromResponse=ft,e})();var T=e=>`connect.sid=${e}`,G=async e=>{let r=e?.csrf??globalThis._csrf;return r?R(r):Z(await dt(e),t=>t.csrfToken)};function Te(e,r={}){if(e===null)return"null";if(Array.isArray(e))return kr(e,r);switch(typeof e){case"string":return JSON.stringify(e);case"bigint":return`${e}n`;case"object":return e.constructor?.name!=="Object"?e.constructor?.name:Ur(e,r);case"function":return e.name||"(anonymous)"}return e?.toString()??"undefined"}function kr(e,r){let{threshold:t=20}=r,o=e.map(a=>Te(a,r)),n=o.join(", ");if(n.length<=t)return`[${n}]`;let s=o.join(`,
`);return`[
${Et(2,s)}
]`}function Ur(e,r){let{threshold:t=20}=r,o=[...Object.keys(e),...Object.getOwnPropertySymbols(e)].map(a=>`${a.toString()}: ${Te(e[a],r)}`),n=o.join(", ");if(n.length<=t)return`{${n}}`;let s=o.join(`,
`);return`{
${Et(2,s)}
}`}function Et(e,r){let t=" ".repeat(e);return r.split(`
`).map(o=>`${t}${o}`).join(`
`)}function xe(e,r,...t){let o;return Object.defineProperties(e,{name:{get:()=>o||(o=`${r}(${t.map(n=>Te(n)).join(", ")})`,o)}})}function Rt(e){return xe(r=>ce(r)&&r.every(t=>e(t)),"isArrayOf",e)}function Ce(e){let r=new Set(e);return xe(t=>r.has(t),"isLiteralOneOf",e)}function ve(e){return e!=null&&!Array.isArray(e)&&typeof e=="object"}var k=async(e,r)=>{let t=e.response.clone(),o=Ce(r);try{let n=await t.json();if(!ve(n))return;if(t.status===422){if(!M(n.message))return;for(let s of["NoQueryError","InvalidURLError"])if(r.includes(s))return{name:s,message:n.message}}return!o(n.name)||!M(n.message)?void 0:n.name==="NotLoggedInError"?!ve(n.detals)||!M(n.detals.project)||!Rt(Fr)(n.detals.loginStrategies)?void 0:{name:n.name,message:n.message,details:{project:n.detals.project,loginStrategies:n.detals.loginStrategies}}:{name:n.name,message:n.message}}catch(n){if(n instanceof SyntaxError)return;throw n}},Fr=Ce(["google","github","microsoft","gyazo","email","saml","easy-trial"]);var _e="`null` or `undefined`",J=z+_e,Mr=H+_e,Be=Y+_e,we=X+_e;function B(e){return e==null}function Oe(e){return B(e)?O(void 0):R(e)}var gt=(e,r)=>{let{sid:t,hostName:o}=g(r??{});return new Request(`https://${o}/api/projects/${e}`,t?{headers:{Cookie:T(t)}}:void 0)},yt=async e=>y(await x(h(e),async r=>await k(r,["NotFoundError","NotLoggedInError","NotMemberError"])??r),r=>r.json()),ht=(()=>{let e=async(r,t)=>{let{fetch:o}=g(t??{}),n=gt(r,t),s=await o(n);return l(s)?s:yt(d(s))};return e.toRequest=gt,e.fromResponse=yt,e})();var Tt=async(e,r)=>{let{sid:t,hostName:o,fetch:n}=g(r??{}),s=await G(r);if(l(s))return s;let a=new Request(`https://${o}/api/embed-text/url?url=${encodeURIComponent(`${e}`)}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":d(s),...t?{Cookie:T(t)}:{}},body:JSON.stringify({timeout:3e3})}),p=await n(a);return l(p)?p:y(await x(h(d(p)),async i=>await k(i,["SessionError","BadRequestError","InvalidURLError"])??i),async i=>{let{title:f}=await i.json();return f})};var xt=async(e,r)=>{let{sid:t,hostName:o,fetch:n}=g(r??{}),s=await G(r);if(l(s))return s;let a=new Request(`https://${o}/api/embed-text/twitter?url=${encodeURIComponent(`${e}`)}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":d(s),...t?{Cookie:T(t)}:{}},body:JSON.stringify({timeout:3e3})}),p=await n(a);return l(p)?p:x(await y(h(d(p)),i=>i.json()),async i=>i.response.status===422?{name:"InvalidURLError",message:(await i.response.json()).message}:await k(i,["SessionError","BadRequestError"])??i)};var _t=async e=>{let{fetch:r,sid:t,hostName:o,gyazoTeamsName:n}=g(e??{}),s=new Request(`https://${o}/api/login/gyazo/oauth-upload/token${n?`?gyazoTeamsName=${n}`:""}`,t?{headers:{Cookie:T(t)}}:void 0),a=await r(s);return l(a)?a:y(await x(h(d(a)),async p=>await k(p,["NotLoggedInError"])??p),p=>p.json().then(i=>i.token))};var Nt=e=>{let r=typeof e=="string"?new TextEncoder().encode(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),t=[1732584193,4023233417,2562383102,271733878],o=new Uint8Array(He),n=0,s=0,a=0;[t,o,n,s,a]=Ot(t,o,n,s,a,r);let p=He-n;p<9&&(p+=He);let i=new Uint8Array(p);i[0]=128,[s,a]=[s<<3,a<<3|s>>>29],i[i.length-8]=s&255,i[i.length-7]=s>>>8&255,i[i.length-6]=s>>>16&255,i[i.length-5]=s>>>24&255,i[i.length-4]=a&255,i[i.length-3]=a>>>8&255,i[i.length-2]=a>>>16&255,i[i.length-1]=a>>>24&255,[t,o,n,s,a]=Ot(t,o,n,s,a,new Uint8Array(i.buffer));let f=new ArrayBuffer(16),m=new DataView(f);return m.setUint32(0,t[0],!0),m.setUint32(4,t[1],!0),m.setUint32(8,t[2],!0),m.setUint32(12,t[3],!0),f},He=64,c=(e,r)=>e<<r|e>>>32-r,U=(e,r)=>e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24,wt=(e,r)=>{let[t,o,n,s]=e,a=U(r,0),p=U(r,4),i=U(r,8),f=U(r,12),m=U(r,16),u=U(r,20),F=U(r,24),C=U(r,28),D=U(r,32),te=U(r,36),re=U(r,40),oe=U(r,44),ne=U(r,48),se=U(r,52),ae=U(r,56),ie=U(r,60);return t=o+c(((n^s)&o^s)+t+a+3614090360,7),s=t+c(((o^n)&t^n)+s+p+3905402710,12),n=s+c(((t^o)&s^o)+n+i+606105819,17),o=n+c(((s^t)&n^t)+o+f+3250441966,22),t=o+c(((n^s)&o^s)+t+m+4118548399,7),s=t+c(((o^n)&t^n)+s+u+1200080426,12),n=s+c(((t^o)&s^o)+n+F+2821735955,17),o=n+c(((s^t)&n^t)+o+C+4249261313,22),t=o+c(((n^s)&o^s)+t+D+1770035416,7),s=t+c(((o^n)&t^n)+s+te+2336552879,12),n=s+c(((t^o)&s^o)+n+re+4294925233,17),o=n+c(((s^t)&n^t)+o+oe+2304563134,22),t=o+c(((n^s)&o^s)+t+ne+1804603682,7),s=t+c(((o^n)&t^n)+s+se+4254626195,12),n=s+c(((t^o)&s^o)+n+ae+2792965006,17),o=n+c(((s^t)&n^t)+o+ie+1236535329,22),t=o+c(((o^n)&s^n)+t+p+4129170786,5),s=t+c(((t^o)&n^o)+s+F+3225465664,9),n=s+c(((s^t)&o^t)+n+oe+643717713,14),o=n+c(((n^s)&t^s)+o+a+3921069994,20),t=o+c(((o^n)&s^n)+t+u+3593408605,5),s=t+c(((t^o)&n^o)+s+re+38016083,9),n=s+c(((s^t)&o^t)+n+ie+3634488961,14),o=n+c(((n^s)&t^s)+o+m+3889429448,20),t=o+c(((o^n)&s^n)+t+te+568446438,5),s=t+c(((t^o)&n^o)+s+ae+3275163606,9),n=s+c(((s^t)&o^t)+n+f+4107603335,14),o=n+c(((n^s)&t^s)+o+D+1163531501,20),t=o+c(((o^n)&s^n)+t+se+2850285829,5),s=t+c(((t^o)&n^o)+s+i+4243563512,9),n=s+c(((s^t)&o^t)+n+C+1735328473,14),o=n+c(((n^s)&t^s)+o+ne+2368359562,20),t=o+c((o^n^s)+t+u+4294588738,4),s=t+c((t^o^n)+s+D+2272392833,11),n=s+c((s^t^o)+n+oe+1839030562,16),o=n+c((n^s^t)+o+ae+4259657740,23),t=o+c((o^n^s)+t+p+2763975236,4),s=t+c((t^o^n)+s+m+1272893353,11),n=s+c((s^t^o)+n+C+4139469664,16),o=n+c((n^s^t)+o+re+3200236656,23),t=o+c((o^n^s)+t+se+681279174,4),s=t+c((t^o^n)+s+a+3936430074,11),n=s+c((s^t^o)+n+f+3572445317,16),o=n+c((n^s^t)+o+F+76029189,23),t=o+c((o^n^s)+t+te+3654602809,4),s=t+c((t^o^n)+s+ne+3873151461,11),n=s+c((s^t^o)+n+ie+530742520,16),o=n+c((n^s^t)+o+i+3299628645,23),t=o+c((n^(o|~s))+t+a+4096336452,6),s=t+c((o^(t|~n))+s+C+1126891415,10),n=s+c((t^(s|~o))+n+ae+2878612391,15),o=n+c((s^(n|~t))+o+u+4237533241,21),t=o+c((n^(o|~s))+t+ne+1700485571,6),s=t+c((o^(t|~n))+s+f+2399980690,10),n=s+c((t^(s|~o))+n+re+4293915773,15),o=n+c((s^(n|~t))+o+p+2240044497,21),t=o+c((n^(o|~s))+t+D+1873313359,6),s=t+c((o^(t|~n))+s+ie+4264355552,10),n=s+c((t^(s|~o))+n+F+2734768916,15),o=n+c((s^(n|~t))+o+se+1309151649,21),t=o+c((n^(o|~s))+t+m+4149444226,6),s=t+c((o^(t|~n))+s+oe+3174756917,10),n=s+c((t^(s|~o))+n+i+718787259,15),o=n+c((s^(n|~t))+o+te+3951481745,21),[e[0]+t>>>0,e[1]+o>>>0,e[2]+n>>>0,e[3]+s>>>0]},Ot=(e,r,t,o,n,s)=>{let a=64-t;if(s.length<a)r.set(s,t),t+=s.length;else{r.set(s.slice(0,a),t),e=wt(e,r);let p=a;for(;p+64<=s.length;)e=wt(e,s.slice(p,p+64)),p+=64;r.fill(0).set(s.slice(p),0),t=s.length-p}return[o,n]=Pr(o,n,s.length),[e,r,t,o,n]},Pr=(e,r,t)=>(e+=t,e>4294967295&&(r+=1),[e>>>0,r]);var Ir=new TextEncoder;function Sr(e){let r=typeof e;return r!=="object"?r:e===null?"null":e?.constructor?.name??"object"}function bt(e){if(typeof e=="string")return Ir.encode(e);if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new TypeError(`Cannot validate the input as it must be a Uint8Array, a string, or an ArrayBuffer: received a value of the type ${Sr(e)}`)}var Lt=new TextEncoder().encode("0123456789abcdef"),YR=new TextEncoder,Cr=new TextDecoder;function kt(e){let r=bt(e),t=new Uint8Array(r.length*2);for(let o=0;o<r.length;o++){let n=r[o];t[o*2]=Lt[n>>4],t[o*2+1]=Lt[n&15]}return Cr.decode(t)}var Ut=async(e,r,t)=>{let o=`${kt(Nt(await e.arrayBuffer()))}`,n=await vr(e,r,o,t);if(l(n))return n;let s=d(n);if("embedUrl"in s)return R(s);let a=await Br(s.signedUrl,e,t);return l(a)?a:Hr(r,s.fileId,o,t)},vr=async(e,r,t,o)=>{let{sid:n,hostName:s,fetch:a,csrf:p}=g(o??{}),i={md5:t,size:e.size,contentType:e.type,name:e.name},f=await ge(Oe(p),()=>G(o));if(l(f))return f;let m=new Request(`https://${s}/api/gcs/${r}/upload-request`,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":d(f),...n?{Cookie:T(n)}:{}}}),u=await a(m);return l(u)?u:y(await x(h(d(u)),async F=>F.response.status===402?{name:"FileCapacityError",message:(await F.response.json()).message}:F),F=>F.json())},Br=async(e,r,t)=>{let{sid:o,fetch:n}=g(t??{}),s=await n(e,{method:"PUT",body:r,headers:{"Content-Type":r.type,...o?{Cookie:T(o)}:{}}});return l(s)?s:Z(await x(h(d(s)),async a=>a.response.headers.get("Content-Type")?.includes?.("/xml")?{name:"GCSError",message:await a.response.text()}:a),()=>{})},Hr=async(e,r,t,o)=>{let{sid:n,hostName:s,fetch:a,csrf:p}=g(o??{}),i=await ge(Oe(p),()=>G(o));if(l(i))return i;let f=new Request(`https://${s}/api/gcs/${e}/verify`,{method:"POST",body:JSON.stringify({md5:t,fileId:r}),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":d(i),...n?{Cookie:T(n)}:{}}}),m=await a(f);return l(m)?m:y(await x(h(d(m)),async u=>u.response.status===404?{name:"NotFoundError",message:(await u.response.json()).message}:u),u=>u.json())};var Ft=(e,r)=>{let t=new FormData;return t.append("data",e),t.append("metadata",JSON.stringify({app:"Gyazo",title:e.name})),GM_fetch(`https://gif.gyazo.com/${r?.teams?"teams":"gif"}/upload`,{method:"POST",body:t,credentials:"include",headers:{Origin:"https://gyazo.com","sec-fetch-site":"same-site"},referrer:"https://gyazo.com/"})};var Ne="",Mt=!1,be=new Map,At=async(e,r,t,o)=>{let n=be.get(e.href);if(n)return n;if(e.hostname==="video.twimg.com"||`${e}`.endsWith(".svg")){let i=await GM_fetch(e);if(!i.ok)return;let f=i.headers.get("content-type")?.split?.(";")?.[0]??`${e}`.endsWith(".mp4")?"video/mp4":"video/webm",m=new File([await i.blob()],o||`${r}`,{type:f});if(f==="video/mp4"){let C=await Ft(m);if(C.ok){let D=new URL(await C.text());return be.set(e.href,D),D}}let u=await Ut(m,t);if(E(u))throw Error(v(u).name);let F=new URL(P(u).embedUrl);return be.set(e.href,F),F}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(Mt){if(!Ne)return}else{let i=await _t();if(Mt=!0,E(i)){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(Ne=P(i)||"",!Ne){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let a=await st(await s.blob(),{accessToken:Ne,refererURL:r,description:o});if(E(a))throw Error(v(a).name);let p=new URL(P(a).permalink_url);return be.set(e.href,p),p};var St=[["&","&"],["<","<"],[">",">"],['"',"""],["'","'"]],Gr=Object.fromEntries([...St.map(([e,r])=>[r,e]),["'","'"],[" "," "]]),jr=new Map(St),Fg=new RegExp(`[${[...jr.keys()].join("")}]`,"g");var $r={entityList:Gr},Dr=1114111,Vr=/&#([0-9]+);/g,Wr=/&#x(\p{AHex}+);/gu,Pt=new WeakMap;function Ge(e,r={}){let{entityList:t}={...$r,...r},o=Pt.get(t);return o||(o=new RegExp(`(${Object.keys(t).sort((n,s)=>s.length-n.length).join("|")})`,"g"),Pt.set(t,o)),e.replaceAll(o,n=>t[n]).replaceAll(Vr,(n,s)=>It(s,10)).replaceAll(Wr,(n,s)=>It(s,16))}function It(e,r){let t=parseInt(e,r);return t>Dr?"�":String.fromCodePoint(t)}var Le=e=>{let r={name:e.user.name,screenName:e.user.screen_name},t=new Date(e.created_at),o=[...e.entities.hashtags.map(a=>({type:"hashtag",...a})),...e.entities.symbols.map(a=>({type:"symbol",...a})),...e.entities.user_mentions.map(a=>({type:"mention",name:a.name,screenName:a.screen_name,indices:a.indices})),...e.entities.urls.map(a=>{let p={type:"url",indices:a.indices,url:new URL(a.expanded_url)};if(e.card&&e.card?.url===a.url){let{description:i,title:f}=e.card.binding_values,m="STRING";i?.type===m&&(p.description=i.string_value),f?.type===m&&(p.title=f.string_value)}return p}),...e.entities.media?.map?.(a=>({type:"media",indices:a.indices,media:e.mediaDetails?.flatMap?.(p=>p.url===a.url?[{type:p.type,url:new URL(p.video_info?.variants?.sort?.((i,f)=>(f.bitrate??0)-(i.bitrate??0))?.[0].url??p.media_url_https)}]:[])??[]}))??[]].sort((a,p)=>a.indices[0]-p.indices[0]),n=[];{let a=0,p=e.text;for(let{indices:i,...f}of o){let m=[...p].slice(0,i[0]-a).join("");n.push({type:"plain",text:Ge(m)}),n.push(f),p=[...p].slice(i[1]-a).join(""),a=i[1]}p&&n.push({type:"plain",text:Ge(p)})}let s={id:e.id_str,content:n,author:r,posted:t,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=Le(e.parent)),e.quoted_tweet&&(s.quote=Le(e.quoted_tweet)),s};var qr=["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"],ke=(e=scrapbox.Project.name,r=location.host)=>t=>{if(t.host!==r)return t;let[,o,n]=t.pathname.match(/^\/([\w\d][\w\d-]{0,22}[\w\d])(?:\/?|\/(.+))$/)??[];return!o||qr.includes(o)?t:n?o===e?`[${decodeURIComponent(n)}]`:`[/${o}/${decodeURIComponent(n)}]`:`[/${o}]`};var Ct=(e=Kr)=>r=>{let[,t]=r.href.match(/^https:\/\/(?:(?:www\.|mobile\.|m\.)?twitter|x)\.com\/[\w\d_]+\/(?:status|statuses)\/(\d+)/)??[];return t?(async()=>{let o=await(ot(t)??xt(r.href));if(E(o))throw v(o);let n=P(o);return e("images"in n?{...n,id:t}:n,r)})():r},Kr=async e=>{if("images"in e)return ee(e);let{quote:r,replyTo:t,...o}=Le(e);return[...t?[...(await ee(t)).split(`
`).map(n=>` > ${n}`),...t.quote?(await ee(t.quote)).split(`
`).map(n=>` > ${n}`):[]]:[],...(await ee(o)).split(`
`).map(n=>`> ${n}`),...r?(await ee(r)).split(`
`).map(n=>`> > ${n}`):[]].join(`
`)},ee=async e=>{let r=new URL(`https://twitter.com/${"author"in e?e.author.screenName:e.screenName}/status/${e.id}`);if("images"in e)return[`> [@${$e(e.screenName)} ${r.origin}${r.pathname}]`,...e.description?.split?.(`
`)?.map?.(n=>`> ${$e(n)}`)??["> [/ no description provided]"],...e.images.length>0?[`> ${e.images.map(n=>`[${n}]`)}`]:[]].join(`
`);let t=e.content,o=e.author.screenName;return[`[@${$e(o)} ${r}]`,...(await Promise.all(t.map(async n=>{switch(n.type){case"plain":return n.text;case"hashtag":return` #${n.text} `;case"symbol":return` #$${n.text} `;case"mention":return`[@${n.screenName} https://twitter.com/${n.screenName}]`;case"media":{let s=[],a=1;for(;a<n.media.length;a+=2)s.push(`[${await je(n.media[a-1],r)}] [${await je(n.media[a],r)}]`);return a===n.media.length&&s.push(`[${await je(n.media[a-1],r)}]`),`
${s.join(`
`)}
`}case"url":return`${ke()(n.url)} `}}))).join("").split(`
`)].join(`
`)},Ue="",zr=async()=>{if(Ue)return Ue;let e=await ht(scrapbox.Project.name);if(E(e))throw new Error(v(e).name);return Ue=P(e).id,Ue},je=async(e,r)=>await At(e.url,r,await zr(),"")??e.url,$e=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]`]\s*/g," ").trim();var vt=e=>window.GM_fetch?.(`https://t.co/${e}`)?.then?.(r=>W(K(r),async t=>{let o=new DOMParser().parseFromString(await t.text(),"text/html");try{return new URL(o.title)}catch(n){if(n instanceof TypeError)return;throw n}}));var Bt=e=>{let r=window.GM_fetch;if(["bit.ly","amzn.to","amzn.asia","goo.gl","s.nikkei.com","apple.co","nico.ms","w.wiki"].includes(e.hostname)&&r)return r(e).then(o=>o.ok?new URL(o.url):e);if(e.hostname!=="t.co")return e;let t=vt(e.pathname.slice(1));return t?t.then(o=>Ie(o,()=>e,n=>n??e)):e};var Ht=e=>{if(!e.pathname.startsWith("/wiki/"))return e;if(!/^\w+\.wikipedia\.org$/.test(e.hostname)){let[,n]=e.hostname.match(/^(\w+)\.m\.wikipedia\.org$/)??[];if(!n)return e;e.hostname=`${n}.wikipedia.org`}let r=decodeURIComponent(e.pathname.slice(6)),t=e.hash?decodeURIComponent(e.hash.slice(1)):"",o=`${e.origin}/wiki/${r}`;return t?`[${t} | ${r} - Wikipedia ${o}#${t}]`:`[${r} - Wikipedia ${o}]`};var Gt=e=>{if(e.hostname!=="www.wikiwand.com")return e;let[,r,t]=e.pathname.match(/^\/([^\/]+)\/([^\/]+)/)??[];return!r||!t||(e.hostname=`${r}.wikipedia.org`,e.pathname=`/wiki/${t}`,e.hash=e.hash.startsWith("#/")?`#${e.hash.slice(2)}`:e.hash),e};var De=e=>{if(!e.hostname.startsWith("www.google."))return e;let r=e.searchParams.get("url");return r?new URL(decodeURIComponent(r)):e};var jt=/charset=([^;]+)/,$t=e=>window.GM_fetch?.(`${e}`)?.then?.(r=>W(K(r),async t=>{let o=t.headers.get("content-type")?.match?.(jt)?.[1]??await Yr(t.clone());return new TextDecoder(o).decode(await t.arrayBuffer())})),Yr=async e=>{let r=new DOMParser().parseFromString(await e.text(),"text/html");return r.querySelector("meta[charset]")?.getAttribute?.("charset")??r.querySelector('meta[http-equiv="content-type"]')?.getAttribute?.("content")?.match?.(jt)?.[1]??"utf-8"};var Dt=(e=Xr)=>async r=>e(await Jr(r),r),Xr=(e,r)=>{let t=(M(e)?e:e.title).replace(/\s/g," ").replaceAll("[","[").replaceAll("]","]");return t?`[${r.hash?`${decodeURIComponent(r.hash.slice(1))} | `:""}${t} ${r}]`:`${r}`},Jr=async e=>{let r=$t(e);if(!r){let o=await Tt(e);if(E(o))throw v(o);return P(o)}let t=await r;if(E(t))throw v(t);return new DOMParser().parseFromString(P(t),"text/html")};var Vt=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[,r]=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 r&&(e.hash="",e.search="",e.pathname=`/dp/${r}`),e};var Wt=e=>{if(!/(?:[0-9a-z-]\.)?gyazo\.com/.test(e.hostname))return e;let[,r]=e.pathname.match(/^\/([0-9a-f]{32})(?:\/raw)?$/)??[];return r?`[https://gyazo.com/${r}]`:e};var qt=(e,...r)=>{if(e instanceof URL)return Ae(new URL(e),...r);let t=0,o=0,n=0,s=!1,a=e.split(/(https?:\/\/\S+)/g).map(m=>{if(!/^https?:\/\/\S+$/.test(m))return m;t++;try{let u=Ae(new URL(m),...r);return M(u)?(o++,u):(s=!0,[u,m])}catch(u){return console.error(u),n++,m}});if(!s)return a.join("");let{render:p,dispose:i}=ze(),f=()=>p({type:"spinner"},{type:"text",text:`URL: ${o}/${t} converted, ${n} failed`});return f(),Promise.all(a.map(async m=>{if(M(m))return m;try{let u=await m[0];return o++,u}catch(u){return console.error(u),n++,m[1]}finally{f()}})).then(m=>(p({type:"check-circle"},{type:"text",text:`URL: ${o}/${t} converted, ${n} failed`}),m.join(""))).finally(()=>{setTimeout(i,1e3)})};var Qr=[De,Bt,De,Gt,Vt,ke(),Wt,Ct(),Ht,Dt()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let r=qt(e,...Qr);if(typeof r=="string")return e===r?void 0:r;r.then(t=>{if(e!==t)return Ke(t)})}});