@microlink/function 0.1.1 → 0.1.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.
@@ -1,1167 +1,958 @@
1
- ;(function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined'
3
- ? (module.exports = factory(require('url')))
4
- : typeof define === 'function' && define.amd
5
- ? define(['url'], factory)
6
- : ((global =
7
- typeof globalThis !== 'undefined' ? globalThis : global || self),
8
- (global.microlink = factory(global.require$$0$1)))
9
- })(this, function (require$$0$1) {
10
- 'use strict'
11
-
12
- function _interopDefaultLegacy (e) {
13
- return e && typeof e === 'object' && 'default' in e ? e : { default: e }
14
- }
15
-
16
- var require$$0__default = /*#__PURE__*/ _interopDefaultLegacy(require$$0$1)
17
-
18
- var commonjsGlobal =
19
- typeof globalThis !== 'undefined'
20
- ? globalThis
21
- : typeof window !== 'undefined'
22
- ? window
23
- : typeof global !== 'undefined'
24
- ? global
25
- : typeof self !== 'undefined'
26
- ? self
27
- : {}
28
-
29
- function getAugmentedNamespace (n) {
30
- if (n.__esModule) return n
31
- var a = Object.defineProperty({}, '__esModule', { value: true })
32
- Object.keys(n).forEach(function (k) {
33
- var d = Object.getOwnPropertyDescriptor(n, k)
34
- Object.defineProperty(
35
- a,
36
- k,
37
- d.get
38
- ? d
39
- : {
40
- enumerable: true,
41
- get: function () {
42
- return n[k]
43
- }
44
- }
45
- )
46
- })
47
- return a
48
- }
49
-
50
- const factory$2 = ({ mql, VERSION, toCompress }) => {
51
- const microlink = (code, mqlOpts, gotOpts) => {
52
- const compress = toCompress(code)
53
-
54
- return async (url, opts) => {
55
- const { data } = await mql(
56
- url,
57
- {
58
- function: await compress,
59
- meta: false,
60
- ...mqlOpts,
61
- ...opts
62
- },
63
- gotOpts
64
- )
65
-
66
- return data.function
67
- }
68
- }
69
-
70
- microlink.version = VERSION
71
- microlink.mql = mql
72
-
73
- return microlink
74
- }
75
-
76
- var factory_1$1 = factory$2
77
-
78
- const URL$1 = commonjsGlobal.window
79
- ? window.URL
80
- : require$$0__default['default'].URL
81
- const REGEX_HTTP_PROTOCOL = /^https?:\/\//i
82
-
83
- var lightweight = url => {
84
- try {
85
- return REGEX_HTTP_PROTOCOL.test(new URL$1(url).href)
86
- } catch (err) {
87
- return false
88
- }
89
- }
90
-
91
- var dist = {}
92
-
93
- function iter (output, nullish, sep, val, key) {
94
- var k,
95
- pfx = key ? key + sep : key
96
-
97
- if (val == null) {
98
- if (nullish) output[key] = val
99
- } else if (typeof val != 'object') {
100
- output[key] = val
101
- } else if (Array.isArray(val)) {
102
- for (k = 0; k < val.length; k++) {
103
- iter(output, nullish, sep, val[k], pfx + k)
104
- }
105
- } else {
106
- for (k in val) {
107
- iter(output, nullish, sep, val[k], pfx + k)
108
- }
109
- }
110
- }
111
-
112
- function flattie (input, glue, toNull) {
113
- var output = {}
114
- if (typeof input == 'object') {
115
- iter(output, !!toNull, glue || '.', input, '')
116
- }
117
- return output
118
- }
119
-
120
- dist.flattie = flattie
121
-
122
- function encode (obj, pfx) {
123
- var k,
124
- i,
125
- tmp,
126
- str = ''
127
-
128
- for (k in obj) {
129
- if ((tmp = obj[k]) !== void 0) {
130
- if (Array.isArray(tmp)) {
131
- for (i = 0; i < tmp.length; i++) {
132
- str && (str += '&')
133
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i])
134
- }
135
- } else {
136
- str && (str += '&')
137
- str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp)
138
- }
139
- }
140
- }
141
-
142
- return (pfx || '') + str
143
- }
144
-
145
- function toValue (mix) {
146
- if (!mix) return ''
147
- var str = decodeURIComponent(mix)
148
- if (str === 'false') return false
149
- if (str === 'true') return true
150
- return +str * 0 === 0 ? +str : str
151
- }
152
-
153
- function decode (str) {
154
- var tmp,
155
- k,
156
- out = {},
157
- arr = str.split('&')
158
-
159
- while ((tmp = arr.shift())) {
160
- tmp = tmp.split('=')
161
- k = tmp.shift()
162
- if (out[k] !== void 0) {
163
- out[k] = [].concat(out[k], toValue(tmp.shift()))
164
- } else {
165
- out[k] = toValue(tmp.shift())
166
- }
167
- }
168
-
169
- return out
170
- }
171
-
172
- var qss_m = /*#__PURE__*/ Object.freeze({
173
- __proto__: null,
174
- encode: encode,
175
- decode: decode
176
- })
177
-
178
- var require$$2 = /*@__PURE__*/ getAugmentedNamespace(qss_m)
179
-
180
- var ky$1 = { exports: {} }
181
-
182
- ;(function (module, exports) {
183
- ;(function (global, factory) {
184
- module.exports = factory()
185
- })(commonjsGlobal, function () {
186
- /*! MIT License © Sindre Sorhus */
187
-
188
- const isObject = value => value !== null && typeof value === 'object'
189
- const supportsAbortController =
190
- typeof globalThis.AbortController === 'function'
191
- const supportsStreams = typeof globalThis.ReadableStream === 'function'
192
- const supportsFormData = typeof globalThis.FormData === 'function'
193
-
194
- const mergeHeaders = (source1, source2) => {
195
- const result = new globalThis.Headers(source1 || {})
196
- const isHeadersInstance = source2 instanceof globalThis.Headers
197
- const source = new globalThis.Headers(source2 || {})
198
-
199
- for (const [key, value] of source) {
200
- if (
201
- (isHeadersInstance && value === 'undefined') ||
202
- value === undefined
203
- ) {
204
- result.delete(key)
205
- } else {
206
- result.set(key, value)
207
- }
208
- }
209
-
210
- return result
211
- }
212
-
213
- const deepMerge = (...sources) => {
214
- let returnValue = {}
215
- let headers = {}
216
-
217
- for (const source of sources) {
218
- if (Array.isArray(source)) {
219
- if (!Array.isArray(returnValue)) {
220
- returnValue = []
221
- }
222
-
223
- returnValue = [...returnValue, ...source]
224
- } else if (isObject(source)) {
225
- for (let [key, value] of Object.entries(source)) {
226
- if (isObject(value) && key in returnValue) {
227
- value = deepMerge(returnValue[key], value)
228
- }
229
-
230
- returnValue = { ...returnValue, [key]: value }
231
- }
232
-
233
- if (isObject(source.headers)) {
234
- headers = mergeHeaders(headers, source.headers)
235
- }
236
- }
237
-
238
- returnValue.headers = headers
239
- }
240
-
241
- return returnValue
242
- }
243
-
244
- const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete']
245
-
246
- const responseTypes = {
247
- json: 'application/json',
248
- text: 'text/*',
249
- formData: 'multipart/form-data',
250
- arrayBuffer: '*/*',
251
- blob: '*/*'
252
- }
253
-
254
- const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace']
255
-
256
- const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504]
257
-
258
- const retryAfterStatusCodes = [413, 429, 503]
259
-
260
- const stop = Symbol('stop')
261
-
262
- class HTTPError extends Error {
263
- constructor (response, request, options) {
264
- // Set the message to the status text, such as Unauthorized,
265
- // with some fallbacks. This message should never be undefined.
266
- super(
267
- response.statusText ||
268
- String(
269
- response.status === 0 || response.status
270
- ? response.status
271
- : 'Unknown response error'
272
- )
273
- )
274
- this.name = 'HTTPError'
275
- this.response = response
276
- this.request = request
277
- this.options = options
278
- }
279
- }
280
-
281
- class TimeoutError extends Error {
282
- constructor (request) {
283
- super('Request timed out')
284
- this.name = 'TimeoutError'
285
- this.request = request
286
- }
287
- }
288
-
289
- const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
290
-
291
- // `Promise.race()` workaround (#91)
292
- const timeout = (request, abortController, options) =>
293
- new Promise((resolve, reject) => {
294
- const timeoutID = setTimeout(() => {
295
- if (abortController) {
296
- abortController.abort()
297
- }
298
-
299
- reject(new TimeoutError(request))
300
- }, options.timeout)
301
-
302
- /* eslint-disable promise/prefer-await-to-then */
303
- options
304
- .fetch(request)
305
- .then(resolve)
306
- .catch(reject)
307
- .then(() => {
308
- clearTimeout(timeoutID)
309
- })
310
- /* eslint-enable promise/prefer-await-to-then */
311
- })
312
-
313
- const normalizeRequestMethod = input =>
314
- requestMethods.includes(input) ? input.toUpperCase() : input
315
-
316
- const defaultRetryOptions = {
317
- limit: 2,
318
- methods: retryMethods,
319
- statusCodes: retryStatusCodes,
320
- afterStatusCodes: retryAfterStatusCodes
321
- }
322
-
323
- const normalizeRetryOptions = (retry = {}) => {
324
- if (typeof retry === 'number') {
325
- return {
326
- ...defaultRetryOptions,
327
- limit: retry
328
- }
329
- }
330
-
331
- if (retry.methods && !Array.isArray(retry.methods)) {
332
- throw new Error('retry.methods must be an array')
333
- }
334
-
335
- if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
336
- throw new Error('retry.statusCodes must be an array')
337
- }
338
-
339
- return {
340
- ...defaultRetryOptions,
341
- ...retry,
342
- afterStatusCodes: retryAfterStatusCodes
343
- }
344
- }
345
-
346
- // The maximum value of a 32bit int (see issue #117)
347
- const maxSafeTimeout = 2147483647
348
-
349
- class Ky {
350
- constructor (input, options = {}) {
351
- this._retryCount = 0
352
- this._input = input
353
- this._options = {
354
- // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
355
- credentials: this._input.credentials || 'same-origin',
356
- ...options,
357
- headers: mergeHeaders(this._input.headers, options.headers),
358
- hooks: deepMerge(
359
- {
360
- beforeRequest: [],
361
- beforeRetry: [],
362
- afterResponse: []
363
- },
364
- options.hooks
365
- ),
366
- method: normalizeRequestMethod(
367
- options.method || this._input.method
368
- ),
369
- prefixUrl: String(options.prefixUrl || ''),
370
- retry: normalizeRetryOptions(options.retry),
371
- throwHttpErrors: options.throwHttpErrors !== false,
372
- timeout:
373
- typeof options.timeout === 'undefined' ? 10000 : options.timeout,
374
- fetch: options.fetch || globalThis.fetch.bind(globalThis)
375
- }
376
-
377
- if (
378
- typeof this._input !== 'string' &&
379
- !(
380
- this._input instanceof URL ||
381
- this._input instanceof globalThis.Request
382
- )
383
- ) {
384
- throw new TypeError('`input` must be a string, URL, or Request')
385
- }
386
-
387
- if (this._options.prefixUrl && typeof this._input === 'string') {
388
- if (this._input.startsWith('/')) {
389
- throw new Error(
390
- '`input` must not begin with a slash when using `prefixUrl`'
391
- )
392
- }
393
-
394
- if (!this._options.prefixUrl.endsWith('/')) {
395
- this._options.prefixUrl += '/'
396
- }
397
-
398
- this._input = this._options.prefixUrl + this._input
399
- }
400
-
401
- if (supportsAbortController) {
402
- this.abortController = new globalThis.AbortController()
403
- if (this._options.signal) {
404
- this._options.signal.addEventListener('abort', () => {
405
- this.abortController.abort()
406
- })
407
- }
408
-
409
- this._options.signal = this.abortController.signal
410
- }
411
-
412
- this.request = new globalThis.Request(this._input, this._options)
413
-
414
- if (this._options.searchParams) {
415
- const textSearchParams =
416
- typeof this._options.searchParams === 'string'
417
- ? this._options.searchParams.replace(/^\?/, '')
418
- : new URLSearchParams(this._options.searchParams).toString()
419
- const searchParams = '?' + textSearchParams
420
- const url = this.request.url.replace(
421
- /(?:\?.*?)?(?=#|$)/,
422
- searchParams
423
- )
424
-
425
- // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
426
- if (
427
- ((supportsFormData &&
428
- this._options.body instanceof globalThis.FormData) ||
429
- this._options.body instanceof URLSearchParams) &&
430
- !(this._options.headers && this._options.headers['content-type'])
431
- ) {
432
- this.request.headers.delete('content-type')
433
- }
434
-
435
- this.request = new globalThis.Request(
436
- new globalThis.Request(url, this.request),
437
- this._options
438
- )
439
- }
440
-
441
- if (this._options.json !== undefined) {
442
- this._options.body = JSON.stringify(this._options.json)
443
- this.request.headers.set('content-type', 'application/json')
444
- this.request = new globalThis.Request(this.request, {
445
- body: this._options.body
446
- })
447
- }
448
-
449
- const fn = async () => {
450
- if (this._options.timeout > maxSafeTimeout) {
451
- throw new RangeError(
452
- `The \`timeout\` option cannot be greater than ${maxSafeTimeout}`
453
- )
454
- }
455
-
456
- await delay(1)
457
- let response = await this._fetch()
458
-
459
- for (const hook of this._options.hooks.afterResponse) {
460
- // eslint-disable-next-line no-await-in-loop
461
- const modifiedResponse = await hook(
462
- this.request,
463
- this._options,
464
- this._decorateResponse(response.clone())
465
- )
466
-
467
- if (modifiedResponse instanceof globalThis.Response) {
468
- response = modifiedResponse
469
- }
470
- }
471
-
472
- this._decorateResponse(response)
473
-
474
- if (!response.ok && this._options.throwHttpErrors) {
475
- throw new HTTPError(response, this.request, this._options)
476
- }
477
-
478
- // If `onDownloadProgress` is passed, it uses the stream API internally
479
- /* istanbul ignore next */
480
- if (this._options.onDownloadProgress) {
481
- if (typeof this._options.onDownloadProgress !== 'function') {
482
- throw new TypeError(
483
- 'The `onDownloadProgress` option must be a function'
484
- )
485
- }
486
-
487
- if (!supportsStreams) {
488
- throw new Error(
489
- 'Streams are not supported in your environment. `ReadableStream` is missing.'
490
- )
491
- }
492
-
493
- return this._stream(
494
- response.clone(),
495
- this._options.onDownloadProgress
496
- )
497
- }
498
-
499
- return response
500
- }
501
-
502
- const isRetriableMethod = this._options.retry.methods.includes(
503
- this.request.method.toLowerCase()
504
- )
505
- const result = isRetriableMethod ? this._retry(fn) : fn()
506
-
507
- for (const [type, mimeType] of Object.entries(responseTypes)) {
508
- result[type] = async () => {
509
- this.request.headers.set(
510
- 'accept',
511
- this.request.headers.get('accept') || mimeType
512
- )
513
-
514
- const response = (await result).clone()
515
-
516
- if (type === 'json') {
517
- if (response.status === 204) {
518
- return ''
519
- }
520
-
521
- if (options.parseJson) {
522
- return options.parseJson(await response.text())
523
- }
524
- }
525
-
526
- return response[type]()
527
- }
528
- }
529
-
530
- return result
531
- }
532
-
533
- _calculateRetryDelay (error) {
534
- this._retryCount++
535
-
536
- if (
537
- this._retryCount < this._options.retry.limit &&
538
- !(error instanceof TimeoutError)
539
- ) {
540
- if (error instanceof HTTPError) {
541
- if (
542
- !this._options.retry.statusCodes.includes(error.response.status)
543
- ) {
544
- return 0
545
- }
546
-
547
- const retryAfter = error.response.headers.get('Retry-After')
548
- if (
549
- retryAfter &&
550
- this._options.retry.afterStatusCodes.includes(
551
- error.response.status
552
- )
553
- ) {
554
- let after = Number(retryAfter)
555
- if (Number.isNaN(after)) {
556
- after = Date.parse(retryAfter) - Date.now()
557
- } else {
558
- after *= 1000
559
- }
560
-
561
- if (
562
- typeof this._options.retry.maxRetryAfter !== 'undefined' &&
563
- after > this._options.retry.maxRetryAfter
564
- ) {
565
- return 0
566
- }
567
-
568
- return after
569
- }
570
-
571
- if (error.response.status === 413) {
572
- return 0
573
- }
574
- }
575
-
576
- const BACKOFF_FACTOR = 0.3
577
- return BACKOFF_FACTOR * 2 ** (this._retryCount - 1) * 1000
578
- }
579
-
580
- return 0
581
- }
582
-
583
- _decorateResponse (response) {
584
- if (this._options.parseJson) {
585
- response.json = async () => {
586
- return this._options.parseJson(await response.text())
587
- }
588
- }
589
-
590
- return response
591
- }
592
-
593
- async _retry (fn) {
594
- try {
595
- return await fn()
596
- } catch (error) {
597
- const ms = Math.min(
598
- this._calculateRetryDelay(error),
599
- maxSafeTimeout
600
- )
601
- if (ms !== 0 && this._retryCount > 0) {
602
- await delay(ms)
603
-
604
- for (const hook of this._options.hooks.beforeRetry) {
605
- // eslint-disable-next-line no-await-in-loop
606
- const hookResult = await hook({
607
- request: this.request,
608
- options: this._options,
609
- error,
610
- retryCount: this._retryCount
611
- })
612
-
613
- // If `stop` is returned from the hook, the retry process is stopped
614
- if (hookResult === stop) {
615
- return
616
- }
617
- }
618
-
619
- return this._retry(fn)
620
- }
621
-
622
- if (this._options.throwHttpErrors) {
623
- throw error
624
- }
625
- }
626
- }
627
-
628
- async _fetch () {
629
- for (const hook of this._options.hooks.beforeRequest) {
630
- // eslint-disable-next-line no-await-in-loop
631
- const result = await hook(this.request, this._options)
632
-
633
- if (result instanceof Request) {
634
- this.request = result
635
- break
636
- }
637
-
638
- if (result instanceof Response) {
639
- return result
640
- }
641
- }
642
-
643
- if (this._options.timeout === false) {
644
- return this._options.fetch(this.request.clone())
645
- }
646
-
647
- return timeout(
648
- this.request.clone(),
649
- this.abortController,
650
- this._options
651
- )
652
- }
653
-
654
- /* istanbul ignore next */
655
- _stream (response, onDownloadProgress) {
656
- const totalBytes = Number(response.headers.get('content-length')) || 0
657
- let transferredBytes = 0
658
-
659
- return new globalThis.Response(
660
- new globalThis.ReadableStream({
661
- async start (controller) {
662
- const reader = response.body.getReader()
663
-
664
- if (onDownloadProgress) {
665
- onDownloadProgress(
666
- { percent: 0, transferredBytes: 0, totalBytes },
667
- new Uint8Array()
668
- )
669
- }
670
-
671
- async function read () {
672
- const { done, value } = await reader.read()
673
- if (done) {
674
- controller.close()
675
- return
676
- }
677
-
678
- if (onDownloadProgress) {
679
- transferredBytes += value.byteLength
680
- const percent =
681
- totalBytes === 0 ? 0 : transferredBytes / totalBytes
682
- onDownloadProgress(
683
- { percent, transferredBytes, totalBytes },
684
- value
685
- )
686
- }
687
-
688
- controller.enqueue(value)
689
- await read()
690
- }
691
-
692
- await read()
693
- }
694
- })
695
- )
696
- }
697
- }
698
-
699
- const validateAndMerge = (...sources) => {
700
- for (const source of sources) {
701
- if (
702
- (!isObject(source) || Array.isArray(source)) &&
703
- typeof source !== 'undefined'
704
- ) {
705
- throw new TypeError('The `options` argument must be an object')
706
- }
707
- }
708
-
709
- return deepMerge({}, ...sources)
710
- }
711
-
712
- const createInstance = defaults => {
713
- const ky = (input, options) =>
714
- new Ky(input, validateAndMerge(defaults, options))
715
-
716
- for (const method of requestMethods) {
717
- ky[method] = (input, options) =>
718
- new Ky(input, validateAndMerge(defaults, options, { method }))
719
- }
720
-
721
- ky.HTTPError = HTTPError
722
- ky.TimeoutError = TimeoutError
723
- ky.create = newDefaults => createInstance(validateAndMerge(newDefaults))
724
- ky.extend = newDefaults =>
725
- createInstance(validateAndMerge(defaults, newDefaults))
726
- ky.stop = stop
727
-
728
- return ky
729
- }
730
-
731
- const ky = createInstance()
732
-
733
- return ky
734
- })
735
- })(ky$1)
736
-
737
- var lib = { exports: {} }
738
-
739
- var _nodeResolve_empty = {}
740
-
741
- var _nodeResolve_empty$1 = /*#__PURE__*/ Object.freeze({
742
- __proto__: null,
743
- default: _nodeResolve_empty
744
- })
745
-
746
- var require$$0 = /*@__PURE__*/ getAugmentedNamespace(_nodeResolve_empty$1)
747
-
748
- const os = require$$0
749
-
750
- const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/
751
- const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/
752
- const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir()
753
-
754
- var cleanStack$1 = (stack, options) => {
755
- options = Object.assign({ pretty: false }, options)
756
-
757
- return stack
758
- .replace(/\\/g, '/')
759
- .split('\n')
760
- .filter(line => {
761
- const pathMatches = line.match(extractPathRegex)
762
- if (pathMatches === null || !pathMatches[1]) {
763
- return true
764
- }
765
-
766
- const match = pathMatches[1]
767
-
768
- // Electron
769
- if (
770
- match.includes('.app/Contents/Resources/electron.asar') ||
771
- match.includes('.app/Contents/Resources/default_app.asar')
772
- ) {
773
- return false
774
- }
775
-
776
- return !pathRegex.test(match)
777
- })
778
- .filter(line => line.trim() !== '')
779
- .map(line => {
780
- if (options.pretty) {
781
- return line.replace(extractPathRegex, (m, p1) =>
782
- m.replace(p1, p1.replace(homeDir, '~'))
783
- )
784
- }
785
-
786
- return line
787
- })
788
- .join('\n')
789
- }
790
-
791
- const copyProperty = (to, from, property, ignoreNonConfigurable) => {
792
- // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
793
- // `Function#prototype` is non-writable and non-configurable so can never be modified.
794
- if (property === 'length' || property === 'prototype') {
795
- return
796
- }
797
-
798
- const toDescriptor = Object.getOwnPropertyDescriptor(to, property)
799
- const fromDescriptor = Object.getOwnPropertyDescriptor(from, property)
800
-
801
- if (
802
- !canCopyProperty(toDescriptor, fromDescriptor) &&
803
- ignoreNonConfigurable
804
- ) {
805
- return
806
- }
807
-
808
- Object.defineProperty(to, property, fromDescriptor)
809
- }
810
-
811
- // `Object.defineProperty()` throws if the property exists, is not configurable and either:
812
- // - one its descriptors is changed
813
- // - it is non-writable and its value is changed
814
- const canCopyProperty = function (toDescriptor, fromDescriptor) {
815
- return (
816
- toDescriptor === undefined ||
817
- toDescriptor.configurable ||
818
- (toDescriptor.writable === fromDescriptor.writable &&
819
- toDescriptor.enumerable === fromDescriptor.enumerable &&
820
- toDescriptor.configurable === fromDescriptor.configurable &&
821
- (toDescriptor.writable || toDescriptor.value === fromDescriptor.value))
822
- )
823
- }
824
-
825
- const changePrototype = (to, from) => {
826
- const fromPrototype = Object.getPrototypeOf(from)
827
- if (fromPrototype === Object.getPrototypeOf(to)) {
828
- return
829
- }
830
-
831
- Object.setPrototypeOf(to, fromPrototype)
832
- }
833
-
834
- const wrappedToString = (withName, fromBody) =>
835
- `/* Wrapped ${withName}*/\n${fromBody}`
836
-
837
- const toStringDescriptor = Object.getOwnPropertyDescriptor(
838
- Function.prototype,
839
- 'toString'
840
- )
841
- const toStringName = Object.getOwnPropertyDescriptor(
842
- Function.prototype.toString,
843
- 'name'
844
- )
845
-
846
- // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
847
- // We use `bind()` instead of a closure for the same reason.
848
- // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
849
- const changeToString = (to, from, name) => {
850
- const withName = name === '' ? '' : `with ${name.trim()}() `
851
- const newToString = wrappedToString.bind(null, withName, from.toString())
852
- // Ensure `to.toString.toString` is non-enumerable and has the same `same`
853
- Object.defineProperty(newToString, 'name', toStringName)
854
- Object.defineProperty(to, 'toString', {
855
- ...toStringDescriptor,
856
- value: newToString
857
- })
858
- }
859
-
860
- const mimicFn$2 = (to, from, { ignoreNonConfigurable = false } = {}) => {
861
- const { name } = to
862
-
863
- for (const property of Reflect.ownKeys(from)) {
864
- copyProperty(to, from, property, ignoreNonConfigurable)
865
- }
866
-
867
- changePrototype(to, from)
868
- changeToString(to, from, name)
869
-
870
- return to
871
- }
872
-
873
- var mimicFn_1 = mimicFn$2
874
-
875
- var helpers = {
876
- isFunction: obj => typeof obj === 'function',
877
- isString: obj => typeof obj === 'string',
878
- composeErrorMessage: (code, description) => `${code}, ${description}`,
879
- inherits: (ctor, superCtor) => {
880
- ctor.super_ = superCtor
881
- ctor.prototype = Object.create(superCtor.prototype, {
882
- constructor: {
883
- value: ctor,
884
- enumerable: false,
885
- writable: true,
886
- configurable: true
887
- }
888
- })
889
- }
890
- }
891
-
892
- const { isFunction, composeErrorMessage } = helpers
893
-
894
- function interfaceObject (error, ...props) {
895
- Object.assign(error, ...props)
896
-
897
- error.description = isFunction(error.message)
898
- ? error.message(error)
899
- : error.message
900
-
901
- error.message = error.code
902
- ? composeErrorMessage(error.code, error.description)
903
- : error.description
904
- }
905
-
906
- var addErrorProps$1 = interfaceObject
907
-
908
- const cleanStack = cleanStack$1
909
- const mimicFn$1 = mimicFn_1
910
-
911
- const addErrorProps = addErrorProps$1
912
- const { isString } = helpers
913
-
914
- function createExtendError$1 (ErrorClass, classProps) {
915
- function ExtendError (props) {
916
- const error = new ErrorClass()
917
- const errorProps = isString(props) ? { message: props } : props
918
- addErrorProps(error, classProps, errorProps)
919
-
920
- error.stack = cleanStack(error.stack)
921
- return error
922
- }
923
-
924
- ExtendError.prototype = ErrorClass.prototype
925
- mimicFn$1(ExtendError, ErrorClass)
926
-
927
- return ExtendError
928
- }
929
-
930
- var createExtendError_1 = createExtendError$1
931
-
932
- const { inherits } = helpers
933
- const mimicFn = mimicFn_1
934
-
935
- const REGEX_CLASS_NAME = /[^0-9a-zA-Z_$]/
936
-
937
- function createError$1 (className) {
938
- if (typeof className !== 'string') {
939
- throw new TypeError('Expected className to be a string')
940
- }
941
-
942
- if (REGEX_CLASS_NAME.test(className)) {
943
- throw new Error('className contains invalid characters')
944
- }
945
-
946
- function ErrorClass () {
947
- Object.defineProperty(this, 'name', {
948
- configurable: true,
949
- value: className,
950
- writable: true
951
- })
952
-
953
- Error.captureStackTrace(this, this.constructor)
954
- }
955
-
956
- inherits(ErrorClass, Error)
957
- mimicFn(ErrorClass, Error)
958
- return ErrorClass
959
- }
960
-
961
- var createError_1 = createError$1
962
-
963
- const createExtendError = createExtendError_1
964
- const createError = createError_1
965
-
966
- const createErrorClass = ErrorClass => (className, props) => {
967
- const errorClass = createError(className || ErrorClass.name)
968
- return createExtendError(errorClass, props)
969
- }
970
-
971
- lib.exports = createErrorClass(Error)
972
- lib.exports.type = createErrorClass(TypeError)
973
- lib.exports.range = createErrorClass(RangeError)
974
- lib.exports.eval = createErrorClass(EvalError)
975
- lib.exports.syntax = createErrorClass(SyntaxError)
976
- lib.exports.reference = createErrorClass(ReferenceError)
977
- lib.exports.uri = createErrorClass(URIError)
978
-
979
- const ENDPOINT = {
980
- FREE: 'https://api.microlink.io',
981
- PRO: 'https://pro.microlink.io'
982
- }
983
-
984
- const isObject = input => typeof input === 'object'
985
-
986
- const pickBy = obj => {
987
- Object.keys(obj).forEach(key => obj[key] == null && delete obj[key])
988
- return obj
989
- }
990
-
991
- const parseBody = (input, error, url) => {
992
- try {
993
- return JSON.parse(input)
994
- } catch (_) {
995
- const message = input || error.message
996
-
997
- return {
998
- status: 'error',
999
- data: { url: message },
1000
- more: 'https://microlink.io/efatal',
1001
- code: 'EFATAL',
1002
- message,
1003
- url
1004
- }
1005
- }
1006
- }
1007
-
1008
- const factory$1 = ({
1009
- VERSION,
1010
- MicrolinkError,
1011
- isUrlHttp,
1012
- stringify,
1013
- got,
1014
- flatten
1015
- }) => {
1016
- const assertUrl = (url = '') => {
1017
- if (!isUrlHttp(url)) {
1018
- const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`
1019
- throw new MicrolinkError({
1020
- status: 'fail',
1021
- data: { url: message },
1022
- more: 'https://microlink.io/docs/api/api-parameters/url',
1023
- code: 'EINVALURLCLIENT',
1024
- message,
1025
- url
1026
- })
1027
- }
1028
- }
1029
-
1030
- const mapRules = rules => {
1031
- if (!isObject(rules)) return
1032
- const flatRules = flatten(rules)
1033
- return Object.keys(flatRules).reduce(
1034
- (acc, key) => ({ ...acc, [`data.${key}`]: flatRules[key] }),
1035
- {}
1036
- )
1037
- }
1038
-
1039
- const fetchFromApi = async (apiUrl, opts = {}) => {
1040
- try {
1041
- const response = await got(apiUrl, opts)
1042
- return opts.responseType === 'buffer'
1043
- ? { body: response.body, response }
1044
- : { ...response.body, response }
1045
- } catch (err) {
1046
- const { response = {} } = err
1047
- const {
1048
- statusCode,
1049
- body: rawBody,
1050
- headers,
1051
- url: uri = apiUrl
1052
- } = response
1053
-
1054
- const body =
1055
- isObject(rawBody) && !Buffer.isBuffer(rawBody)
1056
- ? rawBody
1057
- : parseBody(rawBody, err, uri)
1058
-
1059
- throw MicrolinkError({
1060
- ...body,
1061
- message: body.message,
1062
- url: uri,
1063
- statusCode,
1064
- headers
1065
- })
1066
- }
1067
- }
1068
-
1069
- const getApiUrl = (
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('url')) :
3
+ typeof define === 'function' && define.amd ? define(['url'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.microlink = factory(global.require$$0$1));
5
+ })(this, (function (require$$0$1) { 'use strict';
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
10
+
11
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
12
+
13
+ function getAugmentedNamespace(n) {
14
+ if (n.__esModule) return n;
15
+ var a = Object.defineProperty({}, '__esModule', {value: true});
16
+ Object.keys(n).forEach(function (k) {
17
+ var d = Object.getOwnPropertyDescriptor(n, k);
18
+ Object.defineProperty(a, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () {
21
+ return n[k];
22
+ }
23
+ });
24
+ });
25
+ return a;
26
+ }
27
+
28
+ const factory$2 = ({ mql, VERSION, toCompress }) => {
29
+ const microlink = (code, mqlOpts, gotOpts) => {
30
+ const compress = toCompress(code);
31
+
32
+ return async (url, opts) => {
33
+ const { data } = await mql(
34
+ url,
35
+ {
36
+ function: await compress,
37
+ meta: false,
38
+ ...mqlOpts,
39
+ ...opts
40
+ },
41
+ gotOpts
42
+ );
43
+
44
+ return data.function
45
+ }
46
+ };
47
+
48
+ microlink.version = VERSION;
49
+ microlink.mql = mql;
50
+
51
+ return microlink
52
+ };
53
+
54
+ var factory_1$1 = factory$2;
55
+
56
+ const URL$1 = commonjsGlobal.window ? window.URL : require$$0__default["default"].URL;
57
+ const REGEX_HTTP_PROTOCOL = /^https?:\/\//i;
58
+
59
+ var lightweight = url => {
60
+ try {
61
+ return REGEX_HTTP_PROTOCOL.test(new URL$1(url).href)
62
+ } catch (err) {
63
+ return false
64
+ }
65
+ };
66
+
67
+ var dist = {};
68
+
69
+ function iter(output, nullish, sep, val, key) {
70
+ var k, pfx = key ? (key + sep) : key;
71
+
72
+ if (val == null) {
73
+ if (nullish) output[key] = val;
74
+ } else if (typeof val != 'object') {
75
+ output[key] = val;
76
+ } else if (Array.isArray(val)) {
77
+ for (k=0; k < val.length; k++) {
78
+ iter(output, nullish, sep, val[k], pfx + k);
79
+ }
80
+ } else {
81
+ for (k in val) {
82
+ iter(output, nullish, sep, val[k], pfx + k);
83
+ }
84
+ }
85
+ }
86
+
87
+ function flattie(input, glue, toNull) {
88
+ var output = {};
89
+ if (typeof input == 'object') {
90
+ iter(output, !!toNull, glue || '.', input, '');
91
+ }
92
+ return output;
93
+ }
94
+
95
+ dist.flattie = flattie;
96
+
97
+ function encode(obj, pfx) {
98
+ var k, i, tmp, str='';
99
+
100
+ for (k in obj) {
101
+ if ((tmp = obj[k]) !== void 0) {
102
+ if (Array.isArray(tmp)) {
103
+ for (i=0; i < tmp.length; i++) {
104
+ str && (str += '&');
105
+ str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp[i]);
106
+ }
107
+ } else {
108
+ str && (str += '&');
109
+ str += encodeURIComponent(k) + '=' + encodeURIComponent(tmp);
110
+ }
111
+ }
112
+ }
113
+
114
+ return (pfx || '') + str;
115
+ }
116
+
117
+ function toValue(mix) {
118
+ if (!mix) return '';
119
+ var str = decodeURIComponent(mix);
120
+ if (str === 'false') return false;
121
+ if (str === 'true') return true;
122
+ return (+str * 0 === 0) ? (+str) : str;
123
+ }
124
+
125
+ function decode(str) {
126
+ var tmp, k, out={}, arr=str.split('&');
127
+
128
+ while (tmp = arr.shift()) {
129
+ tmp = tmp.split('=');
130
+ k = tmp.shift();
131
+ if (out[k] !== void 0) {
132
+ out[k] = [].concat(out[k], toValue(tmp.shift()));
133
+ } else {
134
+ out[k] = toValue(tmp.shift());
135
+ }
136
+ }
137
+
138
+ return out;
139
+ }
140
+
141
+ var qss_m = /*#__PURE__*/Object.freeze({
142
+ __proto__: null,
143
+ encode: encode,
144
+ decode: decode
145
+ });
146
+
147
+ var require$$2 = /*@__PURE__*/getAugmentedNamespace(qss_m);
148
+
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
+ const ENDPOINT = {
372
+ FREE: 'https://api.microlink.io',
373
+ PRO: 'https://pro.microlink.io'
374
+ };
375
+
376
+ const isObject = input => input !== null && typeof input === 'object';
377
+
378
+ const parseBody = (input, error, url) => {
379
+ try {
380
+ return JSON.parse(input)
381
+ } catch (_) {
382
+ const message = input || error.message;
383
+
384
+ return {
385
+ status: 'error',
386
+ data: { url: message },
387
+ more: 'https://microlink.io/efatalclient',
388
+ code: 'EFATALCLIENT',
389
+ message,
390
+ url
391
+ }
392
+ }
393
+ };
394
+
395
+ const factory$1 = ({
396
+ VERSION,
397
+ MicrolinkError,
398
+ isUrlHttp,
399
+ stringify,
400
+ got,
401
+ flatten
402
+ }) => {
403
+ const assertUrl = (url = '') => {
404
+ if (!isUrlHttp(url)) {
405
+ const message = `The \`url\` as \`${url}\` is not valid. Ensure it has protocol (http or https) and hostname.`;
406
+ throw new MicrolinkError({
407
+ status: 'fail',
408
+ data: { url: message },
409
+ more: 'https://microlink.io/docs/api/api-parameters/url',
410
+ code: 'EINVALURLCLIENT',
411
+ message,
412
+ url
413
+ })
414
+ }
415
+ };
416
+
417
+ const mapRules = rules => {
418
+ if (!isObject(rules)) return
419
+ const flatRules = flatten(rules);
420
+ return Object.keys(flatRules).reduce((acc, key) => {
421
+ acc[`data.${key}`] = flatRules[key].toString();
422
+ return acc
423
+ }, {})
424
+ };
425
+
426
+ const fetchFromApi = async (apiUrl, opts = {}, retryCount = 0) => {
427
+ try {
428
+ const response = await got(apiUrl, opts);
429
+ return opts.responseType === 'buffer'
430
+ ? { body: response.body, response }
431
+ : { ...response.body, response }
432
+ } catch (err) {
433
+ const { response = {} } = err;
434
+ const { statusCode, body: rawBody, headers, url: uri = apiUrl } = response;
435
+ const isBuffer = Buffer.isBuffer(rawBody);
436
+
437
+ const body =
438
+ isObject(rawBody) && !isBuffer
439
+ ? rawBody
440
+ : parseBody(isBuffer ? rawBody.toString() : rawBody, err, uri);
441
+
442
+ if (body.code === 'EFATALCLIENT' && retryCount++ < 2) {
443
+ return fetchFromApi(apiUrl, opts, retryCount)
444
+ }
445
+
446
+ throw MicrolinkError({
447
+ ...body,
448
+ message: body.message,
449
+ url: uri,
450
+ statusCode,
451
+ headers
452
+ })
453
+ }
454
+ };
455
+
456
+ const getApiUrl = (
457
+ url,
458
+ { data, apiKey, endpoint, retry, cache, ...opts } = {},
459
+ { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
460
+ ) => {
461
+ const isPro = !!apiKey;
462
+ const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE'];
463
+
464
+ const apiUrl = `${apiEndpoint}?${stringify({
1070
465
  url,
1071
- { data, apiKey, endpoint, retry, cache, ...opts } = {},
1072
- { responseType = 'json', headers: gotHeaders, ...gotOpts } = {}
1073
- ) => {
1074
- const isPro = !!apiKey
1075
- const apiEndpoint = endpoint || ENDPOINT[isPro ? 'PRO' : 'FREE']
1076
-
1077
- const apiUrl = `${apiEndpoint}?${stringify({
1078
- url,
1079
- ...mapRules(data),
1080
- ...flatten(pickBy(opts))
1081
- })}`
1082
-
1083
- const headers = isPro
1084
- ? { ...gotHeaders, 'x-api-key': apiKey }
1085
- : { ...gotHeaders }
1086
- return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
1087
- }
1088
-
1089
- const createMql = defaultOpts => async (url, opts, gotOpts) => {
1090
- assertUrl(url)
1091
- const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
1092
- ...defaultOpts,
1093
- ...gotOpts
1094
- })
1095
- return fetchFromApi(apiUrl, fetchOpts)
1096
- }
1097
-
1098
- const mql = createMql()
1099
- mql.MicrolinkError = MicrolinkError
1100
- mql.getApiUrl = getApiUrl
1101
- mql.fetchFromApi = fetchFromApi
1102
- mql.mapRules = mapRules
1103
- mql.version = VERSION
1104
- mql.stream = got.stream
1105
- mql.buffer = createMql({ responseType: 'buffer' })
1106
-
1107
- return mql
1108
- }
1109
-
1110
- var factory_1 = factory$1
1111
-
1112
- const isUrlHttp = lightweight
1113
- const { flattie: flatten } = dist
1114
- const { encode: stringify } = require$$2
1115
- const ky = ky$1.exports
1116
- const whoops = lib.exports
1117
-
1118
- const factory = factory_1
1119
-
1120
- const MicrolinkError = whoops('MicrolinkError')
1121
-
1122
- const got = async (url, opts) => {
1123
- try {
1124
- if (opts.timeout === undefined) opts.timeout = false
1125
- const response = await ky(url, opts)
1126
- const body = await response.json()
1127
- const {
1128
- headers,
1129
- status: statusCode,
1130
- statusText: statusMessage
1131
- } = response
1132
- return { url: response.url, body, headers, statusCode, statusMessage }
1133
- } catch (err) {
1134
- if (err.response) {
1135
- const { response } = err
1136
- err.response = {
1137
- ...response,
1138
- headers: [...response.headers.entries()].reduce(
1139
- (acc, [key, value]) => ({ ...acc, [key]: value }),
1140
- {}
1141
- ),
1142
- statusCode: response.status,
1143
- body: await response.text()
1144
- }
1145
- }
1146
- throw err
1147
- }
1148
- }
1149
-
1150
- var browser$1 = factory({
1151
- MicrolinkError,
1152
- isUrlHttp,
1153
- stringify,
1154
- got,
1155
- flatten,
1156
- VERSION: '0.9.3'
1157
- })
1158
-
1159
- var browser = factory_1$1({
1160
- mql: browser$1,
1161
- toCompress: code => code.toString(),
1162
- VERSION: '0.1.1'
1163
- })
1164
-
1165
- return browser
1166
- })
466
+ ...mapRules(data),
467
+ ...flatten(opts)
468
+ })}`;
469
+
470
+ const headers = isPro
471
+ ? { ...gotHeaders, 'x-api-key': apiKey }
472
+ : { ...gotHeaders };
473
+ return [apiUrl, { ...gotOpts, responseType, cache, retry, headers }]
474
+ };
475
+
476
+ const createMql = defaultOpts => async (url, opts, gotOpts) => {
477
+ assertUrl(url);
478
+ const [apiUrl, fetchOpts] = getApiUrl(url, opts, {
479
+ ...defaultOpts,
480
+ ...gotOpts
481
+ });
482
+ return fetchFromApi(apiUrl, fetchOpts)
483
+ };
484
+
485
+ const mql = createMql();
486
+ mql.MicrolinkError = MicrolinkError;
487
+ mql.getApiUrl = getApiUrl;
488
+ mql.fetchFromApi = fetchFromApi;
489
+ mql.mapRules = mapRules;
490
+ mql.version = VERSION;
491
+ mql.stream = got.stream;
492
+ mql.buffer = createMql({ responseType: 'buffer' });
493
+
494
+ return mql
495
+ };
496
+
497
+ var factory_1 = factory$1;
498
+
499
+ var ky$1 = {exports: {}};
500
+
501
+ (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;
904
+ const { flattie: flatten } = dist;
905
+ const { encode: stringify } = require$$2;
906
+ const whoops = lib.exports;
907
+
908
+ const factory = factory_1;
909
+ const { default: ky } = ky$1.exports;
910
+
911
+ const MicrolinkError = whoops('MicrolinkError');
912
+
913
+ const got = async (url, opts) => {
914
+ try {
915
+ if (opts.timeout === undefined) opts.timeout = false;
916
+ const response = await ky(url, opts);
917
+ const body = await response.json();
918
+ const { headers, status: statusCode, statusText: statusMessage } = response;
919
+ return { url: response.url, body, headers, statusCode, statusMessage }
920
+ } catch (err) {
921
+ if (err.response) {
922
+ const { response } = err;
923
+ err.response = {
924
+ ...response,
925
+ headers: Array.from(response.headers.entries()).reduce(
926
+ (acc, [key, value]) => {
927
+ acc[key] = value;
928
+ return acc
929
+ },
930
+ {}
931
+ ),
932
+ statusCode: response.status,
933
+ body: await response.text()
934
+ };
935
+ }
936
+ throw err
937
+ }
938
+ };
939
+
940
+ var browser$1 = factory({
941
+ MicrolinkError,
942
+ isUrlHttp,
943
+ stringify,
944
+ got,
945
+ flatten,
946
+ VERSION: '0.10.15'
947
+ });
948
+
949
+ var browser = factory_1$1({
950
+ mql: browser$1,
951
+ toCompress: code => code.toString(),
952
+ VERSION: '0.1.3'
953
+ });
954
+
955
+ return browser;
956
+
957
+ }));
1167
958
  //# sourceMappingURL=microlink-function.js.map