@microlink/mql 0.11.6-1 → 0.11.6-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function e(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var r=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(r,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})})),r}var r={exports:{}};const s=/^https?:\/\//i;var o={};function n(t,e,r,s,o){var i,a=o?o+r:o;if(null==s)e&&(t[o]=s);else if("object"!=typeof s)t[o]=s;else if(Array.isArray(s))for(i=0;i<s.length;i++)n(t,e,r,s[i],a+i);else for(i in s)n(t,e,r,s[i],a+i)}o.flattie=function(t,e,r){var s={};return"object"==typeof t&&n(s,!!r,e||".",t,""),s};const i={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},a=t=>null!==t&&"object"==typeof t;var u=({VERSION:t,MicrolinkError:e,urlHttp:r,got:s,flatten:o})=>{const n=t=>{if(!a(t))return;const e=o(t);return Object.keys(e).reduce(((t,r)=>(t[`data.${r}`]=e[r].toString(),t)),{})},u=async(t,r={})=>{try{const e=await s(t,r);return"buffer"===r.responseType?{body:e.body,response:e}:{...e.body,response:e}}catch(r){const{response:s={}}=r,{statusCode:n,body:i,headers:u={},url:l=t}=s,c=null!=(o=i)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),h=a(i)&&!c?i:((t,e,r)=>{try{return JSON.parse(t)}catch(s){const o=t||e.message;return{status:"error",data:{url:o},more:"https://microlink.io/efatalclient",code:"EFATALCLIENT",message:o,url:r}}})(c?i.toString():i,r,l);throw new e({...h,message:h.message,url:l,statusCode:n,headers:u})}var o},l=(t,{data:e,apiKey:r,endpoint:s,retry:a,cache:u,...l}={},{responseType:c="json",headers:h,...p}={})=>{const f=!!r;return[`${s||i[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...n(e),...o(l)}).toString()}`,{...p,responseType:c,cache:u,retry:a,headers:f?{...h,"x-api-key":r}:{...h}}]},c=t=>async(s,o,n)=>{((t="")=>{if(!r(t)){const r=`The \`url\` as \`${t}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new e({status:"fail",data:{url:r},more:"https://microlink.io/docs/api/api-parameters/url",code:"EINVALURLCLIENT",message:r,url:t})}})(s);const[i,a]=l(s,o,{...t,...n});return u(i,a)},h=c();return h.MicrolinkError=e,h.getApiUrl=l,h.fetchFromApi=u,h.mapRules=n,h.version=t,h.stream=s.stream,h.buffer=c({responseType:"buffer"}),h};class l extends Error{constructor(t,e,r){const s=`${t.status||0===t.status?t.status:""} ${t.statusText||""}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=e,this.options=r}}class c extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const h=t=>null!==t&&"object"==typeof t,p=(...t)=>{for(const e of t)if((!h(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return d({},...t)},f=(t={},e={})=>{const r=new globalThis.Headers(t),s=e instanceof globalThis.Headers,o=new globalThis.Headers(e);for(const[t,e]of o.entries())s&&"undefined"===e||void 0===e?r.delete(t):r.set(t,e);return r},d=(...t)=>{let e={},r={};for(const s of t)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(h(s)){for(let[t,r]of Object.entries(s))h(r)&&t in e&&(r=d(e[t],r)),e={...e,[t]:r};h(s.headers)&&(r=f(r,s.headers),e.headers=r)}return e},y=(()=>{let t=!1,e=!1;const r="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return r&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")),t&&!e})(),b="function"==typeof globalThis.AbortController,m="function"==typeof globalThis.ReadableStream,_="function"==typeof globalThis.FormData,w=["get","post","put","patch","head","delete"],g={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},T=2147483647,R=Symbol("stop"),v={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},E={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},q=t=>w.includes(t)?t.toUpperCase():t,x=[413,429,503],P={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:x,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:t=>.3*2**(t-1)*1e3},j=(t={})=>{if("number"==typeof t)return{...P,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...P,...t,afterStatusCodes:x}};class C{static create(t,e){const r=new C(t,e),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>T)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let t=await r._fetch();for(const e of r._options.hooks.afterResponse){const s=await e(r.request,r._options,r._decorateResponse(t.clone()));s instanceof globalThis.Response&&(t=s)}if(r._decorateResponse(t),!t.ok&&r._options.throwHttpErrors){let e=new l(t,r.request,r._options);for(const t of r._options.hooks.beforeError)e=await t(e);throw e}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!m)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(t.clone(),r._options.onDownloadProgress)}return t},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[t,s]of Object.entries(g))o[t]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const n=(await o).clone();if("json"===t){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await n.text())}return n[t]()};return o}constructor(t,e={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:f(this._input.headers,e.headers),hooks:d({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:q(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:j(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(b){if(this.abortController=new globalThis.AbortController,this._options.signal){const t=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(t.reason)}))}this._options.signal=this.abortController.signal}if(y&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const t="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);!(_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(e,{...this.request}),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof c)){if(t instanceof l){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),T);if(0!==r&&this._retryCount>0){await async function(t,{signal:e}){return new Promise(((r,s)=>{function o(){clearTimeout(n),s(e.reason)}e&&(e.throwIfAborted(),e.addEventListener("abort",o,{once:!0}));const n=setTimeout((()=>{e?.removeEventListener("abort",o),r()}),t)}))}(r,{signal:this._options.signal});for(const t of this._options.hooks.beforeRetry){if(await t({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===R)return}return this._retry(t)}throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}const t=((t,e)=>{const r={};for(const s in e)s in E||s in v||s in t||(r[s]=e[s]);return r})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),t):async function(t,e,r,s){return new Promise(((o,n)=>{const i=setTimeout((()=>{r&&r.abort(),n(new c(t))}),s.timeout);s.fetch(t,e).then(o).catch(n).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const r=Number(t.headers.get("content-length"))||0;let s=0;return 204===t.status?(e&&e({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(o){const n=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await async function t(){const{done:i,value:a}=await n.read();if(i)o.close();else{if(e){s+=a.byteLength;e({percent:0===r?0:s/r,transferredBytes:s,totalBytes:r},a)}o.enqueue(a),await t()}}()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}const O=t=>{const e=(e,r)=>C.create(e,p(t,r));for(const r of w)e[r]=(e,s)=>C.create(e,p(t,s,{method:r}));return e.create=t=>O(p(t)),e.extend=e=>O(p(t,e)),e.stop=R,e},A=O();var k=e(Object.freeze({__proto__:null,HTTPError:l,TimeoutError:c,default:A}));const S=t=>{try{const{href:e}=new URL(t);return s.test(e)&&e}catch(t){return!1}},{flattie:U}=o,L=u,{default:N}=k;class I extends Error{constructor(t){super(),this.name="MicrolinkError",Object.assign(this,t),this.description=this.message,this.message=this.code?`${this.code}, ${this.description}`:this.description}}const D=L({MicrolinkError:I,urlHttp:S,got:async(t,e)=>{try{e.retry>0&&(e.retry=e.retry+1),void 0===e.timeout&&(e.timeout=!1);const r=await N(t,e),s=await r.json(),{headers:o,status:n}=r;return{url:r.url,body:s,headers:o,statusCode:n}}catch(t){if(t.response){const{response:e}=t;t.response={...e,headers:Array.from(e.headers.entries()).reduce(((t,[e,r])=>(t[e]=r,t)),{}),statusCode:e.status,body:await e.text()}}throw t}},flatten:U,VERSION:"0.11.6-0"});r.exports=D;var M=r.exports.MicrolinkError=D.MicrolinkError,H=r.exports.getApiUrl=D.getApiUrl,$=r.exports.mapRules=D.mapRules,B=r.exports.version=D.version,F=t(r.exports);export{M as MicrolinkError,F as default,H as getApiUrl,$ as mapRules,B as version};
1
+ function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function e(t){if(t.__esModule)return t;var e=t.default;if("function"==typeof e){var r=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach((function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(r,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})})),r}var r={exports:{}};const s=/^https?:\/\//i;var o={};function n(t,e,r,s,o){var i,a=o?o+r:o;if(null==s)e&&(t[o]=s);else if("object"!=typeof s)t[o]=s;else if(Array.isArray(s))for(i=0;i<s.length;i++)n(t,e,r,s[i],a+i);else for(i in s)n(t,e,r,s[i],a+i)}o.flattie=function(t,e,r){var s={};return"object"==typeof t&&n(s,!!r,e||".",t,""),s};const i={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},a=t=>null!==t&&"object"==typeof t;var u=({VERSION:t,MicrolinkError:e,urlHttp:r,got:s,flatten:o})=>{const n=t=>{if(!a(t))return;const e=o(t);return Object.keys(e).reduce(((t,r)=>(t[`data.${r}`]=e[r].toString(),t)),{})},u=async(t,r={})=>{try{const e=await s(t,r);return"buffer"===r.responseType?{body:e.body,response:e}:{...e.body,response:e}}catch(r){const{response:s={}}=r,{statusCode:n,body:i,headers:u={},url:l=t}=s,c=null!=(o=i)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),h=a(i)&&!c?i:((t,e,r)=>{try{return JSON.parse(t)}catch(s){const o=t||e.message;return{status:"error",data:{url:o},more:"https://microlink.io/efatalclient",code:"EFATALCLIENT",message:o,url:r}}})(c?i.toString():i,r,l);throw new e({...h,message:h.message,url:l,statusCode:n,headers:u})}var o},l=(t,{data:e,apiKey:r,endpoint:s,retry:a,cache:u,...l}={},{responseType:c="json",headers:h,...p}={})=>{const f=!!r;return[`${s||i[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...n(e),...o(l)}).toString()}`,{...p,responseType:c,cache:u,retry:a,headers:f?{...h,"x-api-key":r}:{...h}}]},c=t=>async(s,o,n)=>{((t="")=>{if(!r(t)){const r=`The \`url\` as \`${t}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new e({status:"fail",data:{url:r},more:"https://microlink.io/docs/api/api-parameters/url",code:"EINVALURLCLIENT",message:r,url:t})}})(s);const[i,a]=l(s,o,{...t,...n});return u(i,a)},h=c();return h.MicrolinkError=e,h.getApiUrl=l,h.fetchFromApi=u,h.mapRules=n,h.version=t,h.stream=s.stream,h.buffer=c({responseType:"buffer"}),h};class l extends Error{constructor(t,e,r){const s=`${t.status||0===t.status?t.status:""} ${t.statusText||""}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=e,this.options=r}}class c extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const h=t=>null!==t&&"object"==typeof t,p=(...t)=>{for(const e of t)if((!h(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return d({},...t)},f=(t={},e={})=>{const r=new globalThis.Headers(t),s=e instanceof globalThis.Headers,o=new globalThis.Headers(e);for(const[t,e]of o.entries())s&&"undefined"===e||void 0===e?r.delete(t):r.set(t,e);return r},d=(...t)=>{let e={},r={};for(const s of t)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(h(s)){for(let[t,r]of Object.entries(s))h(r)&&t in e&&(r=d(e[t],r)),e={...e,[t]:r};h(s.headers)&&(r=f(r,s.headers),e.headers=r)}return e},y=(()=>{let t=!1,e=!1;const r="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return r&&s&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")),t&&!e})(),b="function"==typeof globalThis.AbortController,m="function"==typeof globalThis.ReadableStream,_="function"==typeof globalThis.FormData,w=["get","post","put","patch","head","delete"],g={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},T=2147483647,R=Symbol("stop"),v={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},E={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},q=t=>w.includes(t)?t.toUpperCase():t,x=[413,429,503],P={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:x,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:t=>.3*2**(t-1)*1e3},j=(t={})=>{if("number"==typeof t)return{...P,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...P,...t,afterStatusCodes:x}};class C{static create(t,e){const r=new C(t,e),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>T)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let t=await r._fetch();for(const e of r._options.hooks.afterResponse){const s=await e(r.request,r._options,r._decorateResponse(t.clone()));s instanceof globalThis.Response&&(t=s)}if(r._decorateResponse(t),!t.ok&&r._options.throwHttpErrors){let e=new l(t,r.request,r._options);for(const t of r._options.hooks.beforeError)e=await t(e);throw e}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!m)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(t.clone(),r._options.onDownloadProgress)}return t},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[t,s]of Object.entries(g))o[t]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const n=(await o).clone();if("json"===t){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await n.text())}return n[t]()};return o}constructor(t,e={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:f(this._input.headers,e.headers),hooks:d({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:q(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:j(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(b){if(this.abortController=new globalThis.AbortController,this._options.signal){const t=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(t.reason)}))}this._options.signal=this.abortController.signal}if(y&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const t="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);!(_&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(e,{...this.request}),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof c)){if(t instanceof l){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),T);if(0!==r&&this._retryCount>0){await async function(t,{signal:e}){return new Promise(((r,s)=>{function o(){clearTimeout(n),s(e.reason)}e&&(e.throwIfAborted(),e.addEventListener("abort",o,{once:!0}));const n=setTimeout((()=>{e?.removeEventListener("abort",o),r()}),t)}))}(r,{signal:this._options.signal});for(const t of this._options.hooks.beforeRetry){if(await t({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===R)return}return this._retry(t)}throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}const t=((t,e)=>{const r={};for(const s in e)s in E||s in v||s in t||(r[s]=e[s]);return r})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),t):async function(t,e,r,s){return new Promise(((o,n)=>{const i=setTimeout((()=>{r&&r.abort(),n(new c(t))}),s.timeout);s.fetch(t,e).then(o).catch(n).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),t,this.abortController,this._options)}_stream(t,e){const r=Number(t.headers.get("content-length"))||0;let s=0;return 204===t.status?(e&&e({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(o){const n=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await async function t(){const{done:i,value:a}=await n.read();if(i)o.close();else{if(e){s+=a.byteLength;e({percent:0===r?0:s/r,transferredBytes:s,totalBytes:r},a)}o.enqueue(a),await t()}}()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}const O=t=>{const e=(e,r)=>C.create(e,p(t,r));for(const r of w)e[r]=(e,s)=>C.create(e,p(t,s,{method:r}));return e.create=t=>O(p(t)),e.extend=e=>O(p(t,e)),e.stop=R,e},A=O();var k=e(Object.freeze({__proto__:null,HTTPError:l,TimeoutError:c,default:A}));const S=t=>{try{const{href:e}=new URL(t);return s.test(e)&&e}catch(t){return!1}},{flattie:U}=o,L=u,{default:N}=k;class I extends Error{constructor(t){super(),this.name="MicrolinkError",Object.assign(this,t),this.description=this.message,this.message=this.code?`${this.code}, ${this.description}`:this.description}}const D=L({MicrolinkError:I,urlHttp:S,got:async(t,e)=>{try{e.retry>0&&(e.retry=e.retry+1),void 0===e.timeout&&(e.timeout=!1);const r=await N(t,e),s=await r.json(),{headers:o,status:n}=r;return{url:r.url,body:s,headers:o,statusCode:n}}catch(t){if(t.response){const{response:e}=t;t.response={...e,headers:Array.from(e.headers.entries()).reduce(((t,[e,r])=>(t[e]=r,t)),{}),statusCode:e.status,body:await e.text()}}throw t}},flatten:U,VERSION:"0.11.6-3"});r.exports=D;var M=r.exports.MicrolinkError=D.MicrolinkError,H=r.exports.getApiUrl=D.getApiUrl,$=r.exports.mapRules=D.mapRules,B=r.exports.version=D.version,F=t(r.exports);export{M as MicrolinkError,F as default,H as getApiUrl,$ as mapRules,B as version};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@microlink/mql",
3
3
  "description": "Microlink Query Language. The official HTTP client to interact with Microlink API for Node.js, browsers & Deno.",
