@microlink/mql 0.10.39 → 0.11.0-0

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.
package/dist/mql.min.js CHANGED
@@ -1,3 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).mql=e()}(this,(function(){"use strict";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}const e=/^https?:\/\//i;var r={};function s(t,e,r,o,n){var i,a=n?n+r:n;if(null==o)e&&(t[n]=o);else if("object"!=typeof o)t[n]=o;else if(Array.isArray(o))for(i=0;i<o.length;i++)s(t,e,r,o[i],a+i);else for(i in o)s(t,e,r,o[i],a+i)}r.flattie=function(t,e,r){var o={};return"object"==typeof t&&s(o,!!r,e||".",t,""),o};const o={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},n=t=>null!==t&&"object"==typeof t;var i=({VERSION:t,MicrolinkError:e,urlHttp:r,got:s,flatten:i})=>{const a=t=>{if(!n(t))return;const e=i(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:i,body:a,headers:u={},url:l=t}=s,h=null!=(o=a)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),c=n(a)&&!h?a:((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}}})(h?a.toString():a,r,l);throw new e({...c,message:c.message,url:l,statusCode:i,headers:u})}var o},l=(t,{data:e,apiKey:r,endpoint:s,retry:n,cache:u,...l}={},{responseType:h="json",headers:c,...p}={})=>{const f=!!r;return[`${s||o[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...a(e),...i(l)}).toString()}`,{...p,responseType:h,cache:u,retry:n,headers:f?{...c,"x-api-key":r}:{...c}}]},h=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)},c=h();return c.MicrolinkError=e,c.getApiUrl=l,c.fetchFromApi=u,c.mapRules=a,c.version=t,c.stream=s.stream,c.buffer=h({responseType:"buffer"}),c},a={exports:{}};!function(t,e){!function(t){class e 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 r 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 s=t=>null!==t&&"object"==typeof t,o=(...t)=>{for(const e of t)if((!s(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return i({},...t)},n=(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},i=(...t)=>{let e={},r={};for(const o of t)if(Array.isArray(o))Array.isArray(e)||(e=[]),e=[...e,...o];else if(s(o)){for(let[t,r]of Object.entries(o))s(r)&&t in e&&(r=i(e[t],r)),e={...e,[t]:r};s(o.headers)&&(r=n(r,o.headers),e.headers=r)}return e},a=(()=>{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})(),u="function"==typeof globalThis.AbortController,l="function"==typeof globalThis.ReadableStream,h="function"==typeof globalThis.FormData,c=["get","post","put","patch","head","delete"],p={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},f=2147483647,d=Symbol("stop"),y=t=>c.includes(t)?t.toUpperCase():t,b=[413,429,503],m={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:b,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY},w=(t={})=>{if("number"==typeof t)return{...m,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{...m,...t,afterStatusCodes:b}};async function g(t,e,s){return new Promise(((o,n)=>{const i=setTimeout((()=>{e&&e.abort(),n(new r(t))}),s.timeout);s.fetch(t).then(o).catch(n).then((()=>{clearTimeout(i)}))}))}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)}))}class T{static create(t,r){const s=new T(t,r),o=async()=>{if("number"==typeof s._options.timeout&&s._options.timeout>f)throw new RangeError(`The \`timeout\` option cannot be greater than ${f}`);await Promise.resolve();let t=await s._fetch();for(const e of s._options.hooks.afterResponse){const r=await e(s.request,s._options,s._decorateResponse(t.clone()));r instanceof globalThis.Response&&(t=r)}if(s._decorateResponse(t),!t.ok&&s._options.throwHttpErrors){let r=new e(t,s.request,s._options);for(const t of s._options.hooks.beforeError)r=await t(r);throw r}if(s._options.onDownloadProgress){if("function"!=typeof s._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!l)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return s._stream(t.clone(),s._options.onDownloadProgress)}return t},n=s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(o):o();for(const[t,e]of Object.entries(p))n[t]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||e);const o=(await n).clone();if("json"===t){if(204===o.status)return"";if(0===(await o.clone().arrayBuffer()).byteLength)return"";if(r.parseJson)return r.parseJson(await o.text())}return o[t]()};return n}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:n(this._input.headers,e.headers),hooks:i({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:y(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:w(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(u){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(a&&(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);!(h&&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 r)){if(t instanceof e){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 r=.3;return Math.min(this._options.retry.backoffLimit,r*2**(this._retryCount-1)*1e3)}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),f);if(0!==r&&this._retryCount>0){await _(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})===d)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}return!1===this._options.timeout?this._options.fetch(this.request.clone()):g(this.request.clone(),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();async function i(){const{done:t,value:a}=await n.read();t?o.close():(e&&(s+=a.byteLength,e({percent:0===r?0:s/r,transferredBytes:s,totalBytes:r},a)),o.enqueue(a),await i())}e&&e({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await i()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}
2
- /*! MIT License © Sindre Sorhus */const R=t=>{const e=(e,r)=>T.create(e,o(t,r));for(const r of c)e[r]=(e,s)=>T.create(e,o(t,s,{method:r}));return e.create=t=>R(o(t)),e.extend=e=>R(o(t,e)),e.stop=d,e},E=R();t.HTTPError=e,t.TimeoutError=r,t.default=E,Object.defineProperty(t,"__esModule",{value:!0})}(e)}(0,a.exports);var u=a.exports;const l=t=>{try{const{href:r}=new URL(t);return e.test(r)&&r}catch(t){return!1}},{flattie:h}=r,c=i,{default:p}=u;class f 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}}return t(c({MicrolinkError:f,urlHttp:l,got:async(t,e)=>{try{e.retry>0&&(e.retry=e.retry+1),void 0===e.timeout&&(e.timeout=!1);const r=await p(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:h,VERSION:"0.10.39"}))}));
3
- //# sourceMappingURL=mql.min.js.map
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).mql=e()}(this,(function(){"use strict";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}const r=/^https?:\/\//i;var s={};function o(t,e,r,s,n){var i,a=n?n+r:n;if(null==s)e&&(t[n]=s);else if("object"!=typeof s)t[n]=s;else if(Array.isArray(s))for(i=0;i<s.length;i++)o(t,e,r,s[i],a+i);else for(i in s)o(t,e,r,s[i],a+i)}s.flattie=function(t,e,r){var s={};return"object"==typeof t&&o(s,!!r,e||".",t,""),s};const n={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},i=t=>null!==t&&"object"==typeof t;var a=({VERSION:t,MicrolinkError:e,urlHttp:r,got:s,flatten:o})=>{const a=t=>{if(!i(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:a,headers:u={},url:l=t}=s,h=null!=(o=a)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),c=i(a)&&!h?a:((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}}})(h?a.toString():a,r,l);throw new e({...c,message:c.message,url:l,statusCode:n,headers:u})}var o},l=(t,{data:e,apiKey:r,endpoint:s,retry:i,cache:u,...l}={},{responseType:h="json",headers:c,...p}={})=>{const f=!!r;return[`${s||n[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...a(e),...o(l)}).toString()}`,{...p,responseType:h,cache:u,retry:i,headers:f?{...c,"x-api-key":r}:{...c}}]},h=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)},c=h();return c.MicrolinkError=e,c.getApiUrl=l,c.fetchFromApi=u,c.mapRules=a,c.version=t,c.stream=s.stream,c.buffer=h({responseType:"buffer"}),c};class u 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 l 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,c=(...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 f({},...t)},p=(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},f=(...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=f(e[t],r)),e={...e,[t]:r};h(s.headers)&&(r=p(r,s.headers),e.headers=r)}return e},d=(()=>{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})(),y="function"==typeof globalThis.AbortController,b="function"==typeof globalThis.ReadableStream,m="function"==typeof globalThis.FormData,_=["get","post","put","patch","head","delete"],g={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},w=2147483647,T=Symbol("stop"),R=t=>_.includes(t)?t.toUpperCase():t,v=[413,429,503],E={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:v,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY},q=(t={})=>{if("number"==typeof t)return{...E,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{...E,...t,afterStatusCodes:v}};class j{static create(t,e){const r=new j(t,e),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>w)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 u(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(!b)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:p(this._input.headers,e.headers),hooks:f({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:R(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:q(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(y){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(d&&(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);!(m&&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 l)){if(t instanceof u){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=.3;return Math.min(this._options.retry.backoffLimit,e*2**(this._retryCount-1)*1e3)}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),w);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})===T)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}return!1===this._options.timeout?this._options.fetch(this.request.clone()):async function(t,e,r){return new Promise(((s,o)=>{const n=setTimeout((()=>{e&&e.abort(),o(new l(t))}),r.timeout);r.fetch(t).then(s).catch(o).then((()=>{clearTimeout(n)}))}))}(this.request.clone(),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})}}
2
+ /*! MIT License © Sindre Sorhus */const P=t=>{const e=(e,r)=>j.create(e,c(t,r));for(const r of _)e[r]=(e,s)=>j.create(e,c(t,s,{method:r}));return e.create=t=>P(c(t)),e.extend=e=>P(c(t,e)),e.stop=T,e},C=P();var O=e(Object.freeze({__proto__:null,HTTPError:u,TimeoutError:l,default:C}));const x=t=>{try{const{href:e}=new URL(t);return r.test(e)&&e}catch(t){return!1}},{flattie:A}=s,S=a,{default:k}=O;class L 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}}return t(S({MicrolinkError:L,urlHttp:x,got:async(t,e)=>{try{e.retry>0&&(e.retry=e.retry+1),void 0===e.timeout&&(e.timeout=!1);const r=await k(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:A,VERSION:"0.10.39"}))}));
package/package.json CHANGED
@@ -2,18 +2,18 @@
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.10.39",
5
+ "version": "0.11.0-0",
6
6
  "types": "index.d.ts",
