scrapbox-chatGPT
code:mod.js
const l=()=>({ok:!1,value:{name:"UnauthorizedError",message:"Please log in https://chat.openai.com."}}),k=()=>({ok:!1,value:{name:"TooManyRequestsError",message:"Too many request."}}),T=()=>({ok:!1,value:{name:"BlockedByCloudflareError",message:"Please pass Cloudflare security check at https://chat.openai.com."}}),v=r=>{try{const e=new DOMParser().parseFromString(r,"text/html");if(!e)return!1;const t=e.querySelector("title");return t?t.innerText==="Just a moment...":!1}catch{return!1}};let f="",y=0;const h=()=>{if(f&&y>new Date().getTime())return Promise.resolve({ok:!0,value:f});if(GM_fetch)return(async()=>{const e=await(await GM_fetch("https://chat.openai.com/api/auth/session")).text();if(v(e))return T();const t=JSON.parse(e);if(!t.accessToken)return l();const{accessToken:a,expires:n}=t;return n&&(y=new Date(n).getTime()),f=a,{ok:!0,value:a}})()},p=()=>{f=""};export{h as getAccessToken};export{p as resetAccessToken};class c extends Error{response;name;constructor(e){super(${e.status} ${e.statusText} when fetching ${e.url}),this.response=e,this.name="HTTPError",Error.captureStackTrace&&Error.captureStackTrace(this,c)}}export{c as HTTPError};const b=r=>{if(!GM_fetch)return;const e=h();if(e)return(async()=>{const t=await e;if(!t.ok)return t;const a=await GM_fetch(https://chat.openai.com/backend-api/conversation/${r},{headers:{"Content-Type":"application/json",Authorization:Bearer ${t.value},Referrer:"https://chat.openai.com"}});if(!a.ok)switch(a.status){case 401:return p(),l();case 429:return k();default:throw new c(a)}return{ok:!0,value:await a.json()}})()};export{b as getConversation};const g=()=>{const r="abcdef0123456789",e=[];for(let t=0;t<36;t++)et=t===8||t===13||t===18||t===23?"-":rMath.ceil(Math.random()*r.length-1);return e.join("")};typeof ReadableStream.prototypeSymbol.asyncIterator!="function"&&Object.defineProperty(ReadableStream.prototype,Symbol.asyncIterator,{async*value(){const r=this.getReader();try{for(;;){const{done:e,value:t}=await r.read();if(e)return;yield t}}finally{r.releaseLock()}},writable:!0,enumerable:!1,configurable:!0});const x=(r,e)=>{if(!GM_fetch)return;const t=h();if(t)return(async()=>{const a=await t;if(!a.ok)return a;const n=a.value,o={action:"next",history_and_training_disabled:!1,messages:[{id:g(),author:{role:"user"},content:{content_type:"text",parts:r}}],model:e?.model??"text-davinci-002-render-sha",parent_message_id:e?.parentMessageId??g(),timezone_offset_min:E()};e&&(o.conversation_id=e.conversationId);const s=await GM_fetch("https://chat.openai.com/backend-api/conversation",{method:"POST",headers:{"Content-Type":"application/json",Authorization:Bearer ${n},Referrer:"https://chat.openai.com"},body:JSON.stringify(o)});if(!s.ok)switch(s.status){case 401:return p(),l();case 429:return k();case 413:return{ok:!1,value:{name:"TooLongMessageError",message:(await s.json()).detail?.message}};default:throw new c(s)}if(!s.body)throw Error("No content in Response of https://chat.openai.com/backend-api/conversation");return{ok:!0,value:async function*(){let i="";for await(const w of s.body){i+=String.fromCharCode(...w);const d=i.split(/\n\n/).map(u=>u.replace(/^data: /,""));if(!(d.length<2)){i=d.pop();for(const u of d){if(u==="DONE")return;try{yield JSON.parse(u)}catch(m){if(!(m instanceof SyntaxError))throw m;console.error(m)}}if(i==="DONE")return}}}()}})()},E=()=>new Date().getTimezoneOffset();export{x as sendMessage};const _=(r,e)=>{if(!GM_fetch)return;const t=h();if(t)return(async()=>{const a=await t;if(!a.ok)return a;const n=await GM_fetch(https://chat.openai.com/backend-api/conversation/${r},{method:"POST",headers:{"Content-Type":"application/json",Authorization:Bearer ${a.value},Referrer:"https://chat.openai.com"},body:JSON.stringify({message_id:e})});if(!n.ok)switch(n.status){case 401:return p(),l();case 429:return k();default:throw new c(n)}const o=await n.json();return"title"in o?{ok:!0,value:o.title}:{ok:!1,value:{name:"HasAlreadyTitleError",message:o.message}}})()};export{_ as generateChatTitle};