generated at
scrapbox-url-customizer

2023/11/16
いい加減ツイートの画像をなんとかしたいので使う
scrapbox-embed-tweetから乗り換える
エラーが出るが多分tokenのやつだろう
token付けた
js
let e=await o(`https://cdn.syndication.twimg.com/tweet-result?id=${t}&token=x`)
それでもうまくいかないな
9月くらいにtakkerがbundleしてくれたやつを使おう
関係なかった
url-info-proxyを入れてないからだ
関係なかった(あるけど)
いらないらしい
>GM fetchが必要ですtakker
動いた!
返信ツイートを取得すると返信元のツイートを取得してしまう
連ツイを転記する際に不便かも
ChatGPTに教えてもらって消した
引用も消すの忘れてた
HTMLエンティティがデコードされてないので処理を追加した
js
function decodeHtmlEntities(encodedString) { var textArea = document.createElement('textarea'); textArea.innerHTML = encodedString; return textArea.textContent; }
js
return[...D(n).map(s=>`> ${decodeHtmlEntities(s)}`),]
v0.2.3で対応されているらしいのでそっちをバンドルした
結局v0.2.4にしたはず(うろ覚え)

script.js
var Qe=e=>typeof e=="object"&&e!==null,Ze=e=>Qe(e)?(e.name===void 0||typeof e.name=="string")&&typeof e.message=="string":!1,te=e=>{try{let o=typeof e=="string"?JSON.parse(e):e;return Ze(o)?o:!1}catch(o){if(o instanceof SyntaxError)return!1;throw o}};var re=!1;scrapbox.addListener("lines:changed",()=>re=!1);scrapbox.addListener("layout:changed",()=>re=!1);var oe=(e,o)=>{if(!(e instanceof HTMLDivElement))throw new TypeError(`"${o}" must be HTMLDivElememt but actual is "${e}"`)};var ne=(e,o)=>{if(!(e instanceof HTMLTextAreaElement))throw new TypeError(`"${o}" must be HTMLTextAreaElement but actual is "${e}"`)};var T=()=>{let e=document.getElementById("text-input");if(e)return ne(e,"textarea#text-input"),e};var se=()=>et(document.getElementsByClassName("status-bar")?.[0],"div.status-bar"),et=(e,o)=>{if(e)return oe(e,o),e};var W=e=>new Promise(o=>setTimeout(()=>o(),e));var ae=async e=>{let o=T();if(!o)throw Error("#text-input is not ditected.");o.focus(),o.value=e;let t=new InputEvent("input",{bubbles:!0});o.dispatchEvent(t),await W(1)};var ce=()=>{let e=se();if(!e)throw new Error("div.status-bar can't be found");let o=document.createElement("div");return e.append(o),{render:(...t)=>{o.textContent="";let r=pe(...t);r&&o.append(r)},dispose:()=>o.remove()}},pe=(...e)=>{let o=e.flatMap(r=>{switch(r.type){case"spinner":return[at()];case"check-circle":return[ct()];case"exclamation-triangle":return[pt()];case"text":return[F(r.text)];case"group":{let n=pe(...r.items);return n?[n]:[]}}});if(o.length===0)return;if(o.length===1)return o[0];let t=document.createElement("span");return t.classList.add("item-group"),t.append(...o),t},F=e=>{let o=document.createElement("span");return o.classList.add("item"),o.append(e),o},at=()=>{let e=document.createElement("i");return e.classList.add("fa","fa-spinner"),F(e)},ct=()=>{let e=document.createElement("i");return e.classList.add("kamon","kamon-check-circle"),F(e)},pt=()=>{let e=document.createElement("i");return e.classList.add("fas","fa-exclamation-triangle"),F(e)};var y=e=>[...e].map((o,t)=>o===" "?"_":!ut.includes(o)||t===e.length-1&&dt.includes(o)?encodeURIComponent(o):o).join(""),ut='@$&+=:;",',dt=':;",';var ue=e=>{if(e===0)return;let o={};return e&1&&(o.capture=!0),e&2&&(o.once=!0),e&4&&(o.passive=!0),o};var lt=new Map;scrapbox.on("layout:changed",()=>{let e=T();if(e)for(let[o,t]of lt)for(let[r,n]of t)for(let s of n)e.addEventListener(o,r,ue(s))});var x=e=>typeof e=="string";var V=(e,...o)=>{let t=e;for(let r of o){let n=t instanceof Promise?t.then(s=>x(s)?s:r(s)):r(t);if(x(n))return n;t=n instanceof URL?new URL(n):n.then(s=>x(s)?s:new URL(s))}return t instanceof Promise?t.then(r=>`${r}`):`${e}`};var R=e=>e.ok?void 0:{name:"HTTPError",message:`${e.status} ${e.statusText}`,response:e};var de=e=>{if(!window.GM_fetch)return;let o=window.GM_fetch;return(async()=>{let t=await o(`https://cdn.syndication.twimg.com/tweet-result?id=${e}&token=x`),r=R(t);return r?{ok:!1,value:r}:{ok:!0,value:await t.json()}})()};var H=e=>{let{fetch:o=globalThis.fetch,...t}=e;return{fetch:o,...t}},me=e=>typeof e=="object"&&e!==null;var v=class e extends Error{name="UnexpectedResponseError";status;statusText;body;path;constructor(o){super(`${o.status} ${o.statusText} when fetching ${o.path.toString()}`),this.status=o.status,this.statusText=o.statusText,this.body=o.body,this.path=o.path,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};var j=async e=>{let o=await e.text();if(e.ok)return{ok:!0,value:o};if(e.status===400)return{ok:!1,value:{name:"BadRequestError",message:o}};try{let t=JSON.parse(o);if(!me(t)||typeof t.message!="string")throw new v({status:e.status,statusText:e.statusText,body:o,path:new URL(e.url)});switch(e.status){case 401:return{ok:!1,value:{name:"UnauthorizedError",message:t.message}};case 403:return{ok:!1,value:{name:"NotPrivilegeError",message:t.message}};case 404:return{ok:!1,value:{name:"NotFoundError",message:t.message}};case 422:return{ok:!1,value:{name:"InvalidParameterError",message:t.message}};case 429:return{ok:!1,value:{name:"RateLimitError",message:t.message}};default:throw new v({status:e.status,statusText:e.statusText,body:o,path:new URL(e.url)})}}catch(t){throw t instanceof SyntaxError?new v({status:e.status,statusText:e.statusText,body:o,path:new URL(e.url)}):t}};var le=async(e,o)=>{let{title:t,description:r,metadataIsPublic:n,collectionId:s,refererURL:a,accessToken:i,created:c,app:l,fetch:p}=H(o),u=new FormData;u.append("imagedata",e),u.append("access_token",i),a&&u.append("referer_url",a.toString()),l!==void 0&&u.append("app",l),t!==void 0&&u.append("title",t),r!=null&&u.append("desc",r),s&&u.append("collection_id",s),n&&u.append("metadata_is_public","true"),c!==void 0&&u.append("created_at",`${c}`);let h=await p("https://upload.gyazo.com/api/upload",{method:"POST",mode:"cors",credentials:"omit",body:u}),g=await j(h);return g.ok?{ok:!0,value:JSON.parse(g.value)}:g};var d=e=>{let{fetch:o=globalThis.fetch,hostName:t="scrapbox.io",...r}=e;return{fetch:o,hostName:t,...r}};var E=class e extends Error{constructor(t){super(`${t.status} ${t.statusText} when fetching ${t.url}`);this.response=t;Error.captureStackTrace&&Error.captureStackTrace(this,e)}name="UnexpectedResponseError"},f=async e=>{let o=e.clone(),t=await o.text(),r=te(t);if(!r)throw new E(o);return{ok:!1,value:r}};var fe=async e=>{let{sid:o,hostName:t,fetch:r}=d(e??{}),n=new Request(`https://${t}/api/users/me`,o?{headers:{Cookie:m(o)}}:void 0),s=await r(n);if(!s.ok)throw new E(s);return await s.json()};var m=e=>`connect.sid=${e}`,w=async e=>globalThis._csrf?globalThis._csrf:(await fe(e)).csrfToken;var ge=(e,o,t)=>{let{sid:r,hostName:n,followRename:s,projects:a}=d(t??{}),i=new URLSearchParams;i.append("followRename",`${s??!0}`);for(let l of a??[])i.append("projects",l);let c=`https://${n}/api/pages/${e}/${y(o)}?${i.toString()}`;return new Request(c,r?{headers:{Cookie:m(r)}}:void 0)},he=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."}}:f(e),X=async(e,o,t)=>{let{fetch:r}=d(t??{}),n=ge(e,o,t),s=await r(n);return await he(s)};X.toRequest=ge;X.fromResponse=he;var xe=(e,o)=>{let{sid:t,hostName:r,sort:n,limit:s,skip:a}=d(o??{}),i=new URLSearchParams;n!==void 0&&i.append("sort",n),s!==void 0&&i.append("limit",`${s}`),a!==void 0&&i.append("skip",`${a}`);let c=`https://${r}/api/pages/${e}?${i.toString()}`;return new Request(c,t?{headers:{Cookie:m(t)}}:void 0)},Ee=async e=>e.ok?{ok:!0,value:await e.json()}:f(e),we=async(e,o)=>{let{fetch:t}=d(o??{}),r=await t(xe(e,o));return await Ee(r)};we.toRequest=xe;we.fromResponse=Ee;var ye=(e,o,t,r)=>{let{sid:n,hostName:s}=d(r??{}),a=`https://${s}/api/table/${e}/${y(o)}/${encodeURIComponent(t)}.csv`;return new Request(a,n?{headers:{Cookie:m(n)}}:void 0)},be=async e=>e.ok?{ok:!0,value:await e.text()}:e.status===404?{ok:!1,value:{name:"NotFoundError",message:"Table not found."}}:f(e),Le=async(e,o,t,r)=>{let{fetch:n}=d(r??{}),s=ye(e,o,t,r),a=await n(s);return await be(a)};Le.toRequest=ye;Le.fromResponse=be;var Te=(e,o)=>{let{sid:t,hostName:r}=d(o??{});return new Request(`https://${r}/api/projects/${e}`,t?{headers:{Cookie:m(t)}}:void 0)},ke=async e=>e.ok?{ok:!0,value:await e.json()}:f(e),A=async(e,o)=>{let{fetch:t}=d(o??{}),r=Te(e,o),n=await t(r);return ke(n)};A.toRequest=Te;A.fromResponse=ke;var Re=(e,o)=>{let{sid:t,hostName:r}=d(o??{}),n=new URLSearchParams;for(let s of e)n.append("ids",s);return new Request(`https://${r}/api/projects?${n.toString()}`,t?{headers:{Cookie:m(t)}}:void 0)},ve=async e=>e.ok?{ok:!0,value:await e.json()}:f(e),Pe=async(e,o)=>{let{fetch:t}=d(o??{}),r=await t(Re(e,o));return ve(r)};Pe.toRequest=Re;Pe.fromResponse=ve;var Me=async(e,o)=>{let{sid:t,hostName:r,fetch:n,csrf:s}=d(o??{}),a=new Request(`https://${r}/api/embed-text/url?url=${encodeURIComponent(e.toString())}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":s??await w(o),...t?{Cookie:m(t)}:{}},body:JSON.stringify({timeout:3e3})}),i=await n(a);if(!i.ok)return i.status===422?{ok:!1,value:{name:"InvalidURLError",message:(await i.json()).message}}:f(i);let{title:c}=await i.json();return{ok:!0,value:c}};var Ne=async(e,o)=>{let{sid:t,hostName:r,fetch:n,csrf:s}=d(o??{}),a=new Request(`https://${r}/api/embed-text/twitter?url=${encodeURIComponent(e.toString())}`,{method:"POST",headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":s??await w(o),...t?{Cookie:m(t)}:{}},body:JSON.stringify({timeout:3e3})}),i=await n(a);return i.ok?{ok:!0,value:await i.json()}:i.status===422?{ok:!1,value:{name:"InvalidURLError",message:(await i.json()).message}}:f(i)};var Ie=async e=>{let{sid:o,hostName:t,gyazoTeamsName:r}=d(e??{}),n=new Request(`https://${t}/api/login/gyazo/oauth-upload/token${r?`?gyazoTeamsName=${r}`:""}`,o?{headers:{Cookie:m(o)}}:void 0),s=await fetch(n);if(!s.ok)return f(s);let{token:a}=await s.json();return{ok:!0,value:a}};var Ce=(e,o,t,r)=>{let{sid:n,hostName:s}=d(r??{}),a=`https://${s}/api/code/${e}/${y(o)}/${y(t)}`;return new Request(a,n?{headers:{Cookie:m(n)}}:void 0)},_e=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"}}:f(e),Ue=async(e,o,t,r)=>{let{fetch:n}=d(r??{}),s=Ce(e,o,t,r),a=await n(s);return await _e(a)};Ue.toRequest=Ce;Ue.fromResponse=_e;var Se=new TextEncoder().encode("0123456789abcdef");function Oe(e){let o=new Uint8Array(e.length*2);for(let t=0;t<o.length;t++){let r=e[t];o[t*2]=Se[r>>4],o[t*2+1]=Se[r&15]}return o}var $e="md5: `data` is invalid type",k=64,P=class{#e;#t;#r;#o;#n;#i;#s;#a;constructor(){this.#e=1732584193,this.#t=4023233417,this.#r=2562383102,this.#o=271733878,this.#n=new Uint8Array(k),this.#i=0,this.#s=0,this.#a=0}#p(o){let t=this.#s;t+=o,t>4294967295&&(this.#a+=1),this.#s=t>>>0}#c(o){let t=this.#e,r=this.#t,n=this.#r,s=this.#o,a=L=>o[L]|o[L+1]<<8|o[L+2]<<16|o[L+3]<<24,i=(L,ee)=>L<<ee|L>>>32-ee,c=a(0),l=a(4),p=a(8),u=a(12),h=a(16),g=a(20),b=a(24),N=a(28),I=a(32),C=a(36),_=a(40),U=a(44),S=a(48),O=a(52),$=a(56),B=a(60);t=r+i(((n^s)&r^s)+t+c+3614090360,7),s=t+i(((r^n)&t^n)+s+l+3905402710,12),n=s+i(((t^r)&s^r)+n+p+606105819,17),r=n+i(((s^t)&n^t)+r+u+3250441966,22),t=r+i(((n^s)&r^s)+t+h+4118548399,7),s=t+i(((r^n)&t^n)+s+g+1200080426,12),n=s+i(((t^r)&s^r)+n+b+2821735955,17),r=n+i(((s^t)&n^t)+r+N+4249261313,22),t=r+i(((n^s)&r^s)+t+I+1770035416,7),s=t+i(((r^n)&t^n)+s+C+2336552879,12),n=s+i(((t^r)&s^r)+n+_+4294925233,17),r=n+i(((s^t)&n^t)+r+U+2304563134,22),t=r+i(((n^s)&r^s)+t+S+1804603682,7),s=t+i(((r^n)&t^n)+s+O+4254626195,12),n=s+i(((t^r)&s^r)+n+$+2792965006,17),r=n+i(((s^t)&n^t)+r+B+1236535329,22),t=r+i(((r^n)&s^n)+t+l+4129170786,5),s=t+i(((t^r)&n^r)+s+b+3225465664,9),n=s+i(((s^t)&r^t)+n+U+643717713,14),r=n+i(((n^s)&t^s)+r+c+3921069994,20),t=r+i(((r^n)&s^n)+t+g+3593408605,5),s=t+i(((t^r)&n^r)+s+_+38016083,9),n=s+i(((s^t)&r^t)+n+B+3634488961,14),r=n+i(((n^s)&t^s)+r+h+3889429448,20),t=r+i(((r^n)&s^n)+t+C+568446438,5),s=t+i(((t^r)&n^r)+s+$+3275163606,9),n=s+i(((s^t)&r^t)+n+u+4107603335,14),r=n+i(((n^s)&t^s)+r+I+1163531501,20),t=r+i(((r^n)&s^n)+t+O+2850285829,5),s=t+i(((t^r)&n^r)+s+p+4243563512,9),n=s+i(((s^t)&r^t)+n+N+1735328473,14),r=n+i(((n^s)&t^s)+r+S+2368359562,20),t=r+i((r^n^s)+t+g+4294588738,4),s=t+i((t^r^n)+s+I+2272392833,11),n=s+i((s^t^r)+n+U+1839030562,16),r=n+i((n^s^t)+r+$+4259657740,23),t=r+i((r^n^s)+t+l+2763975236,4),s=t+i((t^r^n)+s+h+1272893353,11),n=s+i((s^t^r)+n+N+4139469664,16),r=n+i((n^s^t)+r+_+3200236656,23),t=r+i((r^n^s)+t+O+681279174,4),s=t+i((t^r^n)+s+c+3936430074,11),n=s+i((s^t^r)+n+u+3572445317,16),r=n+i((n^s^t)+r+b+76029189,23),t=r+i((r^n^s)+t+C+3654602809,4),s=t+i((t^r^n)+s+S+3873151461,11),n=s+i((s^t^r)+n+B+530742520,16),r=n+i((n^s^t)+r+p+3299628645,23),t=r+i((n^(r|~s))+t+c+4096336452,6),s=t+i((r^(t|~n))+s+N+1126891415,10),n=s+i((t^(s|~r))+n+$+2878612391,15),r=n+i((s^(n|~t))+r+g+4237533241,21),t=r+i((n^(r|~s))+t+S+1700485571,6),s=t+i((r^(t|~n))+s+u+2399980690,10),n=s+i((t^(s|~r))+n+_+4293915773,15),r=n+i((s^(n|~t))+r+l+2240044497,21),t=r+i((n^(r|~s))+t+I+1873313359,6),s=t+i((r^(t|~n))+s+B+4264355552,10),n=s+i((t^(s|~r))+n+b+2734768916,15),r=n+i((s^(n|~t))+r+O+1309151649,21),t=r+i((n^(r|~s))+t+h+4149444226,6),s=t+i((r^(t|~n))+s+U+3174756917,10),n=s+i((t^(s|~r))+n+p+718787259,15),r=n+i((s^(n|~t))+r+C+3951481745,21),this.#e=this.#e+t>>>0,this.#t=this.#t+r>>>0,this.#r=this.#r+n>>>0,this.#o=this.#o+s>>>0}update(o){let t;if(typeof o=="string")t=new TextEncoder().encode(o);else if(typeof o=="object")if(o instanceof ArrayBuffer||ArrayBuffer.isView(o))t=new Uint8Array(o);else throw new TypeError($e);else throw new TypeError($e);let r=this.#i,n=k-r;if(t.length<n)this.#n.set(t,r),r+=t.length;else{this.#n.set(t.slice(0,n),r),this.#c(this.#n);let s=n;for(;s+k<=t.length;)this.#c(t.slice(s,s+k)),s+=k;this.#n.fill(0).set(t.slice(s),0),r=t.length-s}return this.#i=r,this.#p(t.length),this}digest(){let o=k-this.#i;o<9&&(o+=k);let t=new Uint8Array(o);t[0]=128;let r=this.#s<<3,n=this.#a<<3|this.#s>>>29;t[t.length-8]=r&255,t[t.length-7]=r>>>8&255,t[t.length-6]=r>>>16&255,t[t.length-5]=r>>>24&255,t[t.length-4]=n&255,t[t.length-3]=n>>>8&255,t[t.length-2]=n>>>16&255,t[t.length-1]=n>>>24&255,this.update(t.buffer);let s=new ArrayBuffer(16),a=new DataView(s);return a.setUint32(0,this.#e,!0),a.setUint32(4,this.#t,!0),a.setUint32(8,this.#r,!0),a.setUint32(12,this.#o,!0),s}toString(o="hex"){let t=this.digest();switch(o){case"hex":return new TextDecoder().decode(Oe(new Uint8Array(t)));case"base64":{let r=new Uint8Array(t),n="";for(let s=0;s<r.length;++s)n+=String.fromCharCode(r[s]);return btoa(n)}default:throw new Error("md5: invalid format")}}};var Be=async(e,o,t)=>{let r=new P().update(await e.arrayBuffer()).toString(),n=await gt(e,o,r,t);if(!n.ok)return n;if("embedUrl"in n.value)return{ok:!0,value:n.value};let s=await ht(n.value.signedUrl,e,t);return s.ok?xt(o,n.value.fileId,r,t):s},gt=async(e,o,t,r)=>{let{sid:n,hostName:s,fetch:a,csrf:i}=d(r??{}),c={md5:t,size:e.size,contentType:e.type,name:e.name},l=i??await w(),p=new Request(`https://${s}/api/gcs/${o}/upload-request`,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":l,...n?{Cookie:m(n)}:{}}}),u=await a(p);return u.ok?{ok:!0,value:await u.json()}:f(u)},ht=async(e,o,t)=>{let{sid:r,fetch:n}=d(t??{}),s=await n(e,{method:"PUT",body:o,headers:{"Content-Type":o.type,...r?{Cookie:m(r)}:{}}});if(!s.ok){if(s.headers.get("Content-Type")?.includes?.("/xml"))return{ok:!1,value:{name:"GCSError",message:await s.text()}};throw new E(s)}return{ok:!0,value:void 0}},xt=async(e,o,t,r)=>{let{sid:n,hostName:s,fetch:a,csrf:i}=d(r??{}),c=i??await w(),l=new Request(`https://${s}/api/gcs/${e}/verify`,{method:"POST",body:JSON.stringify({md5:t,fileId:o}),headers:{"Content-Type":"application/json;charset=utf-8","X-CSRF-TOKEN":c,...n?{Cookie:m(n)}:{}}}),p=await a(l);if(!p.ok){try{if(p.status===404)return{ok:!1,value:{name:"NotFoundError",message:(await p.json()).message}}}catch{throw new E(p)}throw new E(p)}return{ok:!0,value:await p.json()}};var Fe=(e,o)=>{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/${o?.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 D="",He=!1,q=new Map,je=async(e,o,t,r)=>{let n=q.get(e.href);if(n)return n;if(e.hostname==="video.twimg.com"||`${e}`.endsWith(".svg")){let c=await GM_fetch(e);if(!c.ok)return;let l=c.headers.get("content-type")?.split?.(";")?.[0]??`${e}`.endsWith(".mp4")?"video/mp4":"video/webm",p=new File([await c.blob()],r||`${o}`,{type:l});if(l==="video/mp4"){let g=await Fe(p);if(g.ok){let b=new URL(await g.text());return q.set(e.href,b),b}}let u=await Be(p,t);if(!u.ok)throw Error(u.value.name);let h=new URL(u.value.embedUrl);return q.set(e.href,h),h}if(e.hostname!=="pbs.twimg.com"||!e.pathname.startsWith("/media"))return;if(He){if(!D)return}else{let c=await Ie();if(He=!0,!c.ok){alert("You haven't logged in Gyazo yet, so you can only upload images to scrapbox.io.");return}if(D=c.value||"",!D){alert("You haven't connect Gyazo to scrapbox.io yet.");return}}let s=await GM_fetch(e);if(!s.ok)return;let a=await le(await s.blob(),{accessToken:D,refererURL:o,description:r});if(!a.ok)throw Error(a.value.name);let i=new URL(a.value.permalink_url);return q.set(e.href,i),i};var Et={"&lt;":"<","&gt;":">","&amp;":"&","&quot;":'"',"&#x27;":"'","&#x60;":"`"},Y=e=>e.replace(/&(lt|gt|amp|quot|#x27|#x60);/g,o=>Et[o]);var G=e=>{let o={name:e.user.name,screenName:e.user.screen_name},t=new Date(e.created_at),r=[...e.entities.hashtags.map(a=>({type:"hashtag",...a})),...e.entities.symbols.map(a=>({type:"symbol",...a})),...e.entities.user_mentions.map(a=>({type:"mention",name:a.name,screenName:a.screen_name,indices:a.indices})),...e.entities.urls.map(a=>{let i={type:"url",indices:a.indices,url:new URL(a.expanded_url)};if(e.card&&e.card?.url===a.url){let{description:c,title:l}=e.card.binding_values,p="STRING";c?.type===p&&(i.description=c.string_value),l?.type===p&&(i.title=l.string_value)}return i}),...e.entities.media?.map?.(a=>({type:"media",indices:a.indices,media:e.mediaDetails?.flatMap?.(i=>i.url===a.url?[{type:i.type,url:new URL(i.video_info?.variants?.sort?.((c,l)=>(l.bitrate??0)-(c.bitrate??0))?.[0].url??i.media_url_https)}]:[])??[]}))??[]].sort((a,i)=>a.indices[0]-i.indices[0]),n=[];{let a=0,i=e.text;for(let{indices:c,...l}of r){let p=[...i].slice(0,c[0]-a).join("");n.push({type:"plain",text:Y(p)}),n.push(l),i=[...i].slice(c[1]-a).join(""),a=c[1]}i&&n.push({type:"plain",text:Y(i)})}let s={id:e.id_str,content:n,author:o,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=G(e.parent)),e.quoted_tweet&&(s.quote=G(e.quoted_tweet)),s};var wt=["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"],K=(e=scrapbox.Project.name,o=location.host)=>t=>{if(t.host!==o)return t;let[,r,n]=t.pathname.match(/^\/([\w\d][\w\d-]{0,22}[\w\d])(?:\/?|\/(.+))$/)??[];return!r||wt.includes(r)?t:n?r===e?`[${decodeURIComponent(n)}]`:`[/${r}/${decodeURIComponent(n)}]`:`[/${r}]`};var Ae=(e=yt)=>o=>{let[,t]=o.href.match(/^https:\/\/(?:(?:www\.|mobile\.|m\.)?twitter|x)\.com\/[\w\d_]+\/(?:status|statuses)\/(\d+)/)??[];return t?(async()=>{let r=await(de(t)??Ne(o.href));if(!r.ok)throw r.value;return e("images"in r.value?{...r.value,id:t}:r.value,o)})():o},yt=async e=>{if("images"in e)return M(e);let{quote:o,replyTo:t,...r}=G(e);return[...t?[...(await M(t)).split(` `).map(n=>` > ${n}`),...t.quote?(await M(t.quote)).split(` `).map(n=>` > ${n}`):[]]:[],...(await M(r)).split(` `).map(n=>`> ${n}`),...o?(await M(o)).split(` `).map(n=>`> > ${n}`):[]].join(` `)},M=async e=>{let o=new URL(`https://twitter.com/${"author"in e?e.author.screenName:e.screenName}/status/${e.id}`);if("images"in e)return[`> [@${Q(e.screenName)} ${o.origin}${o.pathname}]`,...e.description?.split?.(` `)?.map?.(n=>`> ${Q(n)}`)??["> [/ no description provided]"],...e.images.length>0?[`> ${e.images.map(n=>`[${n}]`)}`]:[]].join(` `);let t=e.content,r=e.author.screenName;return[`[@${Q(r)} ${o}]`,...(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 J(n.media[a-1],o)}] [${await J(n.media[a],o)}]`);return a===n.media.length&&s.push(`[${await J(n.media[a-1],o)}]`),` ${s.join(` `)} `}case"url":return`${K()(n.url)} `}}))).join("").split(` `)].join(` `)},z="",bt=async()=>{if(z)return z;let e=await A(scrapbox.Project.name);if(!e.ok)throw new Error(e.value.name);return z=e.value.id,z},J=async(e,o)=>await je(e.url,o,await bt(),"")??e.url,Q=e=>e.replace(/\b/gm,"").replace(/[\s\r\n\u2028\u2029]+/gm," ").replace(/\s*[[\]`]\s*/g," ").trim();var De=e=>{if(!window.GM_fetch)return;let o=window.GM_fetch;return(async()=>{let t=await o(`https://t.co/${e}`),r=R(t);return r?{ok:!1,value:r}:{ok:!0,value:new DOMParser().parseFromString(await t.text(),"text/html").title}})()};var qe=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(t=>t.ok?new URL(t.url):e);if(e.hostname!=="t.co")return e;let o=De(e.pathname.slice(1));return o?(async()=>{let t=await o;if(!t.ok)throw t.value;try{return new URL(t.value)}catch(r){if(r instanceof TypeError)return e;throw r}})():e};var Ge=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 o=decodeURIComponent(e.pathname.slice(6)),t=e.hash?decodeURIComponent(e.hash.slice(1)):"",r=`${e.origin}/wiki/${o}`;return t?`[${t} | ${o} - Wikipedia ${r}#${t}]`:`[${o} - Wikipedia ${r}]`};var Ke=e=>{if(e.hostname!=="www.wikiwand.com")return e;let[,o,t]=e.pathname.match(/^\/([^\/]+)\/([^\/]+)/)??[];return!o||!t||(e.hostname=`${o}.wikipedia.org`,e.pathname=`/wiki/${t}`,e.hash=e.hash.startsWith("#/")?`#${e.hash.slice(2)}`:e.hash),e};var Z=e=>{if(!e.hostname.startsWith("www.google."))return e;let o=e.searchParams.get("url");return o?new URL(decodeURIComponent(o)):e};var ze=/charset=([^;]+)/,We=e=>{if(!window.GM_fetch)return;let o=window.GM_fetch;return(async()=>{let t=await o(`${e}`),r=R(t);if(r)return{ok:!1,value:r};let n=t.headers.get("content-type")?.match?.(ze)?.[1]??await Lt(t.clone());return{ok:!0,value:new TextDecoder(n).decode(await t.arrayBuffer())}})()},Lt=async e=>{let o=new DOMParser().parseFromString(await e.text(),"text/html");return o.querySelector("meta[charset]")?.getAttribute?.("charset")??o.querySelector('meta[http-equiv="content-type"]')?.getAttribute?.("content")?.match?.(ze)?.[1]??"utf-8"};var Ve=(e=Tt)=>async o=>e(await kt(o),o),Tt=(e,o)=>{let t=(x(e)?e:e.title).replace(/\s/g," ").replaceAll("[","[").replaceAll("]","]");return t?`[${o.hash?`${decodeURIComponent(o.hash.slice(1))} | `:""}${t} ${o}]`:`${o}`},kt=async e=>{let o=We(e);if(!o){let r=await Me(e);if(!r.ok)throw r.value;return r.value}let t=await o;if(!t.ok)throw t.value;return new DOMParser().parseFromString(t.value,"text/html")};var Xe=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[,o]=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 o&&(e.hash="",e.search="",e.pathname=`/dp/${o}`),e};var Ye=e=>{if(!/(?:[0-9a-z-]\.)?gyazo\.com/.test(e.hostname))return e;let[,o]=e.pathname.match(/^\/([0-9a-f]{32})(?:\/raw)?$/)??[];return o?`[https://gyazo.com/${o}]`:e};var Je=(e,...o)=>{if(e instanceof URL)return V(new URL(e),...o);let t=0,r=0,n=0,s=!1,a=e.split(/(https?:\/\/\S+)/g).map(p=>{if(!/^https?:\/\/\S+$/.test(p))return p;t++;try{let u=V(new URL(p),...o);return x(u)?(r++,u):(s=!0,[u,p])}catch(u){return console.error(u),n++,p}});if(!s)return a.join("");let{render:i,dispose:c}=ce(),l=()=>i({type:"spinner"},{type:"text",text:`URL: ${r}/${t} converted, ${n} failed`});return l(),Promise.all(a.map(async p=>{if(x(p))return p;try{let u=await p[0];return r++,u}catch(u){return console.error(u),n++,p[1]}finally{l()}})).then(p=>(i({type:"check-circle"},{type:"text",text:`URL: ${r}/${t} converted, ${n} failed`}),p.join(""))).finally(()=>{setTimeout(c,1e3)})};var Rt=[Z,qe,Z,Ke,Xe,K(),Ye,Ae(),Ge,Ve()];scrapbox.PopupMenu.addButton({title:e=>/https?:\/\/\S+/.test(e)?"URL":"",onClick:e=>{let o=Je(e,...Rt);if(typeof o=="string")return e===o?void 0:o;o.then(t=>{if(e!==t)return ae(t)})}});