7
7
  "browser": "src/lightweight.js",
8
8
  "umd:main": "dist/mql.js",
9
9
  "unpkg": "dist/mql.js",
10
10
  "exports": {
11
11
  ".": {
12
- "import": "./dist/mql.js",
12
+ "import": "./src/node.mjs",
13
13
  "require": "./src/node.js"
14
14
  },
15
15
  "./lightweight": {
16
- "import": "./dist/mql.js",
16
+ "import": "./dist/lightweight.mjs",
17
17
  "require": "./src/lightweight.js"
18
18
  }
19
19
  },
@@ -55,16 +55,19 @@
55
55
  "query"
56
56
  ],
57
57
  "dependencies": {
58
+ "ky": "~1.0.0",
58
59
  "flattie": "~1.1.0",
59
60
  "got": "~11.8.6",
60
- "url-http": "~1.1.0",
61
+ "url-http": "^1.1.0",
61
62
  "whoops": "~4.1.1"
62
63
  },
63
64
  "devDependencies": {
65
+ "@chialab/cjs-to-esm": "~0.17.11",
64
66
  "@commitlint/cli": "latest",
65
67
  "@commitlint/config-conventional": "latest",
66
68
  "@ksmithut/prettier-standard": "latest",
67
69
  "@rollup/plugin-commonjs": "latest",
70
+ "@rollup/plugin-json": "~6.0.0",
68
71
  "@rollup/plugin-node-resolve": "latest",
69
72
  "@rollup/plugin-replace": "latest",
70
73
  "@rollup/plugin-terser": "latest",
@@ -75,12 +78,14 @@
75
78
  "conventional-github-releaser": "latest",
76
79
  "esm": "latest",
77
80
  "git-authors-cli": "latest",
78
- "ky": "latest",
79
81
  "nano-staged": "latest",
80
82
  "npm-check-updates": "latest",
81
83
  "prettier-standard": "latest",
82
84
  "rollup": "latest",
85
+ "rollup-plugin-cjs-es": "~2.0.0",
83
86
  "rollup-plugin-filesize": "latest",
87
+ "rollup-plugin-magic-string": "~1.0.4",
88
+ "rollup-plugin-rewrite": "~0.0.4",
84
89
  "rollup-plugin-visualizer": "latest",
85
90
  "simple-git-hooks": "latest",
86
91
  "standard": "latest",
@@ -98,25 +103,6 @@
98
103
  "lightweight",
99
104
  "src"
100
105
  ],
