UNPKG

uploadcare-widget

Version:
1,380 lines (1,339 loc) 194 kB
/** * @license uploadcare-widget v3.23.3 * * Copyright (c) 2025 Uploadcare, Inc. * * This source code is licensed under the BSD 2-Clause License * found in the LICENSE file in the root directory of this source tree. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.uploadcare = factory(global.$)); })(this, (function ($) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var $__default = /*#__PURE__*/_interopDefaultLegacy($); function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = it.call(o); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } // utils var log = function log() { var ref; try { var _ref; return (ref = window.console) != null ? typeof ref.log === 'function' ? (_ref = ref).log.apply(_ref, arguments) : undefined : undefined; } catch (error) {} }; var debug = function debug() { var ref; if ((ref = window.console) != null ? ref.debug : undefined) { try { var _window$console; return (_window$console = window.console).debug.apply(_window$console, arguments); } catch (error) {} } else { return log.apply(void 0, ['Debug:'].concat(Array.prototype.slice.call(arguments))); } }; var warn = function warn() { var ref; if ((ref = window.console) != null ? ref.warn : undefined) { try { var _window$console2; return (_window$console2 = window.console).warn.apply(_window$console2, arguments); } catch (error) {} } else { return log.apply(void 0, ['Warning:'].concat(Array.prototype.slice.call(arguments))); } }; var messages = {}; var warnOnce = function warnOnce(msg) { if (messages[msg] == null) { messages[msg] = true; return warn(msg); } }; var isWindowDefined = function isWindowDefined() { return (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object'; }; var isWindowDefined$1 = /*#__PURE__*/Object.freeze({ __proto__: null, isWindowDefined: isWindowDefined }); var REQUEST_WAS_THROTTLED_CODE = 'RequestThrottledError'; var DEFAULT_THROTTLED_TIMEOUT = 15000; /** * @typedef {object} RetryState * @property {number} [attempt] * @property {number} [timeoutId] * @property {JQuery.jqXHR} [jqXHR] */ /** * @typedef {object} RetryConfig * @property {number} baseTimeout * @property {number} attempts * @property {number} throttledAttempts * @property {number} factor * @property {boolean} debugUploads * @property {Function} [onAttemptFail] */ /** * @param {JQuery.jqXHR} jqXHR * @param {RetryConfig} config * @param {RetryState} state */ function getRetrySettings(jqXHR, config, state) { var _jqXHR$responseJSON; var isThrottled = (jqXHR === null || jqXHR === void 0 || (_jqXHR$responseJSON = jqXHR.responseJSON) === null || _jqXHR$responseJSON === void 0 || (_jqXHR$responseJSON = _jqXHR$responseJSON.error) === null || _jqXHR$responseJSON === void 0 ? void 0 : _jqXHR$responseJSON.error_code) === REQUEST_WAS_THROTTLED_CODE; if (isThrottled && state.attempt < config.throttledAttempts) { var retryAfter = Number.parseFloat(jqXHR.getResponseHeader('retry-after')); return { shouldRetry: true, retryTimeout: Number.isFinite(retryAfter) ? Math.ceil(retryAfter * 1000) : DEFAULT_THROTTLED_TIMEOUT }; } var isRequestFailed = ['error', 'timeout'].indexOf(jqXHR.statusText) !== -1; if (isRequestFailed && state.attempt < config.attempts) { var retryTimeout = Math.round(config.baseTimeout * Math.pow(config.factor, state.attempt)); return { shouldRetry: true, retryTimeout: retryTimeout }; } return { shouldRetry: false }; } /** * * @param {JQuery.jqXHR} jqXHR * @param {JQuery.AjaxSettings} ajaxSettings * @param {RetryConfig} config * @param {RetryState} state * @returns */ function createPipeFilter(jqXHR, ajaxSettings, config, state) { return function () { var df = $__default["default"].Deferred(); function nextRequest() { state.jqXHR = $__default["default"].ajax(ajaxSettings).retry(config, _objectSpread2(_objectSpread2({}, state), {}, { attempt: state.attempt + 1 })).done(df.resolve).fail(df.reject); } var _getRetrySettings = getRetrySettings(jqXHR, config, state), shouldRetry = _getRetrySettings.shouldRetry, retryTimeout = _getRetrySettings.retryTimeout; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (shouldRetry) { var _config$onAttemptFail; (_config$onAttemptFail = config.onAttemptFail) === null || _config$onAttemptFail === void 0 || _config$onAttemptFail.call(config, { attempt: state.attempt }); if (config.debugUploads) { log("Attempt failed. Retry #".concat(state.attempt + 1, " in ").concat(retryTimeout, "ms"), jqXHR); } state.timeoutId = setTimeout(nextRequest, retryTimeout); } else if (jqXHR.state() === 'resolved') { df.resolveWith(jqXHR, args); } else { df.rejectWith(jqXHR, args); } return df; }; } /** * * @param {JQuery.jqXHR} jqXHR * @param {JQuery.AjaxSettings} ajaxSettings * @param {RetryConfig} retryConfig * @param {RetryState} retryState * @returns {JQuery.PromiseBase} */ function ajaxRetry(jqXHR, ajaxSettings, retryConfig, retryState) { var missedOption = ['baseTimeout', 'attempts', 'factor'].find(function (key) { return typeof retryConfig[key] === 'undefined'; }); if (missedOption) { warn("Option key \"".concat(missedOption, "\" is missed in the retry config.")); return jqXHR; } retryState = { attempt: retryState.attempt || 0, timeoutId: null, jqXHR: null }; retryConfig = _objectSpread2({ baseTimeout: null, attempts: null, factor: null, onAttemptFail: null, debugUploads: false }, retryConfig); var pipeFilter = createPipeFilter(jqXHR, ajaxSettings, retryConfig, retryState); var df = jqXHR.then(pipeFilter, pipeFilter); df.abort = function () { var _retryState$jqXHR; clearTimeout(retryState.timeoutId); for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } jqXHR.abort.apply(jqXHR, args); (_retryState$jqXHR = retryState.jqXHR) === null || _retryState$jqXHR === void 0 || _retryState$jqXHR.abort.apply(_retryState$jqXHR, args); }; return df; } isWindowDefined() && function () { $__default["default"].ajaxPrefilter(function (ajaxSettings, _, jqXHR) { jqXHR.retry = function (retryConfig) { var retryState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return ajaxRetry(jqXHR, ajaxSettings, retryConfig, retryState); }; }); }(); // from https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js if (isWindowDefined() && window.XDomainRequest) { $__default["default"].ajaxTransport(function (s) { if (s.crossDomain && s.async) { if (s.timeout) { s.xdrTimeout = s.timeout; delete s.timeout; } var xdr; return { send: function send(_, complete) { function callback(status, statusText, responses, responseHeaders) { xdr.onload = xdr.onerror = xdr.ontimeout = function () {}; xdr = undefined; complete(status, statusText, responses, responseHeaders); } xdr = new XDomainRequest(); xdr.onload = function () { callback(200, "OK", { text: xdr.responseText }, "Content-Type: " + xdr.contentType); }; xdr.onerror = function () { callback(404, "Not Found"); }; xdr.onprogress = function () {}; xdr.ontimeout = function () { callback(0, "timeout"); }; xdr.timeout = s.xdrTimeout || Number.MAX_VALUE; xdr.open(s.type, s.url.replace(/^https?:/, '')); xdr.send(s.hasContent && s.data || null); }, abort: function abort() { if (xdr) { xdr.onerror = function () {}; xdr.abort(); } } }; } }); } var version = "3.23.3"; // utils.abilities var fileAPI = isWindowDefined() && !!(window.File && window.FileList && window.FileReader); var sendFileAPI = isWindowDefined() && !!(window.FormData && fileAPI); // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/draganddrop.js var dragAndDrop = isWindowDefined() && function () { var el; el = document.createElement('div'); return 'draggable' in el || 'ondragstart' in el && 'ondrop' in el; }(); // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas.js var canvas = isWindowDefined() && function () { var el; el = document.createElement('canvas'); return !!(el.getContext && el.getContext('2d')); }(); var fileDragAndDrop = fileAPI && dragAndDrop; var iOSVersion = null; // TODO: don't access to navigator in module scope (NODE don't have navigator) var ios = isWindowDefined() && /^[^(]+\(iP(?:hone|od|ad);\s*(.+?)\)/.exec(navigator.userAgent); if (ios) { var ver = /OS (\d*)_(\d*)/.exec(ios[1]); if (ver) { iOSVersion = +ver[1] + ver[2] / 10; } } // There is no a guaranteed way to detect iPadOs, cause it mimics the desktop safari. // So we're checkin for multitouch support and `navigator.platform` value. // Since no desktop macs with multitouch exists, this check will work. For now at least. // Workaround source: https://stackoverflow.com/questions/57776001/how-to-detect-ipad-pro-as-ipad-using-javascript var isIpadOs = isWindowDefined() && navigator.maxTouchPoints && navigator.maxTouchPoints > 2 && /MacIntel/.test(navigator.platform); var Blob = false; try { if (isWindowDefined() && new window.Blob()) { Blob = window.Blob; } } catch (error) {} var url = isWindowDefined() && (window.URL || window.webkitURL || false); var URL$1 = url && url.createObjectURL && url; var FileReader = isWindowDefined() && (window.FileReader != null ? window.FileReader.prototype.readAsArrayBuffer : undefined) && window.FileReader; var indexOf$2 = [].indexOf; // utils var unique = function unique(arr) { var item, j, len, result; result = []; for (j = 0, len = arr.length; j < len; j++) { item = arr[j]; if (indexOf$2.call(result, item) < 0) { result.push(item); } } return result; }; var defer = function defer(fn) { return setTimeout(fn, 0); }; var gcd = function gcd(a, b) { var c; while (b) { c = a % b; a = b; b = c; } return a; }; var once = function once(fn) { var called, result; called = false; result = null; return function () { if (!called) { result = fn.apply(this, arguments); called = true; } return result; }; }; var wrapToPromise = function wrapToPromise(value) { return $__default["default"].Deferred().resolve(value).promise(); }; // same as promise.then(), but if filter returns promise // it will be just passed forward without any special behavior var then = function then(pr, doneFilter, failFilter, progressFilter) { var compose, df; df = $__default["default"].Deferred(); compose = function compose(fn1, fn2) { if (fn1 && fn2) { return function () { return fn2.call(this, fn1.apply(this, arguments)); }; } else { return fn1 || fn2; } }; pr.then(compose(doneFilter, df.resolve), compose(failFilter, df.reject), compose(progressFilter, df.notify)); return df.promise(); }; // Build copy of source with only specified methods. // Handles chaining correctly. var bindAll = function bindAll(source, methods) { var target; target = {}; $__default["default"].each(methods, function (i, method) { var fn = source[method]; if ($__default["default"].isFunction(fn)) { target[method] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var result = fn.apply(source, args); // Fix chaining if (result === source) { return target; } else { return result; } }; } else { target[method] = fn; } }); return target; }; var upperCase = function upperCase(s) { return s.replace(/([A-Z])/g, '_$1').toUpperCase(); }; var publicCallbacks = function publicCallbacks(callbacks) { var result; result = callbacks.add; result.add = callbacks.add; result.remove = callbacks.remove; return result; }; var uuid = function uuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0; var v = c === 'x' ? r : r & 3 | 8; return v.toString(16); }); }; // splitUrlRegex("url") => ["url", "scheme", "host", "path", "query", "fragment"] var splitUrlRegex = /^(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)\??([^#]*)#?(.*)$/; var uuidRegex = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i; var groupIdRegex = new RegExp("".concat(uuidRegex.source, "~[0-9]+"), 'i'); var cdnUrlRegex = new RegExp("^/?(".concat(uuidRegex.source, ")(?:/(-/(?:[^/]+/)+)?([^/]*))?$"), 'i'); var splitCdnUrl = function splitCdnUrl(url) { return cdnUrlRegex.exec(splitUrlRegex.exec(url)[3]); }; var escapeRegExp = function escapeRegExp(str) { return str.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); }; var globRegexp = function globRegexp(str) { var flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'i'; var parts; parts = $__default["default"].map(str.split('*'), escapeRegExp); return new RegExp('^' + parts.join('.+') + '$', flags); }; var normalizeUrl = function normalizeUrl(url) { var scheme; // google.com/ → google.com // /google.com/ → /google.com // //google.com/ → http://google.com // http://google.com/ → http://google.com scheme = document.location.protocol; if (scheme !== 'http:') { scheme = 'https:'; } return url.replace(/^\/\//, scheme + '//').replace(/\/+$/, ''); }; var fitText = function fitText(text, max) { if (text.length > max) { var head = Math.ceil((max - 3) / 2); var tail = Math.floor((max - 3) / 2); return text.slice(0, head) + '...' + text.slice(-tail); } else { return text; } }; var fitSizeInCdnLimit = function fitSizeInCdnLimit(objSize) { return fitSize(objSize, [2048, 2048]); }; var fitSize = function fitSize(objSize, boxSize, upscale) { var heightRation, widthRatio; if (objSize[0] > boxSize[0] || objSize[1] > boxSize[1] || upscale) { widthRatio = boxSize[0] / objSize[0]; heightRation = boxSize[1] / objSize[1]; if (!boxSize[0] || boxSize[1] && widthRatio > heightRation) { return [Math.round(heightRation * objSize[0]), boxSize[1]]; } else { return [boxSize[0], Math.round(widthRatio * objSize[1])]; } } else { return objSize.slice(); } }; var applyCropCoordsToInfo = function applyCropCoordsToInfo(info, crop, size, coords) { var downscale, h, modifiers, prefered, upscale, w, wholeImage; w = coords.width; h = coords.height; prefered = crop.preferedSize; modifiers = ''; wholeImage = w === size[0] && h === size[1]; if (!wholeImage) { modifiers += "-/crop/".concat(w, "x").concat(h, "/").concat(coords.left, ",").concat(coords.top, "/"); } downscale = crop.downscale && (w > prefered[0] || h > prefered[1]); upscale = crop.upscale && (w < prefered[0] || h < prefered[1]); if (downscale || upscale) { var _prefered = prefered; var _prefered2 = _slicedToArray(_prefered, 2); coords.sw = _prefered2[0]; coords.sh = _prefered2[1]; modifiers += "-/resize/".concat(prefered.join('x'), "/"); } else if (!wholeImage) { modifiers += '-/preview/'; } info = $__default["default"].extend({}, info); info.cdnUrlModifiers = modifiers; info.cdnUrl = "".concat(info.originalUrl).concat(modifiers || ''); info.crop = coords; return info; }; var imagesOnlyAcceptTypes = ['image/*', 'image/heif', 'image/heif-sequence', 'image/heic', 'image/heic-sequence', 'image/avif', 'image/avif-sequence', '.heif', '.heifs', '.heic', '.heics', '.avif', '.avifs'].join(','); var fileInput = function fileInput(container, settings, fn) { var accept, input, _run; input = null; accept = settings.inputAcceptTypes; if (accept === '') { accept = settings.imagesOnly ? imagesOnlyAcceptTypes : null; } (_run = function run() { input = (settings.multiple ? $__default["default"]('<input type="file" multiple>') : $__default["default"]('<input type="file">')).attr('accept', accept).css({ position: 'absolute', top: 0, opacity: 0, margin: 0, padding: 0, width: 'auto', height: 'auto', cursor: container.css('cursor') }).on('change', function () { fn(this); $__default["default"](this).hide(); return _run(); }); return container.append(input); })(); return container.css({ position: 'relative', overflow: 'hidden' // to make it posible to set `cursor:pointer` on button // http://stackoverflow.com/a/9182787/478603 }).mousemove(function (e) { var left, top, width; var _$$offset = $__default["default"](this).offset(); left = _$$offset.left; top = _$$offset.top; width = input.width(); return input.css({ left: e.pageX - left - width + 10, top: e.pageY - top - 10 }); }); }; var fileSelectDialog = function fileSelectDialog(container, settings, fn) { var attributes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var accept; accept = settings.inputAcceptTypes; if (accept === '') { accept = settings.imagesOnly ? imagesOnlyAcceptTypes : null; } return $__default["default"](settings.multiple ? '<input type="file" multiple>' : '<input type="file">').attr('accept', accept).attr(attributes).css({ position: 'fixed', bottom: 0, opacity: 0 }).on('change', function () { fn(this); return $__default["default"](this).remove(); }).appendTo(container).focus().click().hide(); }; var fileSizeLabels = 'B KB MB GB TB PB EB ZB YB'.split(' '); var readableFileSize = function readableFileSize(value) { var onNaN = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var postfix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; var digits, fixedTo, i, threshold; value = parseInt(value, 10); if (isNaN(value)) { return onNaN; } digits = 2; i = 0; threshold = 1000 - 5 * Math.pow(10, 2 - Math.max(digits, 3)); while (value > threshold && i < fileSizeLabels.length - 1) { i++; value /= 1024; } value += 0.000000000000001; fixedTo = Math.max(0, digits - Math.floor(value).toFixed(0).length); // fixed → number → string, to trim trailing zeroes value = Number(value.toFixed(fixedTo)); // eslint-disable-next-line no-irregular-whitespace return "".concat(prefix).concat(value, "\xA0").concat(fileSizeLabels[i]).concat(postfix); }; var ajaxDefaults = { dataType: 'json', crossDomain: true, cache: false }; var jsonp = function jsonp(url, type, data) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var jqXHR = $__default["default"].ajax($__default["default"].extend({ url: url, type: type, data: data }, options, ajaxDefaults)).retry(options.retryConfig).fail(function (_, textStatus, errorThrown) { var text = "".concat(textStatus, " (").concat(errorThrown, ")"); warn("JSONP unexpected error: ".concat(text, " while loading ").concat(url)); }); var df = jqXHR.then(function (data) { if (data.error) { var message, code; if (typeof data.error === 'string') { // /from_url/state/ case message = data.error; code = data.error_code; } else { // other cases (direct/multipart/group) message = data.error.content; code = data.error.error_code; } return $__default["default"].Deferred().reject({ message: message, code: code }); } return data; }); df.abort = jqXHR.abort.bind(jqXHR); return df; }; var canvasToBlob = function canvasToBlob(canvas, type, quality, callback) { var arr, binStr, dataURL, i, j, ref; if (window.HTMLCanvasElement.prototype.toBlob) { return canvas.toBlob(callback, type, quality); } dataURL = canvas.toDataURL(type, quality); dataURL = dataURL.split(','); binStr = window.atob(dataURL[1]); arr = new Uint8Array(binStr.length); for (i = j = 0, ref = binStr.length; j < ref; i = j += 1) { arr[i] = binStr.charCodeAt(i); } return callback(new window.Blob([arr], { type: /:(.+\/.+);/.exec(dataURL[0])[1] })); }; var taskRunner = function taskRunner(capacity) { var queue, _release, run, running; running = 0; queue = []; _release = function release() { var task; if (queue.length) { task = queue.shift(); return defer(function () { return task(_release); }); } else { running -= 1; return running; } }; run = function run(task) { if (!capacity || running < capacity) { running += 1; return defer(function () { return task(_release); }); } else { return queue.push(task); } }; return run; }; // This is work around bug in jquery https://github.com/jquery/jquery/issues/2013 // action, add listener, callbacks, // ... .then handlers, argument index, [final state] var pipeTuples = [['notify', 'progress', 2], ['resolve', 'done', 0], ['reject', 'fail', 1]]; var fixedPipe = function fixedPipe(promise) { for (var _len2 = arguments.length, fns = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { fns[_key2 - 1] = arguments[_key2]; } return $__default["default"].Deferred(function (newDefer) { return $__default["default"].each(pipeTuples, function (i, tuple) { var fn; // Map tuples (progress, done, fail) to arguments (done, fail, progress) fn = $__default["default"].isFunction(fns[tuple[2]]) && fns[tuple[2]]; return promise[tuple[1]](function () { var returned; returned = fn && fn.apply(this, arguments); if (returned && $__default["default"].isFunction(returned.promise)) { return returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject); } else { return newDefer[tuple[0] + 'With'](this === promise ? newDefer.promise() : this, fn ? [returned] : arguments); } }); }); }).promise(); }; var getMetadataObject = function getMetadataObject(settings) { var metadata; if (settings.metadataCallback) { metadata = settings.metadataCallback() || {}; } else { metadata = settings.metadata || {}; } metadata = _objectSpread2({}, metadata); $__default["default"].each(metadata, function (key, value) { metadata[key] = String(value); }); return metadata; }; var isObject = function isObject(input) { return Object.prototype.toString.call(input) === '[object Object]'; }; var TestPixel = { R: 55, G: 110, B: 165, A: 255 }; var FILL_STYLE = "rgba(".concat(TestPixel.R, ", ").concat(TestPixel.G, ", ").concat(TestPixel.B, ", ").concat(TestPixel.A / 255, ")"); function canvasTest(width, height) { // Wrapped into try/catch because memory alloction errors can be thrown due to insufficient RAM try { var fill = [width - 1, height - 1, 1, 1]; // x, y, width, height var cropCvs = document.createElement('canvas'); cropCvs.width = 1; cropCvs.height = 1; var testCvs = document.createElement('canvas'); testCvs.width = width; testCvs.height = height; var cropCtx = cropCvs.getContext('2d'); var testCtx = testCvs.getContext('2d'); if (testCtx) { testCtx.fillStyle = FILL_STYLE; testCtx.fillRect.apply(testCtx, fill); // Render the test pixel in the bottom-right corner of the // test canvas in the top-left of the 1x1 crop canvas. This // dramatically reducing the time for getImageData to complete. cropCtx.drawImage(testCvs, width - 1, height - 1, 1, 1, 0, 0, 1, 1); } var imageData = cropCtx && cropCtx.getImageData(0, 0, 1, 1).data; var isTestPass = false; if (imageData) { // On IE10, imageData have type CanvasPixelArray, not Uint8ClampedArray. // CanvasPixelArray supports index access operations only. // Array buffers can't be destructuredd and compared with JSON.stringify isTestPass = imageData[0] === TestPixel.R && imageData[1] === TestPixel.G && imageData[2] === TestPixel.B && imageData[3] === TestPixel.A; } testCvs.width = testCvs.height = 1; return isTestPass; } catch (e) { log("Failed to test for max canvas size of ".concat(width, "x").concat(height, "."), e); return false; } } function memoize(fn, serializer) { var cache = {}; return function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var key = serializer(args, cache); return key in cache ? cache[key] : cache[key] = fn.apply(void 0, args); }; } var sizes = { squareSide: [ // Safari (iOS < 9, ram >= 256) // We are supported mobile safari < 9 since widget v2, by 5 Mpx limit // so it's better to continue support despite the absence of this browser in the support table Math.floor(Math.sqrt(5 * 1000 * 1000)), // IE Mobile (Windows Phone 8.x) // Safari (iOS >= 9) 4096, // IE 9 (Win) 8192, // Firefox 63 (Mac, Win) 11180, // Chrome 68 (Android 6) 10836, // Chrome 68 (Android 5) 11402, // Chrome 68 (Android 7.1-9) 14188, // Chrome 70 (Mac, Win) // Chrome 68 (Android 4.4) // Edge 17 (Win) // Safari 7-12 (Mac) 16384], dimension: [ // IE Mobile (Windows Phone 8.x) 4096, // IE 9 (Win) 8192, // Edge 17 (Win) // IE11 (Win) 16384, // Chrome 70 (Mac, Win) // Chrome 68 (Android 4.4-9) // Firefox 63 (Mac, Win) 32767, // Chrome 83 (Mac, Win) // Safari 7-12 (Mac) // Safari (iOS 9-12) // Actually Safari has a much bigger limits - 4194303 of width and 8388607 of height, // but we will not use them 65535] }; var MAX_SQUARE_SIDE = sizes.squareSide[sizes.squareSide.length - 1]; function wrapAsync(fn) { return function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var df = $__default["default"].Deferred(); defer(function () { var passed = fn.apply(void 0, args); df.resolve(passed); }); return df.promise(); }; } /** * Memoization key serealizer, that prevents unnecessary canvas tests. * No need to make test if we know that: * - browser supports higher canvas size * - browser doesn't support lower canvas size */ function memoKeySerializer(args, cache) { var _args = _slicedToArray(args, 1), w = _args[0]; var cachedWidths = Object.keys(cache).map(function (val) { return parseInt(val, 10); }).sort(function (a, b) { return a - b; }); for (var i = 0; i < cachedWidths.length; i++) { var cachedWidth = cachedWidths[i]; var isSupported = !!cache[cachedWidth]; // higher supported canvas size, return it if (cachedWidth > w && isSupported) { return cachedWidth; } // lower unsupported canvas size, return it if (cachedWidth < w && !isSupported) { return cachedWidth; } } // use canvas width as the key, // because we're doing dimension test by width - [dimension, 1] return w; } // separate memoization for square and dimension tests var squareTest = wrapAsync(memoize(canvasTest, memoKeySerializer)); var dimensionTest = wrapAsync(memoize(canvasTest, memoKeySerializer)); function testCanvasSize(w, h) { var df = $__default["default"].Deferred(); var testSquareSide = sizes.squareSide.find(function (side) { return side * side >= w * h; }); var testDimension = sizes.dimension.find(function (side) { return side >= w && side >= h; }); if (!testSquareSide || !testDimension) { return df.reject(); } var tasks = [squareTest(testSquareSide, testSquareSide), dimensionTest(testDimension, 1)]; $__default["default"].when.apply($__default["default"], tasks).done(function (squareSupported, dimensionSupported) { if (squareSupported && dimensionSupported) { df.resolve(); } else { df.reject(); } }); return df.promise(); } const o = (n, e) => { const r = new URL(e); return r.hostname = `${n}.${r.hostname}`, r.toString().replace(/\/$/, ""); }, t = "0123456789abcdefghijklmnopqrstuvwxyz", c = (n) => { if (n <= 0n) return "0"; let e = ""; for (; n > 0n; ) { const r = n % 36n; e = t[Number(r)] + e, n = n / 36n; } return e; }; /** * [js-sha256]{@link https://github.com/emn178/js-sha256} * * @license MIT * @version 0.11.1 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2014-2025 */ const h = "0123456789abcdef".split(""), g = [-2147483648, 8388608, 32768, 128], y = [24, 16, 8, 0], E = [ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]; class P { blocks; h0; h1; h2; h3; h4; h5; h6; h7; block; start; bytes; hBytes; first; lastByteIndex; constructor() { this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], this.h0 = 1779033703, this.h1 = 3144134277, this.h2 = 1013904242, this.h3 = 2773480762, this.h4 = 1359893119, this.h5 = 2600822924, this.h6 = 528734635, this.h7 = 1541459225, this.block = this.start = this.bytes = this.hBytes = 0, this.first = !0, this.lastByteIndex = 0; } update(t) { let i, c = 0, s; const o = t.length, e = this.blocks; for (; c < o; ) { for (s = this.start; c < o && s < 64; ++c) i = t.charCodeAt(c), i < 128 ? e[s >>> 2] |= i << y[s++ & 3] : i < 2048 ? (e[s >>> 2] |= (192 | i >>> 6) << y[s++ & 3], e[s >>> 2] |= (128 | i & 63) << y[s++ & 3]) : i < 55296 || i >= 57344 ? (e[s >>> 2] |= (224 | i >>> 12) << y[s++ & 3], e[s >>> 2] |= (128 | i >>> 6 & 63) << y[s++ & 3], e[s >>> 2] |= (128 | i & 63) << y[s++ & 3]) : (i = 65536 + ((i & 1023) << 10 | t.charCodeAt(++c) & 1023), e[s >>> 2] |= (240 | i >>> 18) << y[s++ & 3], e[s >>> 2] |= (128 | i >>> 12 & 63) << y[s++ & 3], e[s >>> 2] |= (128 | i >>> 6 & 63) << y[s++ & 3], e[s >>> 2] |= (128 | i & 63) << y[s++ & 3]); this.lastByteIndex = s, this.bytes += s - this.start, s >= 64 ? (this.block = e[16], this.start = s - 64, this.hash()) : this.start = s; } return this.bytes > 4294967295 && (this.hBytes += this.bytes / 4294967296 << 0, this.bytes = this.bytes % 4294967296), this; } finalize() { const t = this.blocks, i = this.lastByteIndex; t[16] = this.block, t[i >>> 2] |= g[i & 3], this.block = t[16], i >= 56 && (t[0] = this.block, t[16] = t[1] = t[2] = t[3] = t[4] = t[5] = t[6] = t[7] = t[8] = t[9] = t[10] = t[11] = t[12] = t[13] = t[14] = t[15] = 0), t[14] = this.hBytes << 3 | this.bytes >>> 29, t[15] = this.bytes << 3, this.hash(); } hash() { let t = this.h0, i = this.h1, c = this.h2, s = this.h3, o = this.h4, e = this.h5, l = this.h6, a = this.h7, r, b, f, x, n, k, B, I, H, S, C; const d = this.blocks; for (r = 16; r < 64; ++r) n = d[r - 15], b = (n >>> 7 | n << 25) ^ (n >>> 18 | n << 14) ^ n >>> 3, n = d[r - 2], f = (n >>> 17 | n << 15) ^ (n >>> 19 | n << 13) ^ n >>> 10, d[r] = d[r - 16] + b + d[r - 7] + f << 0; for (C = i & c, r = 0; r < 64; r += 4) this.first ? (I = 704751109, n = d[0] - 210244248, a = n - 1521486534 << 0, s = n + 143694565 << 0, this.first = !1) : (b = (t >>> 2 | t << 30) ^ (t >>> 13 | t << 19) ^ (t >>> 22 | t << 10), f = (o >>> 6 | o << 26) ^ (o >>> 11 | o << 21) ^ (o >>> 25 | o << 7), I = t & i, x = I ^ t & c ^ C, B = o & e ^ ~o & l, n = a + f + B + E[r] + d[r], k = b + x, a = s + n << 0, s = n + k << 0), b = (s >>> 2 | s << 30) ^ (s >>> 13 | s << 19) ^ (s >>> 22 | s << 10), f = (a >>> 6 | a << 26) ^ (a >>> 11 | a << 21) ^ (a >>> 25 | a << 7), H = s & t, x = H ^ s & i ^ I, B = a & o ^ ~a & e, n = l + f + B + E[r + 1] + d[r + 1], k = b + x, l = c + n << 0, c = n + k << 0, b = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10), f = (l >>> 6 | l << 26) ^ (l >>> 11 | l << 21) ^ (l >>> 25 | l << 7), S = c & s, x = S ^ c & t ^ H, B = l & a ^ ~l & o, n = e + f + B + E[r + 2] + d[r + 2], k = b + x, e = i + n << 0, i = n + k << 0, b = (i >>> 2 | i << 30) ^ (i >>> 13 | i << 19) ^ (i >>> 22 | i << 10), f = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7), C = i & c, x = C ^ i & s ^ S, B = e & l ^ ~e & a, n = o + f + B + E[r + 3] + d[r + 3], k = b + x, o = t + n << 0, t = n + k << 0; this.h0 = this.h0 + t << 0, this.h1 = this.h1 + i << 0, this.h2 = this.h2 + c << 0, this.h3 = this.h3 + s << 0, this.h4 = this.h4 + o << 0, this.h5 = this.h5 + e << 0, this.h6 = this.h6 + l << 0, this.h7 = this.h7 + a << 0; } hex() { this.finalize(); const t = this.h0, i = this.h1, c = this.h2, s = this.h3, o = this.h4, e = this.h5, l = this.h6, a = this.h7; return h[t >>> 28 & 15] + h[t >>> 24 & 15] + h[t >>> 20 & 15] + h[t >>> 16 & 15] + h[t >>> 12 & 15] + h[t >>> 8 & 15] + h[t >>> 4 & 15] + h[t & 15] + h[i >>> 28 & 15] + h[i >>> 24 & 15] + h[i >>> 20 & 15] + h[i >>> 16 & 15] + h[i >>> 12 & 15] + h[i >>> 8 & 15] + h[i >>> 4 & 15] + h[i & 15] + h[c >>> 28 & 15] + h[c >>> 24 & 15] + h[c >>> 20 & 15] + h[c >>> 16 & 15] + h[c >>> 12 & 15] + h[c >>> 8 & 15] + h[c >>> 4 & 15] + h[c & 15] + h[s >>> 28 & 15] + h[s >>> 24 & 15] + h[s >>> 20 & 15] + h[s >>> 16 & 15] + h[s >>> 12 & 15] + h[s >>> 8 & 15] + h[s >>> 4 & 15] + h[s & 15] + h[o >>> 28 & 15] + h[o >>> 24 & 15] + h[o >>> 20 & 15] + h[o >>> 16 & 15] + h[o >>> 12 & 15] + h[o >>> 8 & 15] + h[o >>> 4 & 15] + h[o & 15] + h[e >>> 28 & 15] + h[e >>> 24 & 15] + h[e >>> 20 & 15] + h[e >>> 16 & 15] + h[e >>> 12 & 15] + h[e >>> 8 & 15] + h[e >>> 4 & 15] + h[e & 15] + h[l >>> 28 & 15] + h[l >>> 24 & 15] + h[l >>> 20 & 15] + h[l >>> 16 & 15] + h[l >>> 12 & 15] + h[l >>> 8 & 15] + h[l >>> 4 & 15] + h[l & 15] + h[a >>> 28 & 15] + h[a >>> 24 & 15] + h[a >>> 20 & 15] + h[a >>> 16 & 15] + h[a >>> 12 & 15] + h[a >>> 8 & 15] + h[a >>> 4 & 15] + h[a & 15]; } } function R(u) { const t = new P(); t.update(u); const i = t.hex(); return BigInt(`0x${i}`); } const T = 10, X = (u) => { const t = R(u); return c(t).slice(0, T); }, j = (u, t) => { const i = X(u); return o(i, t); }; var indexOf$1 = [].indexOf; // settings var arrayOptions, constrainOptions, constraints, defaultPreviewUrlCallback, defaults$1, initialSettings, flagOptions, intOptions, integration, integrationToUserAgent, buildRetryConfig, normalize, parseCrop, parseShrink, presets, script, str2arr, transformOptions, transforms, urlOptions, callbackOptions, objectOptions; defaults$1 = { // developer hooks live: true, manualStart: false, locale: null, localePluralize: null, localeTranslations: null, // widget & dialog settings systemDialog: false, crop: false, previewStep: false, imagesOnly: false, clearable: false, multiple: false, multipleMax: 1000, multipleMin: 1, multipleMaxStrict: false, imageShrink: false, pathValue: true, tabs: 'file camera url facebook gdrive gphotos dropbox instagram evernote flickr onedrive', preferredTypes: '', inputAcceptTypes: '', // '' means default, null means "disable accept" // upload settings doNotStore: false, publicKey: null, secureSignature: '', secureExpire: '', pusherKey: '79ae88bd931ea68464d9', cdnBase: 'https://ucarecdn.com', cdnBasePrefixed: 'https://ucarecd.net', urlBase: 'https://upload.uploadcare.com', socialBase: 'https://social.uploadcare.com', previewProxy: null, previewUrlCallback: null, remoteTabSessionKey: null, metadata: null, metadataCallback: null, // fine tuning imagePreviewMaxSize: 25 * 1024 * 1024, multipartMinSize: 10 * 1024 * 1024, multipartPartSize: 5 * 1024 * 1024, multipartMinLastPartSize: 1024 * 1024, multipartConcurrency: 4, // `multipartMaxAttempts` is deprecated, value will be assigned to `retryAttempts` if set multipartMaxAttempts: null, retryAttempts: 3, retryThrottledAttempts: 10, retryBaseTimeout: 1000, retryFactor: 2, parallelDirectUploads: 10, passWindowOpen: false, // camera cameraMirrorDefault: true, // camera recording enableAudioRecording: true, enableVideoRecording: true, videoPreferredMimeTypes: null, audioBitsPerSecond: null, videoBitsPerSecond: null, // social sources settings topLevelOrigin: null, // maintain settings scriptBase: "//ucarecdn.com/widget/".concat(version, "/uploadcare/"), debugUploads: false, integration: '' }; initialSettings = _objectSpread2({}, defaults$1); transforms = { multipleMax: { from: 0, to: 1000 } }; constraints = { multipleMax: { min: 1, max: 1000 } }; presets = { tabs: { all: 'file camera url facebook gdrive gphotos drop