4
4
  "homepage": "https://microlink.io/mql",
5
- "version": "0.11.6-1",
5
+ "version": "0.11.6-3",
6
6
  "types": "lightweight/index.d.ts",
7
7
  "exports": {
8
8
  "require": "./src/node.js",
@@ -86,7 +86,8 @@
86
86
  },
87
87
  "files": [
88
88
  "lightweight",
89
- "src"
89
+ "src/factory.js",
90
+ "src/node.js"
90
91
  ],
91
92
  "license": "MIT",
92
93
  "ava": {
@@ -119,8 +120,8 @@
119
120
  },
120
121
  "standard": {
121
122
  "ignore": [
122
- "src/node.mjs",
123
- "lightweight/index.js"
123
+ "lightweight/index.js",
124
+ "src/node.mjs"
124
125
  ]
125
126
  },
126
127
  "standard-version": {
package/src/ky.js DELETED
@@ -1,559 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ky = {}));
5
- })(this, (function (exports) { 'use strict';
6
-
7
- // eslint-lint-disable-next-line @typescript-eslint/naming-convention
8
- class HTTPError extends Error {
9
- constructor(response, request, options) {
10
- const code = (response.status || response.status === 0) ? response.status : '';
11
- const title = response.statusText || '';
12
- const status = `${code} ${title}`.trim();
13
- const reason = status ? `status code ${status}` : 'an unknown error';
14
- super(`Request failed with ${reason}`);
15
- Object.defineProperty(this, "response", {
16
- enumerable: true,
17
- configurable: true,
18
- writable: true,
19
- value: void 0
20
- });
21
- Object.defineProperty(this, "request", {
22
- enumerable: true,
23
- configurable: true,
24
- writable: true,
25
- value: void 0
26
- });
27
- Object.defineProperty(this, "options", {
28
- enumerable: true,
29
- configurable: true,
30
- writable: true,
31
- value: void 0
32
- });
33
- this.name = 'HTTPError';
34
- this.response = response;
35
- this.request = request;
36
- this.options = options;
37
- }
38
- }
39
-
40
- class TimeoutError extends Error {
41
- constructor(request) {
42
- super('Request timed out');
43
- Object.defineProperty(this, "request", {
44
- enumerable: true,
45
- configurable: true,
46
- writable: true,
47
- value: void 0
48
- });
49
- this.name = 'TimeoutError';
50
- this.request = request;
51
- }
52
- }
53
-
54
- // eslint-disable-next-line @typescript-eslint/ban-types
55
- const isObject = (value) => value !== null && typeof value === 'object';
56
-
57
- const validateAndMerge = (...sources) => {
58
- for (const source of sources) {
59
- if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {
60
- throw new TypeError('The `options` argument must be an object');
61
- }
62
- }
63
- return deepMerge({}, ...sources);
64
- };
65
- const mergeHeaders = (source1 = {}, source2 = {}) => {
66
- const result = new globalThis.Headers(source1);
67
- const isHeadersInstance = source2 instanceof globalThis.Headers;
68
- const source = new globalThis.Headers(source2);
69
- for (const [key, value] of source.entries()) {
70
- if ((isHeadersInstance && value === 'undefined') || value === undefined) {
71
- result.delete(key);
72
- }
73
- else {
74
- result.set(key, value);
75
- }
76
- }
77
- return result;
78
- };
79
- // TODO: Make this strongly-typed (no `any`).
80
- const deepMerge = (...sources) => {
81
- let returnValue = {};
82
- let headers = {};
83
- for (const source of sources) {
84
- if (Array.isArray(source)) {
85
- if (!Array.isArray(returnValue)) {
86
- returnValue = [];
87
- }
88
- returnValue = [...returnValue, ...source];
89
- }
90
- else if (isObject(source)) {
91
- for (let [key, value] of Object.entries(source)) {
92
- if (isObject(value) && key in returnValue) {
93
- value = deepMerge(returnValue[key], value);
94
- }
95
- returnValue = { ...returnValue, [key]: value };
96
- }
97
- if (isObject(source.headers)) {
98
- headers = mergeHeaders(headers, source.headers);
99
- returnValue.headers = headers;
100
- }
101
- }
102
- }
103
- return returnValue;
104
- };
105
-
106
- const supportsRequestStreams = (() => {
107
- let duplexAccessed = false;
108
- let hasContentType = false;
109
- const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
110
- const supportsRequest = typeof globalThis.Request === 'function';
111
- if (supportsReadableStream && supportsRequest) {
112
- hasContentType = new globalThis.Request('https://empty.invalid', {
113
- body: new globalThis.ReadableStream(),
114
- method: 'POST',
115
- // @ts-expect-error - Types are outdated.
116
- get duplex() {
117
- duplexAccessed = true;
118
- return 'half';
119
- },
120
- }).headers.has('Content-Type');
121
- }
122
- return duplexAccessed && !hasContentType;
123
- })();
124
- const supportsAbortController = typeof globalThis.AbortController === 'function';
125
- const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';
126
- const supportsFormData = typeof globalThis.FormData === 'function';
127
- const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
128
- const responseTypes = {
129
- json: 'application/json',
130
- text: 'text/*',
131
- formData: 'multipart/form-data',
132
- arrayBuffer: '*/*',
133
- blob: '*/*',
134
- };
135
- // The maximum value of a 32bit int (see issue #117)
136
- const maxSafeTimeout = 2147483647;
137
- const stop = Symbol('stop');
138
- const kyOptionKeys = {
139
- json: true,
140
- parseJson: true,
141
- searchParams: true,
142
- prefixUrl: true,
143
- retry: true,
144
- timeout: true,
145
- hooks: true,
146
- throwHttpErrors: true,
147
- onDownloadProgress: true,
148
- fetch: true,
149
- };
150
- const requestOptionsRegistry = {
151
- method: true,
152
- headers: true,
153
- body: true,
154
- mode: true,
155
- credentials: true,
156
- cache: true,
157
- redirect: true,
158
- referrer: true,
159
- referrerPolicy: true,
160
- integrity: true,
161
- keepalive: true,
162
- signal: true,
163
- window: true,
164
- dispatcher: true,
165
- duplex: true,
166
- };
167
-
168
- const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
169
- const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
170
- const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
171
- const retryAfterStatusCodes = [413, 429, 503];
172
- const defaultRetryOptions = {
173
- limit: 2,
174
- methods: retryMethods,
175
- statusCodes: retryStatusCodes,
176
- afterStatusCodes: retryAfterStatusCodes,
177
- maxRetryAfter: Number.POSITIVE_INFINITY,
178
- backoffLimit: Number.POSITIVE_INFINITY,
179
- delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,
180
- };
181
- const normalizeRetryOptions = (retry = {}) => {
182
- if (typeof retry === 'number') {
183
- return {
184
- ...defaultRetryOptions,
185
- limit: retry,
186
- };
187
- }
188
- if (retry.methods && !Array.isArray(retry.methods)) {
189
- throw new Error('retry.methods must be an array');
190
- }
191
- if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
192
- throw new Error('retry.statusCodes must be an array');
193
- }
194
- return {
195
- ...defaultRetryOptions,
196
- ...retry,
197
- afterStatusCodes: retryAfterStatusCodes,
198
- };
199
- };
200
-
201
- // `Promise.race()` workaround (#91)
202
- async function timeout(request, init, abortController, options) {
203
- return new Promise((resolve, reject) => {
204
- const timeoutId = setTimeout(() => {
205
- if (abortController) {
206
- abortController.abort();
207
- }
208
- reject(new TimeoutError(request));
209
- }, options.timeout);
210
- void options
211
- .fetch(request, init)
212
- .then(resolve)
213
- .catch(reject)
214
- .then(() => {
215
- clearTimeout(timeoutId);
216
- });
217
- });
218
- }
219
-
220
- // https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111
221
- async function delay(ms, { signal }) {
222
- return new Promise((resolve, reject) => {
223
- if (signal) {
224
- signal.throwIfAborted();
225
- signal.addEventListener('abort', abortHandler, { once: true });
226
- }
227
- function abortHandler() {
228
- clearTimeout(timeoutId);
229
- reject(signal.reason);
230
- }
231
- const timeoutId = setTimeout(() => {
232
- signal?.removeEventListener('abort', abortHandler);
233
- resolve();
234
- }, ms);
235
- });
236
- }
237
-
238
- const findUnknownOptions = (request, options) => {
239
- const unknownOptions = {};
240
- for (const key in options) {
241
- if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys) && !(key in request)) {
242
- unknownOptions[key] = options[key];
243
- }
244
- }
245
- return unknownOptions;
246
- };
247
-
248
- class Ky {
249
- static create(input, options) {
250
- const ky = new Ky(input, options);
251
- const fn = async () => {
252
- if (typeof ky._options.timeout === 'number' && ky._options.timeout > maxSafeTimeout) {
253
- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
254
- }
255
- // Delay the fetch so that body method shortcuts can set the Accept header
256
- await Promise.resolve();
257
- let response = await ky._fetch();
258
- for (const hook of ky._options.hooks.afterResponse) {
259
- // eslint-disable-next-line no-await-in-loop
260
- const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
261
- if (modifiedResponse instanceof globalThis.Response) {
262
- response = modifiedResponse;
263
- }
264
- }
265
- ky._decorateResponse(response);
266
- if (!response.ok && ky._options.throwHttpErrors) {
267
- let error = new HTTPError(response, ky.request, ky._options);
268
- for (const hook of ky._options.hooks.beforeError) {
269
- // eslint-disable-next-line no-await-in-loop
270
- error = await hook(error);
271
- }
272
- throw error;
273
- }
274
- // If `onDownloadProgress` is passed, it uses the stream API internally
275
- /* istanbul ignore next */
276
- if (ky._options.onDownloadProgress) {
277
- if (typeof ky._options.onDownloadProgress !== 'function') {
278
- throw new TypeError('The `onDownloadProgress` option must be a function');
279
- }
280
- if (!supportsResponseStreams) {
281
- throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
282
- }
283
- return ky._stream(response.clone(), ky._options.onDownloadProgress);
284
- }
285
- return response;
286
- };
287
- const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
288
- const result = (isRetriableMethod ? ky._retry(fn) : fn());
289
- for (const [type, mimeType] of Object.entries(responseTypes)) {
290
- result[type] = async () => {
291
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
292
- ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
293
- const awaitedResult = await result;
294
- const response = awaitedResult.clone();
295
- if (type === 'json') {
296
- if (response.status === 204) {
297
- return '';
298
- }
299
- const arrayBuffer = await response.clone().arrayBuffer();
300
- const responseSize = arrayBuffer.byteLength;
301
- if (responseSize === 0) {
302
- return '';
303
- }
304
- if (options.parseJson) {
305
- return options.parseJson(await response.text());
306
- }
307
- }
308
- return response[type]();
309
- };
310
- }
311
- return result;
312
- }
313
- // eslint-disable-next-line complexity
314
- constructor(input, options = {}) {
315
- Object.defineProperty(this, "request", {
316
- enumerable: true,
317
- configurable: true,
318
- writable: true,
319
- value: void 0
320
- });
321
- Object.defineProperty(this, "abortController", {
322
- enumerable: true,
323
- configurable: true,
324
- writable: true,
325
- value: void 0
326
- });
327
- Object.defineProperty(this, "_retryCount", {
328
- enumerable: true,
329
- configurable: true,
330
- writable: true,
331
- value: 0
332
- });
333
- Object.defineProperty(this, "_input", {
334
- enumerable: true,
335
- configurable: true,
336
- writable: true,
337
- value: void 0
338
- });
339
- Object.defineProperty(this, "_options", {
340
- enumerable: true,
341
- configurable: true,
342
- writable: true,
343
- value: void 0
344
- });
345
- this._input = input;
346
- this._options = {
347
- // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
348
- credentials: this._input.credentials || 'same-origin',
349
- ...options,
350
- headers: mergeHeaders(this._input.headers, options.headers),
351
- hooks: deepMerge({
352
- beforeRequest: [],
353
- beforeRetry: [],
354
- beforeError: [],
355
- afterResponse: [],
356
- }, options.hooks),
357
- method: normalizeRequestMethod(options.method ?? this._input.method),
358
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
359
- prefixUrl: String(options.prefixUrl || ''),
360
- retry: normalizeRetryOptions(options.retry),
361
- throwHttpErrors: options.throwHttpErrors !== false,
362
- timeout: options.timeout ?? 10000,
363
- fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
364
- };
365
- if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
366
- throw new TypeError('`input` must be a string, URL, or Request');
367
- }
368
- if (this._options.prefixUrl && typeof this._input === 'string') {
369
- if (this._input.startsWith('/')) {
370
- throw new Error('`input` must not begin with a slash when using `prefixUrl`');
371
- }
372
- if (!this._options.prefixUrl.endsWith('/')) {
373
- this._options.prefixUrl += '/';
374
- }
375
- this._input = this._options.prefixUrl + this._input;
376
- }
377
- if (supportsAbortController) {
378
- this.abortController = new globalThis.AbortController();
379
- if (this._options.signal) {
380
- const originalSignal = this._options.signal;
381
- this._options.signal.addEventListener('abort', () => {
382
- this.abortController.abort(originalSignal.reason);
383
- });
384
- }
385
- this._options.signal = this.abortController.signal;
386
- }
387
- if (supportsRequestStreams) {
388
- // @ts-expect-error - Types are outdated.
389
- this._options.duplex = 'half';
390
- }
391
- this.request = new globalThis.Request(this._input, this._options);
392
- if (this._options.searchParams) {
393
- // eslint-disable-next-line unicorn/prevent-abbreviations
394
- const textSearchParams = typeof this._options.searchParams === 'string'
395
- ? this._options.searchParams.replace(/^\?/, '')
396
- : new URLSearchParams(this._options.searchParams).toString();
397
- // eslint-disable-next-line unicorn/prevent-abbreviations
398
- const searchParams = '?' + textSearchParams;
399
- const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
400
- // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
401
- if (((supportsFormData && this._options.body instanceof globalThis.FormData)
402
- || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
403
- this.request.headers.delete('content-type');
404
- }
405
- // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.
406
- this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);
407
- }
408
- if (this._options.json !== undefined) {
409
- this._options.body = JSON.stringify(this._options.json);
410
- this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
411
- this.request = new globalThis.Request(this.request, { body: this._options.body });
412
- }
413
- }
414
- _calculateRetryDelay(error) {
415
- this._retryCount++;
416
- if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
417
- if (error instanceof HTTPError) {
418
- if (!this._options.retry.statusCodes.includes(error.response.status)) {
419
- return 0;
420
- }
421
- const retryAfter = error.response.headers.get('Retry-After');
422
- if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
423
- let after = Number(retryAfter);
424
- if (Number.isNaN(after)) {
425
- after = Date.parse(retryAfter) - Date.now();
426
- }
427
- else {
428
- after *= 1000;
429
- }
430
- if (this._options.retry.maxRetryAfter !== undefined && after > this._options.retry.maxRetryAfter) {
431
- return 0;
432
- }
433
- return after;
434
- }
435
- if (error.response.status === 413) {
436
- return 0;
437
- }
438
- }
439
- const retryDelay = this._options.retry.delay(this._retryCount);
440
- return Math.min(this._options.retry.backoffLimit, retryDelay);
441
- }
442
- return 0;
443
- }
444
- _decorateResponse(response) {
445
- if (this._options.parseJson) {
446
- response.json = async () => this._options.parseJson(await response.text());
447
- }
448
- return response;
449
- }
450
- async _retry(fn) {
451
- try {
452
- return await fn();
453
- }
454
- catch (error) {
455
- const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
456
- if (ms !== 0 && this._retryCount > 0) {
457
- await delay(ms, { signal: this._options.signal });
458
- for (const hook of this._options.hooks.beforeRetry) {
459
- // eslint-disable-next-line no-await-in-loop
460
- const hookResult = await hook({
461
- request: this.request,
462
- options: this._options,
463
- error: error,
464
- retryCount: this._retryCount,
465
- });
466
- // If `stop` is returned from the hook, the retry process is stopped
467
- if (hookResult === stop) {
468
- return;
469
- }
470
- }
471
- return this._retry(fn);
472
- }
473
- throw error;
474
- }
475
- }
476
- async _fetch() {
477
- for (const hook of this._options.hooks.beforeRequest) {
478
- // eslint-disable-next-line no-await-in-loop
479
- const result = await hook(this.request, this._options);
480
- if (result instanceof Request) {
481
- this.request = result;
482
- break;
483
- }
484
- if (result instanceof Response) {
485
- return result;
486
- }
487
- }
488
- const nonRequestOptions = findUnknownOptions(this.request, this._options);
489
- if (this._options.timeout === false) {
490
- return this._options.fetch(this.request.clone(), nonRequestOptions);
491
- }
492
- return timeout(this.request.clone(), nonRequestOptions, this.abortController, this._options);
493
- }
494
- /* istanbul ignore next */
495
- _stream(response, onDownloadProgress) {
496
- const totalBytes = Number(response.headers.get('content-length')) || 0;
497
- let transferredBytes = 0;
498
- if (response.status === 204) {
499
- if (onDownloadProgress) {
500
- onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
501
- }
502
- return new globalThis.Response(null, {
503
- status: response.status,
504
- statusText: response.statusText,
505
- headers: response.headers,
506
- });
507
- }
508
- return new globalThis.Response(new globalThis.ReadableStream({
509
- async start(controller) {
510
- const reader = response.body.getReader();
511
- if (onDownloadProgress) {
512
- onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
513
- }
514
- async function read() {
515
- const { done, value } = await reader.read();
516
- if (done) {
517
- controller.close();
518
- return;
519
- }
520
- if (onDownloadProgress) {
521
- transferredBytes += value.byteLength;
522
- const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
523
- onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
524
- }
525
- controller.enqueue(value);
526
- await read();
527
- }
528
- await read();
529
- },
530
- }), {
531
- status: response.status,
532
- statusText: response.statusText,
533
- headers: response.headers,
534
- });
535
- }
536
- }
537
-
538
- /*! MIT License © Sindre Sorhus */
539
- const createInstance = (defaults) => {
540
- // eslint-disable-next-line @typescript-eslint/promise-function-async
541
- const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
542
- for (const method of requestMethods) {
543
- // eslint-disable-next-line @typescript-eslint/promise-function-async
544
- ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
545
- }
546
- ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
547
- ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
548
- ky.stop = stop;
549
- return ky;
550
- };
551
- const ky = createInstance();
552
-
553
- exports.HTTPError = HTTPError;
554
- exports.TimeoutError = TimeoutError;
555
- exports.default = ky;
556
-
557
- Object.defineProperty(exports, '__esModule', { value: true });
558
-
559
- }));
@@ -1,60 +0,0 @@
1
- 'use strict'
2
-
3
- const urlHttp = require('url-http/lightweight')
4
- const { flattie: flatten } = require('flattie')
5
- const factory = require('./factory')
6
- const { default: ky } = require('ky')
7
-
8
- class MicrolinkError extends Error {
9
- constructor (props) {
10
- super()
11
- this.name = 'MicrolinkError'
12
- Object.assign(this, props)
13
- this.description = this.message
14
- this.message = this.code
15
- ? `${this.code}, ${this.description}`
16
- : this.description
17
- }
18
- }
19
-
20
- const got = async (url, opts) => {
21
- try {
22
- if (opts.retry > 0) opts.retry = opts.retry + 1
23
- if (opts.timeout === undefined) opts.timeout = false
24
- const response = await ky(url, opts)
25
- const body = await response.json()
26
- const { headers, status: statusCode } = response
27
- return { url: response.url, body, headers, statusCode }
28
- } catch (err) {
29
- if (err.response) {
30
- const { response } = err
31
- err.response = {
32
- ...response,
33
- headers: Array.from(response.headers.entries()).reduce(
34
- (acc, [key, value]) => {
35
- acc[key] = value
36
- return acc
37
- },
38
- {}
39
- ),
40
- statusCode: response.status,
41
- body: await response.text()
42
- }
43
- }
44
- throw err
45
- }
46
- }
47
-
48
- const mql = factory({
49
- MicrolinkError,
50
- urlHttp,
51
- got,
52
- flatten,
53
- VERSION: '__MQL_VERSION__'
54
- })
55
-
56
- module.exports = mql
57
- module.exports.MicrolinkError = mql.MicrolinkError
58
- module.exports.getApiUrl = mql.getApiUrl
59
- module.exports.mapRules = mql.mapRules
60
- module.exports.version = mql.version
package/src/node.d.ts DELETED
@@ -1,29 +0,0 @@
1
- import { MqlPayload, MqlOptions, MicrolinkApiOptions } from '../lightweight'
2
-
3
- export { MqlError, MqlPayload } from '../lightweight'
4
-
5
- export type MqlResponse = MqlPayload & {
6
- response: {
7
- url: string;
8
- isFromCache?: boolean;
9
- statusCode: number;
10
- headers: { [key: string]: string };
11
- body: MqlPayload
12
- };
13
- }
14
-
15
- declare function mql(
16
- url: string,
17
- opts?: MqlOptions & MicrolinkApiOptions,
18
- gotOpts?: object
19
- ): Promise<MqlResponse>;
20
-
21
- declare namespace mql {
22
- function stream(
23
- url: string,
24
- opts?: MqlOptions & MicrolinkApiOptions,
25
- gotOpts?: object
26
- ): NodeJS.ReadableStream;
27
- }
28
-
29
- export default mql;
package/src/node.mjs DELETED
@@ -1,158 +0,0 @@
1
- import require$$0 from 'whoops';
2
- import require$$1 from 'url-http/lightweight';
3
- import require$$2 from 'got';
4
- import * as require$$3 from 'flattie';
5
-
6
- function getDefaultExportFromCjs (x) {
7
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
8
- }
9
-
10
- var node$1 = {exports: {}};
11
-
12
- const ENDPOINT = {
13
- FREE: 'https://api.microlink.io/',
14
- PRO: 'https://pro.microlink.io/'
15
- };
16
-
17
- const isObject = input => input !== null && typeof input === 'object';
18
-
19
- const isBuffer = input =>
20
- input != null &&
21
- input.constructor != null &&
22
- typeof input.constructor.isBuffer === 'function' &&
23
- input.constructor.isBuffer(input);
24
-
25
- const parseBody = (input, error, url) => {
26
- try {
27
- return JSON.parse(input)
28
- } catch (_) {
29
- const message = input || error.message;
30
-
31
- return {
32
- status: 'error',
33
- data: { url: message },
34
- more: 'https://microlink.io/efatalclient',
35
- code: 'EFATALCLIENT',
36
- message,
37
- url
38
- }
39
- }
40
- };
41
-
42
- const factory = ({ VERSION, MicrolinkError, urlHttp, got, flatten }) => {
43
- const assertUrl = (url = '') => {
44
- if (!urlHttp(url)) {
45
- const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
46
- throw new MicrolinkError({
47
- status: 'fail',
48
- data: { url: message },
49
- more: 'https://microlink.io/docs/api/api-parameters/url',
50
- code: 'EINVALURLCLIENT',
51
- message,
52
- url
53
- })
54
- }
55
- };
56
-
57
- const mapRules = rules => {
58
- if (!isObject(rules)) return
59
- const flatRules = flatten(rules);
60
- return Object.keys(flatRules).reduce((acc, key) => {
61
- acc[`data.${key}`] = flatRules[key].toString();
62
- return acc
63
- }, {})
64
- };
65
-
66
- const fetchFromApi = async (apiUrl, opts = {}) => {
67
- try {
68
- const response = await got(apiUrl, opts);
69
- return opts.responseType === 'buffer'
70
- ? { body: response.body, response }
71
- : { ...response.body, response }
72
- } catch (err) {
73
- const { response = {} } = err;
74
- const {
75
- statusCode,
76
- body: rawBody,
77
- headers = {},
78
- url: uri = apiUrl
79
- } = response;
80
- const isBodyBuffer = isBuffer(rawBody);
81
-
82
- const body =
83
- isObject(rawBody) && !isBodyBuffer
84
- ? rawBody
85
- : parseBody(isBodyBuffer ? rawBody.toString() : rawBody, err, uri);
86
-
87
- throw new MicrolinkError({
88
- ...body,
89
- message: body.message,
90
- url: uri,
91
- statusCode,
92
- headers
93
- })
94
- }
95
- };
96
-
97
- const getApiUrl = (
98
- url,
99
- { data, apiKey, endpoint, retry, cache, ...opts } = {},
100
- { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
101
- ) => {
102
- const isPro = !!apiKey;
103
- const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE'];
104
-
105
- const apiUrl = `${apiEndpoint}?${new URLSearchParams({
106
- url,
107
- ...mapRules(data),
108
- ...flatten(opts)
109
- }).toString()}`;
110
-
111
- const headers = isPro
112
- ? { ...gotHeaders, 'x-api-key': apiKey }
113
- : { ...gotHeaders };
114
- return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
115
- };
116
-
117
- const createMql = defaultOpts => async (url, opts, gotOpts) => {
118
- assertUrl(url);
119
- const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
120
- ...defaultOpts,
121
- ...gotOpts
122
- });
123
- return fetchFromApi(apiUrl, fetchOpts)
124
- };
125
-
126
- const mql = createMql();
127
- mql.MicrolinkError = MicrolinkError;
128
- mql.getApiUrl = getApiUrl;
129
- mql.fetchFromApi = fetchFromApi;
130
- mql.mapRules = mapRules;
131
- mql.version = VERSION;
132
- mql.stream = got.stream;
133
- mql.buffer = createMql({ responseType: 'buffer' });
134
-
135
- return mql
136
- };
137
-
138
- var factory_1 = factory;
139
-
140
- node$1.exports = factory_1({
141
- MicrolinkError: require$$0('MicrolinkError'),
142
- urlHttp: require$$1,
143
- got: require$$2.extend({ headers: { 'user-agent': undefined } }),
144
- flatten: require$$3.flattie,
145
- VERSION: '0.11.6-0'
146
- });
147
-
148
- var render = node$1.exports.render = (input, { width = '650px' } = {}) => {
149
- if (input && input.url && input.type) {
150
- return `<img width="${width}" src="${input.url}" />`
151
- }
152
- return input
153
- };
154
-
155
- var nodeExports = node$1.exports;
156
- var node = /*@__PURE__*/getDefaultExportFromCjs(nodeExports);
157
-
158
- export { node as default, render };