@microlink/mql 0.10.18 → 0.10.21

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.js CHANGED
@@ -1,18 +1,20 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('url')) :
3
- typeof define === 'function' && define.amd ? define(['url'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.mql = factory(global.require$$0$1));
5
- })(this, (function (require$$0$1) { 'use strict';
6
-
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
-
9
- var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
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';
10
6
 
11
7
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
12
8
 
13
9
  function getAugmentedNamespace(n) {
14
- if (n.__esModule) return n;
15
- var a = Object.defineProperty({}, '__esModule', {value: true});
10
+ var f = n.default;
11
+ if (typeof f == "function") {
12
+ var a = function () {
13
+ return f.apply(this, arguments);
14
+ };
15
+ a.prototype = f.prototype;
16
+ } else a = {};
17
+ Object.defineProperty(a, '__esModule', {value: true});
16
18
  Object.keys(n).forEach(function (k) {
17
19
  var d = Object.getOwnPropertyDescriptor(n, k);
18
20
  Object.defineProperty(a, k, d.get ? d : {
@@ -25,7 +27,7 @@
25
27
  return a;
26
28
  }
27
29
 
28
- const URL$1 = commonjsGlobal.window ? window.URL : require$$0__default["default"].URL;
30
+ const URL$1 = window.URL;
29
31
  const REGEX_HTTP_PROTOCOL = /^https?:\/\//i;
30
32
 
31
33
  var lightweight = url => {
@@ -307,6 +309,12 @@
307
309
 
308
310
  const isObject = input => input !== null && typeof input === 'object';
309
311
 
312
+ const isBuffer = input =>
313
+ input != null &&
314
+ input.constructor != null &&
315
+ typeof input.constructor.isBuffer === 'function' &&
316
+ input.constructor.isBuffer(input);
317
+
310
318
  const parseBody = (input, error, url) => {
311
319
  try {
312
320
  return JSON.parse(input)
@@ -327,13 +335,13 @@
327
335
  const factory$1 = ({
328
336
  VERSION,
329
337
  MicrolinkError,
330
- isUrlHttp,
338
+ urlHttp,
331
339
  stringify,
332
340
  got,
333
341
  flatten
334
342
  }) => {
335
343
  const assertUrl = (url = '') => {
336
- if (!isUrlHttp(url)) {
344
+ if (!urlHttp(url)) {
337
345
  const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
338
346
  throw new MicrolinkError({
339
347
  status: 'fail',
@@ -364,12 +372,12 @@
364
372
  } catch (err) {
365
373
  const { response = {} } = err;
366
374
  const { statusCode, body: rawBody, headers, url: uri = apiUrl } = response;
367
- const isBuffer = Buffer.isBuffer(rawBody);
375
+ const isBodyBuffer = isBuffer(rawBody);
368
376
 
369
377
  const body =
370
- isObject(rawBody) && !isBuffer
378
+ isObject(rawBody) && !isBodyBuffer
371
379
  ? rawBody
372
- : parseBody(isBuffer ? rawBody.toString() : rawBody, err, uri);
380
+ : parseBody(isBodyBuffer ? rawBody.toString() : rawBody, err, uri);
373
381
 
374
382
  if (body.code === 'EFATALCLIENT' && retryCount++ < 2) {
375
383
  return fetchFromApi(apiUrl, opts, retryCount)
@@ -431,408 +439,414 @@
431
439
  var ky$1 = {exports: {}};
432
440
 
433
441
  (function (module, exports) {
434
- (function (global, factory) {
435
- factory(exports) ;
436
- })(commonjsGlobal, (function (exports) {
437
- // eslint-lint-disable-next-line @typescript-eslint/naming-convention
438
- class HTTPError extends Error {
439
- constructor(response, request, options) {
440
- const code = (response.status || response.status === 0) ? response.status : '';
441
- const title = response.statusText || '';
442
- const status = `${code} ${title}`.trim();
443
- const reason = status ? `status code ${status}` : 'an unknown error';
444
- super(`Request failed with ${reason}`);
445
- this.name = 'HTTPError';
446
- this.response = response;
447
- this.request = request;
448
- this.options = options;
449
- }
450
- }
451
-
452
- class TimeoutError extends Error {
453
- constructor(request) {
454
- super('Request timed out');
455
- this.name = 'TimeoutError';
456
- this.request = request;
457
- }
458
- }
459
-
460
- // eslint-disable-next-line @typescript-eslint/ban-types
461
- const isObject = (value) => value !== null && typeof value === 'object';
462
-
463
- const validateAndMerge = (...sources) => {
464
- for (const source of sources) {
465
- if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
466
- throw new TypeError('The `options` argument must be an object');
467
- }
468
- }
469
- return deepMerge({}, ...sources);
470
- };
471
- const mergeHeaders = (source1 = {}, source2 = {}) => {
472
- const result = new globalThis.Headers(source1);
473
- const isHeadersInstance = source2 instanceof globalThis.Headers;
474
- const source = new globalThis.Headers(source2);
475
- for (const [key, value] of source.entries()) {
476
- if ((isHeadersInstance && value === 'undefined') || value === undefined) {
477
- result.delete(key);
478
- }
479
- else {
480
- result.set(key, value);
481
- }
482
- }
483
- return result;
484
- };
485
- // TODO: Make this strongly-typed (no `any`).
486
- const deepMerge = (...sources) => {
487
- let returnValue = {};
488
- let headers = {};
489
- for (const source of sources) {
490
- if (Array.isArray(source)) {
491
- if (!Array.isArray(returnValue)) {
492
- returnValue = [];
493
- }
494
- returnValue = [...returnValue, ...source];
495
- }
496
- else if (isObject(source)) {
497
- for (let [key, value] of Object.entries(source)) {
498
- if (isObject(value) && key in returnValue) {
499
- value = deepMerge(returnValue[key], value);
500
- }
501
- returnValue = { ...returnValue, [key]: value };
502
- }
503
- if (isObject(source.headers)) {
504
- headers = mergeHeaders(headers, source.headers);
505
- returnValue.headers = headers;
506
- }
507
- }
508
- }
509
- return returnValue;
510
- };
511
-
512
- const supportsAbortController = typeof globalThis.AbortController === 'function';
513
- const supportsStreams = typeof globalThis.ReadableStream === 'function';
514
- const supportsFormData = typeof globalThis.FormData === 'function';
515
- const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
516
- const responseTypes = {
517
- json: 'application/json',
518
- text: 'text/*',
519
- formData: 'multipart/form-data',
520
- arrayBuffer: '*/*',
521
- blob: '*/*',
522
- };
523
- // The maximum value of a 32bit int (see issue #117)
524
- const maxSafeTimeout = 2147483647;
525
- const stop = Symbol('stop');
526
-
527
- const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
528
- const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
529
- const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
530
- const retryAfterStatusCodes = [413, 429, 503];
531
- const defaultRetryOptions = {
532
- limit: 2,
533
- methods: retryMethods,
534
- statusCodes: retryStatusCodes,
535
- afterStatusCodes: retryAfterStatusCodes,
536
- maxRetryAfter: Number.POSITIVE_INFINITY,
537
- };
538
- const normalizeRetryOptions = (retry = {}) => {
539
- if (typeof retry === 'number') {
540
- return {
541
- ...defaultRetryOptions,
542
- limit: retry,
543
- };
544
- }
545
- if (retry.methods && !Array.isArray(retry.methods)) {
546
- throw new Error('retry.methods must be an array');
547
- }
548
- if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
549
- throw new Error('retry.statusCodes must be an array');
550
- }
551
- return {
552
- ...defaultRetryOptions,
553
- ...retry,
554
- afterStatusCodes: retryAfterStatusCodes,
555
- };
556
- };
557
-
558
- // `Promise.race()` workaround (#91)
559
- const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
560
- const timeoutId = setTimeout(() => {
561
- if (abortController) {
562
- abortController.abort();
563
- }
564
- reject(new TimeoutError(request));
565
- }, options.timeout);
566
- /* eslint-disable promise/prefer-await-to-then */
567
- void options
568
- .fetch(request)
569
- .then(resolve)
570
- .catch(reject)
571
- .then(() => {
572
- clearTimeout(timeoutId);
573
- });
574
- /* eslint-enable promise/prefer-await-to-then */
575
- });
576
- const delay = async (ms) => new Promise(resolve => {
577
- setTimeout(resolve, ms);
578
- });
579
-
580
- class Ky {
581
- // eslint-disable-next-line complexity
582
- constructor(input, options = {}) {
583
- var _a, _b;
584
- this._retryCount = 0;
585
- this._input = input;
586
- this._options = {
587
- // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
588
- credentials: this._input.credentials || 'same-origin',
589
- ...options,
590
- headers: mergeHeaders(this._input.headers, options.headers),
591
- hooks: deepMerge({
592
- beforeRequest: [],
593
- beforeRetry: [],
594
- afterResponse: [],
595
- }, options.hooks),
596
- method: normalizeRequestMethod((_a = options.method) !== null && _a !== void 0 ? _a : this._input.method),
597
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
598
- prefixUrl: String(options.prefixUrl || ''),
599
- retry: normalizeRetryOptions(options.retry),
600
- throwHttpErrors: options.throwHttpErrors !== false,
601
- timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
602
- fetch: (_b = options.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis),
603
- };
604
- if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
605
- throw new TypeError('`input` must be a string, URL, or Request');
606
- }
607
- if (this._options.prefixUrl && typeof this._input === 'string') {
608
- if (this._input.startsWith('/')) {
609
- throw new Error('`input` must not begin with a slash when using `prefixUrl`');
610
- }
611
- if (!this._options.prefixUrl.endsWith('/')) {
612
- this._options.prefixUrl += '/';
613
- }
614
- this._input = this._options.prefixUrl + this._input;
615
- }
616
- if (supportsAbortController) {
617
- this.abortController = new globalThis.AbortController();
618
- if (this._options.signal) {
619
- this._options.signal.addEventListener('abort', () => {
620
- this.abortController.abort();
621
- });
622
- }
623
- this._options.signal = this.abortController.signal;
624
- }
625
- this.request = new globalThis.Request(this._input, this._options);
626
- if (this._options.searchParams) {
627
- // eslint-disable-next-line unicorn/prevent-abbreviations
628
- const textSearchParams = typeof this._options.searchParams === 'string'
629
- ? this._options.searchParams.replace(/^\?/, '')
630
- : new URLSearchParams(this._options.searchParams).toString();
631
- // eslint-disable-next-line unicorn/prevent-abbreviations
632
- const searchParams = '?' + textSearchParams;
633
- const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
634
- // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
635
- if (((supportsFormData && this._options.body instanceof globalThis.FormData)
636
- || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
637
- this.request.headers.delete('content-type');
638
- }
639
- this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
640
- }
641
- if (this._options.json !== undefined) {
642
- this._options.body = JSON.stringify(this._options.json);
643
- this.request.headers.set('content-type', 'application/json');
644
- this.request = new globalThis.Request(this.request, { body: this._options.body });
645
- }
646
- }
647
- // eslint-disable-next-line @typescript-eslint/promise-function-async
648
- static create(input, options) {
649
- const ky = new Ky(input, options);
650
- const fn = async () => {
651
- if (ky._options.timeout > maxSafeTimeout) {
652
- throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
653
- }
654
- // Delay the fetch so that body method shortcuts can set the Accept header
655
- await Promise.resolve();
656
- let response = await ky._fetch();
657
- for (const hook of ky._options.hooks.afterResponse) {
658
- // eslint-disable-next-line no-await-in-loop
659
- const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
660
- if (modifiedResponse instanceof globalThis.Response) {
661
- response = modifiedResponse;
662
- }
663
- }
664
- ky._decorateResponse(response);
665
- if (!response.ok && ky._options.throwHttpErrors) {
666
- throw new HTTPError(response, ky.request, ky._options);
667
- }
668
- // If `onDownloadProgress` is passed, it uses the stream API internally
669
- /* istanbul ignore next */
670
- if (ky._options.onDownloadProgress) {
671
- if (typeof ky._options.onDownloadProgress !== 'function') {
672
- throw new TypeError('The `onDownloadProgress` option must be a function');
673
- }
674
- if (!supportsStreams) {
675
- throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
676
- }
677
- return ky._stream(response.clone(), ky._options.onDownloadProgress);
678
- }
679
- return response;
680
- };
681
- const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
682
- const result = (isRetriableMethod ? ky._retry(fn) : fn());
683
- for (const [type, mimeType] of Object.entries(responseTypes)) {
684
- result[type] = async () => {
685
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
686
- ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
687
- const response = (await result).clone();
688
- if (type === 'json') {
689
- if (response.status === 204) {
690
- return '';
691
- }
692
- if (options.parseJson) {
693
- return options.parseJson(await response.text());
694
- }
695
- }
696
- return response[type]();
697
- };
698
- }
699
- return result;
700
- }
701
- _calculateRetryDelay(error) {
702
- this._retryCount++;
703
- if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
704
- if (error instanceof HTTPError) {
705
- if (!this._options.retry.statusCodes.includes(error.response.status)) {
706
- return 0;
707
- }
708
- const retryAfter = error.response.headers.get('Retry-After');
709
- if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
710
- let after = Number(retryAfter);
711
- if (Number.isNaN(after)) {
712
- after = Date.parse(retryAfter) - Date.now();
713
- }
714
- else {
715
- after *= 1000;
716
- }
717
- if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
718
- return 0;
719
- }
720
- return after;
721
- }
722
- if (error.response.status === 413) {
723
- return 0;
724
- }
725
- }
726
- const BACKOFF_FACTOR = 0.3;
727
- return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
728
- }
729
- return 0;
730
- }
731
- _decorateResponse(response) {
732
- if (this._options.parseJson) {
733
- response.json = async () => this._options.parseJson(await response.text());
734
- }
735
- return response;
736
- }
737
- async _retry(fn) {
738
- try {
739
- return await fn();
740
- // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
741
- }
742
- catch (error) {
743
- const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
744
- if (ms !== 0 && this._retryCount > 0) {
745
- await delay(ms);
746
- for (const hook of this._options.hooks.beforeRetry) {
747
- // eslint-disable-next-line no-await-in-loop
748
- const hookResult = await hook({
749
- request: this.request,
750
- options: this._options,
751
- error: error,
752
- retryCount: this._retryCount,
753
- });
754
- // If `stop` is returned from the hook, the retry process is stopped
755
- if (hookResult === stop) {
756
- return;
757
- }
758
- }
759
- return this._retry(fn);
760
- }
761
- throw error;
762
- }
763
- }
764
- async _fetch() {
765
- for (const hook of this._options.hooks.beforeRequest) {
766
- // eslint-disable-next-line no-await-in-loop
767
- const result = await hook(this.request, this._options);
768
- if (result instanceof Request) {
769
- this.request = result;
770
- break;
771
- }
772
- if (result instanceof Response) {
773
- return result;
774
- }
775
- }
776
- if (this._options.timeout === false) {
777
- return this._options.fetch(this.request.clone());
778
- }
779
- return timeout(this.request.clone(), this.abortController, this._options);
780
- }
781
- /* istanbul ignore next */
782
- _stream(response, onDownloadProgress) {
783
- const totalBytes = Number(response.headers.get('content-length')) || 0;
784
- let transferredBytes = 0;
785
- return new globalThis.Response(new globalThis.ReadableStream({
786
- async start(controller) {
787
- const reader = response.body.getReader();
788
- if (onDownloadProgress) {
789
- onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
790
- }
791
- async function read() {
792
- const { done, value } = await reader.read();
793
- if (done) {
794
- controller.close();
795
- return;
796
- }
797
- if (onDownloadProgress) {
798
- transferredBytes += value.byteLength;
799
- const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
800
- onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
801
- }
802
- controller.enqueue(value);
803
- await read();
804
- }
805
- await read();
806
- },
807
- }));
808
- }
809
- }
810
-
811
- /*! MIT License © Sindre Sorhus */
812
- const createInstance = (defaults) => {
813
- // eslint-disable-next-line @typescript-eslint/promise-function-async
814
- const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
815
- for (const method of requestMethods) {
816
- // eslint-disable-next-line @typescript-eslint/promise-function-async
817
- ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
818
- }
819
- ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
820
- ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
821
- ky.stop = stop;
822
- return ky;
823
- };
824
- const ky = createInstance();
825
-
826
- exports.HTTPError = HTTPError;
827
- exports.TimeoutError = TimeoutError;
828
- exports["default"] = ky;
829
-
830
- Object.defineProperty(exports, '__esModule', { value: true });
831
-
832
- }));
833
- }(ky$1, ky$1.exports));
834
-
835
- const isUrlHttp = lightweight;
442
+ (function (global, factory) {
443
+ factory(exports) ;
444
+ })(commonjsGlobal, (function (exports) {
445
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
446
+ class HTTPError extends Error {
447
+ constructor(response, request, options) {
448
+ const code = (response.status || response.status === 0) ? response.status : '';
449
+ const title = response.statusText || '';
450
+ const status = `${code} ${title}`.trim();
451
+ const reason = status ? `status code ${status}` : 'an unknown error';
452
+ super(`Request failed with ${reason}`);
453
+ this.name = 'HTTPError';
454
+ this.response = response;
455
+ this.request = request;
456
+ this.options = options;
457
+ }
458
+ }
459
+
460
+ class TimeoutError extends Error {
461
+ constructor(request) {
462
+ super('Request timed out');
463
+ this.name = 'TimeoutError';
464
+ this.request = request;
465
+ }
466
+ }
467
+
468
+ // eslint-disable-next-line @typescript-eslint/ban-types
469
+ const isObject = (value) => value !== null && typeof value === 'object';
470
+
471
+ const validateAndMerge = (...sources) => {
472
+ for (const source of sources) {
473
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
474
+ throw new TypeError('The `options` argument must be an object');
475
+ }
476
+ }
477
+ return deepMerge({}, ...sources);
478
+ };
479
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
480
+ const result = new globalThis.Headers(source1);
481
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
482
+ const source = new globalThis.Headers(source2);
483
+ for (const [key, value] of source.entries()) {
484
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
485
+ result.delete(key);
486
+ }
487
+ else {
488
+ result.set(key, value);
489
+ }
490
+ }
491
+ return result;
492
+ };
493
+ // TODO: Make this strongly-typed (no `any`).
494
+ const deepMerge = (...sources) => {
495
+ let returnValue = {};
496
+ let headers = {};
497
+ for (const source of sources) {
498
+ if (Array.isArray(source)) {
499
+ if (!Array.isArray(returnValue)) {
500
+ returnValue = [];
501
+ }
502
+ returnValue = [...returnValue, ...source];
503
+ }
504
+ else if (isObject(source)) {
505
+ for (let [key, value] of Object.entries(source)) {
506
+ if (isObject(value) && key in returnValue) {
507
+ value = deepMerge(returnValue[key], value);
508
+ }
509
+ returnValue = { ...returnValue, [key]: value };
510
+ }
511
+ if (isObject(source.headers)) {
512
+ headers = mergeHeaders(headers, source.headers);
513
+ returnValue.headers = headers;
514
+ }
515
+ }
516
+ }
517
+ return returnValue;
518
+ };
519
+
520
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
521
+ const supportsStreams = typeof globalThis.ReadableStream === 'function';
522
+ const supportsFormData = typeof globalThis.FormData === 'function';
523
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
524
+ const responseTypes = {
525
+ json: 'application/json',
526
+ text: 'text/*',
527
+ formData: 'multipart/form-data',
528
+ arrayBuffer: '*/*',
529
+ blob: '*/*',
530
+ };
531
+ // The maximum value of a 32bit int (see issue #117)
532
+ const maxSafeTimeout = 2147483647;
533
+ const stop = Symbol('stop');
534
+
535
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
536
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
537
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
538
+ const retryAfterStatusCodes = [413, 429, 503];
539
+ const defaultRetryOptions = {
540
+ limit: 2,
541
+ methods: retryMethods,
542
+ statusCodes: retryStatusCodes,
543
+ afterStatusCodes: retryAfterStatusCodes,
544
+ maxRetryAfter: Number.POSITIVE_INFINITY,
545
+ };
546
+ const normalizeRetryOptions = (retry = {}) => {
547
+ if (typeof retry === 'number') {
548
+ return {
549
+ ...defaultRetryOptions,
550
+ limit: retry,
551
+ };
552
+ }
553
+ if (retry.methods && !Array.isArray(retry.methods)) {
554
+ throw new Error('retry.methods must be an array');
555
+ }
556
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
557
+ throw new Error('retry.statusCodes must be an array');
558
+ }
559
+ return {
560
+ ...defaultRetryOptions,
561
+ ...retry,
562
+ afterStatusCodes: retryAfterStatusCodes,
563
+ };
564
+ };
565
+
566
+ // `Promise.race()` workaround (#91)
567
+ const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
568
+ const timeoutId = setTimeout(() => {
569
+ if (abortController) {
570
+ abortController.abort();
571
+ }
572
+ reject(new TimeoutError(request));
573
+ }, options.timeout);
574
+ /* eslint-disable promise/prefer-await-to-then */
575
+ void options
576
+ .fetch(request)
577
+ .then(resolve)
578
+ .catch(reject)
579
+ .then(() => {
580
+ clearTimeout(timeoutId);
581
+ });
582
+ /* eslint-enable promise/prefer-await-to-then */
583
+ });
584
+ const delay = async (ms) => new Promise(resolve => {
585
+ setTimeout(resolve, ms);
586
+ });
587
+
588
+ class Ky {
589
+ // eslint-disable-next-line complexity
590
+ constructor(input, options = {}) {
591
+ var _a, _b;
592
+ this._retryCount = 0;
593
+ this._input = input;
594
+ this._options = {
595
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
596
+ credentials: this._input.credentials || 'same-origin',
597
+ ...options,
598
+ headers: mergeHeaders(this._input.headers, options.headers),
599
+ hooks: deepMerge({
600
+ beforeRequest: [],
601
+ beforeRetry: [],
602
+ beforeError: [],
603
+ afterResponse: [],
604
+ }, options.hooks),
605
+ method: normalizeRequestMethod((_a = options.method) !== null && _a !== void 0 ? _a : this._input.method),
606
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
607
+ prefixUrl: String(options.prefixUrl || ''),
608
+ retry: normalizeRetryOptions(options.retry),
609
+ throwHttpErrors: options.throwHttpErrors !== false,
610
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
611
+ fetch: (_b = options.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis),
612
+ };
613
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
614
+ throw new TypeError('`input` must be a string, URL, or Request');
615
+ }
616
+ if (this._options.prefixUrl && typeof this._input === 'string') {
617
+ if (this._input.startsWith('/')) {
618
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
619
+ }
620
+ if (!this._options.prefixUrl.endsWith('/')) {
621
+ this._options.prefixUrl += '/';
622
+ }
623
+ this._input = this._options.prefixUrl + this._input;
624
+ }
625
+ if (supportsAbortController) {
626
+ this.abortController = new globalThis.AbortController();
627
+ if (this._options.signal) {
628
+ this._options.signal.addEventListener('abort', () => {
629
+ this.abortController.abort();
630
+ });
631
+ }
632
+ this._options.signal = this.abortController.signal;
633
+ }
634
+ this.request = new globalThis.Request(this._input, this._options);
635
+ if (this._options.searchParams) {
636
+ // eslint-disable-next-line unicorn/prevent-abbreviations
637
+ const textSearchParams = typeof this._options.searchParams === 'string'
638
+ ? this._options.searchParams.replace(/^\?/, '')
639
+ : new URLSearchParams(this._options.searchParams).toString();
640
+ // eslint-disable-next-line unicorn/prevent-abbreviations
641
+ const searchParams = '?' + textSearchParams;
642
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
643
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
644
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
645
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
646
+ this.request.headers.delete('content-type');
647
+ }
648
+ this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
649
+ }
650
+ if (this._options.json !== undefined) {
651
+ this._options.body = JSON.stringify(this._options.json);
652
+ this.request.headers.set('content-type', 'application/json');
653
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
654
+ }
655
+ }
656
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
657
+ static create(input, options) {
658
+ const ky = new Ky(input, options);
659
+ const fn = async () => {
660
+ if (ky._options.timeout > maxSafeTimeout) {
661
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
662
+ }
663
+ // Delay the fetch so that body method shortcuts can set the Accept header
664
+ await Promise.resolve();
665
+ let response = await ky._fetch();
666
+ for (const hook of ky._options.hooks.afterResponse) {
667
+ // eslint-disable-next-line no-await-in-loop
668
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
669
+ if (modifiedResponse instanceof globalThis.Response) {
670
+ response = modifiedResponse;
671
+ }
672
+ }
673
+ ky._decorateResponse(response);
674
+ if (!response.ok && ky._options.throwHttpErrors) {
675
+ let error = new HTTPError(response, ky.request, ky._options);
676
+ for (const hook of ky._options.hooks.beforeError) {
677
+ // eslint-disable-next-line no-await-in-loop
678
+ error = await hook(error);
679
+ }
680
+ throw error;
681
+ }
682
+ // If `onDownloadProgress` is passed, it uses the stream API internally
683
+ /* istanbul ignore next */
684
+ if (ky._options.onDownloadProgress) {
685
+ if (typeof ky._options.onDownloadProgress !== 'function') {
686
+ throw new TypeError('The `onDownloadProgress` option must be a function');
687
+ }
688
+ if (!supportsStreams) {
689
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
690
+ }
691
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
692
+ }
693
+ return response;
694
+ };
695
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
696
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
697
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
698
+ result[type] = async () => {
699
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
700
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
701
+ const response = (await result).clone();
702
+ if (type === 'json') {
703
+ if (response.status === 204) {
704
+ return '';
705
+ }
706
+ if (options.parseJson) {
707
+ return options.parseJson(await response.text());
708
+ }
709
+ }
710
+ return response[type]();
711
+ };
712
+ }
713
+ return result;
714
+ }
715
+ _calculateRetryDelay(error) {
716
+ this._retryCount++;
717
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
718
+ if (error instanceof HTTPError) {
719
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
720
+ return 0;
721
+ }
722
+ const retryAfter = error.response.headers.get('Retry-After');
723
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
724
+ let after = Number(retryAfter);
725
+ if (Number.isNaN(after)) {
726
+ after = Date.parse(retryAfter) - Date.now();
727
+ }
728
+ else {
729
+ after *= 1000;
730
+ }
731
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
732
+ return 0;
733
+ }
734
+ return after;
735
+ }
736
+ if (error.response.status === 413) {
737
+ return 0;
738
+ }
739
+ }
740
+ const BACKOFF_FACTOR = 0.3;
741
+ return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
742
+ }
743
+ return 0;
744
+ }
745
+ _decorateResponse(response) {
746
+ if (this._options.parseJson) {
747
+ response.json = async () => this._options.parseJson(await response.text());
748
+ }
749
+ return response;
750
+ }
751
+ async _retry(fn) {
752
+ try {
753
+ return await fn();
754
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
755
+ }
756
+ catch (error) {
757
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
758
+ if (ms !== 0 && this._retryCount > 0) {
759
+ await delay(ms);
760
+ for (const hook of this._options.hooks.beforeRetry) {
761
+ // eslint-disable-next-line no-await-in-loop
762
+ const hookResult = await hook({
763
+ request: this.request,
764
+ options: this._options,
765
+ error: error,
766
+ retryCount: this._retryCount,
767
+ });
768
+ // If `stop` is returned from the hook, the retry process is stopped
769
+ if (hookResult === stop) {
770
+ return;
771
+ }
772
+ }
773
+ return this._retry(fn);
774
+ }
775
+ throw error;
776
+ }
777
+ }
778
+ async _fetch() {
779
+ for (const hook of this._options.hooks.beforeRequest) {
780
+ // eslint-disable-next-line no-await-in-loop
781
+ const result = await hook(this.request, this._options);
782
+ if (result instanceof Request) {
783
+ this.request = result;
784
+ break;
785
+ }
786
+ if (result instanceof Response) {
787
+ return result;
788
+ }
789
+ }
790
+ if (this._options.timeout === false) {
791
+ return this._options.fetch(this.request.clone());
792
+ }
793
+ return timeout(this.request.clone(), this.abortController, this._options);
794
+ }
795
+ /* istanbul ignore next */
796
+ _stream(response, onDownloadProgress) {
797
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
798
+ let transferredBytes = 0;
799
+ return new globalThis.Response(new globalThis.ReadableStream({
800
+ async start(controller) {
801
+ const reader = response.body.getReader();
802
+ if (onDownloadProgress) {
803
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
804
+ }
805
+ async function read() {
806
+ const { done, value } = await reader.read();
807
+ if (done) {
808
+ controller.close();
809
+ return;
810
+ }
811
+ if (onDownloadProgress) {
812
+ transferredBytes += value.byteLength;
813
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
814
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
815
+ }
816
+ controller.enqueue(value);
817
+ await read();
818
+ }
819
+ await read();
820
+ },
821
+ }));
822
+ }
823
+ }
824
+
825
+ /*! MIT License © Sindre Sorhus */
826
+ const createInstance = (defaults) => {
827
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
828
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
829
+ for (const method of requestMethods) {
830
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
831
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
832
+ }
833
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
834
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
835
+ ky.stop = stop;
836
+ return ky;
837
+ };
838
+ const ky = createInstance();
839
+
840
+ exports.HTTPError = HTTPError;
841
+ exports.TimeoutError = TimeoutError;
842
+ exports["default"] = ky;
843
+
844
+ Object.defineProperty(exports, '__esModule', { value: true });
845
+
846
+ }));
847
+ } (ky$1, ky$1.exports));
848
+
849
+ const urlHttp = lightweight;
836
850
  const { flattie: flatten } = dist;
837
851
  const { encode: stringify } = require$$2;
838
852
  const whoops = lib.exports;
@@ -847,8 +861,8 @@
847
861
  if (opts.timeout === undefined) opts.timeout = false;
848
862
  const response = await ky(url, opts);
849
863
  const body = await response.json();
850
- const { headers, status: statusCode, statusText: statusMessage } = response;
851
- return { url: response.url, body, headers, statusCode, statusMessage }
864
+ const { headers, status: statusCode } = response;
865
+ return { url: response.url, body, headers, statusCode }
852
866
  } catch (err) {
853
867
  if (err.response) {
854
868
  const { response } = err;
@@ -871,11 +885,11 @@
871
885
 
872
886
  var browser = factory({
873
887
  MicrolinkError,
874
- isUrlHttp,
888
+ urlHttp,
875
889
  stringify,
876
890
  got,
877
891
  flatten,
878
- VERSION: '0.10.18'
892
+ VERSION: '0.10.21'
879
893
  });
880
894
 
881
895
  return browser;