@microlink/function 0.1.4 → 0.1.7

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