@microlink/mql 0.10.17 → 0.10.20

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 ADDED
@@ -0,0 +1,892 @@
1
+ (function (global, factory) {
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
+
7
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
8
+
9
+ function getAugmentedNamespace(n) {
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});
18
+ Object.keys(n).forEach(function (k) {
19
+ var d = Object.getOwnPropertyDescriptor(n, k);
20
+ Object.defineProperty(a, k, d.get ? d : {
21
+ enumerable: true,
22
+ get: function () {
23
+ return n[k];
24
+ }
25
+ });
26
+ });
27
+ return a;
28
+ }
29
+
30
+ const URL$1 = window.URL;
31
+ const REGEX_HTTP_PROTOCOL = /^https?:\/\//i;
32
+
33
+ var lightweight = url => {
34
+ try {
35
+ return REGEX_HTTP_PROTOCOL.test(new URL$1(url).href)
36
+ } catch (err) {
37
+ return false
38
+ }
39
+ };
40
+
41
+ var dist = {};
42
+
43
+ function iter(output, nullish, sep, val, key) {
44
+ var k, pfx = key ? (key + sep) : key;
45
+
46
+ if (val == null) {
47
+ if (nullish) output[key] = val;
48
+ } else if (typeof val != 'object') {
49
+ output[key] = val;
50
+ } else if (Array.isArray(val)) {
51
+ for (k=0; k < val.length; k++) {
52
+ iter(output, nullish, sep, val[k], pfx + k);
53
+ }
54
+ } else {
55
+ for (k in val) {
56
+ iter(output, nullish, sep, val[k], pfx + k);
57
+ }
58
+ }
59
+ }
60
+
61
+ function flattie(input, glue, toNull) {
62
+ var output = {};
63
+ if (typeof input == 'object') {
64
+ iter(output, !!toNull, glue || '.', input, '');
65
+ }
66
+ return output;
67
+ }
68
+
69
+ dist.flattie = flattie;
70
+
71
+ function encode(obj, pfx) {
72
+ var k, i, tmp, str='';
73
+
74
+ for (k in obj) {
75
+ if ((tmp = obj[k]) !== void 0) {
76
+ if (Array.isArray(tmp)) {
77
+ for (i=0; i < tmp.length; i++) {
78
+ str && (str += '&');
79
+ str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i]);
80
+ }
81
+ } else {
82
+ str && (str += '&');
83
+ str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp);
84
+ }
85
+ }
86
+ }
87
+
88
+ return (pfx || '') + str;
89
+ }
90
+
91
+ function toValue(mix) {
92
+ if (!mix) return '';
93
+ var str = decodeURIComponent(mix);
94
+ if (str === 'false') return false;
95
+ if (str === 'true') return true;
96
+ return (+str * 0 === 0) ? (+str) : str;
97
+ }
98
+
99
+ function decode(str) {
100
+ var tmp, k, out={}, arr=str.split('&');
101
+
102
+ while (tmp = arr.shift()) {
103
+ tmp = tmp.split('=');
104
+ k = tmp.shift();
105
+ if (out[k] !== void 0) {
106
+ out[k] = [].concat(out[k], toValue(tmp.shift()));
107
+ } else {
108
+ out[k] = toValue(tmp.shift());
109
+ }
110
+ }
111
+
112
+ return out;
113
+ }
114
+
115
+ var qss_m = /*#__PURE__*/Object.freeze({
116
+ __proto__: null,
117
+ encode: encode,
118
+ decode: decode
119
+ });
120
+
121
+ var require$$2 = /*@__PURE__*/getAugmentedNamespace(qss_m);
122
+
123
+ var lib = {exports: {}};
124
+
125
+ var _rollupPluginShim1 = str => str;
126
+
127
+ var _rollupPluginShim1$1 = /*#__PURE__*/Object.freeze({
128
+ __proto__: null,
129
+ 'default': _rollupPluginShim1
130
+ });
131
+
132
+ var require$$0 = /*@__PURE__*/getAugmentedNamespace(_rollupPluginShim1$1);
133
+
134
+ const copyProperty = (to, from, property, ignoreNonConfigurable) => {
135
+ // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
136
+ // `Function#prototype` is non-writable and non-configurable so can never be modified.
137
+ if (property === 'length' || property === 'prototype') {
138
+ return;
139
+ }
140
+
141
+ const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
142
+ const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
143
+
144
+ if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
145
+ return;
146
+ }
147
+
148
+ Object.defineProperty(to, property, fromDescriptor);
149
+ };
150
+
151
+ // `Object.defineProperty()` throws if the property exists, is not configurable and either:
152
+ // - one its descriptors is changed
153
+ // - it is non-writable and its value is changed
154
+ const canCopyProperty = function (toDescriptor, fromDescriptor) {
155
+ return toDescriptor === undefined || toDescriptor.configurable || (
156
+ toDescriptor.writable === fromDescriptor.writable &&
157
+ toDescriptor.enumerable === fromDescriptor.enumerable &&
158
+ toDescriptor.configurable === fromDescriptor.configurable &&
159
+ (toDescriptor.writable || toDescriptor.value === fromDescriptor.value)
160
+ );
161
+ };
162
+
163
+ const changePrototype = (to, from) => {
164
+ const fromPrototype = Object.getPrototypeOf(from);
165
+ if (fromPrototype === Object.getPrototypeOf(to)) {
166
+ return;
167
+ }
168
+
169
+ Object.setPrototypeOf(to, fromPrototype);
170
+ };
171
+
172
+ const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
173
+
174
+ const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
175
+ const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');
176
+
177
+ // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
178
+ // We use `bind()` instead of a closure for the same reason.
179
+ // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
180
+ const changeToString = (to, from, name) => {
181
+ const withName = name === '' ? '' : `with ${name.trim()}() `;
182
+ const newToString = wrappedToString.bind(null, withName, from.toString());
183
+ // Ensure `to.toString.toString` is non-enumerable and has the same `same`
184
+ Object.defineProperty(newToString, 'name', toStringName);
185
+ Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString});
186
+ };
187
+
188
+ const mimicFn$2 = (to, from, {ignoreNonConfigurable = false} = {}) => {
189
+ const {name} = to;
190
+
191
+ for (const property of Reflect.ownKeys(from)) {
192
+ copyProperty(to, from, property, ignoreNonConfigurable);
193
+ }
194
+
195
+ changePrototype(to, from);
196
+ changeToString(to, from, name);
197
+
198
+ return to;
199
+ };
200
+
201
+ var mimicFn_1 = mimicFn$2;
202
+
203
+ var helpers = {
204
+ isFunction: obj => typeof obj === 'function',
205
+ isString: obj => typeof obj === 'string',
206
+ composeErrorMessage: (code, description) => `${code}, ${description}`,
207
+ inherits: (ctor, superCtor) => {
208
+ ctor.super_ = superCtor;
209
+ ctor.prototype = Object.create(superCtor.prototype, {
210
+ constructor: {
211
+ value: ctor,
212
+ enumerable: false,
213
+ writable: true,
214
+ configurable: true
215
+ }
216
+ });
217
+ }
218
+ };
219
+
220
+ const {isFunction, composeErrorMessage} = helpers;
221
+
222
+ function interfaceObject (error, ...props) {
223
+ Object.assign(error, ...props);
224
+
225
+ error.description = isFunction(error.message) ? error.message(error) : error.message;
226
+
227
+ error.message = error.code
228
+ ? composeErrorMessage(error.code, error.description)
229
+ : error.description;
230
+ }
231
+
232
+ var addErrorProps$1 = interfaceObject;
233
+
234
+ const cleanStack = require$$0;
235
+ const mimicFn$1 = mimicFn_1;
236
+
237
+ const addErrorProps = addErrorProps$1;
238
+ const {isString} = helpers;
239
+
240
+ function createExtendError$1 (ErrorClass, classProps) {
241
+ function ExtendError (props) {
242
+ const error = new ErrorClass();
243
+ const errorProps = isString(props) ? {message: props} : props;
244
+ addErrorProps(error, classProps, errorProps);
245
+
246
+ error.stack = cleanStack(error.stack);
247
+ return error
248
+ }
249
+
250
+ ExtendError.prototype = ErrorClass.prototype;
251
+ mimicFn$1(ExtendError, ErrorClass);
252
+
253
+ return ExtendError
254
+ }
255
+
256
+ var createExtendError_1 = createExtendError$1;
257
+
258
+ const {inherits} = helpers;
259
+ const mimicFn = mimicFn_1;
260
+
261
+ const REGEX_CLASS_NAME = /[^0-9a-zA-Z_$]/;
262
+
263
+ function createError$1 (className) {
264
+ if (typeof className !== 'string') {
265
+ throw new TypeError('Expected className to be a string')
266
+ }
267
+
268
+ if (REGEX_CLASS_NAME.test(className)) {
269
+ throw new Error('className contains invalid characters')
270
+ }
271
+
272
+ function ErrorClass () {
273
+ Object.defineProperty(this, 'name', {
274
+ configurable: true,
275
+ value: className,
276
+ writable: true
277
+ });
278
+
279
+ Error.captureStackTrace(this, this.constructor);
280
+ }
281
+
282
+ inherits(ErrorClass, Error);
283
+ mimicFn(ErrorClass, Error);
284
+ return ErrorClass
285
+ }
286
+
287
+ var createError_1 = createError$1;
288
+
289
+ const createExtendError = createExtendError_1;
290
+ const createError = createError_1;
291
+
292
+ const createErrorClass = ErrorClass => (className, props) => {
293
+ const errorClass = createError(className || ErrorClass.name);
294
+ return createExtendError(errorClass, props)
295
+ };
296
+
297
+ lib.exports = createErrorClass(Error);
298
+ lib.exports.type = createErrorClass(TypeError);
299
+ lib.exports.range = createErrorClass(RangeError);
300
+ lib.exports.eval = createErrorClass(EvalError);
301
+ lib.exports.syntax = createErrorClass(SyntaxError);
302
+ lib.exports.reference = createErrorClass(ReferenceError);
303
+ lib.exports.uri = createErrorClass(URIError);
304
+
305
+ const ENDPOINT = {
306
+ FREE: 'https://api.microlink.io',
307
+ PRO: 'https://pro.microlink.io'
308
+ };
309
+
310
+ const isObject = input => input !== null && typeof input === 'object';
311
+
312
+ const parseBody = (input, error, url) => {
313
+ try {
314
+ return JSON.parse(input)
315
+ } catch (_) {
316
+ const message = input || error.message;
317
+
318
+ return {
319
+ status: 'error',
320
+ data: { url: message },
321
+ more: 'https://microlink.io/efatalclient',
322
+ code: 'EFATALCLIENT',
323
+ message,
324
+ url
325
+ }
326
+ }
327
+ };
328
+
329
+ const factory$1 = ({
330
+ VERSION,
331
+ MicrolinkError,
332
+ urlHttp,
333
+ stringify,
334
+ got,
335
+ flatten
336
+ }) => {
337
+ const assertUrl = (url = '') => {
338
+ if (!urlHttp(url)) {
339
+ const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
340
+ throw new MicrolinkError({
341
+ status: 'fail',
342
+ data: { url: message },
343
+ more: 'https://microlink.io/docs/api/api-parameters/url',
344
+ code: 'EINVALURLCLIENT',
345
+ message,
346
+ url
347
+ })
348
+ }
349
+ };
350
+
351
+ const mapRules = rules => {
352
+ if (!isObject(rules)) return
353
+ const flatRules = flatten(rules);
354
+ return Object.keys(flatRules).reduce((acc, key) => {
355
+ acc[`data.${key}`] = flatRules[key].toString();
356
+ return acc
357
+ }, {})
358
+ };
359
+
360
+ const fetchFromApi = async (apiUrl, opts = {}, retryCount = 0) => {
361
+ try {
362
+ const response = await got(apiUrl, opts);
363
+ return opts.responseType === 'buffer'
364
+ ? { body: response.body, response }
365
+ : { ...response.body, response }
366
+ } catch (err) {
367
+ const { response = {} } = err;
368
+ const { statusCode, body: rawBody, headers, url: uri = apiUrl } = response;
369
+ const isBuffer = Buffer.isBuffer(rawBody);
370
+
371
+ const body =
372
+ isObject(rawBody) && !isBuffer
373
+ ? rawBody
374
+ : parseBody(isBuffer ? rawBody.toString() : rawBody, err, uri);
375
+
376
+ if (body.code === 'EFATALCLIENT' && retryCount++ < 2) {
377
+ return fetchFromApi(apiUrl, opts, retryCount)
378
+ }
379
+
380
+ throw MicrolinkError({
381
+ ...body,
382
+ message: body.message,
383
+ url: uri,
384
+ statusCode,
385
+ headers
386
+ })
387
+ }
388
+ };
389
+
390
+ const getApiUrl = (
391
+ url,
392
+ { data, apiKey, endpoint, retry, cache, ...opts } = {},
393
+ { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
394
+ ) => {
395
+ const isPro = !!apiKey;
396
+ const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE'];
397
+
398
+ const apiUrl = `${apiEndpoint}?${stringify({
399
+ url,
400
+ ...mapRules(data),
401
+ ...flatten(opts)
402
+ })}`;
403
+
404
+ const headers = isPro
405
+ ? { ...gotHeaders, 'x-api-key': apiKey }
406
+ : { ...gotHeaders };
407
+ return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
408
+ };
409
+
410
+ const createMql = defaultOpts => async (url, opts, gotOpts) => {
411
+ assertUrl(url);
412
+ const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
413
+ ...defaultOpts,
414
+ ...gotOpts
415
+ });
416
+ return fetchFromApi(apiUrl, fetchOpts)
417
+ };
418
+
419
+ const mql = createMql();
420
+ mql.MicrolinkError = MicrolinkError;
421
+ mql.getApiUrl = getApiUrl;
422
+ mql.fetchFromApi = fetchFromApi;
423
+ mql.mapRules = mapRules;
424
+ mql.version = VERSION;
425
+ mql.stream = got.stream;
426
+ mql.buffer = createMql({ responseType: 'buffer' });
427
+
428
+ return mql
429
+ };
430
+
431
+ var factory_1 = factory$1;
432
+
433
+ var ky$1 = {exports: {}};
434
+
435
+ (function (module, exports) {
436
+ (function (global, factory) {
437
+ factory(exports) ;
438
+ })(commonjsGlobal, (function (exports) {
439
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
440
+ class HTTPError extends Error {
441
+ constructor(response, request, options) {
442
+ const code = (response.status || response.status === 0) ? response.status : '';
443
+ const title = response.statusText || '';
444
+ const status = `${code} ${title}`.trim();
445
+ const reason = status ? `status code ${status}` : 'an unknown error';
446
+ super(`Request failed with ${reason}`);
447
+ this.name = 'HTTPError';
448
+ this.response = response;
449
+ this.request = request;
450
+ this.options = options;
451
+ }
452
+ }
453
+
454
+ class TimeoutError extends Error {
455
+ constructor(request) {
456
+ super('Request timed out');
457
+ this.name = 'TimeoutError';
458
+ this.request = request;
459
+ }
460
+ }
461
+
462
+ // eslint-disable-next-line @typescript-eslint/ban-types
463
+ const isObject = (value) => value !== null && typeof value === 'object';
464
+
465
+ const validateAndMerge = (...sources) => {
466
+ for (const source of sources) {
467
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
468
+ throw new TypeError('The `options` argument must be an object');
469
+ }
470
+ }
471
+ return deepMerge({}, ...sources);
472
+ };
473
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
474
+ const result = new globalThis.Headers(source1);
475
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
476
+ const source = new globalThis.Headers(source2);
477
+ for (const [key, value] of source.entries()) {
478
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
479
+ result.delete(key);
480
+ }
481
+ else {
482
+ result.set(key, value);
483
+ }
484
+ }
485
+ return result;
486
+ };
487
+ // TODO: Make this strongly-typed (no `any`).
488
+ const deepMerge = (...sources) => {
489
+ let returnValue = {};
490
+ let headers = {};
491
+ for (const source of sources) {
492
+ if (Array.isArray(source)) {
493
+ if (!Array.isArray(returnValue)) {
494
+ returnValue = [];
495
+ }
496
+ returnValue = [...returnValue, ...source];
497
+ }
498
+ else if (isObject(source)) {
499
+ for (let [key, value] of Object.entries(source)) {
500
+ if (isObject(value) && key in returnValue) {
501
+ value = deepMerge(returnValue[key], value);
502
+ }
503
+ returnValue = { ...returnValue, [key]: value };
504
+ }
505
+ if (isObject(source.headers)) {
506
+ headers = mergeHeaders(headers, source.headers);
507
+ returnValue.headers = headers;
508
+ }
509
+ }
510
+ }
511
+ return returnValue;
512
+ };
513
+
514
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
515
+ const supportsStreams = typeof globalThis.ReadableStream === 'function';
516
+ const supportsFormData = typeof globalThis.FormData === 'function';
517
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
518
+ const responseTypes = {
519
+ json: 'application/json',
520
+ text: 'text/*',
521
+ formData: 'multipart/form-data',
522
+ arrayBuffer: '*/*',
523
+ blob: '*/*',
524
+ };
525
+ // The maximum value of a 32bit int (see issue #117)
526
+ const maxSafeTimeout = 2147483647;
527
+ const stop = Symbol('stop');
528
+
529
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
530
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
531
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
532
+ const retryAfterStatusCodes = [413, 429, 503];
533
+ const defaultRetryOptions = {
534
+ limit: 2,
535
+ methods: retryMethods,
536
+ statusCodes: retryStatusCodes,
537
+ afterStatusCodes: retryAfterStatusCodes,
538
+ maxRetryAfter: Number.POSITIVE_INFINITY,
539
+ };
540
+ const normalizeRetryOptions = (retry = {}) => {
541
+ if (typeof retry === 'number') {
542
+ return {
543
+ ...defaultRetryOptions,
544
+ limit: retry,
545
+ };
546
+ }
547
+ if (retry.methods && !Array.isArray(retry.methods)) {
548
+ throw new Error('retry.methods must be an array');
549
+ }
550
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
551
+ throw new Error('retry.statusCodes must be an array');
552
+ }
553
+ return {
554
+ ...defaultRetryOptions,
555
+ ...retry,
556
+ afterStatusCodes: retryAfterStatusCodes,
557
+ };
558
+ };
559
+
560
+ // `Promise.race()` workaround (#91)
561
+ const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
562
+ const timeoutId = setTimeout(() => {
563
+ if (abortController) {
564
+ abortController.abort();
565
+ }
566
+ reject(new TimeoutError(request));
567
+ }, options.timeout);
568
+ /* eslint-disable promise/prefer-await-to-then */
569
+ void options
570
+ .fetch(request)
571
+ .then(resolve)
572
+ .catch(reject)
573
+ .then(() => {
574
+ clearTimeout(timeoutId);
575
+ });
576
+ /* eslint-enable promise/prefer-await-to-then */
577
+ });
578
+ const delay = async (ms) => new Promise(resolve => {
579
+ setTimeout(resolve, ms);
580
+ });
581
+
582
+ class Ky {
583
+ // eslint-disable-next-line complexity
584
+ constructor(input, options = {}) {
585
+ var _a, _b;
586
+ this._retryCount = 0;
587
+ this._input = input;
588
+ this._options = {
589
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
590
+ credentials: this._input.credentials || 'same-origin',
591
+ ...options,
592
+ headers: mergeHeaders(this._input.headers, options.headers),
593
+ hooks: deepMerge({
594
+ beforeRequest: [],
595
+ beforeRetry: [],
596
+ beforeError: [],
597
+ afterResponse: [],
598
+ }, options.hooks),
599
+ method: normalizeRequestMethod((_a = options.method) !== null && _a !== void 0 ? _a : this._input.method),
600
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
601
+ prefixUrl: String(options.prefixUrl || ''),
602
+ retry: normalizeRetryOptions(options.retry),
603
+ throwHttpErrors: options.throwHttpErrors !== false,
604
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
605
+ fetch: (_b = options.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis),
606
+ };
607
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
608
+ throw new TypeError('`input` must be a string, URL, or Request');
609
+ }
610
+ if (this._options.prefixUrl && typeof this._input === 'string') {
611
+ if (this._input.startsWith('/')) {
612
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
613
+ }
614
+ if (!this._options.prefixUrl.endsWith('/')) {
615
+ this._options.prefixUrl += '/';
616
+ }
617
+ this._input = this._options.prefixUrl + this._input;
618
+ }
619
+ if (supportsAbortController) {
620
+ this.abortController = new globalThis.AbortController();
621
+ if (this._options.signal) {
622
+ this._options.signal.addEventListener('abort', () => {
623
+ this.abortController.abort();
624
+ });
625
+ }
626
+ this._options.signal = this.abortController.signal;
627
+ }
628
+ this.request = new globalThis.Request(this._input, this._options);
629
+ if (this._options.searchParams) {
630
+ // eslint-disable-next-line unicorn/prevent-abbreviations
631
+ const textSearchParams = typeof this._options.searchParams === 'string'
632
+ ? this._options.searchParams.replace(/^\?/, '')
633
+ : new URLSearchParams(this._options.searchParams).toString();
634
+ // eslint-disable-next-line unicorn/prevent-abbreviations
635
+ const searchParams = '?' + textSearchParams;
636
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
637
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
638
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
639
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
640
+ this.request.headers.delete('content-type');
641
+ }
642
+ this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
643
+ }
644
+ if (this._options.json !== undefined) {
645
+ this._options.body = JSON.stringify(this._options.json);
646
+ this.request.headers.set('content-type', 'application/json');
647
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
648
+ }
649
+ }
650
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
651
+ static create(input, options) {
652
+ const ky = new Ky(input, options);
653
+ const fn = async () => {
654
+ if (ky._options.timeout > maxSafeTimeout) {
655
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
656
+ }
657
+ // Delay the fetch so that body method shortcuts can set the Accept header
658
+ await Promise.resolve();
659
+ let response = await ky._fetch();
660
+ for (const hook of ky._options.hooks.afterResponse) {
661
+ // eslint-disable-next-line no-await-in-loop
662
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
663
+ if (modifiedResponse instanceof globalThis.Response) {
664
+ response = modifiedResponse;
665
+ }
666
+ }
667
+ ky._decorateResponse(response);
668
+ if (!response.ok && ky._options.throwHttpErrors) {
669
+ let error = new HTTPError(response, ky.request, ky._options);
670
+ for (const hook of ky._options.hooks.beforeError) {
671
+ // eslint-disable-next-line no-await-in-loop
672
+ error = await hook(error);
673
+ }
674
+ throw error;
675
+ }
676
+ // If `onDownloadProgress` is passed, it uses the stream API internally
677
+ /* istanbul ignore next */
678
+ if (ky._options.onDownloadProgress) {
679
+ if (typeof ky._options.onDownloadProgress !== 'function') {
680
+ throw new TypeError('The `onDownloadProgress` option must be a function');
681
+ }
682
+ if (!supportsStreams) {
683
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
684
+ }
685
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
686
+ }
687
+ return response;
688
+ };
689
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
690
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
691
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
692
+ result[type] = async () => {
693
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
694
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
695
+ const response = (await result).clone();
696
+ if (type === 'json') {
697
+ if (response.status === 204) {
698
+ return '';
699
+ }
700
+ if (options.parseJson) {
701
+ return options.parseJson(await response.text());
702
+ }
703
+ }
704
+ return response[type]();
705
+ };
706
+ }
707
+ return result;
708
+ }
709
+ _calculateRetryDelay(error) {
710
+ this._retryCount++;
711
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
712
+ if (error instanceof HTTPError) {
713
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
714
+ return 0;
715
+ }
716
+ const retryAfter = error.response.headers.get('Retry-After');
717
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
718
+ let after = Number(retryAfter);
719
+ if (Number.isNaN(after)) {
720
+ after = Date.parse(retryAfter) - Date.now();
721
+ }
722
+ else {
723
+ after *= 1000;
724
+ }
725
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
726
+ return 0;
727
+ }
728
+ return after;
729
+ }
730
+ if (error.response.status === 413) {
731
+ return 0;
732
+ }
733
+ }
734
+ const BACKOFF_FACTOR = 0.3;
735
+ return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
736
+ }
737
+ return 0;
738
+ }
739
+ _decorateResponse(response) {
740
+ if (this._options.parseJson) {
741
+ response.json = async () => this._options.parseJson(await response.text());
742
+ }
743
+ return response;
744
+ }
745
+ async _retry(fn) {
746
+ try {
747
+ return await fn();
748
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
749
+ }
750
+ catch (error) {
751
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
752
+ if (ms !== 0 && this._retryCount > 0) {
753
+ await delay(ms);
754
+ for (const hook of this._options.hooks.beforeRetry) {
755
+ // eslint-disable-next-line no-await-in-loop
756
+ const hookResult = await hook({
757
+ request: this.request,
758
+ options: this._options,
759
+ error: error,
760
+ retryCount: this._retryCount,
761
+ });
762
+ // If `stop` is returned from the hook, the retry process is stopped
763
+ if (hookResult === stop) {
764
+ return;
765
+ }
766
+ }
767
+ return this._retry(fn);
768
+ }
769
+ throw error;
770
+ }
771
+ }
772
+ async _fetch() {
773
+ for (const hook of this._options.hooks.beforeRequest) {
774
+ // eslint-disable-next-line no-await-in-loop
775
+ const result = await hook(this.request, this._options);
776
+ if (result instanceof Request) {
777
+ this.request = result;
778
+ break;
779
+ }
780
+ if (result instanceof Response) {
781
+ return result;
782
+ }
783
+ }
784
+ if (this._options.timeout === false) {
785
+ return this._options.fetch(this.request.clone());
786
+ }
787
+ return timeout(this.request.clone(), this.abortController, this._options);
788
+ }
789
+ /* istanbul ignore next */
790
+ _stream(response, onDownloadProgress) {
791
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
792
+ let transferredBytes = 0;
793
+ return new globalThis.Response(new globalThis.ReadableStream({
794
+ async start(controller) {
795
+ const reader = response.body.getReader();
796
+ if (onDownloadProgress) {
797
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
798
+ }
799
+ async function read() {
800
+ const { done, value } = await reader.read();
801
+ if (done) {
802
+ controller.close();
803
+ return;
804
+ }
805
+ if (onDownloadProgress) {
806
+ transferredBytes += value.byteLength;
807
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
808
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
809
+ }
810
+ controller.enqueue(value);
811
+ await read();
812
+ }
813
+ await read();
814
+ },
815
+ }));
816
+ }
817
+ }
818
+
819
+ /*! MIT License © Sindre Sorhus */
820
+ const createInstance = (defaults) => {
821
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
822
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
823
+ for (const method of requestMethods) {
824
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
825
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
826
+ }
827
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
828
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
829
+ ky.stop = stop;
830
+ return ky;
831
+ };
832
+ const ky = createInstance();
833
+
834
+ exports.HTTPError = HTTPError;
835
+ exports.TimeoutError = TimeoutError;
836
+ exports["default"] = ky;
837
+
838
+ Object.defineProperty(exports, '__esModule', { value: true });
839
+
840
+ }));
841
+ } (ky$1, ky$1.exports));
842
+
843
+ const urlHttp = lightweight;
844
+ const { flattie: flatten } = dist;
845
+ const { encode: stringify } = require$$2;
846
+ const whoops = lib.exports;
847
+
848
+ const factory = factory_1;
849
+ const { default: ky } = ky$1.exports;
850
+
851
+ const MicrolinkError = whoops('MicrolinkError');
852
+
853
+ const got = async (url, opts) => {
854
+ try {
855
+ if (opts.timeout === undefined) opts.timeout = false;
856
+ const response = await ky(url, opts);
857
+ const body = await response.json();
858
+ const { headers, status: statusCode } = response;
859
+ return { url: response.url, body, headers, statusCode }
860
+ } catch (err) {
861
+ if (err.response) {
862
+ const { response } = err;
863
+ err.response = {
864
+ ...response,
865
+ headers: Array.from(response.headers.entries()).reduce(
866
+ (acc, [key, value]) => {
867
+ acc[key] = value;
868
+ return acc
869
+ },
870
+ {}
871
+ ),
872
+ statusCode: response.status,
873
+ body: await response.text()
874
+ };
875
+ }
876
+ throw err
877
+ }
878
+ };
879
+
880
+ var browser = factory({
881
+ MicrolinkError,
882
+ urlHttp,
883
+ stringify,
884
+ got,
885
+ flatten,
886
+ VERSION: '0.10.20'
887
+ });
888
+
889
+ return browser;
890
+
891
+ }));
892
+ //# sourceMappingURL=mql.js.map