@microlink/mql 0.11.0-2 → 0.11.0-4

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