@microlink/mql 0.11.0-0 → 0.11.0-2

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