101
- "scripts": {
102
- "build": "rollup -c rollup.config.js --bundleConfigAsCjs",
103
- "build:kys": "[ -f src/ky.js ] || rollup node_modules/ky/distribution/index.js --format=umd --name=ky --exports=named --file=src/ky.js",
104
- "clean": "rm -rf node_modules",
105
- "clean:build": "rm -rf dist",
106
- "contributors": "(npx git-authors-cli && npx finepack --sort-ignore-object-at ava && git add package.json && git commit -m 'build: contributors' --no-verify) || true",
107
- "dev": "npm run build -- -w",
108
- "lint": "standard && tsd",
109
- "postrelease": "npm run release:tags && npm run release:github && (ci-publish || npm publish --access=public)",
110
- "prebuild": "npm run clean:build && npm run build:kys",
111
- "prerelease": "npm run update:check",
112
- "pretest": "npm run lint && npm run build",
113
- "release": "standard-version -a",
114
- "release:github": "conventional-github-releaser -p angular",
115
- "release:tags": "git push --follow-tags origin HEAD:master",
116
- "test": "c8 ava --verbose",
117
- "update": "ncu -u",
118
- "update:check": "ncu -- --error-level 2"
119
- },
120
106
  "license": "MIT",
121
107
  "ava": {
122
108
  "files": [
@@ -163,5 +149,24 @@
163
149
  },
164
150
  "tsd": {
165
151
  "directory": "test"
152
+ },
153
+ "scripts": {
154
+ "build": "rollup -c rollup.config.js --bundleConfigAsCjs",
155
+ "build:kys": "[ -f src/ky.js ] || rollup node_modules/ky/distribution/index.js --format=umd --name=ky --exports=named --file=src/ky.js",
156
+ "clean": "rm -rf node_modules",
157
+ "clean:build": "rm -rf dist",
158
+ "contributors": "(npx git-authors-cli && npx finepack --sort-ignore-object-at ava && git add package.json && git commit -m 'build: contributors' --no-verify) || true",
159
+ "dev": "npm run build -- -w",
160
+ "lint": "standard && tsd",
161
+ "postrelease": "npm run release:tags && npm run release:github && (ci-publish || npm publish --access=public)",
162
+ "prebuild": "npm run clean:build && npm run build:kys",
163
+ "prerelease": "npm run update:check",
164
+ "pretest": "npm run lint && npm run build",
165
+ "release": "standard-version -a",
166
+ "release:github": "conventional-github-releaser -p angular",
167
+ "release:tags": "git push --follow-tags origin HEAD:master",
168
+ "test": "c8 ava --verbose",
169
+ "update": "ncu -u",
170
+ "update:check": "ncu -- --error-level 2"
166
171
  }
167
- }
172
+ }
@@ -4,7 +4,7 @@ const urlHttp = require('url-http/lightweight')
4
4
  const { flattie: flatten } = require('flattie')
