@microlink/mql 0.12.3 → 0.13.1

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.
@@ -10,10 +10,10 @@ type ScreenshotOverlay = {
10
10
  }
11
11
 
12
12
  type PdfMargin = {
13
+ bottom?: string | number;
14
+ left?: string | number;
15
+ right?: string | number;
13
16
  top?: string | number;
14
- bottom?: string | number;
15
- left?: string | number;
16
- right?: string | number;
17
17
  }
18
18
 
19
19
  type PdfOptions = {
@@ -28,18 +28,19 @@ type PdfOptions = {
28
28
 
29
29
  type ScreenshotOptions = {
30
30
  codeScheme?: string;
31
- omitBackground?: boolean;
32
- type?: "jpeg" | "png";
33
31
  element?: string;
34
32
  fullPage?: boolean;
35
- overlay?: ScreenshotOverlay
33
+ omitBackground?: boolean;
34
+ optimizeForSpeed?: boolean;
35
+ overlay?: ScreenshotOverlay,
36
+ type?: "jpeg" | "png";
36
37
  }
37
38
 
38
39
  type MqlClientOptions = {
39
- endpoint?: string;
40
40
  apiKey?: string;
41
- retry?: number;
42
41
  cache?: Map<string, any>;
42
+ endpoint?: string;
43
+ retry?: number;
43
44
  }
44
45
 
45
46
  type MqlQuery = {
@@ -83,8 +84,9 @@ type MicrolinkApiOptions = {
83
84
  screenshot?: boolean | ScreenshotOptions;
84
85
  scripts?: string | string[];
85
86
  scroll?: string;
86
- styles?: string | string[];
87
87
  staleTtl?: string | number;
88
+ stream?: string;
89
+ styles?: string | string[];
88
90
  timeout?: number;
89
91
  ttl?: string | number;
90
92
  video?: boolean;
@@ -100,41 +102,33 @@ type IframeInfo = {
100
102
  }
101
103
 
102
104
  type MediaInfo = {
103
- url: string;
104
- type?: string;
105
- palette?: string[];
105
+ alternative_color?: string;
106
106
  background_color?: string;
107
107
  color?: string;
108
- alternative_color?: string;
109
- width?: number;
110
- height?: number;
111
- duration?: number;
112
108
  duration_pretty?: string;
109
+ duration?: number;
110
+ height?: number;
111
+ palette?: string[];
112
+ type?: string;
113
+ url: string;
114
+ width?: number;
113
115
  }
114
116
 
115
117
  type MqlResponseData = {
116
- // A human-readable representation of the author's name.
118
+ audio?: MediaInfo | null;
117
119
  author?: string | null;
118
- // An ISO 8601 representation of the date the article was published.
119
120
  date?: string | null;
120
- // The publisher's chosen description of the article.
121
121
  description?: string | null;
122
- // An ISO 639-1 representation of the url content language.
122
+ function?: MqlFunctionResult;
123
+ iframe?: IframeInfo | null;
124
+ image?: MediaInfo | null;
123
125
  lang?: string | null;
124
- // An image URL that best represents the publisher brand.
125
126
  logo?: MediaInfo | null;
126
- // A human-readable representation of the publisher's name.
127
127
  publisher?: string | null;
128
- // The publisher's chosen title of the article.
128
+ screenshot?: MediaInfo | null;
129
129
  title?: string | null;
130
- // The URL of the article.
131
130
  url?: string;
132
- image?: MediaInfo | null;
133
- screenshot?: MediaInfo | null;
134
131
  video?: MediaInfo | null;
135
- audio?: MediaInfo | null;
136
- iframe?: IframeInfo | null;
137
- function?: MqlFunctionResult;
138
132
  }
139
133
 
140
134
  type MqlFunctionResult = {
@@ -165,25 +159,26 @@ type HTTPResponseRaw = HTTPResponse & { body: ArrayBuffer };
165
159
  export type MqlResponse = MqlPayload & { response: HTTPResponseWithBody };
166
160
 
167
161
  export type MqlError = {
168
- headers: { [key: string]: string };
162
+ code: string;
169
163
  data?: MqlResponseData;
170
- statusCode?: number;
171
- name: string;
172
- message: string;
173
164
  description: string;
174
- status: MqlStatus;
175
- code: string;
165
+ headers: { [key: string]: string };
166
+ message: string;
176
167
  more: string;
168
+ name: string;
169
+ status: MqlStatus;
170
+ statusCode?: number;
177
171
  url: string;
178
172
  }
179
173
 
180
174
  export type MqlOptions = MqlClientOptions & MicrolinkApiOptions;
181
175
 
182
176
  interface mql {
177
+ (url: string, opts?: MqlOptions & { stream: string }, gotOpts?: object): Promise<Response>;
183
178
  (url: string, opts?: MqlOptions, gotOpts?: object): Promise<MqlResponse>;
179
+ arrayBuffer: (url: string, opts?: MqlOptions, gotOpts?: object) => Promise<HTTPResponseRaw>;
184
180
  extend: (gotOpts?: object) => mql;
185
181
  stream: (input: RequestInfo, init?: RequestInit) => ReadableStream;
186
- arrayBuffer: (url: string, opts?: MqlOptions, gotOpts?: object) => Promise<HTTPResponseRaw>;
187
182
  }
188
183
 
189
184
  declare const mql: mql;
@@ -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:c=t}=s,l=null!=(o=i)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),h=a(i)&&!l?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}}})(l?i.toString():i,r,c);throw new e({...h,message:h.message,url:c,statusCode:n,headers:u})}var o},c=(t,{data:e,apiKey:r,endpoint:s,retry:a,cache:u,...c}={},{responseType:l="json",headers:h,...p}={})=>{const f=!!r;return[`${s||i[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...n(e),...o(c)}).toString()}`,{...p,responseType:l,cache:u,retry:a,headers:f?{...h,"x-api-key":r}:{...h}}]},l=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]=c(s,o,{...t,...n});return u(i,a)},h=l();return h.extend=l,h.MicrolinkError=e,h.getApiUrl=c,h.fetchFromApi=u,h.mapRules=n,h.version=t,h.stream=s.stream,h};class c 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,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},x=t=>w.includes(t)?t.toUpperCase():t,q=[413,429,503],P={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:q,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:q}};class A{static create(t,e){const r=new A(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 c(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={}){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;const r="credentials"in Request.prototype;if(this._options={credentials:r?this._input.credentials:void 0,...e,headers:f(this._input.headers,e.headers),hooks:d({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:x(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 l)){if(t instanceof c){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 l(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 C=t=>{const e=(e,r)=>A.create(e,p(t,r));for(const r of w)e[r]=(e,s)=>A.create(e,p(t,s,{method:r}));return e.create=t=>C(p(t)),e.extend=e=>C(p(t,e)),e.stop=R,e},O=C();var k=e(Object.freeze({__proto__:null,HTTPError:c,TimeoutError:l,default:O}));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=async(t,{responseType:e,...r})=>{try{void 0===r.timeout&&(r.timeout=!1);const s=await N(t,r),o=await s[e](),{headers:n,status:i}=s;return{url:s.url,body:o,headers:n,statusCode:i}}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}};D.stream=(...t)=>N(...t).then((t=>t.body));const B=L({MicrolinkError:I,urlHttp:S,got:D,flatten:U,VERSION:"0.12.3"});r.exports=B;var M=r.exports.arrayBuffer=B.extend({responseType:"arrayBuffer"}),H=r.exports.extend=B.extend,$=r.exports.fetchFromApi=B.fetchFromApi,F=r.exports.getApiUrl=B.getApiUrl,J=r.exports.mapRules=B.mapRules,V=r.exports.MicrolinkError=B.MicrolinkError,W=r.exports.version=B.version,Y=t(r.exports);export{V as MicrolinkError,M as arrayBuffer,Y as default,H as extend,$ as fetchFromApi,F as getApiUrl,J as mapRules,W 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};class i 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 a 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 u=t=>null!==t&&"object"==typeof t,c=(...t)=>{for(const e of t)if((!u(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return h({},...t)},l=(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},h=(...t)=>{let e={},r={};for(const s of t)if(Array.isArray(s))Array.isArray(e)||(e=[]),e=[...e,...s];else if(u(s)){for(let[t,r]of Object.entries(s))u(r)&&t in e&&(r=h(e[t],r)),e={...e,[t]:r};u(s.headers)&&(r=l(r,s.headers),e.headers=r)}return e},p=(()=>{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})(),f="function"==typeof globalThis.AbortController,d="function"==typeof globalThis.ReadableStream,y="function"==typeof globalThis.FormData,b=["get","post","put","patch","head","delete"],m={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},_=2147483647,w=Symbol("stop"),g={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},T={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},R=t=>b.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,delay:t=>.3*2**(t-1)*1e3},x=(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 q{static create(t,e){const r=new q(t,e),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>_)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 i(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(!d)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(m))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={}){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;const r="credentials"in Request.prototype;if(this._options={credentials:r?this._input.credentials:void 0,...e,headers:l(this._input.headers,e.headers),hooks:h({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:R(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:x(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(f){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(p&&(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);!(y&&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 a)){if(t instanceof i){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),_);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})===w)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 T||s in g||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 a(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 P=t=>{const e=(e,r)=>q.create(e,c(t,r));for(const r of b)e[r]=(e,s)=>q.create(e,c(t,s,{method:r}));return e.create=t=>P(c(t)),e.extend=e=>P(c(t,e)),e.stop=w,e},j=P();var A=e(Object.freeze({__proto__:null,HTTPError:i,TimeoutError:a,default:j}));const C={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},O=t=>null!==t&&"object"==typeof t;var k=t=>({VERSION:e,MicrolinkError:r,urlHttp:s,got:o,flatten:n})=>{const i=t=>{if(!O(t))return;const e=n(t);return Object.keys(e).reduce(((t,r)=>(t[`data.${r}`]=e[r].toString(),t)),{})},a=async(e,s={})=>{try{const r=await o(e,s);return s.responseType===t?r:{...r.body,response:r}}catch(t){const{response:s={}}=t,{statusCode:o,body:i,headers:a={},url:u=e}=s,c=null!=(n=i)&&null!=n.constructor&&"function"==typeof n.constructor.isBuffer&&n.constructor.isBuffer(n),l=O(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,t,u);throw new r({...l,message:l.message,url:u,statusCode:o,headers:a})}var n},u=(e,{data:r,apiKey:s,endpoint:o,retry:a,cache:u,...c}={},{responseType:l="json",headers:h,...p}={})=>{const f=!!s,d=`${o||C[f?"PRO":"FREE"]}?${new URLSearchParams({url:e,...i(r),...n(c)}).toString()}`,y=f?{...h,"x-api-key":s}:{...h};return c.stream&&(l=t),[d,{...p,responseType:l,cache:u,retry:a,headers:y}]},c=t=>async(e,o,n)=>{((t="")=>{if(!s(t)){const e=`The \`url\` as \`${t}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new r({status:"fail",data:{url:e},more:"https://microlink.io/docs/api/api-parameters/url",code:"EINVALURLCLIENT",message:e,url:t})}})(e);const[i,c]=u(e,o,{...t,...n});return a(i,c)},l=c();return l.extend=c,l.MicrolinkError=r,l.getApiUrl=u,l.fetchFromApi=a,l.mapRules=i,l.version=e,l.stream=o.stream,l};const S=t=>{try{const{href:e}=new URL(t);return s.test(e)&&e}catch(t){return!1}},{flattie:U}=o,{default:L}=A,N=k("arrayBuffer");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 B=async(t,{responseType:e,...r})=>{try{void 0===r.timeout&&(r.timeout=!1);const s=await L(t,r),o=await s[e](),{headers:n,status:i}=s;return{url:s.url,body:o,headers:n,statusCode:i}}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}};B.stream=(...t)=>L(...t).then((t=>t.body));const D=N({MicrolinkError:I,urlHttp:S,got:B,flatten:U,VERSION:"0.13.1"});r.exports=D;var M=r.exports.arrayBuffer=D.extend({responseType:"arrayBuffer"}),H=r.exports.extend=D.extend,$=r.exports.fetchFromApi=D.fetchFromApi,F=r.exports.getApiUrl=D.getApiUrl,J=r.exports.mapRules=D.mapRules,V=r.exports.MicrolinkError=D.MicrolinkError,W=r.exports.version=D.version,Y=t(r.exports);export{V as MicrolinkError,M as arrayBuffer,Y as default,H as extend,$ as fetchFromApi,F as getApiUrl,J as mapRules,W as version};
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).mql={})}(this,(function(e){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function r(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})})),r}var s={exports:{}};const o=/^https?:\/\//i;var n={};function i(e,t,r,s,o){var n,a=o?o+r:o;if(null==s)t&&(e[o]=s);else if("object"!=typeof s)e[o]=s;else if(Array.isArray(s))for(n=0;n<s.length;n++)i(e,t,r,s[n],a+n);else for(n in s)i(e,t,r,s[n],a+n)}n.flattie=function(e,t,r){var s={};return"object"==typeof e&&i(s,!!r,t||".",e,""),s};const a={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},u=e=>null!==e&&"object"==typeof e;var l=({VERSION:e,MicrolinkError:t,urlHttp:r,got:s,flatten:o})=>{const n=e=>{if(!u(e))return;const t=o(e);return Object.keys(t).reduce(((e,r)=>(e[`data.${r}`]=t[r].toString(),e)),{})},i=async(e,r={})=>{try{const t=await s(e,r);return"buffer"===r.responseType?{body:t.body,response:t}:{...t.body,response:t}}catch(r){const{response:s={}}=r,{statusCode:n,body:i,headers:a={},url:l=e}=s,c=null!=(o=i)&&null!=o.constructor&&"function"==typeof o.constructor.isBuffer&&o.constructor.isBuffer(o),h=u(i)&&!c?i:((e,t,r)=>{try{return JSON.parse(e)}catch(s){const o=e||t.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 t({...h,message:h.message,url:l,statusCode:n,headers:a})}var o},l=(e,{data:t,apiKey:r,endpoint:s,retry:i,cache:u,...l}={},{responseType:c="json",headers:h,...p}={})=>{const f=!!r;return[`${s||a[f?"PRO":"FREE"]}?${new URLSearchParams({url:e,...n(t),...o(l)}).toString()}`,{...p,responseType:c,cache:u,retry:i,headers:f?{...h,"x-api-key":r}:{...h}}]},c=e=>async(s,o,n)=>{((e="")=>{if(!r(e)){const r=`The \`url\` as \`${e}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new t({status:"fail",data:{url:r},more:"https://microlink.io/docs/api/api-parameters/url",code:"EINVALURLCLIENT",message:r,url:e})}})(s);const[a,u]=l(s,o,{...e,...n});return i(a,u)},h=c();return h.extend=c,h.MicrolinkError=t,h.getApiUrl=l,h.fetchFromApi=i,h.mapRules=n,h.version=e,h.stream=s.stream,h};class c extends Error{constructor(e,t,r){const s=`${e.status||0===e.status?e.status:""} ${e.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=e,this.request=t,this.options=r}}class h extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const p=e=>null!==e&&"object"==typeof e,f=(...e)=>{for(const t of e)if((!p(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return y({},...e)},d=(e={},t={})=>{const r=new globalThis.Headers(e),s=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(const[e,t]of o.entries())s&&"undefined"===t||void 0===t?r.delete(e):r.set(e,t);return r},y=(...e)=>{let t={},r={};for(const s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(p(s)){for(let[e,r]of Object.entries(s))p(r)&&e in t&&(r=y(t[e],r)),t={...t,[e]:r};p(s.headers)&&(r=d(r,s.headers),t.headers=r)}return t},b=(()=>{let e=!1,t=!1;const r="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return r&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")),e&&!t})(),m="function"==typeof globalThis.AbortController,_="function"==typeof globalThis.ReadableStream,g="function"==typeof globalThis.FormData,w=["get","post","put","patch","head","delete"],T={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},R=2147483647,v=Symbol("stop"),x={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=e=>w.includes(e)?e.toUpperCase():e,P=[413,429,503],j={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:P,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},A=(e={})=>{if("number"==typeof e)return{...j,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...j,...e,afterStatusCodes:P}};class C{static create(e,t){const r=new C(e,t),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>R)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await r._fetch();for(const t of r._options.hooks.afterResponse){const s=await t(r.request,r._options,r._decorateResponse(e.clone()));s instanceof globalThis.Response&&(e=s)}if(r._decorateResponse(e),!e.ok&&r._options.throwHttpErrors){let t=new c(e,r.request,r._options);for(const e of r._options.hooks.beforeError)t=await e(t);throw t}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!_)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(e.clone(),r._options.onDownloadProgress)}return e},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[e,s]of Object.entries(T))o[e]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const n=(await o).clone();if("json"===e){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await n.text())}return n[e]()};return o}constructor(e,t={}){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=e;const r="credentials"in Request.prototype;if(this._options={credentials:r?this._input.credentials:void 0,...t,headers:d(this._input.headers,t.headers),hooks:y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:q(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:A(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:t.timeout??1e4,fetch:t.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(m){if(this.abortController=new globalThis.AbortController,this._options.signal){const e=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(e.reason)}))}this._options.signal=this.abortController.signal}if(b&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(g&&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(t,{...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(e){if(this._retryCount++,this._retryCount<=this._options.retry.limit&&!(e instanceof h)){if(e instanceof c){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const t=e.response.headers.get("Retry-After");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t);return Number.isNaN(e)?e=Date.parse(t)-Date.now():e*=1e3,void 0!==this._options.retry.maxRetryAfter&&e>this._options.retry.maxRetryAfter?0:e}if(413===e.response.status)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),R);if(0!==r&&this._retryCount>0){await async function(e,{signal:t}){return new Promise(((r,s)=>{function o(){clearTimeout(n),s(t.reason)}t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));const n=setTimeout((()=>{t?.removeEventListener("abort",o),r()}),e)}))}(r,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===v)return}return this._retry(e)}throw t}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}const e=((e,t)=>{const r={};for(const s in t)s in E||s in x||s in e||(r[s]=t[s]);return r})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),e):async function(e,t,r,s){return new Promise(((o,n)=>{const i=setTimeout((()=>{r&&r.abort(),n(new h(e))}),s.timeout);s.fetch(e,t).then(o).catch(n).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let s=0;return 204===e.status?(t&&t({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(o){const n=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await async function e(){const{done:i,value:a}=await n.read();if(i)o.close();else{if(t){s+=a.byteLength;t({percent:0===r?0:s/r,transferredBytes:s,totalBytes:r},a)}o.enqueue(a),await e()}}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}const O=e=>{const t=(t,r)=>C.create(t,f(e,r));for(const r of w)t[r]=(t,s)=>C.create(t,f(e,s,{method:r}));return t.create=e=>O(f(e)),t.extend=t=>O(f(e,t)),t.stop=v,t},k=O();var S=r(Object.freeze({__proto__:null,HTTPError:c,TimeoutError:h,default:k}));const U=e=>{try{const{href:t}=new URL(e);return o.test(t)&&t}catch(e){return!1}},{flattie:L}=n,N=l,{default:I}=S;class B extends Error{constructor(e){super(),this.name="MicrolinkError",Object.assign(this,e),this.description=this.message,this.message=this.code?`${this.code}, ${this.description}`:this.description}}const D=async(e,{responseType:t,...r})=>{try{void 0===r.timeout&&(r.timeout=!1);const s=await I(e,r),o=await s[t](),{headers:n,status:i}=s;return{url:s.url,body:o,headers:n,statusCode:i}}catch(e){if(e.response){const{response:t}=e;e.response={...t,headers:Array.from(t.headers.entries()).reduce(((e,[t,r])=>(e[t]=r,e)),{}),statusCode:t.status,body:await t.text()}}throw e}};D.stream=(...e)=>I(...e).then((e=>e.body));const M=N({MicrolinkError:B,urlHttp:U,got:D,flatten:L,VERSION:"0.12.3"});s.exports=M;var F=s.exports.arrayBuffer=M.extend({responseType:"arrayBuffer"}),H=s.exports.extend=M.extend,$=s.exports.fetchFromApi=M.fetchFromApi,J=s.exports.getApiUrl=M.getApiUrl,V=s.exports.mapRules=M.mapRules,W=s.exports.MicrolinkError=M.MicrolinkError,Y=s.exports.version=M.version,z=t(s.exports);e.MicrolinkError=W,e.arrayBuffer=F,e.default=z,e.extend=H,e.fetchFromApi=$,e.getApiUrl=J,e.mapRules=V,e.version=Y,Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).mql={})}(this,(function(e){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function r(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})})),r}var s={exports:{}};const o=/^https?:\/\//i;var n={};function i(e,t,r,s,o){var n,a=o?o+r:o;if(null==s)t&&(e[o]=s);else if("object"!=typeof s)e[o]=s;else if(Array.isArray(s))for(n=0;n<s.length;n++)i(e,t,r,s[n],a+n);else for(n in s)i(e,t,r,s[n],a+n)}n.flattie=function(e,t,r){var s={};return"object"==typeof e&&i(s,!!r,t||".",e,""),s};class a extends Error{constructor(e,t,r){const s=`${e.status||0===e.status?e.status:""} ${e.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=e,this.request=t,this.options=r}}class u extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const l=e=>null!==e&&"object"==typeof e,c=(...e)=>{for(const t of e)if((!l(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return p({},...e)},h=(e={},t={})=>{const r=new globalThis.Headers(e),s=t instanceof globalThis.Headers,o=new globalThis.Headers(t);for(const[e,t]of o.entries())s&&"undefined"===t||void 0===t?r.delete(e):r.set(e,t);return r},p=(...e)=>{let t={},r={};for(const s of e)if(Array.isArray(s))Array.isArray(t)||(t=[]),t=[...t,...s];else if(l(s)){for(let[e,r]of Object.entries(s))l(r)&&e in t&&(r=p(t[e],r)),t={...t,[e]:r};l(s.headers)&&(r=h(r,s.headers),t.headers=r)}return t},f=(()=>{let e=!1,t=!1;const r="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;return r&&s&&(t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")),e&&!t})(),d="function"==typeof globalThis.AbortController,y="function"==typeof globalThis.ReadableStream,b="function"==typeof globalThis.FormData,m=["get","post","put","patch","head","delete"],_={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},g=2147483647,w=Symbol("stop"),T={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},R={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},v=e=>m.includes(e)?e.toUpperCase():e,x=[413,429,503],E={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:e=>.3*2**(e-1)*1e3},q=(e={})=>{if("number"==typeof e)return{...E,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...E,...e,afterStatusCodes:x}};class P{static create(e,t){const r=new P(e,t),s=async()=>{if("number"==typeof r._options.timeout&&r._options.timeout>g)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await r._fetch();for(const t of r._options.hooks.afterResponse){const s=await t(r.request,r._options,r._decorateResponse(e.clone()));s instanceof globalThis.Response&&(e=s)}if(r._decorateResponse(e),!e.ok&&r._options.throwHttpErrors){let t=new a(e,r.request,r._options);for(const e of r._options.hooks.beforeError)t=await e(t);throw t}if(r._options.onDownloadProgress){if("function"!=typeof r._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!y)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(e.clone(),r._options.onDownloadProgress)}return e},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(s):s();for(const[e,s]of Object.entries(_))o[e]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||s);const n=(await o).clone();if("json"===e){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await n.text())}return n[e]()};return o}constructor(e,t={}){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=e;const r="credentials"in Request.prototype;if(this._options={credentials:r?this._input.credentials:void 0,...t,headers:h(this._input.headers,t.headers),hooks:p({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:v(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:q(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:t.timeout??1e4,fetch:t.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(d){if(this.abortController=new globalThis.AbortController,this._options.signal){const e=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(e.reason)}))}this._options.signal=this.abortController.signal}if(f&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(b&&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(t,{...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(e){if(this._retryCount++,this._retryCount<=this._options.retry.limit&&!(e instanceof u)){if(e instanceof a){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const t=e.response.headers.get("Retry-After");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t);return Number.isNaN(e)?e=Date.parse(t)-Date.now():e*=1e3,void 0!==this._options.retry.maxRetryAfter&&e>this._options.retry.maxRetryAfter?0:e}if(413===e.response.status)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),g);if(0!==r&&this._retryCount>0){await async function(e,{signal:t}){return new Promise(((r,s)=>{function o(){clearTimeout(n),s(t.reason)}t&&(t.throwIfAborted(),t.addEventListener("abort",o,{once:!0}));const n=setTimeout((()=>{t?.removeEventListener("abort",o),r()}),e)}))}(r,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===w)return}return this._retry(e)}throw t}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}const e=((e,t)=>{const r={};for(const s in t)s in R||s in T||s in e||(r[s]=t[s]);return r})(this.request,this._options);return!1===this._options.timeout?this._options.fetch(this.request.clone(),e):async function(e,t,r,s){return new Promise(((o,n)=>{const i=setTimeout((()=>{r&&r.abort(),n(new u(e))}),s.timeout);s.fetch(e,t).then(o).catch(n).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let s=0;return 204===e.status?(t&&t({percent:1,totalBytes:r,transferredBytes:s},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(o){const n=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array),await async function e(){const{done:i,value:a}=await n.read();if(i)o.close();else{if(t){s+=a.byteLength;t({percent:0===r?0:s/r,transferredBytes:s,totalBytes:r},a)}o.enqueue(a),await e()}}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}const j=e=>{const t=(t,r)=>P.create(t,c(e,r));for(const r of m)t[r]=(t,s)=>P.create(t,c(e,s,{method:r}));return t.create=e=>j(c(e)),t.extend=t=>j(c(e,t)),t.stop=w,t},A=j();var C=r(Object.freeze({__proto__:null,HTTPError:a,TimeoutError:u,default:A}));const O={FREE:"https://api.microlink.io/",PRO:"https://pro.microlink.io/"},k=e=>null!==e&&"object"==typeof e;var S=e=>({VERSION:t,MicrolinkError:r,urlHttp:s,got:o,flatten:n})=>{const i=e=>{if(!k(e))return;const t=n(e);return Object.keys(t).reduce(((e,r)=>(e[`data.${r}`]=t[r].toString(),e)),{})},a=async(t,s={})=>{try{const r=await o(t,s);return s.responseType===e?r:{...r.body,response:r}}catch(e){const{response:s={}}=e,{statusCode:o,body:i,headers:a={},url:u=t}=s,l=null!=(n=i)&&null!=n.constructor&&"function"==typeof n.constructor.isBuffer&&n.constructor.isBuffer(n),c=k(i)&&!l?i:((e,t,r)=>{try{return JSON.parse(e)}catch(s){const o=e||t.message;return{status:"error",data:{url:o},more:"https://microlink.io/efatalclient",code:"EFATALCLIENT",message:o,url:r}}})(l?i.toString():i,e,u);throw new r({...c,message:c.message,url:u,statusCode:o,headers:a})}var n},u=(t,{data:r,apiKey:s,endpoint:o,retry:a,cache:u,...l}={},{responseType:c="json",headers:h,...p}={})=>{const f=!!s,d=`${o||O[f?"PRO":"FREE"]}?${new URLSearchParams({url:t,...i(r),...n(l)}).toString()}`,y=f?{...h,"x-api-key":s}:{...h};return l.stream&&(c=e),[d,{...p,responseType:c,cache:u,retry:a,headers:y}]},l=e=>async(t,o,n)=>{((e="")=>{if(!s(e)){const t=`The \`url\` as \`${e}\` is not valid. Ensure it has protocol (http or https) and hostname.`;throw new r({status:"fail",data:{url:t},more:"https://microlink.io/docs/api/api-parameters/url",code:"EINVALURLCLIENT",message:t,url:e})}})(t);const[i,l]=u(t,o,{...e,...n});return a(i,l)},c=l();return c.extend=l,c.MicrolinkError=r,c.getApiUrl=u,c.fetchFromApi=a,c.mapRules=i,c.version=t,c.stream=o.stream,c};const U=e=>{try{const{href:t}=new URL(e);return o.test(t)&&t}catch(e){return!1}},{flattie:L}=n,{default:N}=C,I=S("arrayBuffer");class B extends Error{constructor(e){super(),this.name="MicrolinkError",Object.assign(this,e),this.description=this.message,this.message=this.code?`${this.code}, ${this.description}`:this.description}}const D=async(e,{responseType:t,...r})=>{try{void 0===r.timeout&&(r.timeout=!1);const s=await N(e,r),o=await s[t](),{headers:n,status:i}=s;return{url:s.url,body:o,headers:n,statusCode:i}}catch(e){if(e.response){const{response:t}=e;e.response={...t,headers:Array.from(t.headers.entries()).reduce(((e,[t,r])=>(e[t]=r,e)),{}),statusCode:t.status,body:await t.text()}}throw e}};D.stream=(...e)=>N(...e).then((e=>e.body));const M=I({MicrolinkError:B,urlHttp:U,got:D,flatten:L,VERSION:"0.13.1"});s.exports=M;var F=s.exports.arrayBuffer=M.extend({responseType:"arrayBuffer"}),H=s.exports.extend=M.extend,$=s.exports.fetchFromApi=M.fetchFromApi,J=s.exports.getApiUrl=M.getApiUrl,V=s.exports.mapRules=M.mapRules,W=s.exports.MicrolinkError=M.MicrolinkError,Y=s.exports.version=M.version,z=t(s.exports);e.MicrolinkError=W,e.arrayBuffer=F,e.default=z,e.extend=H,e.fetchFromApi=$,e.getApiUrl=J,e.mapRules=V,e.version=Y,Object.defineProperty(e,"__esModule",{value:!0})}));
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.12.3",
5
+ "version": "0.13.1",
6
6
  "types": "lightweight/index.d.ts",
7
7
  "exports": {
8
8
  "require": "./src/node.js",
@@ -139,6 +139,7 @@
139
139
  "standard": {
140
140
  "ignore": [
141
141
  "lightweight/index.js",
142
+ "lightweight/index.umd.js",
142
143
  "src/node.mjs"
143
144
  ]
144
145
  },
package/src/factory.js CHANGED
@@ -28,7 +28,13 @@ const parseBody = (input, error, url) => {
28
28
  }
29
29
  }
30
30
 
31
- const factory = ({ VERSION, MicrolinkError, urlHttp, got, flatten }) => {
31
+ const factory = streamResponseType => ({
32
+ VERSION,
33
+ MicrolinkError,
34
+ urlHttp,
35
+ got,
36
+ flatten
37
+ }) => {
32
38
  const assertUrl = (url = '') => {
33
39
  if (!urlHttp(url)) {
34
40
  const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`
@@ -55,8 +61,8 @@ const factory = ({ VERSION, MicrolinkError, urlHttp, got, flatten }) => {
55
61
  const fetchFromApi = async (apiUrl, opts = {}) => {
56
62
  try {
57
63
  const response = await got(apiUrl, opts)
58
- return opts.responseType === 'buffer'
59
- ? { body: response.body, response }
64
+ return opts.responseType === streamResponseType
65
+ ? response
60
66
  : { ...response.body, response }
61
67
  } catch (err) {
62
68
  const { response = {} } = err
@@ -100,6 +106,10 @@ const factory = ({ VERSION, MicrolinkError, urlHttp, got, flatten }) => {
100
106
  const headers = isPro
101
107
  ? { ...gotHeaders, 'x-api-key': apiKey }
102
108
  : { ...gotHeaders }
109
+
110
+ if (opts.stream) {
111
+ responseType = streamResponseType
112
+ }
103
113
  return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
104
114
  }
105
115
 
package/src/node.js CHANGED
@@ -1,4 +1,4 @@
1
- const mql = require('./factory')({
1
+ const mql = require('./factory')('buffer')({
2
2
  MicrolinkError: require('whoops')('MicrolinkError'),
3
3
  urlHttp: require('url-http/lightweight'),
4
4
  got: require('got').extend({ headers: { 'user-agent': undefined } }),