@microlink/mql 0.13.6 → 0.13.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.mql = {}));
5
- })(this, (function (exports) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.mql = factory());
5
+ })(this, (function () { 'use strict';
6
6
 
7
7
  function getDefaultExportFromCjs (x) {
8
8
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
@@ -33,75 +33,55 @@
33
33
  return a;
34
34
  }
35
35
 
36
- var lightweight$2 = {exports: {}};
37
-
38
- const REGEX_HTTP_PROTOCOL = /^https?:\/\//i;
39
-
40
- var lightweight$1 = url => {
41
- try {
42
- const { href } = new URL(url);
43
- return REGEX_HTTP_PROTOCOL.test(href) && href
44
- } catch (err) {
45
- return false
46
- }
47
- };
36
+ var lightweight$1 = {exports: {}};
48
37
 
49
38
  var dist = {};
50
39
 
51
- function iter(output, nullish, sep, val, key) {
52
- var k, pfx = key ? (key + sep) : key;
53
-
54
- if (val == null) {
55
- if (nullish) output[key] = val;
56
- } else if (typeof val != 'object') {
57
- output[key] = val;
58
- } else if (Array.isArray(val)) {
59
- for (k=0; k < val.length; k++) {
60
- iter(output, nullish, sep, val[k], pfx + k);
61
- }
62
- } else {
63
- for (k in val) {
64
- iter(output, nullish, sep, val[k], pfx + k);
40
+ var hasRequiredDist;
41
+
42
+ function requireDist () {
43
+ if (hasRequiredDist) return dist;
44
+ hasRequiredDist = 1;
45
+ function iter(output, nullish, sep, val, key) {
46
+ var k, pfx = key ? (key + sep) : key;
47
+
48
+ if (val == null) {
49
+ if (nullish) output[key] = val;
50
+ } else if (typeof val != 'object') {
51
+ output[key] = val;
52
+ } else if (Array.isArray(val)) {
53
+ for (k=0; k < val.length; k++) {
54
+ iter(output, nullish, sep, val[k], pfx + k);
55
+ }
56
+ } else {
57
+ for (k in val) {
58
+ iter(output, nullish, sep, val[k], pfx + k);
59
+ }
65
60
  }
66
61
  }
67
- }
68
62
 
69
- function flattie(input, glue, toNull) {
70
- var output = {};
71
- if (typeof input == 'object') {
72
- iter(output, !!toNull, glue || '.', input, '');
63
+ function flattie(input, glue, toNull) {
64
+ var output = {};
65
+ if (typeof input == 'object') {
66
+ iter(output, !!toNull, glue || '.', input, '');
67
+ }
68
+ return output;
73
69
  }
74
- return output;
75
- }
76
70
 
77
- dist.flattie = flattie;
71
+ dist.flattie = flattie;
72
+ return dist;
73
+ }
78
74
 
79
- // eslint-lint-disable-next-line @typescript-eslint/naming-convention
80
75
  class HTTPError extends Error {
76
+ response;
77
+ request;
78
+ options;
81
79
  constructor(response, request, options) {
82
80
  const code = (response.status || response.status === 0) ? response.status : '';
83
81
  const title = response.statusText || '';
84
82
  const status = `${code} ${title}`.trim();
85
83
  const reason = status ? `status code ${status}` : 'an unknown error';
86
- super(`Request failed with ${reason}`);
87
- Object.defineProperty(this, "response", {
88
- enumerable: true,
89
- configurable: true,
90
- writable: true,
91
- value: void 0
92
- });
93
- Object.defineProperty(this, "request", {
94
- enumerable: true,
95
- configurable: true,
96
- writable: true,
97
- value: void 0
98
- });
99
- Object.defineProperty(this, "options", {
100
- enumerable: true,
101
- configurable: true,
102
- writable: true,
103
- value: void 0
104
- });
84
+ super(`Request failed with ${reason}: ${request.method} ${request.url}`);
105
85
  this.name = 'HTTPError';
106
86
  this.response = response;
107
87
  this.request = request;
@@ -110,25 +90,20 @@
110
90
  }
111
91
 
112
92
  class TimeoutError extends Error {
93
+ request;
113
94
  constructor(request) {
114
- super('Request timed out');
115
- Object.defineProperty(this, "request", {
116
- enumerable: true,
117
- configurable: true,
118
- writable: true,
119
- value: void 0
120
- });
95
+ super(`Request timed out: ${request.method} ${request.url}`);
121
96
  this.name = 'TimeoutError';
122
97
  this.request = request;
123
98
  }
124
99
  }
125
100
 
126
101
  // eslint-disable-next-line @typescript-eslint/ban-types
127
- const isObject$1 = (value) => value !== null && typeof value === 'object';
102
+ const isObject = (value) => value !== null && typeof value === 'object';
128
103
 
129
104
  const validateAndMerge = (...sources) => {
130
105
  for (const source of sources) {
131
- if ((!isObject$1(source) || Array.isArray(source)) && source !== undefined) {
106
+ if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {
132
107
  throw new TypeError('The `options` argument must be an object');
133
108
  }
134
109
  }
@@ -148,10 +123,22 @@
148
123
  }
149
124
  return result;
150
125
  };
126
+ function newHookValue(original, incoming, property) {
127
+ return (Object.hasOwn(incoming, property) && incoming[property] === undefined)
128
+ ? []
129
+ : deepMerge(original[property] ?? [], incoming[property] ?? []);
130
+ }
131
+ const mergeHooks = (original = {}, incoming = {}) => ({
132
+ beforeRequest: newHookValue(original, incoming, 'beforeRequest'),
133
+ beforeRetry: newHookValue(original, incoming, 'beforeRetry'),
134
+ afterResponse: newHookValue(original, incoming, 'afterResponse'),
135
+ beforeError: newHookValue(original, incoming, 'beforeError'),
136
+ });
151
137
  // TODO: Make this strongly-typed (no `any`).
152
138
  const deepMerge = (...sources) => {
153
139
  let returnValue = {};
154
140
  let headers = {};
141
+ let hooks = {};
155
142
  for (const source of sources) {
156
143
  if (Array.isArray(source)) {
157
144
  if (!Array.isArray(returnValue)) {
@@ -159,14 +146,18 @@
159
146
  }
160
147
  returnValue = [...returnValue, ...source];
161
148
  }
162
- else if (isObject$1(source)) {
149
+ else if (isObject(source)) {
163
150
  for (let [key, value] of Object.entries(source)) {
164
- if (isObject$1(value) && key in returnValue) {
151
+ if (isObject(value) && key in returnValue) {
165
152
  value = deepMerge(returnValue[key], value);
166
153
  }
167
154
  returnValue = { ...returnValue, [key]: value };
168
155
  }
169
- if (isObject$1(source.headers)) {
156
+ if (isObject(source.hooks)) {
157
+ hooks = mergeHooks(hooks, source.hooks);
158
+ returnValue.hooks = hooks;
159
+ }
160
+ if (isObject(source.headers)) {
170
161
  headers = mergeHeaders(headers, source.headers);
171
162
  returnValue.headers = headers;
172
163
  }
@@ -181,15 +172,24 @@
181
172
  const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
182
173
  const supportsRequest = typeof globalThis.Request === 'function';
183
174
  if (supportsReadableStream && supportsRequest) {
184
- hasContentType = new globalThis.Request('https://empty.invalid', {
185
- body: new globalThis.ReadableStream(),
186
- method: 'POST',
187
- // @ts-expect-error - Types are outdated.
188
- get duplex() {
189
- duplexAccessed = true;
190
- return 'half';
191
- },
192
- }).headers.has('Content-Type');
175
+ try {
176
+ hasContentType = new globalThis.Request('https://empty.invalid', {
177
+ body: new globalThis.ReadableStream(),
178
+ method: 'POST',
179
+ // @ts-expect-error - Types are outdated.
180
+ get duplex() {
181
+ duplexAccessed = true;
182
+ return 'half';
183
+ },
184
+ }).headers.has('Content-Type');
185
+ }
186
+ catch (error) {
187
+ // QQBrowser on iOS throws "unsupported BodyInit type" error (see issue #581)
188
+ if (error instanceof Error && error.message === 'unsupported BodyInit type') {
189
+ return false;
190
+ }
191
+ throw error;
192
+ }
193
193
  }
194
194
  return duplexAccessed && !hasContentType;
195
195
  })();
@@ -210,6 +210,7 @@
210
210
  const kyOptionKeys = {
211
211
  json: true,
212
212
  parseJson: true,
213
+ stringifyJson: true,
213
214
  searchParams: true,
214
215
  prefixUrl: true,
215
216
  retry: true,
@@ -267,7 +268,6 @@
267
268
  return {
268
269
  ...defaultRetryOptions,
269
270
  ...retry,
270
- afterStatusCodes: retryAfterStatusCodes,
271
271
  };
272
272
  };
273
273
 
@@ -383,47 +383,18 @@
383
383
  }
384
384
  return result;
385
385
  }
386
+ request;
387
+ abortController;
388
+ _retryCount = 0;
389
+ _input;
390
+ _options;
386
391
  // eslint-disable-next-line complexity
387
392
  constructor(input, options = {}) {
388
- Object.defineProperty(this, "request", {
389
- enumerable: true,
390
- configurable: true,
391
- writable: true,
392
- value: void 0
393
- });
394
- Object.defineProperty(this, "abortController", {
395
- enumerable: true,
396
- configurable: true,
397
- writable: true,
398
- value: void 0
399
- });
400
- Object.defineProperty(this, "_retryCount", {
401
- enumerable: true,
402
- configurable: true,
403
- writable: true,
404
- value: 0
405
- });
406
- Object.defineProperty(this, "_input", {
407
- enumerable: true,
408
- configurable: true,
409
- writable: true,
410
- value: void 0
411
- });
412
- Object.defineProperty(this, "_options", {
413
- enumerable: true,
414
- configurable: true,
415
- writable: true,
416
- value: void 0
417
- });
418
393
  this._input = input;
419
- const credentials = this._input instanceof Request && 'credentials' in Request.prototype
420
- ? this._input.credentials
421
- : undefined;
422
394
  this._options = {
423
- ...(credentials && { credentials }), // For exactOptionalPropertyTypes
424
395
  ...options,
425
396
  headers: mergeHeaders(this._input.headers, options.headers),
426
- hooks: deepMerge({
397
+ hooks: mergeHooks({
427
398
  beforeRequest: [],
428
399
  beforeRetry: [],
429
400
  beforeError: [],
@@ -451,18 +422,20 @@
451
422
  }
452
423
  if (supportsAbortController) {
453
424
  this.abortController = new globalThis.AbortController();
454
- if (this._options.signal) {
455
- const originalSignal = this._options.signal;
456
- this._options.signal.addEventListener('abort', () => {
457
- this.abortController.abort(originalSignal.reason);
458
- });
459
- }
425
+ const originalSignal = this._options.signal ?? this._input.signal;
426
+ originalSignal?.addEventListener('abort', () => {
427
+ this.abortController.abort(originalSignal.reason);
428
+ });
460
429
  this._options.signal = this.abortController.signal;
461
430
  }
462
431
  if (supportsRequestStreams) {
463
432
  // @ts-expect-error - Types are outdated.
464
433
  this._options.duplex = 'half';
465
434
  }
435
+ if (this._options.json !== undefined) {
436
+ this._options.body = this._options.stringifyJson?.(this._options.json) ?? JSON.stringify(this._options.json);
437
+ this._options.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
438
+ }
466
439
  this.request = new globalThis.Request(this._input, this._options);
467
440
  if (this._options.searchParams) {
468
441
  // eslint-disable-next-line unicorn/prevent-abbreviations
@@ -480,41 +453,38 @@
480
453
  // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.
481
454
  this.request = new globalThis.Request(new globalThis.Request(url, { ...this.request }), this._options);
482
455
  }
483
- if (this._options.json !== undefined) {
484
- this._options.body = JSON.stringify(this._options.json);
485
- this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
486
- this.request = new globalThis.Request(this.request, { body: this._options.body });
487
- }
488
456
  }
489
457
  _calculateRetryDelay(error) {
490
458
  this._retryCount++;
491
- if (this._retryCount <= this._options.retry.limit && !(error instanceof TimeoutError)) {
492
- if (error instanceof HTTPError) {
493
- if (!this._options.retry.statusCodes.includes(error.response.status)) {
494
- return 0;
495
- }
496
- const retryAfter = error.response.headers.get('Retry-After');
497
- if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
498
- let after = Number(retryAfter);
499
- if (Number.isNaN(after)) {
500
- after = Date.parse(retryAfter) - Date.now();
501
- }
502
- else {
503
- after *= 1000;
504
- }
505
- if (this._options.retry.maxRetryAfter !== undefined && after > this._options.retry.maxRetryAfter) {
506
- return 0;
507
- }
508
- return after;
459
+ if (this._retryCount > this._options.retry.limit || error instanceof TimeoutError) {
460
+ throw error;
461
+ }
462
+ if (error instanceof HTTPError) {
463
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
464
+ throw error;
465
+ }
466
+ const retryAfter = error.response.headers.get('Retry-After')
467
+ ?? error.response.headers.get('RateLimit-Reset')
468
+ ?? error.response.headers.get('X-RateLimit-Reset') // GitHub
469
+ ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter
470
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
471
+ let after = Number(retryAfter) * 1000;
472
+ if (Number.isNaN(after)) {
473
+ after = Date.parse(retryAfter) - Date.now();
509
474
  }
510
- if (error.response.status === 413) {
511
- return 0;
475
+ else if (after >= Date.parse('2024-01-01')) {
476
+ // A large number is treated as a timestamp (fixed threshold protects against clock skew)
477
+ after -= Date.now();
512
478
  }
479
+ const max = this._options.retry.maxRetryAfter ?? after;
480
+ return after < max ? after : max;
481
+ }
482
+ if (error.response.status === 413) {
483
+ throw error;
513
484
  }
514
- const retryDelay = this._options.retry.delay(this._retryCount);
515
- return Math.min(this._options.retry.backoffLimit, retryDelay);
516
485
  }
517
- return 0;
486
+ const retryDelay = this._options.retry.delay(this._retryCount);
487
+ return Math.min(this._options.retry.backoffLimit, retryDelay);
518
488
  }
519
489
  _decorateResponse(response) {
520
490
  if (this._options.parseJson) {
@@ -528,24 +498,24 @@
528
498
  }
529
499
  catch (error) {
530
500
  const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
531
- if (ms !== 0 && this._retryCount > 0) {
532
- await delay(ms, { signal: this._options.signal });
533
- for (const hook of this._options.hooks.beforeRetry) {
534
- // eslint-disable-next-line no-await-in-loop
535
- const hookResult = await hook({
536
- request: this.request,
537
- options: this._options,
538
- error: error,
539
- retryCount: this._retryCount,
540
- });
541
- // If `stop` is returned from the hook, the retry process is stopped
542
- if (hookResult === stop) {
543
- return;
544
- }
501
+ if (this._retryCount < 1) {
502
+ throw error;
503
+ }
504
+ await delay(ms, { signal: this._options.signal });
505
+ for (const hook of this._options.hooks.beforeRetry) {
506
+ // eslint-disable-next-line no-await-in-loop
507
+ const hookResult = await hook({
508
+ request: this.request,
509
+ options: this._options,
510
+ error: error,
511
+ retryCount: this._retryCount,
512
+ });
513
+ // If `stop` is returned from the hook, the retry process is stopped
514
+ if (hookResult === stop) {
515
+ return;
545
516
  }
546
- return this._retry(function_);
547
517
  }
548
- throw error;
518
+ return this._retry(function_);
549
519
  }
550
520
  }
551
521
  async _fetch() {
@@ -561,10 +531,13 @@
561
531
  }
562
532
  }
563
533
  const nonRequestOptions = findUnknownOptions(this.request, this._options);
534
+ // Cloning is done here to prepare in advance for retries
535
+ const mainRequest = this.request;
536
+ this.request = mainRequest.clone();
564
537
  if (this._options.timeout === false) {
565
- return this._options.fetch(this.request.clone(), nonRequestOptions);
538
+ return this._options.fetch(mainRequest, nonRequestOptions);
566
539
  }
567
- return timeout(this.request.clone(), nonRequestOptions, this.abortController, this._options);
540
+ return timeout(mainRequest, nonRequestOptions, this.abortController, this._options);
568
541
  }
569
542
  /* istanbul ignore next */
570
543
  _stream(response, onDownloadProgress) {
@@ -619,235 +592,252 @@
619
592
  ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
620
593
  }
621
594
  ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
622
- ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
595
+ ky.extend = (newDefaults) => {
596
+ if (typeof newDefaults === 'function') {
597
+ newDefaults = newDefaults(defaults ?? {});
598
+ }
599
+ return createInstance(validateAndMerge(defaults, newDefaults));
600
+ };
623
601
  ky.stop = stop;
624
602
  return ky;
625
603
  };
626
- const ky$1 = createInstance();
604
+ const ky = createInstance();
627
605
 
628
606
  var distribution = /*#__PURE__*/Object.freeze({
629
607
  __proto__: null,
630
608
  HTTPError: HTTPError,
631
609
  TimeoutError: TimeoutError,
632
- default: ky$1
610
+ default: ky
633
611
  });
634
612
 
635
- var require$$2 = /*@__PURE__*/getAugmentedNamespace(distribution);
636
-
637
- const ENDPOINT = {
638
- FREE: 'https://api.microlink.io/',
639
- PRO: 'https://pro.microlink.io/'
640
- };
641
-
642
- const isObject = input => input !== null && typeof input === 'object';
643
-
644
- const isBuffer = input =>
645
- input != null &&
646
- input.constructor != null &&
647
- typeof input.constructor.isBuffer === 'function' &&
648
- input.constructor.isBuffer(input);
613
+ var require$$1 = /*@__PURE__*/getAugmentedNamespace(distribution);
614
+
615
+ var factory_1;
616
+ var hasRequiredFactory;
617
+
618
+ function requireFactory () {
619
+ if (hasRequiredFactory) return factory_1;
620
+ hasRequiredFactory = 1;
621
+ const ENDPOINT = {
622
+ FREE: 'https://api.microlink.io/',
623
+ PRO: 'https://pro.microlink.io/'
624
+ };
625
+
626
+ const isObject = input => input !== null && typeof input === 'object';
627
+
628
+ const isBuffer = input =>
629
+ input != null &&
630
+ input.constructor != null &&
631
+ typeof input.constructor.isBuffer === 'function' &&
632
+ input.constructor.isBuffer(input);
633
+
634
+ const parseBody = (input, error, url) => {
635
+ try {
636
+ return JSON.parse(input)
637
+ } catch (_) {
638
+ const message = input || error.message;
639
+
640
+ return {
641
+ status: 'error',
642
+ data: { url: message },
643
+ more: 'https://microlink.io/efatalclient',
644
+ code: 'EFATALCLIENT',
645
+ message,
646
+ url
647
+ }
648
+ }
649
+ };
650
+
651
+ const isURL = url => {
652
+ try {
653
+ return /^https?:\/\//i.test(new URL(url).href)
654
+ } catch (_) {
655
+ return false
656
+ }
657
+ };
658
+
659
+ const factory = streamResponseType => ({
660
+ VERSION,
661
+ MicrolinkError,
662
+ got,
663
+ flatten
664
+ }) => {
665
+ const assertUrl = (url = '') => {
666
+ if (!isURL(url)) {
667
+ const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
668
+ throw new MicrolinkError({
669
+ status: 'fail',
670
+ data: { url: message },
671
+ more: 'https://microlink.io/einvalurlclient',
672
+ code: 'EINVALURLCLIENT',
673
+ message,
674
+ url
675
+ })
676
+ }
677
+ };
678
+
679
+ const mapRules = rules => {
680
+ if (!isObject(rules)) return
681
+ const flatRules = flatten(rules);
682
+ return Object.keys(flatRules).reduce((acc, key) => {
683
+ acc[`data.${key}`] = flatRules[key].toString();
684
+ return acc
685
+ }, {})
686
+ };
687
+
688
+ const fetchFromApi = async (apiUrl, opts = {}) => {
689
+ try {
690
+ const response = await got(apiUrl, opts);
691
+ return opts.responseType === streamResponseType
692
+ ? response
693
+ : { ...response.body, response }
694
+ } catch (error) {
695
+ const { response = {} } = error;
696
+ const {
697
+ statusCode,
698
+ body: rawBody,
699
+ headers = {},
700
+ url: uri = apiUrl
701
+ } = response;
702
+ const isBodyBuffer = isBuffer(rawBody);
703
+
704
+ const body =
705
+ isObject(rawBody) && !isBodyBuffer
706
+ ? rawBody
707
+ : parseBody(isBodyBuffer ? rawBody.toString() : rawBody, error, uri);
708
+
709
+ throw new MicrolinkError({
710
+ ...body,
711
+ message: body.message,
712
+ url: uri,
713
+ statusCode,
714
+ headers
715
+ })
716
+ }
717
+ };
718
+
719
+ const getApiUrl = (
720
+ url,
721
+ { data, apiKey, endpoint, retry, cache, ...opts } = {},
722
+ { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
723
+ ) => {
724
+ const isPro = !!apiKey;
725
+ const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE'];
726
+
727
+ const apiUrl = `${apiEndpoint}?${new URLSearchParams({
728
+ url,
729
+ ...mapRules(data),
730
+ ...flatten(opts)
731
+ }).toString()}`;
732
+
733
+ const headers = isPro
734
+ ? { ...gotHeaders, 'x-api-key': apiKey }
735
+ : { ...gotHeaders };
736
+
737
+ if (opts.stream) {
738
+ responseType = streamResponseType;
739
+ }
740
+ return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
741
+ };
742
+
743
+ const createMql = defaultOpts => async (url, opts, gotOpts) => {
744
+ assertUrl(url);
745
+ const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
746
+ ...defaultOpts,
747
+ ...gotOpts
748
+ });
749
+ return fetchFromApi(apiUrl, fetchOpts)
750
+ };
751
+
752
+ const mql = createMql();
753
+ mql.extend = createMql;
754
+ mql.MicrolinkError = MicrolinkError;
755
+ mql.getApiUrl = getApiUrl;
756
+ mql.fetchFromApi = fetchFromApi;
757
+ mql.mapRules = mapRules;
758
+ mql.version = VERSION;
759
+ mql.stream = got.stream;
760
+
761
+ return mql
762
+ };
763
+
764
+ factory_1 = factory;
765
+ return factory_1;
766
+ }
649
767
 
650
- const parseBody = (input, error, url) => {
651
- try {
652
- return JSON.parse(input)
653
- } catch (_) {
654
- const message = input || error.message;
768
+ var hasRequiredLightweight;
655
769
 
656
- return {
657
- status: 'error',
658
- data: { url: message },
659
- more: 'https://microlink.io/efatalclient',
660
- code: 'EFATALCLIENT',
661
- message,
662
- url
663
- }
664
- }
665
- };
770
+ function requireLightweight () {
771
+ if (hasRequiredLightweight) return lightweight$1.exports;
772
+ hasRequiredLightweight = 1;
666
773
 
667
- const factory$1 = streamResponseType => ({
668
- VERSION,
669
- MicrolinkError,
670
- urlHttp,
671
- got,
672
- flatten
673
- }) => {
674
- const assertUrl = (url = '') => {
675
- if (!urlHttp(url)) {
676
- const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
677
- throw new MicrolinkError({
678
- status: 'fail',
679
- data: { url: message },
680
- more: 'https://microlink.io/einvalurlclient',
681
- code: 'EINVALURLCLIENT',
682
- message,
683
- url
684
- })
685
- }
686
- };
687
-
688
- const mapRules = rules => {
689
- if (!isObject(rules)) return
690
- const flatRules = flatten(rules);
691
- return Object.keys(flatRules).reduce((acc, key) => {
692
- acc[`data.${key}`] = flatRules[key].toString();
693
- return acc
694
- }, {})
695
- };
696
-
697
- const fetchFromApi = async (apiUrl, opts = {}) => {
698
- try {
699
- const response = await got(apiUrl, opts);
700
- return opts.responseType === streamResponseType
701
- ? response
702
- : { ...response.body, response }
703
- } catch (error) {
704
- const { response = {} } = error;
705
- const {
706
- statusCode,
707
- body: rawBody,
708
- headers = {},
709
- url: uri = apiUrl
710
- } = response;
711
- const isBodyBuffer = isBuffer(rawBody);
712
-
713
- const body =
714
- isObject(rawBody) && !isBodyBuffer
715
- ? rawBody
716
- : parseBody(isBodyBuffer ? rawBody.toString() : rawBody, error, uri);
717
-
718
- throw new MicrolinkError({
719
- ...body,
720
- message: body.message,
721
- url: uri,
722
- statusCode,
723
- headers
724
- })
725
- }
726
- };
727
-
728
- const getApiUrl = (
729
- url,
730
- { data, apiKey, endpoint, retry, cache, ...opts } = {},
731
- { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
732
- ) => {
733
- const isPro = !!apiKey;
734
- const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE'];
735
-
736
- const apiUrl = `${apiEndpoint}?${new URLSearchParams({
737
- url,
738
- ...mapRules(data),
739
- ...flatten(opts)
740
- }).toString()}`;
741
-
742
- const headers = isPro
743
- ? { ...gotHeaders, 'x-api-key': apiKey }
744
- : { ...gotHeaders };
745
-
746
- if (opts.stream) {
747
- responseType = streamResponseType;
748
- }
749
- return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
750
- };
751
-
752
- const createMql = defaultOpts => async (url, opts, gotOpts) => {
753
- assertUrl(url);
754
- const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
755
- ...defaultOpts,
756
- ...gotOpts
757
- });
758
- return fetchFromApi(apiUrl, fetchOpts)
759
- };
760
-
761
- const mql = createMql();
762
- mql.extend = createMql;
763
- mql.MicrolinkError = MicrolinkError;
764
- mql.getApiUrl = getApiUrl;
765
- mql.fetchFromApi = fetchFromApi;
766
- mql.mapRules = mapRules;
767
- mql.version = VERSION;
768
- mql.stream = got.stream;
769
-
770
- return mql
771
- };
774
+ const { flattie: flatten } = requireDist();
775
+ const { default: ky } = require$$1;
772
776
 
773
- var factory_1 = factory$1;
777
+ const factory = requireFactory()('arrayBuffer');
774
778
 
775
- const urlHttp = lightweight$1;
776
- const { flattie: flatten } = dist;
777
- const { default: ky } = require$$2;
779
+ class MicrolinkError extends Error {
780
+ constructor (props) {
781
+ super();
782
+ this.name = 'MicrolinkError';
783
+ Object.assign(this, props);
784
+ this.description = this.message;
785
+ this.message = this.code
786
+ ? `${this.code}, ${this.description}`
787
+ : this.description;
788
+ }
789
+ }
778
790
 
779
- const factory = factory_1('arrayBuffer');
791
+ const got = async (url, { responseType, ...opts }) => {
792
+ try {
793
+ if (opts.timeout === undefined) opts.timeout = false;
794
+ const response = await ky(url, opts);
795
+ const body = await response[responseType]();
796
+ const { headers, status: statusCode } = response;
797
+ return { url: response.url, body, headers, statusCode }
798
+ } catch (error) {
799
+ if (error.response) {
800
+ const { response } = error;
801
+ error.response = {
802
+ ...response,
803
+ headers: Array.from(response.headers.entries()).reduce(
804
+ (acc, [key, value]) => {
805
+ acc[key] = value;
806
+ return acc
807
+ },
808
+ {}
809
+ ),
810
+ statusCode: response.status,
811
+ body: await response.text()
812
+ };
813
+ }
814
+ throw error
815
+ }
816
+ };
817
+
818
+ got.stream = (...args) => ky(...args).then(res => res.body);
819
+
820
+ const mql = factory({
821
+ MicrolinkError,
822
+ got,
823
+ flatten,
824
+ VERSION: '0.13.7'
825
+ });
780
826
 
781
- class MicrolinkError extends Error {
782
- constructor (props) {
783
- super();
784
- this.name = 'MicrolinkError';
785
- Object.assign(this, props);
786
- this.description = this.message;
787
- this.message = this.code
788
- ? `${this.code}, ${this.description}`
789
- : this.description;
790
- }
827
+ lightweight$1.exports = mql;
828
+ lightweight$1.exports.arrayBuffer = mql.extend({ responseType: 'arrayBuffer' });
829
+ lightweight$1.exports.extend = mql.extend;
830
+ lightweight$1.exports.fetchFromApi = mql.fetchFromApi;
831
+ lightweight$1.exports.getApiUrl = mql.getApiUrl;
832
+ lightweight$1.exports.mapRules = mql.mapRules;
833
+ lightweight$1.exports.MicrolinkError = mql.MicrolinkError;
834
+ lightweight$1.exports.version = mql.version;
835
+ return lightweight$1.exports;
791
836
  }
792
837
 
793
- const got = async (url, { responseType, ...opts }) => {
794
- try {
795
- if (opts.timeout === undefined) opts.timeout = false;
796
- const response = await ky(url, opts);
797
- const body = await response[responseType]();
798
- const { headers, status: statusCode } = response;
799
- return { url: response.url, body, headers, statusCode }
800
- } catch (error) {
801
- if (error.response) {
802
- const { response } = error;
803
- error.response = {
804
- ...response,
805
- headers: Array.from(response.headers.entries()).reduce(
806
- (acc, [key, value]) => {
807
- acc[key] = value;
808
- return acc
809
- },
810
- {}
811
- ),
812
- statusCode: response.status,
813
- body: await response.text()
814
- };
815
- }
816
- throw error
817
- }
818
- };
819
-
820
- got.stream = (...args) => ky(...args).then(res => res.body);
821
-
822
- const mql = factory({
823
- MicrolinkError,
824
- urlHttp,
825
- got,
826
- flatten,
827
- VERSION: '0.13.6'
828
- });
829
-
830
- lightweight$2.exports = mql;
831
- var arrayBuffer = lightweight$2.exports.arrayBuffer = mql.extend({ responseType: 'arrayBuffer' });
832
- var extend = lightweight$2.exports.extend = mql.extend;
833
- var fetchFromApi = lightweight$2.exports.fetchFromApi = mql.fetchFromApi;
834
- var getApiUrl = lightweight$2.exports.getApiUrl = mql.getApiUrl;
835
- var mapRules = lightweight$2.exports.mapRules = mql.mapRules;
836
- var MicrolinkError_1 = lightweight$2.exports.MicrolinkError = mql.MicrolinkError;
837
- var version = lightweight$2.exports.version = mql.version;
838
-
839
- var lightweightExports = lightweight$2.exports;
838
+ var lightweightExports = requireLightweight();
840
839
  var lightweight = /*@__PURE__*/getDefaultExportFromCjs(lightweightExports);
841
840
 
842
- exports.MicrolinkError = MicrolinkError_1;
843
- exports.arrayBuffer = arrayBuffer;
844
- exports.default = lightweight;
845
- exports.extend = extend;
846
- exports.fetchFromApi = fetchFromApi;
847
- exports.getApiUrl = getApiUrl;
848
- exports.mapRules = mapRules;
849
- exports.version = version;
850
-
851
- Object.defineProperty(exports, '__esModule', { value: true });
841
+ return lightweight;
852
842
 
853
843
  }));