5
5
 
6
6
  const factory = require('./factory')
7
- const { default: ky } = require('./ky')
7
+ const { default: ky } = require('ky')
8
8
 
9
9
  class MicrolinkError extends Error {
10
10
  constructor (props) {
@@ -0,0 +1,193 @@
1
+ import require$$0 from 'url-http/lightweight';
2
+ import { flattie as require$$1 } from 'flattie';
3
+ import require$$3 from 'ky';
4
+
5
+ function getDefaultExportFromCjs (x) {
6
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
7
+ }
8
+
9
+ const ENDPOINT = {
10
+ FREE: 'https://api.microlink.io/',
11
+ PRO: 'https://pro.microlink.io/'
12
+ };
13
+
14
+ const isObject = input => input !== null && typeof input === 'object';
15
+
16
+ const isBuffer = input =>
17
+ input != null &&
18
+ input.constructor != null &&
19
+ typeof input.constructor.isBuffer === 'function' &&
20
+ input.constructor.isBuffer(input);
21
+
22
+ const parseBody = (input, error, url) => {
23
+ try {
24
+ return JSON.parse(input)
25
+ } catch (_) {
26
+ const message = input || error.message;
27
+
28
+ return {
29
+ status: 'error',
30
+ data: { url: message },
31
+ more: 'https://microlink.io/efatalclient',
32
+ code: 'EFATALCLIENT',
33
+ message,
34
+ url
35
+ }
36
+ }
37
+ };
38
+
39
+ const factory$1 = ({ VERSION, MicrolinkError, urlHttp, got, flatten }) => {
40
+ const assertUrl = (url = '') => {
41
+ if (!urlHttp(url)) {
42
+ const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
43
+ throw new MicrolinkError({
44
+ status: 'fail',
45
+ data: { url: message },
46
+ more: 'https://microlink.io/docs/api/api-parameters/url',
47
+ code: 'EINVALURLCLIENT',
48
+ message,
49
+ url
50
+ })
51
+ }
52
+ };
53
+
54
+ const mapRules = rules => {
55
+ if (!isObject(rules)) return
56
+ const flatRules = flatten(rules);
57
+ return Object.keys(flatRules).reduce((acc, key) => {
58
+ acc[`data.${key}`] = flatRules[key].toString();
59
+ return acc
60
+ }, {})
61
+ };
62
+
63
+ const fetchFromApi = async (apiUrl, opts = {}) => {
64
+ try {
65
+ const response = await got(apiUrl, opts);
66
+ return opts.responseType === 'buffer'
67
+ ? { body: response.body, response }
68
+ : { ...response.body, response }
69
+ } catch (err) {
70
+ const { response = {} } = err;
71
+ const {
72
+ statusCode,
73
+ body: rawBody,
74
+ headers = {},
75
+ url: uri = apiUrl
76
+ } = response;
77
+ const isBodyBuffer = isBuffer(rawBody);
78
+
79
+ const body =
80
+ isObject(rawBody) && !isBodyBuffer
81
+ ? rawBody
82
+ : parseBody(isBodyBuffer ? rawBody.toString() : rawBody, err, uri);
83
+
84
+ throw new MicrolinkError({
85
+ ...body,
86
+ message: body.message,
87
+ url: uri,
88
+ statusCode,
89
+ headers
90
+ })
91
+ }
92
+ };
93
+
94
+ const getApiUrl = (
95
+ url,
96
+ { data, apiKey, endpoint, retry, cache, ...opts } = {},
97
+ { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
98
+ ) => {
99
+ const isPro = !!apiKey;
100
+ const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE'];
101
+
102
+ const apiUrl = `${apiEndpoint}?${new URLSearchParams({
103
+ url,
104
+ ...mapRules(data),
105
+ ...flatten(opts)
106
+ }).toString()}`;
107
+
108
+ const headers = isPro
109
+ ? { ...gotHeaders, 'x-api-key': apiKey }
110
+ : { ...gotHeaders };
111
+ return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
112
+ };
113
+
114
+ const createMql = defaultOpts => async (url, opts, gotOpts) => {
115
+ assertUrl(url);
116
+ const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
117
+ ...defaultOpts,
118
+ ...gotOpts
119
+ });
120
+ return fetchFromApi(apiUrl, fetchOpts)
121
+ };
122
+
123
+ const mql = createMql();
124
+ mql.MicrolinkError = MicrolinkError;
125
+ mql.getApiUrl = getApiUrl;
126
+ mql.fetchFromApi = fetchFromApi;
127
+ mql.mapRules = mapRules;
128
+ mql.version = VERSION;
129
+ mql.stream = got.stream;
130
+ mql.buffer = createMql({ responseType: 'buffer' });
131
+
132
+ return mql
133
+ };
134
+
135
+ var factory_1 = factory$1;
136
+
137
+ const urlHttp = require$$0;
138
+ const { flattie: flatten } = require$$1;
139
+
140
+ const factory = factory_1;
141
+ const { default: ky } = require$$3;
142
+
143
+ class MicrolinkError extends Error {
144
+ constructor (props) {
145
+ super();
146
+ this.name = 'MicrolinkError';
147
+ Object.assign(this, props);
148
+ this.description = this.message;
149
+ this.message = this.code
150
+ ? `${this.code}, ${this.description}`
151
+ : this.description;
152
+ }
153
+ }
154
+
155
+ const got = async (url, opts) => {
156
+ try {
157
+ if (opts.retry > 0) opts.retry = opts.retry + 1;
158
+ if (opts.timeout === undefined) opts.timeout = false;
159
+ const response = await ky(url, opts);
160
+ const body = await response.json();
161
+ const { headers, status: statusCode } = response;
162
+ return { url: response.url, body, headers, statusCode }
163
+ } catch (err) {
164
+ if (err.response) {
165
+ const { response } = err;
166
+ err.response = {
167
+ ...response,
168
+ headers: Array.from(response.headers.entries()).reduce(
169
+ (acc, [key, value]) => {
170
+ acc[key] = value;
171
+ return acc
172
+ },
173
+ {}
174
+ ),
175
+ statusCode: response.status,
176
+ body: await response.text()
177
+ };
178
+ }
179
+ throw err
180
+ }
181
+ };
182
+
183
+ var lightweight = factory({
184
+ MicrolinkError,
185
+ urlHttp,
186
+ got,
187
+ flatten,
188
+ VERSION: '0.10.39'
189
+ });
190
+
191
+ var lightweight$1 = /*@__PURE__*/getDefaultExportFromCjs(lightweight);
192
+
193
+ export { lightweight$1 as default };
package/src/node.mjs ADDED
@@ -0,0 +1,158 @@
1
+ import require$$1 from 'whoops';
2
+ import require$$2 from 'url-http/lightweight';
3
+ import require$$3 from 'got';
4
+ import { flattie as require$$4 } 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$$1('MicrolinkError'),
142
+ urlHttp: require$$2,
143
+ got: require$$3.extend({ headers: { 'user-agent': undefined } }),
144
+ flatten: require$$4.flattie,
145
+ VERSION: '0.10.39'
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 };