UNPKG

grab-url

Version:

📥 Generate Request to API from Browser

3 lines (2 loc) 10.6 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["grab-api"]={})}(this,function(e){"use strict";function t(e="",t={}){let{color:o=null,style:r="color: #66ccff; font-size: 10pt;",hideInProduction:l,startSpinner:a=!1,stopSpinner:s=!1}=t;const f=n();void 0===l&&(l="undefined"!=typeof window&&(null==window?void 0:window.location.hostname.includes("localhost"))),"object"==typeof e&&(e=i(e)+"\n\n"+JSON.stringify(e,null,2)),o&&void 0!==typeof process&&(e=(f[o]||"")+e+f.reset);var d=0;return a?(global||globalThis).interval=setInterval(()=>{process.stdout.write((f[o]||"")+"\r"+"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏".split("")[d=++d%10]+" "+e+f.reset)},50):s?(clearInterval((global||globalThis).interval),process.stdout.write("\r"+(e||"✔ Done")+" ".repeat(e.length+20)+"\n")):"string"==typeof r?(1==r.split(" ").length||o?r=`color: ${o||r}; font-size: 11pt;`:r.match(/^#[0-9a-fA-F]{6}$/)&&(r=`color: ${r}; font-size: 11pt;`),l?console.debug((r?"%c":"")+(e||""),r):console.log((r?"%c":"")+(e||""),r)):"object"==typeof r&&console.log(e,...r),!0}const o={reset:[0,""],black:[30,"000000"],red:[31,"ff0000"],green:[32,"00ff00"],yellow:[33,"ffff00"],blue:[34,"0000ff"],magenta:[35,"ff00ff"],cyan:[36,"00ffff"],white:[37,"ffffff"],gray:[90,"808080"],brightRed:[91,"ff5555"],brightGreen:[92,"55ff55"],brightYellow:[93,"ffff55"],brightBlue:[94,"5555ff"],brightMagenta:[95,"ff55ff"],brightCyan:[96,"55ffff"],brightWhite:[97,"ffffff"],bgRed:[41,"ff0000"],bgGreen:[42,"00ff00"],bgYellow:[43,"ffff00"],bgBlue:[44,"0000ff"],bgMagenta:[45,"ff00ff"],bgCyan:[46,"00ffff"],bgWhite:[47,"ffffff"],bgGray:[100,"808080"]};function n(e=("undefined"!=typeof window?"html":"ansi")){const t={};for(const[n,[r,l]]of Object.entries(o)){t[n]="html"===e?"#"+l:"["+r+"m"}return t}function r(e){const t=n();return"string"==typeof e?t.yellow:"number"==typeof e?t.cyan:"boolean"==typeof e?t.magenta:"function"==typeof e?t.red:null===e?t.gray:Array.isArray(e)?t.blue:"object"==typeof e?t.green:t.white}function l(e){return"string"==typeof e?'""':"number"==typeof e?"number":"boolean"==typeof e?"bool":"function"==typeof e?"function":null===e?"null":Array.isArray(e)?e.length?"["+l(e[0])+"]":"[]":"object"==typeof e?"{...}":typeof e}function i(e,t=0){const o=n(),a=" ".repeat(t);if("object"!=typeof e||null===e){return r(e)+l(e)+o.reset}if(Array.isArray(e)){let n=o.blue+"["+o.reset;return e.length&&(n+="\n"),e.forEach((o,r)=>{n+=a+" "+i(o,t+1),r<e.length-1&&(n+=","),n+="\n"}),n+=a+o.blue+"]"+o.reset,n}let s=o.green+"{"+o.reset;const f=Object.keys(e);return f.length&&(s+="\n"),f.forEach((n,d)=>{const c=e[n],u=r(c);s+=a+" ","object"!=typeof c||null===c||Array.isArray(c)?Array.isArray(c)?s+=u+n+o.reset+": "+i(c,t+1):s+=u+n+": "+l(c)+o.reset:s+=u+n+o.reset+": "+i(c,t+1),d<f.length-1&&(s+=","),s+="\n"}),s+=a+o.green+"}"+o.reset,s}function a(e){if("undefined"==typeof document)return;let t,o=document.getElementById("alert-overlay");o||(o=document.body.appendChild(document.createElement("div")),o.id="alert-overlay",o.setAttribute("style","position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center"),o.innerHTML='<div id="alert-box" style="background:#fff;padding:1.5em 2em;border-radius:8px;box-shadow:0 2px 16px #0003;min-width:220px;max-height:80vh;position:relative;display:flex;flex-direction:column;">\n <button id="close-alert" style="position:absolute;top:12px;right:20px;font-size:1.5em;background:none;border:none;cursor:pointer;color:black;">&times;</button>\n <div id="alert-list" style="overflow:auto;flex:1;"></div>\n </div>',o.addEventListener("click",e=>e.target==o&&o.remove()),document.getElementById("close-alert").onclick=()=>o.remove()),t=o.querySelector("#alert-list"),t.innerHTML+=`<div style="border-bottom:1px solid #333; font-size:1.2em;margin:0.5em 0;">${e}</div>`}async function s(e,o){var n,r,l,d,c,u,g,p,b,y,h,{headers:m,response:w={},method:v=(o.post?"POST":o.put?"PUT":o.patch?"PATCH":"GET"),cache:T=!1,cacheForTime:S=60,timeout:L=30,baseURL:O="undefined"!=typeof process&&process.env.SERVER_API_URL||"/api/",cancelOngoingIfNew:E=!1,cancelNewIfOngoing:j=!1,rateLimit:x=0,debug:A=!1,infiniteScroll:k=null,setDefaults:P=!1,retryAttempts:N=0,logger:D=t,onRequest:q=null,onResponse:R=null,onError:$=null,onStream:F=null,repeatEvery:I=null,repeat:J=0,debounce:C=0,regrabOnStale:M=!1,regrabOnFocus:H=!1,regrabOnNetwork:z=!1,post:W=!1,put:U=!1,patch:B=!1,body:G=null,..._}={..."undefined"!=typeof window?null==(n=null==window?void 0:window.grab)?void 0:n.defaults:(null==(l=null==(r=global||globalThis)?void 0:r.grab)?void 0:l.defaults)||{},...o};let K=t=>e.startsWith(t);K("http:")||K("https:")?O="":K("/")||O.endsWith("/")?K("/")&&O.endsWith("/")&&(e=e.slice(1)):e="/"+e;try{if(C>0)return await f(async()=>{await s(e,{...o,debounce:0})},1e3*C);if(J>1){for(let t=0;t<J;t++)await s(e,{...o,repeat:0});return w}if(I)return setInterval(async()=>{await s(e,{...o,repeat:0,repeatEvery:null})},1e3*I),w;if(null==o?void 0:o.setDefaults)return void("undefined"!=typeof window?window.grab.defaults={...o,setDefaults:void 0}:void 0!==(global||globalThis).grab&&((global||globalThis).grab.defaults={...o,setDefaults:void 0}));if("undefined"!=typeof window){const t=async()=>await s(e,{...o,cache:!1});M&&T&&setTimeout(t,1e3*S),z&&window.addEventListener("online",t),H&&(window.addEventListener("focus",t),document.addEventListener("visibilitychange",async()=>{"visible"===document.visibilityState&&await t()}))}let n="function"==typeof w?w:null;w&&!n||(w={});var[Y,V,Q]=k||[];if((null==k?void 0:k.length)&&void 0!==Q&&"undefined"!=typeof window){let n="string"==typeof Q?document.querySelector(Q):Q;n||t("paginateDOM not found",{color:"red"}),window.scrollListener&&void 0!==n&&n.removeEventListener("scroll",window.scrollListener),window.scrollListener=async t=>{const n=t.target;localStorage.setItem("scroll",JSON.stringify([n.scrollTop,n.scrollLeft,Q])),n.scrollHeight-n.scrollTop<=n.clientHeight+200&&await s(e,{...o,cache:!1,[Y]:(null==l?void 0:l.currentPage)+1})},n&&n.addEventListener("scroll",window.scrollListener)}let r=JSON.stringify(Y?{..._,[Y]:void 0}:_),l=null==(d=null==s?void 0:s.log)?void 0:d.find(t=>t.request==r&&t.path==e);if(Y){let e=(null==l?void 0:l.currentPage)+1||(null==_?void 0:_[Y])||1;l||(w[V]=[],e=1),l&&(l.currentPage=e),_={..._,[Y]:e}}else{for(let e of Object.keys(w))w[e]=void 0;if(T&&(!S||(null==l?void 0:l.lastFetchTime)>Date.now()-1e3*S)){for(let e of Object.keys(l.res))w[e]=l.res[e];n&&(w=n(w))}}if(n?n({isLoading:!0}):"object"==typeof w&&(w.isLoading=!0),n&&(w=n(w)),x>0&&(null==l?void 0:l.lastFetchTime)&&l.lastFetchTime>Date.now()-1e3*x)throw new Error(`Fetch rate limit exceeded for ${e}. \n Wait ${x}s between requests.`);if(null==l?void 0:l.controller)if(E)l.controller.abort();else if(j)return{isLoading:!0};void 0!==s.log&&(null==(c=s.log)||c.unshift({path:e,request:r,lastFetchTime:Date.now(),controller:new AbortController}));let a={method:v,headers:{"Content-Type":"application/json",Accept:"application/json",...m},body:_.body,redirect:"follow",cache:T?"force-cache":"no-store",signal:E?null==(g=null==(u=s.log[0])?void 0:u.controller)?void 0:g.signal:AbortSignal.timeout(1e3*L)},h="";["POST","PUT","PATCH"].includes(v)?a.body=_.body||JSON.stringify(_):h=(Object.keys(_).length?"?":"")+new URLSearchParams(_).toString(),"function"==typeof q&&([e,w,_,a]=q(e,w,_,a));let P=null,N=new Date,$=null==(p=s.mock)?void 0:p[e],W=e=>new Promise(t=>setTimeout(t,1e3*e||0));if(!$||$.params&&$.method!=v||$.params&&r!=JSON.stringify($.params)){if(P=await fetch(O+e+h,a).catch(e=>{throw new Error(e.message)}),!P.ok)throw new Error(`HTTP error: ${P.status} ${P.statusText}`);let t=P.headers.get("content-type");F?await F(P.body):P=await(t?t.includes("application/json")?P&&P.json():t.includes("application/pdf")||t.includes("application/octet-stream")?P.blob():P.text():P.json()).catch(e=>{throw new Error("Error parsing response: "+e)})}else await W($.delay),P="function"==typeof $.response?$.response(_):$.response;"function"==typeof R&&([e,w,_,a]=R(e,w,_,a)),n?n({isLoading:void 0}):"object"==typeof w&&(null==w||delete w.isLoading),null==l||delete l.controller;const U=((Number(new Date)-Number(N))/1e3).toFixed(1);if(A&&D("Path:"+O+e+h+"\n"+JSON.stringify(o,null,2)+"\nTime: "+U+"s\nResponse: "+i(P)),"object"==typeof P){for(let e of Object.keys(P))w[e]=V==e&&(null==(b=w[e])?void 0:b.length)?[...w[e],...P[e]]:P[e];void 0!==w&&(w.data=P)}else n?n({data:P,...P}):"object"==typeof w&&(w.data=P);return void 0!==s.log&&(null==(y=s.log)||y.unshift({path:e,request:JSON.stringify({..._,paginateKey:void 0}),response:w,lastFetchTime:Date.now()})),n&&(w=n(w)),w}catch(X){let t="Error: "+X.message+"\nPath:"+O+e+"\n";return"function"==typeof $&&$(X.message,O+e,_),o.retryAttempts>0?await s(e,{...o,retryAttempts:--o.retryAttempts}):(!X.message.includes("signal")&&o.debug&&(D(t,{color:"red"}),A&&"undefined"!=typeof document&&a(t)),w.error=X.message,"function"==typeof w?(w.data=w({isLoading:void 0,error:X.message}),w=w.data):null==w||delete w.isLoading,void 0!==s.log&&(null==(h=s.log)||h.unshift({path:e,request:JSON.stringify(_),error:X.message})),w)}}s.instance=(e={})=>(t,o={})=>s(t,{...e,...o});const f=async(e,t)=>{let o;return async function(...n){clearTimeout(o),o=setTimeout(async()=>{clearTimeout(o),await e(...n)},t)}};"undefined"!=typeof window?(window.log=t,window.grab=s,window.grab.log=[],window.grab.mock={},window.grab.defaults={},document.addEventListener("keydown",e=>{if("i"===e.key&&e.ctrlKey){let e=" ";for(let t of grab.log)e+=`<div style="margin-bottom:1em; border-bottom:1px solid #ccc; padding-bottom:1em;">\n <b>Path:</b> ${t.path}<br>\n <b>Request:</b> ${t.request}<br>\n <b>Response:</b> ${JSON.stringify(t.response,null,2)}<br>\n <b>Time:</b> ${new Date(t.lastFetchTime).toLocaleString()}\n </div>`;a(e)}}),document.addEventListener("DOMContentLoaded",()=>{let[e,t,o]=JSON.parse(localStorage.getItem("scroll"))||[];e&&(document.querySelector(o).scrollTop=e,document.querySelector(o).scrollLeft=t)})):"undefined"!=typeof global?(s.log=[],s.mock={},s.defaults={},global.log=t,global.grab=s.instance()):"undefined"!=typeof globalThis&&(s.log=[],s.mock={},s.defaults={},globalThis.log=t,globalThis.grab=s.instance()),e.default=s,e.grab=s,e.log=t,e.printJSONStructure=i,e.showAlert=a,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); //# sourceMappingURL=grab-api.umd.js.map