@scaleflex/widget-xhr-upload 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,794 @@
1
+ var _excluded = ["isVideoProcessActive"],
2
+ _excluded2 = ["isImageProcessActive"];
3
+ function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
4
+ function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
5
+ 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); }
6
+ 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; }
7
+ function _objectSpread(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; }
8
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
9
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
10
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
11
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
12
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
13
+ 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); }
14
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
15
+ function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
16
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
17
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
18
+ function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
19
+ function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); }
20
+ function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; }
21
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
22
+ function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
23
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
24
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
25
+ import { Plugin } from '@scaleflex/widget-core';
26
+ import cuid from 'cuid';
27
+ import Translator from '@scaleflex/widget-utils/lib/Translator';
28
+ import { Provider, RequestClient, Socket } from '@scaleflex/widget-companion-client';
29
+ import emitSocketProgress from '@scaleflex/widget-utils/lib/emitSocketProgress';
30
+ import getSocketHost from '@scaleflex/widget-utils/lib/getSocketHost';
31
+ import settle from '@scaleflex/widget-utils/lib/settle';
32
+ import EventTracker from '@scaleflex/widget-utils/lib/EventTracker';
33
+ import ProgressTimeout from '@scaleflex/widget-utils/lib/ProgressTimeout';
34
+ import RateLimitedQueue from '@scaleflex/widget-utils/lib/RateLimitedQueue';
35
+ import NetworkError from '@scaleflex/widget-utils/lib/NetworkError';
36
+ import isNetworkError from '@scaleflex/widget-utils/lib/isNetworkError';
37
+ import isSupportedVideo from '@scaleflex/widget-utils/lib/isSupportedVideo';
38
+ import isImage from '@scaleflex/widget-utils/lib/isImage';
39
+ import checkConnection from '@scaleflex/widget-utils/lib/checkConnection';
40
+ import { uploadCapabilitiesUpdated } from '@scaleflex/widget-core/lib/slices/uploads.slice';
41
+ import { selectUserSassKey } from '@scaleflex/widget-core/lib/slices/user.slice';
42
+ import { PROGRESS_PANEL_STATUS, PLUGINS_IDS } from '@scaleflex/widget-utils/lib/constants';
43
+
44
+ // TODO: find a way to show version of the current plugin
45
+ // why solution below isn't good?
46
+ // first import doesn't work with webpack 5 as it was deprecated
47
+ // second import fixes webpack 5 issue as it was mentioned in their docs
48
+ // but it exposes our package.json to the client and it is mentioned as security rist in mutiple places
49
+ // https://github.com/axelpale/genversion
50
+ // https://stackoverflow.com/questions/64993118/error-should-not-import-the-named-export-version-imported-as-version
51
+ // https://stackoverflow.com/questions/9153571/is-there-a-way-to-get-version-from-package-json-in-nodejs-code/10855054#10855054
52
+ // import { version } from '../package.json'
53
+ // import packageInfo from '../package.json'
54
+
55
+ var FIELD_NAME = 'files[]';
56
+ function buildResponseError(xhr, error) {
57
+ // No error message
58
+ if (!error) error = new Error('Upload error');
59
+ // Got an error message string
60
+ if (typeof error === 'string') error = new Error(error);
61
+ // Got something else
62
+ if (!(error instanceof Error)) {
63
+ error = _extends(new Error('Upload error'), {
64
+ data: error
65
+ });
66
+ }
67
+ if (isNetworkError(xhr)) {
68
+ error = new NetworkError(error, xhr);
69
+ return error;
70
+ }
71
+ error.request = xhr;
72
+ return error;
73
+ }
74
+
75
+ /**
76
+ * Set `data.type` in the blob to `file.info.type`,
77
+ * because we might have detected a more accurate file type in Filerobot
78
+ * https://stackoverflow.com/a/50875615
79
+ *
80
+ * @param {object} file File object with `data`, `size` and `info` properties
81
+ * @returns {object} blob updated with the new `type` set from `file.info.type`
82
+ */
83
+ function setTypeInBlob(file) {
84
+ var dataWithUpdatedType = file.data.slice(0, file.data.size, file.info.type);
85
+ return dataWithUpdatedType;
86
+ }
87
+ var XHRUpload = /*#__PURE__*/function (_Plugin) {
88
+ // static VERSION = packageInfo.version
89
+
90
+ function XHRUpload(filerobot) {
91
+ var _this;
92
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
93
+ _classCallCheck(this, XHRUpload);
94
+ _this = _callSuper(this, XHRUpload, [filerobot, opts]);
95
+ _this.type = 'uploader';
96
+ _this.id = _this.opts.id || PLUGINS_IDS.XHR_UPLOAD;
97
+ _this.title = 'XHRUpload';
98
+ _this.defaultLocale = {
99
+ strings: {
100
+ timedOut: 'Upload stalled for %{seconds} seconds, aborting.'
101
+ }
102
+ };
103
+
104
+ // Default options
105
+ var defaultOptions = {
106
+ dev: false,
107
+ uploadQueryParams: '',
108
+ method: 'post',
109
+ responseUrlFieldName: 'url',
110
+ uploadToFolderPath: null,
111
+ bundle: false,
112
+ headers: {},
113
+ timeout: 60 * 1000,
114
+ limit: 0,
115
+ withCredentials: false,
116
+ responseType: '',
117
+ info: undefined,
118
+ addInfoCallback: undefined,
119
+ meta: undefined,
120
+ skipUpload: false,
121
+ /**
122
+ * @typedef respObj
123
+ * @property {string} responseText
124
+ * @property {number} status
125
+ * @property {string} statusText
126
+ * @property {object.<string, string>} headers
127
+ *
128
+ * @param {string} responseText the response body string
129
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
130
+ */
131
+ getResponseData: function getResponseData(responseText, response) {
132
+ var parsedResponse = {};
133
+ try {
134
+ parsedResponse = JSON.parse(responseText);
135
+ } catch (err) {
136
+ console.log(err);
137
+ }
138
+ return parsedResponse;
139
+ },
140
+ /**
141
+ *
142
+ * @param {string} responseText the response body string
143
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
144
+ */
145
+ getResponseError: function getResponseError(responseText, response) {
146
+ var error = new Error('Upload error');
147
+ if (isNetworkError(response)) {
148
+ error = new NetworkError(error, response);
149
+ }
150
+ if (responseText) {
151
+ var jsonedResponse = JSON.parse(responseText);
152
+ if (jsonedResponse.hint || jsonedResponse.msg) {
153
+ error = new Error(jsonedResponse.hint || jsonedResponse.msg);
154
+ }
155
+ }
156
+ return error;
157
+ },
158
+ /**
159
+ * Check if the response from the upload endpoint indicates that the upload was successful.
160
+ *
161
+ * @param {number} status the response status code
162
+ * @param {string} responseText the response body string
163
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
164
+ */
165
+ validateStatus: function validateStatus(status, responseText, response) {
166
+ return status >= 200 && status < 300;
167
+ }
168
+ };
169
+ _this.opts = _objectSpread(_objectSpread({}, defaultOptions), opts);
170
+ _this.opts.endpoint = _this.getUploadEndpoint();
171
+ _this.opts.headers['X-Filerobot-Key'] = selectUserSassKey(_this.getGlobalState()) || filerobot.opts.sassKey;
172
+ if (!_this.opts.headers['X-Filerobot-Key']) {
173
+ filerobot.on('sass-key-obtained', function (sassKey) {
174
+ _this.opts.headers['X-Filerobot-Key'] = sassKey;
175
+ });
176
+ }
177
+ _this.i18nInit();
178
+ _this.handleUpload = _this.handleUpload.bind(_this);
179
+
180
+ // Simultaneous upload limiting is shared across all uploads with this plugin.
181
+ // __queue is for internal Filerobot use only!
182
+ if (_this.opts.__queue instanceof RateLimitedQueue) {
183
+ _this.requests = _this.opts.__queue;
184
+ } else {
185
+ _this.requests = new RateLimitedQueue(_this.opts.limit);
186
+ }
187
+ _this.filerobotEvents = Object.create(null);
188
+ return _this;
189
+ }
190
+ _inherits(XHRUpload, _Plugin);
191
+ return _createClass(XHRUpload, [{
192
+ key: "setOptions",
193
+ value: function setOptions(newOpts) {
194
+ _superPropGet(XHRUpload, "setOptions", this, 3)([newOpts]);
195
+ this.i18nInit();
196
+ }
197
+ }, {
198
+ key: "getUploadEndpoint",
199
+ value: function getUploadEndpoint() {
200
+ return "".concat(this.filerobot.opts.apiEndpointWithContainer, "/v4/files");
201
+ }
202
+ }, {
203
+ key: "i18nInit",
204
+ value: function i18nInit() {
205
+ this.translator = new Translator([this.defaultLocale, this.filerobot.locale, this.opts.locale]);
206
+ this.i18n = this.translator.translate.bind(this.translator);
207
+ }
208
+ }, {
209
+ key: "getOptions",
210
+ value: function getOptions(file) {
211
+ var overrides = this.filerobot.getCoreCommonState().xhrUpload;
212
+ var opts = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, this.opts), overrides || {}), file.xhrUpload || {}), {}, {
213
+ headers: {}
214
+ });
215
+ _extends(opts.headers, this.opts.headers);
216
+ if (overrides) {
217
+ _extends(opts.headers, overrides.headers);
218
+ }
219
+ if (file.xhrUpload) {
220
+ _extends(opts.headers, file.xhrUpload.headers);
221
+ }
222
+ return opts;
223
+ }
224
+ }, {
225
+ key: "getRelativeFileName",
226
+ value: function getRelativeFileName(file) {
227
+ var _file$data;
228
+ return typeof ((_file$data = file.data) === null || _file$data === void 0 ? void 0 : _file$data.relativePath) === 'string' ? file.data.relativePath.substr(1).replaceAll('/', '|') : '';
229
+ }
230
+ }, {
231
+ key: "createFormDataUpload",
232
+ value: function createFormDataUpload(file, opts) {
233
+ var formPost = new FormData();
234
+ if (file.meta && Object.keys(file.meta).length > 0 || opts.meta && Object.keys(opts.meta).length > 0) {
235
+ formPost.append("meta[".concat(FIELD_NAME, "]"), JSON.stringify(_objectSpread(_objectSpread({}, file.meta), opts.meta)));
236
+ }
237
+ if (file.info && Object.keys(file.info).length > 0 || opts.info && Object.keys(opts.info).length > 0 || typeof this.opts.addInfoCallback === 'function') {
238
+ var _this$opts$addInfoCal, _this$opts;
239
+ var infoFromCbFn = (_this$opts$addInfoCal = (_this$opts = this.opts).addInfoCallback) === null || _this$opts$addInfoCal === void 0 ? void 0 : _this$opts$addInfoCal.call(_this$opts, file);
240
+ formPost.append("info[".concat(FIELD_NAME, "]"), JSON.stringify(_objectSpread(_objectSpread(_objectSpread({}, file.info), opts.info), _typeof(infoFromCbFn) === 'object' ? infoFromCbFn : {})));
241
+ }
242
+ if (file.tags && Object.keys(file.tags).length > 0 || opts.tags && Object.keys(opts.tags).length > 0) {
243
+ var tagLang = Object.keys(file.tags)[0];
244
+ formPost.append("tags[".concat(FIELD_NAME, "]"), JSON.stringify({
245
+ // ...file.tags,
246
+ // ...opts.tags
247
+ lang: tagLang,
248
+ new_tags: file.tags[tagLang].map(function (_ref) {
249
+ var sid = _ref.sid,
250
+ label = _ref.label;
251
+ return sid || label;
252
+ })
253
+ }));
254
+ }
255
+ if (file.product && Object.keys(file.product).length > 0 || opts.product && Object.keys(opts.product).length > 0) {
256
+ formPost.append("product[".concat(FIELD_NAME, "]"), JSON.stringify(_objectSpread(_objectSpread({}, file.product), opts.product)));
257
+ }
258
+ var dataWithUpdatedType = setTypeInBlob(file);
259
+ var fileName = file.name || this.getRelativeFileName(file);
260
+ if (fileName) {
261
+ formPost.append(FIELD_NAME, dataWithUpdatedType, fileName);
262
+ } else {
263
+ formPost.append(FIELD_NAME, dataWithUpdatedType);
264
+ }
265
+ return formPost;
266
+ }
267
+ }, {
268
+ key: "createBundledUpload",
269
+ value: function createBundledUpload(files, opts) {
270
+ var _this2 = this;
271
+ var formPost = new FormData();
272
+ files.forEach(function (file) {
273
+ var dataWithUpdatedType = setTypeInBlob(file);
274
+ var fileName = file.name || _this2.getRelativeFileName(file);
275
+ if (fileName) {
276
+ formPost.append(FIELD_NAME, dataWithUpdatedType, fileName);
277
+ } else {
278
+ formPost.append(FIELD_NAME, dataWithUpdatedType);
279
+ }
280
+ });
281
+ return formPost;
282
+ }
283
+ }, {
284
+ key: "upload",
285
+ value: function upload(_ref2) {
286
+ var _this3 = this;
287
+ var file = _ref2.file,
288
+ uploadId = _ref2.uploadId,
289
+ current = _ref2.current,
290
+ total = _ref2.total;
291
+ var opts = this.getOptions(file);
292
+ this.filerobot.log("uploading ".concat(current, " of ").concat(total));
293
+ return new Promise(function (resolve, reject) {
294
+ var _videoTranscoding$fil, _imageProcessor$files, _file$toFolder, _opts$uploadToFolderP;
295
+ _this3.filerobot.emit('upload-started', file, {
296
+ uploadId: uploadId
297
+ });
298
+ var data = file.uploadUrl ? JSON.stringify({
299
+ files_urls: [{
300
+ url: file.uploadUrl,
301
+ name: file.name
302
+ }]
303
+ }) : _this3.createFormDataUpload(file, opts);
304
+ var xhr = new XMLHttpRequest();
305
+ _this3.filerobotEvents[file.id] = new EventTracker(_this3.filerobot);
306
+ var timer = new ProgressTimeout(opts.timeout, function () {
307
+ xhr.abort();
308
+ queuedRequest.done();
309
+ var error = new Error(_this3.i18n('timedOut', {
310
+ seconds: Math.ceil(opts.timeout / 1000)
311
+ }));
312
+ _this3.filerobot.emit('upload-error', file, error, {
313
+ uploadId: uploadId
314
+ });
315
+ reject(error);
316
+ });
317
+ var id = cuid();
318
+ xhr.upload.addEventListener('loadstart', function (ev) {
319
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " started"));
320
+ });
321
+ xhr.upload.addEventListener('progress', function (ev) {
322
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " progress: ").concat(ev.loaded, " / ").concat(ev.total));
323
+ // Begin checking for timeouts when progress starts, instead of loading,
324
+ // to avoid timing out requests on browser concurrency queue
325
+ timer.progress();
326
+ var isOnline = checkConnection();
327
+ if (!isOnline) {
328
+ xhr.abort();
329
+ queuedRequest.done();
330
+ var error = new Error(_this3.i18n('filerobotNoInternetConnectionInfo'));
331
+ _this3.filerobot.emit('upload-error', file, error, {
332
+ uploadId: uploadId
333
+ });
334
+ reject(error);
335
+ }
336
+ if (ev.lengthComputable) {
337
+ _this3.filerobot.emit('upload-progress', file, {
338
+ filerobot: _this3,
339
+ bytesFinished: ev.loaded,
340
+ bytesTotal: ev.total,
341
+ uploadId: uploadId
342
+ });
343
+ }
344
+ });
345
+ xhr.addEventListener('load', function (ev) {
346
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " finished"));
347
+ timer.done();
348
+ queuedRequest.done();
349
+ if (_this3.filerobotEvents[file.id]) {
350
+ _this3.filerobotEvents[file.id].remove();
351
+ _this3.filerobotEvents[file.id] = null;
352
+ }
353
+ if (opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
354
+ var body = opts.getResponseData(xhr.responseText, xhr);
355
+ var uploadURL = body[opts.responseUrlFieldName];
356
+ var uploadResp = {
357
+ status: ev.target.status,
358
+ body: body,
359
+ uploadURL: uploadURL
360
+ };
361
+ _this3.filerobot.emit('upload-success', _objectSpread(_objectSpread({}, file), uploadResp.body.file), uploadResp, {
362
+ uploadId: uploadId
363
+ });
364
+ if (uploadURL) {
365
+ _this3.filerobot.log("Download ".concat(file.name, " from ").concat(uploadURL));
366
+ }
367
+ return resolve(file);
368
+ } else {
369
+ var _body = opts.getResponseData(xhr.responseText, xhr);
370
+ var error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
371
+ var response = {
372
+ status: ev.target.status,
373
+ body: _body
374
+ };
375
+ _this3.filerobot.emit('upload-error', file, error, {
376
+ response: response,
377
+ uploadId: uploadId
378
+ });
379
+ return reject(error);
380
+ }
381
+ });
382
+ xhr.addEventListener('error', function (ev) {
383
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " errored"));
384
+ timer.done();
385
+ queuedRequest.done();
386
+ if (_this3.filerobotEvents[file.id]) {
387
+ _this3.filerobotEvents[file.id].remove();
388
+ _this3.filerobotEvents[file.id] = null;
389
+ }
390
+ var error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
391
+ _this3.filerobot.emit('upload-error', file, error, {
392
+ uploadId: uploadId
393
+ });
394
+ return reject(error);
395
+ });
396
+ var _this3$filerobot$getC = _this3.filerobot.getCoreCommonState(),
397
+ _this3$filerobot$getC2 = _this3$filerobot$getC.dndTargetFolderPath,
398
+ dndTargetFolderPath = _this3$filerobot$getC2 === void 0 ? '/' : _this3$filerobot$getC2,
399
+ _this3$filerobot$getC3 = _this3$filerobot$getC.videoTranscoding,
400
+ _this3$filerobot$getC4 = _this3$filerobot$getC3 === void 0 ? {} : _this3$filerobot$getC3,
401
+ _this3$filerobot$getC5 = _this3$filerobot$getC4.isVideoProcessActive,
402
+ isVideoProcessActive = _this3$filerobot$getC5 === void 0 ? false : _this3$filerobot$getC5,
403
+ videoTranscoding = _objectWithoutProperties(_this3$filerobot$getC4, _excluded),
404
+ _this3$filerobot$getC6 = _this3$filerobot$getC.imageProcessor,
405
+ _this3$filerobot$getC7 = _this3$filerobot$getC6 === void 0 ? {} : _this3$filerobot$getC6,
406
+ _this3$filerobot$getC8 = _this3$filerobot$getC7.isImageProcessActive,
407
+ isImageProcessActive = _this3$filerobot$getC8 === void 0 ? false : _this3$filerobot$getC8,
408
+ imageProcessor = _objectWithoutProperties(_this3$filerobot$getC7, _excluded2),
409
+ _this3$filerobot$getC9 = _this3$filerobot$getC.fromDragging,
410
+ fromDragging = _this3$filerobot$getC9 === void 0 ? false : _this3$filerobot$getC9,
411
+ _this3$filerobot$getC10 = _this3$filerobot$getC.isQuickUploader,
412
+ isQuickUploader = _this3$filerobot$getC10 === void 0 ? false : _this3$filerobot$getC10;
413
+ var preprocessorParamsIfFound = '';
414
+ var allowVideoProcesses = isSupportedVideo(file) && isVideoProcessActive && ((_videoTranscoding$fil = videoTranscoding.filesIds) === null || _videoTranscoding$fil === void 0 ? void 0 : _videoTranscoding$fil.includes(file.id));
415
+ var allowImageProcesses = isImage(file) && isImageProcessActive && ((_imageProcessor$files = imageProcessor.filesIds) === null || _imageProcessor$files === void 0 ? void 0 : _imageProcessor$files.includes(file.id));
416
+ if (allowVideoProcesses) {
417
+ preprocessorParamsIfFound = "&postprocess=transcode&video-resolution=".concat(videoTranscoding.resolution, "&video_protocols=").concat(videoTranscoding.protocol);
418
+ } else if (allowImageProcesses) {
419
+ preprocessorParamsIfFound = "&resize=".concat(imageProcessor.values.width, ",").concat(imageProcessor.values.height);
420
+ }
421
+ var fileXhrQueryParams = Object.keys(file.xhrQueryParams || {});
422
+ var fileQueryParams = fileXhrQueryParams.map(function (key) {
423
+ return "".concat(key, "=").concat(file.xhrQueryParams[key]);
424
+ }).join('&');
425
+ var folder = opts.uploadQueryParams.search('(^|&)folder=') > -1 ? '' : "?folder=".concat(encodeURIComponent((_file$toFolder = file.toFolder) !== null && _file$toFolder !== void 0 ? _file$toFolder : ((_opts$uploadToFolderP = opts.uploadToFolderPath) !== null && _opts$uploadToFolderP !== void 0 ? _opts$uploadToFolderP : fromDragging) ? dndTargetFolderPath : '/'));
426
+ var finalEndpoint = "".concat(opts.endpoint).concat(folder).concat(opts.uploadQueryParams ? "".concat(folder ? '&' : '?').concat(opts.uploadQueryParams) : '').concat(isQuickUploader ? '&upload_mode=quick' : '').concat(preprocessorParamsIfFound).concat(fileQueryParams ? "&".concat(fileQueryParams) : '');
427
+ xhr.open(opts.method.toUpperCase(), finalEndpoint, true);
428
+ // IE10 does not allow setting `withCredentials` and `responseType`
429
+ // before `open()` is called.
430
+ xhr.withCredentials = opts.withCredentials;
431
+ if (opts.responseType !== '') {
432
+ xhr.responseType = opts.responseType;
433
+ }
434
+ var headers = _objectSpread(_objectSpread({}, opts.headers), file.xhrHeaders);
435
+ Object.keys(headers).forEach(function (header) {
436
+ xhr.setRequestHeader(header, headers[header]);
437
+ });
438
+ var queuedRequest = _this3.requests.run(function () {
439
+ xhr.send(data);
440
+ return function () {
441
+ timer.done();
442
+ xhr.abort();
443
+ };
444
+ });
445
+ _this3.onFileRemove(file.id, function () {
446
+ queuedRequest.abort();
447
+ reject(new Error('File removed'));
448
+ });
449
+ _this3.onCancelAll(file.id, function () {
450
+ queuedRequest.abort();
451
+ reject(new Error('Upload cancelled'));
452
+ });
453
+ });
454
+ }
455
+ }, {
456
+ key: "uploadRemote",
457
+ value: function uploadRemote(_ref3) {
458
+ var _this4 = this;
459
+ var file = _ref3.file,
460
+ uploadId = _ref3.uploadId;
461
+ var opts = this.getOptions(file);
462
+ return new Promise(function (resolve, reject) {
463
+ var _this4$opts$addInfoCa, _this4$opts;
464
+ var _this4$filerobot$getC = _this4.filerobot.getCoreCommonState(),
465
+ _this4$filerobot$getC2 = _this4$filerobot$getC.videoTranscoding,
466
+ _this4$filerobot$getC3 = _this4$filerobot$getC2 === void 0 ? {} : _this4$filerobot$getC2,
467
+ isVideoProcessActive = _this4$filerobot$getC3.isVideoProcessActive,
468
+ videoFilesIds = _this4$filerobot$getC3.filesIds,
469
+ resolution = _this4$filerobot$getC3.resolution,
470
+ protocol = _this4$filerobot$getC3.protocol,
471
+ _this4$filerobot$getC4 = _this4$filerobot$getC.imageProcessor,
472
+ _this4$filerobot$getC5 = _this4$filerobot$getC4 === void 0 ? {} : _this4$filerobot$getC4,
473
+ isImageProcessActive = _this4$filerobot$getC5.isImageProcessActive,
474
+ filesIds = _this4$filerobot$getC5.filesIds,
475
+ values = _this4$filerobot$getC5.values;
476
+ var allowImageProcesses = isImage(file) && isImageProcessActive && (filesIds === null || filesIds === void 0 ? void 0 : filesIds.includes(file.id));
477
+ var allowVideoProcesses = isSupportedVideo(file) && isVideoProcessActive && (videoFilesIds === null || videoFilesIds === void 0 ? void 0 : videoFilesIds.includes(file.id));
478
+ _this4.filerobot.emit('upload-started', file, {
479
+ uploadId: uploadId
480
+ });
481
+ var folderPath = _this4.filerobot.getRemoteUploadFolder({
482
+ file: file,
483
+ opts: opts
484
+ });
485
+ var restUploadQueryParams = opts.uploadQueryParams.split('&').filter(function (item) {
486
+ return !/^folder=/.test(item);
487
+ }).join('&');
488
+ var infoFromCbFn = (_this4$opts$addInfoCa = (_this4$opts = _this4.opts).addInfoCallback) === null || _this4$opts$addInfoCa === void 0 ? void 0 : _this4$opts$addInfoCa.call(_this4$opts, file);
489
+ var fields = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, file.info), _this4.opts.info), _typeof(infoFromCbFn) === 'object' ? infoFromCbFn : {}), {}, {
490
+ meta: JSON.stringify(file.meta || {}),
491
+ name: file.name,
492
+ 'filerobot-folder': folderPath
493
+ });
494
+ if (allowVideoProcesses) {
495
+ fields['video-resolution'] = resolution;
496
+ fields['video-protocols'] = protocol;
497
+ } else if (allowImageProcesses) {
498
+ fields.resize = "".concat(values.width, ",").concat(values.height);
499
+ }
500
+ var Client = file.remote.providerOptions.provider ? Provider : RequestClient;
501
+ var client = new Client(_this4.filerobot, file.remote.providerOptions);
502
+ client.post(file.remote.url, _objectSpread(_objectSpread({}, file.remote.body), {}, {
503
+ endpoint: "".concat(opts.endpoint, "?folder=").concat(encodeURIComponent(folderPath)).concat(restUploadQueryParams ? "&".concat(restUploadQueryParams) : ''),
504
+ size: file.data.size,
505
+ fieldname: FIELD_NAME,
506
+ metadata: fields,
507
+ httpMethod: opts.method,
508
+ useFormData: true,
509
+ headers: opts.headers
510
+ })).then(function (res) {
511
+ var token = res.token;
512
+ var host = getSocketHost(file.remote.companionUrl);
513
+ var socket = new Socket({
514
+ target: "".concat(host, "/api/").concat(token),
515
+ autoOpen: false
516
+ });
517
+ _this4.filerobotEvents[file.id] = new EventTracker(_this4.filerobot);
518
+ _this4.onFileRemove(file.id, function () {
519
+ socket.send('cancel', {});
520
+ queuedRequest.abort();
521
+ resolve("upload ".concat(file.id, " was removed"));
522
+ });
523
+ _this4.onCancelAll(file.id, function () {
524
+ socket.send('cancel', {});
525
+ queuedRequest.abort();
526
+ resolve("upload ".concat(file.id, " was canceled"));
527
+ });
528
+ _this4.onRetry(file.id, function () {
529
+ socket.send('pause', {});
530
+ socket.send('resume', {});
531
+ });
532
+ _this4.onRetryAll(file.id, function () {
533
+ socket.send('pause', {});
534
+ socket.send('resume', {});
535
+ });
536
+ socket.on('progress', function (progressData) {
537
+ return emitSocketProgress(_this4, progressData, file);
538
+ });
539
+ socket.on('success', function (data) {
540
+ var body = opts.getResponseData(data.response.responseText, data.response);
541
+ var uploadURL = body[opts.responseUrlFieldName];
542
+ var uploadResp = {
543
+ status: data.response.status,
544
+ body: body,
545
+ uploadURL: uploadURL
546
+ };
547
+ _this4.filerobot.emit('upload-success', _objectSpread(_objectSpread({}, file), uploadResp.body.file), uploadResp, {
548
+ uploadId: uploadId
549
+ });
550
+ queuedRequest.done();
551
+ if (_this4.filerobotEvents[file.id]) {
552
+ _this4.filerobotEvents[file.id].remove();
553
+ _this4.filerobotEvents[file.id] = null;
554
+ }
555
+ return resolve();
556
+ });
557
+ socket.on('error', function (errData) {
558
+ var resp = errData.response;
559
+ var error = resp ? opts.getResponseError(resp.responseText, resp) : _extends(new Error(errData.error.message), {
560
+ cause: errData.error
561
+ });
562
+ _this4.filerobot.emit('upload-error', file, error, {
563
+ uploadId: uploadId
564
+ });
565
+ queuedRequest.done();
566
+ if (_this4.filerobotEvents[file.id]) {
567
+ _this4.filerobotEvents[file.id].remove();
568
+ _this4.filerobotEvents[file.id] = null;
569
+ }
570
+ reject(error);
571
+ });
572
+ var queuedRequest = _this4.requests.run(function () {
573
+ socket.open();
574
+ if (file.progress.status === PROGRESS_PANEL_STATUS.PAUSED) {
575
+ socket.send('pause', {});
576
+ }
577
+ return function () {
578
+ return socket.close();
579
+ };
580
+ });
581
+ })["catch"](function (err) {
582
+ _this4.filerobot.emit('upload-error', file, err, {
583
+ uploadId: uploadId
584
+ });
585
+ reject(err);
586
+ });
587
+ });
588
+ }
589
+ }, {
590
+ key: "uploadBundle",
591
+ value: function uploadBundle(files, uploadId) {
592
+ var _this5 = this;
593
+ return new Promise(function (resolve, reject) {
594
+ var endpoint = _this5.opts.endpoint;
595
+ var method = _this5.opts.method;
596
+ var optsFromState = _this5.filerobot.getCoreCommonState().xhrUpload;
597
+ var formData = _this5.createBundledUpload(files, _objectSpread(_objectSpread({}, _this5.opts), optsFromState || {}));
598
+ var xhr = new XMLHttpRequest();
599
+ var timer = new ProgressTimeout(_this5.opts.timeout, function () {
600
+ xhr.abort();
601
+ var error = new Error(_this5.i18n('timedOut', {
602
+ seconds: Math.ceil(_this5.opts.timeout / 1000)
603
+ }));
604
+ emitError(error);
605
+ reject(error);
606
+ });
607
+ var emitError = function emitError(error) {
608
+ files.forEach(function (file) {
609
+ _this5.filerobot.emit('upload-error', file, error, {
610
+ uploadId: uploadId
611
+ });
612
+ });
613
+ };
614
+ xhr.upload.addEventListener('loadstart', function (ev) {
615
+ _this5.filerobot.log('[XHRUpload] started uploading bundle');
616
+ timer.progress();
617
+ });
618
+ xhr.upload.addEventListener('progress', function (ev) {
619
+ timer.progress();
620
+ if (!ev.lengthComputable) return;
621
+ files.forEach(function (file) {
622
+ _this5.filerobot.emit('upload-progress', file, {
623
+ filerobot: _this5,
624
+ bytesFinished: ev.loaded / ev.total * file.size,
625
+ bytesTotal: file.size,
626
+ uploadId: uploadId
627
+ });
628
+ });
629
+ });
630
+ xhr.addEventListener('load', function (ev) {
631
+ timer.done();
632
+ if (_this5.opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
633
+ var body = _this5.opts.getResponseData(xhr.responseText, xhr);
634
+ var uploadResp = {
635
+ status: ev.target.status,
636
+ body: body
637
+ };
638
+ files.forEach(function (file) {
639
+ _this5.filerobot.emit('upload-success', _objectSpread(_objectSpread({}, file), uploadResp.body.file), uploadResp, {
640
+ uploadId: uploadId
641
+ });
642
+ });
643
+ return resolve();
644
+ }
645
+ var error = _this5.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
646
+ error.request = xhr;
647
+ emitError(error);
648
+ return reject(error);
649
+ });
650
+ xhr.addEventListener('error', function (ev) {
651
+ timer.done();
652
+ var error = _this5.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
653
+ emitError(error);
654
+ return reject(error);
655
+ });
656
+ _this5.filerobot.on('cancel-uploads', function () {
657
+ timer.done();
658
+ xhr.abort();
659
+ });
660
+ xhr.open(method.toUpperCase(), endpoint, true);
661
+ // IE10 does not allow setting `withCredentials` and `responseType`
662
+ // before `open()` is called.
663
+ xhr.withCredentials = _this5.opts.withCredentials;
664
+ if (_this5.opts.responseType !== '') {
665
+ xhr.responseType = _this5.opts.responseType;
666
+ }
667
+ Object.keys(_this5.opts.headers).forEach(function (header) {
668
+ xhr.setRequestHeader(header, _this5.opts.headers[header]);
669
+ });
670
+ xhr.send(formData);
671
+ files.forEach(function (file) {
672
+ _this5.filerobot.emit('upload-started', file, {
673
+ uploadId: uploadId
674
+ });
675
+ });
676
+ });
677
+ }
678
+ }, {
679
+ key: "uploadFiles",
680
+ value: function uploadFiles(files, uploadId) {
681
+ var _this6 = this;
682
+ var total = files.length;
683
+ var promises = files.map(function (file, i) {
684
+ var current = parseInt(i, 10) + 1;
685
+ if (file.error) {
686
+ return Promise.reject(new Error(file.error));
687
+ } else if (file.isRemote) {
688
+ return _this6.uploadRemote({
689
+ file: file,
690
+ uploadId: uploadId
691
+ });
692
+ } else {
693
+ return _this6.upload({
694
+ file: file,
695
+ uploadId: uploadId,
696
+ current: current,
697
+ total: total
698
+ });
699
+ }
700
+ });
701
+ return settle(promises);
702
+ }
703
+ }, {
704
+ key: "onFileRemove",
705
+ value: function onFileRemove(fileId, cb) {
706
+ this.filerobotEvents[fileId].on('file-removed', function (file) {
707
+ if (fileId === file.id) cb(file.id);
708
+ });
709
+ }
710
+ }, {
711
+ key: "onRetry",
712
+ value: function onRetry(fileId, cb) {
713
+ this.filerobotEvents[fileId].on('upload-retry', function (targetFileID) {
714
+ if (fileId === targetFileID) {
715
+ cb();
716
+ }
717
+ });
718
+ }
719
+ }, {
720
+ key: "onRetryAll",
721
+ value: function onRetryAll(fileId, cb) {
722
+ var _this7 = this;
723
+ this.filerobotEvents[fileId].on('retry-all', function (filesToRetry) {
724
+ if (!_this7.filerobot.getFileUploading(fileId)) return;
725
+ cb();
726
+ });
727
+ }
728
+ }, {
729
+ key: "onCancelAll",
730
+ value: function onCancelAll(fileId, cb) {
731
+ var _this8 = this;
732
+ this.filerobotEvents[fileId].on('cancel-uploads', function () {
733
+ if (!_this8.filerobot.getFileUploading(fileId)) return;
734
+ cb();
735
+ });
736
+ }
737
+ }, {
738
+ key: "handleUpload",
739
+ value: function handleUpload(fileIds, uploadId) {
740
+ var _this9 = this;
741
+ if (fileIds.length === 0) {
742
+ this.filerobot.log('[XHRUpload] No files to upload!');
743
+ return Promise.resolve();
744
+ }
745
+ if (this.opts.skipUpload) {
746
+ // Duplicated logic from Hub to support FRA-6565
747
+ return Promise.resolve();
748
+ }
749
+
750
+ // no limit configured by the user, and no RateLimitedQueue passed in by a "parent" plugin (basically just AwsS3) using the top secret `__queue` option
751
+ if (this.opts.limit === 0 && !this.opts.__queue) {
752
+ this.filerobot.log('[XHRUpload] When uploading multiple files at once, consider setting the `limit` option (to `10` for example), to limit the number of concurrent uploads, which helps prevent memory and network issues.', 'warning');
753
+ }
754
+ this.filerobot.log('[XHRUpload] Uploading...');
755
+ var files = fileIds.map(function (fileId) {
756
+ return _this9.filerobot.getFileUploading(fileId);
757
+ });
758
+ if (this.opts.bundle) {
759
+ // if bundle: true, we don’t support remote uploads
760
+ var isSomeFileRemote = files.some(function (file) {
761
+ return file.isRemote;
762
+ });
763
+ if (isSomeFileRemote) {
764
+ throw new Error('Can’t upload remote files when bundle: true option is set');
765
+ }
766
+ return this.uploadBundle(files, uploadId);
767
+ }
768
+ return this.uploadFiles(files, uploadId).then(function () {
769
+ return null;
770
+ });
771
+ }
772
+ }, {
773
+ key: "install",
774
+ value: function install() {
775
+ if (this.opts.bundle) {
776
+ this.dispatch(uploadCapabilitiesUpdated({
777
+ allowIndividualCancellation: false
778
+ }));
779
+ }
780
+ this.filerobot.addFilerobot(this.handleUpload);
781
+ }
782
+ }, {
783
+ key: "uninstall",
784
+ value: function uninstall() {
785
+ if (this.opts.bundle) {
786
+ this.dispatch(uploadCapabilitiesUpdated({
787
+ allowIndividualCancellation: true
788
+ }));
789
+ }
790
+ this.filerobot.removeFilerobot(this.handleUpload);
791
+ }
792
+ }]);
793
+ }(Plugin);
794
+ export { XHRUpload as default };