uppy.js 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Uppy = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /**
  3. * Module dependencies.
  4. */
  5. var Emitter = require('emitter');
  6. var reduce = require('reduce');
  7. /**
  8. * Root reference for iframes.
  9. */
  10. var root;
  11. if (typeof window !== 'undefined') { // Browser window
  12. root = window;
  13. } else if (typeof self !== 'undefined') { // Web Worker
  14. root = self;
  15. } else { // Other environments
  16. root = this;
  17. }
  18. /**
  19. * Noop.
  20. */
  21. function noop(){};
  22. /**
  23. * Check if `obj` is a host object,
  24. * we don't want to serialize these :)
  25. *
  26. * TODO: future proof, move to compoent land
  27. *
  28. * @param {Object} obj
  29. * @return {Boolean}
  30. * @api private
  31. */
  32. function isHost(obj) {
  33. var str = {}.toString.call(obj);
  34. switch (str) {
  35. case '[object File]':
  36. case '[object Blob]':
  37. case '[object FormData]':
  38. return true;
  39. default:
  40. return false;
  41. }
  42. }
  43. /**
  44. * Determine XHR.
  45. */
  46. request.getXHR = function () {
  47. if (root.XMLHttpRequest
  48. && (!root.location || 'file:' != root.location.protocol
  49. || !root.ActiveXObject)) {
  50. return new XMLHttpRequest;
  51. } else {
  52. try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
  53. try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
  54. try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
  55. try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
  56. }
  57. return false;
  58. };
  59. /**
  60. * Removes leading and trailing whitespace, added to support IE.
  61. *
  62. * @param {String} s
  63. * @return {String}
  64. * @api private
  65. */
  66. var trim = ''.trim
  67. ? function(s) { return s.trim(); }
  68. : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
  69. /**
  70. * Check if `obj` is an object.
  71. *
  72. * @param {Object} obj
  73. * @return {Boolean}
  74. * @api private
  75. */
  76. function isObject(obj) {
  77. return obj === Object(obj);
  78. }
  79. /**
  80. * Serialize the given `obj`.
  81. *
  82. * @param {Object} obj
  83. * @return {String}
  84. * @api private
  85. */
  86. function serialize(obj) {
  87. if (!isObject(obj)) return obj;
  88. var pairs = [];
  89. for (var key in obj) {
  90. if (null != obj[key]) {
  91. pushEncodedKeyValuePair(pairs, key, obj[key]);
  92. }
  93. }
  94. return pairs.join('&');
  95. }
  96. /**
  97. * Helps 'serialize' with serializing arrays.
  98. * Mutates the pairs array.
  99. *
  100. * @param {Array} pairs
  101. * @param {String} key
  102. * @param {Mixed} val
  103. */
  104. function pushEncodedKeyValuePair(pairs, key, val) {
  105. if (Array.isArray(val)) {
  106. return val.forEach(function(v) {
  107. pushEncodedKeyValuePair(pairs, key, v);
  108. });
  109. }
  110. pairs.push(encodeURIComponent(key)
  111. + '=' + encodeURIComponent(val));
  112. }
  113. /**
  114. * Expose serialization method.
  115. */
  116. request.serializeObject = serialize;
  117. /**
  118. * Parse the given x-www-form-urlencoded `str`.
  119. *
  120. * @param {String} str
  121. * @return {Object}
  122. * @api private
  123. */
  124. function parseString(str) {
  125. var obj = {};
  126. var pairs = str.split('&');
  127. var parts;
  128. var pair;
  129. for (var i = 0, len = pairs.length; i < len; ++i) {
  130. pair = pairs[i];
  131. parts = pair.split('=');
  132. obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
  133. }
  134. return obj;
  135. }
  136. /**
  137. * Expose parser.
  138. */
  139. request.parseString = parseString;
  140. /**
  141. * Default MIME type map.
  142. *
  143. * superagent.types.xml = 'application/xml';
  144. *
  145. */
  146. request.types = {
  147. html: 'text/html',
  148. json: 'application/json',
  149. xml: 'application/xml',
  150. urlencoded: 'application/x-www-form-urlencoded',
  151. 'form': 'application/x-www-form-urlencoded',
  152. 'form-data': 'application/x-www-form-urlencoded'
  153. };
  154. /**
  155. * Default serialization map.
  156. *
  157. * superagent.serialize['application/xml'] = function(obj){
  158. * return 'generated xml here';
  159. * };
  160. *
  161. */
  162. request.serialize = {
  163. 'application/x-www-form-urlencoded': serialize,
  164. 'application/json': JSON.stringify
  165. };
  166. /**
  167. * Default parsers.
  168. *
  169. * superagent.parse['application/xml'] = function(str){
  170. * return { object parsed from str };
  171. * };
  172. *
  173. */
  174. request.parse = {
  175. 'application/x-www-form-urlencoded': parseString,
  176. 'application/json': JSON.parse
  177. };
  178. /**
  179. * Parse the given header `str` into
  180. * an object containing the mapped fields.
  181. *
  182. * @param {String} str
  183. * @return {Object}
  184. * @api private
  185. */
  186. function parseHeader(str) {
  187. var lines = str.split(/\r?\n/);
  188. var fields = {};
  189. var index;
  190. var line;
  191. var field;
  192. var val;
  193. lines.pop(); // trailing CRLF
  194. for (var i = 0, len = lines.length; i < len; ++i) {
  195. line = lines[i];
  196. index = line.indexOf(':');
  197. field = line.slice(0, index).toLowerCase();
  198. val = trim(line.slice(index + 1));
  199. fields[field] = val;
  200. }
  201. return fields;
  202. }
  203. /**
  204. * Return the mime type for the given `str`.
  205. *
  206. * @param {String} str
  207. * @return {String}
  208. * @api private
  209. */
  210. function type(str){
  211. return str.split(/ *; */).shift();
  212. };
  213. /**
  214. * Return header field parameters.
  215. *
  216. * @param {String} str
  217. * @return {Object}
  218. * @api private
  219. */
  220. function params(str){
  221. return reduce(str.split(/ *; */), function(obj, str){
  222. var parts = str.split(/ *= */)
  223. , key = parts.shift()
  224. , val = parts.shift();
  225. if (key && val) obj[key] = val;
  226. return obj;
  227. }, {});
  228. };
  229. /**
  230. * Initialize a new `Response` with the given `xhr`.
  231. *
  232. * - set flags (.ok, .error, etc)
  233. * - parse header
  234. *
  235. * Examples:
  236. *
  237. * Aliasing `superagent` as `request` is nice:
  238. *
  239. * request = superagent;
  240. *
  241. * We can use the promise-like API, or pass callbacks:
  242. *
  243. * request.get('/').end(function(res){});
  244. * request.get('/', function(res){});
  245. *
  246. * Sending data can be chained:
  247. *
  248. * request
  249. * .post('/user')
  250. * .send({ name: 'tj' })
  251. * .end(function(res){});
  252. *
  253. * Or passed to `.send()`:
  254. *
  255. * request
  256. * .post('/user')
  257. * .send({ name: 'tj' }, function(res){});
  258. *
  259. * Or passed to `.post()`:
  260. *
  261. * request
  262. * .post('/user', { name: 'tj' })
  263. * .end(function(res){});
  264. *
  265. * Or further reduced to a single call for simple cases:
  266. *
  267. * request
  268. * .post('/user', { name: 'tj' }, function(res){});
  269. *
  270. * @param {XMLHTTPRequest} xhr
  271. * @param {Object} options
  272. * @api private
  273. */
  274. function Response(req, options) {
  275. options = options || {};
  276. this.req = req;
  277. this.xhr = this.req.xhr;
  278. // responseText is accessible only if responseType is '' or 'text' and on older browsers
  279. this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
  280. ? this.xhr.responseText
  281. : null;
  282. this.statusText = this.req.xhr.statusText;
  283. this.setStatusProperties(this.xhr.status);
  284. this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
  285. // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
  286. // getResponseHeader still works. so we get content-type even if getting
  287. // other headers fails.
  288. this.header['content-type'] = this.xhr.getResponseHeader('content-type');
  289. this.setHeaderProperties(this.header);
  290. this.body = this.req.method != 'HEAD'
  291. ? this.parseBody(this.text ? this.text : this.xhr.response)
  292. : null;
  293. }
  294. /**
  295. * Get case-insensitive `field` value.
  296. *
  297. * @param {String} field
  298. * @return {String}
  299. * @api public
  300. */
  301. Response.prototype.get = function(field){
  302. return this.header[field.toLowerCase()];
  303. };
  304. /**
  305. * Set header related properties:
  306. *
  307. * - `.type` the content type without params
  308. *
  309. * A response of "Content-Type: text/plain; charset=utf-8"
  310. * will provide you with a `.type` of "text/plain".
  311. *
  312. * @param {Object} header
  313. * @api private
  314. */
  315. Response.prototype.setHeaderProperties = function(header){
  316. // content-type
  317. var ct = this.header['content-type'] || '';
  318. this.type = type(ct);
  319. // params
  320. var obj = params(ct);
  321. for (var key in obj) this[key] = obj[key];
  322. };
  323. /**
  324. * Parse the given body `str`.
  325. *
  326. * Used for auto-parsing of bodies. Parsers
  327. * are defined on the `superagent.parse` object.
  328. *
  329. * @param {String} str
  330. * @return {Mixed}
  331. * @api private
  332. */
  333. Response.prototype.parseBody = function(str){
  334. var parse = request.parse[this.type];
  335. return parse && str && (str.length || str instanceof Object)
  336. ? parse(str)
  337. : null;
  338. };
  339. /**
  340. * Set flags such as `.ok` based on `status`.
  341. *
  342. * For example a 2xx response will give you a `.ok` of __true__
  343. * whereas 5xx will be __false__ and `.error` will be __true__. The
  344. * `.clientError` and `.serverError` are also available to be more
  345. * specific, and `.statusType` is the class of error ranging from 1..5
  346. * sometimes useful for mapping respond colors etc.
  347. *
  348. * "sugar" properties are also defined for common cases. Currently providing:
  349. *
  350. * - .noContent
  351. * - .badRequest
  352. * - .unauthorized
  353. * - .notAcceptable
  354. * - .notFound
  355. *
  356. * @param {Number} status
  357. * @api private
  358. */
  359. Response.prototype.setStatusProperties = function(status){
  360. // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
  361. if (status === 1223) {
  362. status = 204;
  363. }
  364. var type = status / 100 | 0;
  365. // status / class
  366. this.status = this.statusCode = status;
  367. this.statusType = type;
  368. // basics
  369. this.info = 1 == type;
  370. this.ok = 2 == type;
  371. this.clientError = 4 == type;
  372. this.serverError = 5 == type;
  373. this.error = (4 == type || 5 == type)
  374. ? this.toError()
  375. : false;
  376. // sugar
  377. this.accepted = 202 == status;
  378. this.noContent = 204 == status;
  379. this.badRequest = 400 == status;
  380. this.unauthorized = 401 == status;
  381. this.notAcceptable = 406 == status;
  382. this.notFound = 404 == status;
  383. this.forbidden = 403 == status;
  384. };
  385. /**
  386. * Return an `Error` representative of this response.
  387. *
  388. * @return {Error}
  389. * @api public
  390. */
  391. Response.prototype.toError = function(){
  392. var req = this.req;
  393. var method = req.method;
  394. var url = req.url;
  395. var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
  396. var err = new Error(msg);
  397. err.status = this.status;
  398. err.method = method;
  399. err.url = url;
  400. return err;
  401. };
  402. /**
  403. * Expose `Response`.
  404. */
  405. request.Response = Response;
  406. /**
  407. * Initialize a new `Request` with the given `method` and `url`.
  408. *
  409. * @param {String} method
  410. * @param {String} url
  411. * @api public
  412. */
  413. function Request(method, url) {
  414. var self = this;
  415. Emitter.call(this);
  416. this._query = this._query || [];
  417. this.method = method;
  418. this.url = url;
  419. this.header = {};
  420. this._header = {};
  421. this.on('end', function(){
  422. var err = null;
  423. var res = null;
  424. try {
  425. res = new Response(self);
  426. } catch(e) {
  427. err = new Error('Parser is unable to parse the response');
  428. err.parse = true;
  429. err.original = e;
  430. return self.callback(err);
  431. }
  432. self.emit('response', res);
  433. if (err) {
  434. return self.callback(err, res);
  435. }
  436. if (res.status >= 200 && res.status < 300) {
  437. return self.callback(err, res);
  438. }
  439. var new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
  440. new_err.original = err;
  441. new_err.response = res;
  442. new_err.status = res.status;
  443. self.callback(new_err, res);
  444. });
  445. }
  446. /**
  447. * Mixin `Emitter`.
  448. */
  449. Emitter(Request.prototype);
  450. /**
  451. * Allow for extension
  452. */
  453. Request.prototype.use = function(fn) {
  454. fn(this);
  455. return this;
  456. }
  457. /**
  458. * Set timeout to `ms`.
  459. *
  460. * @param {Number} ms
  461. * @return {Request} for chaining
  462. * @api public
  463. */
  464. Request.prototype.timeout = function(ms){
  465. this._timeout = ms;
  466. return this;
  467. };
  468. /**
  469. * Clear previous timeout.
  470. *
  471. * @return {Request} for chaining
  472. * @api public
  473. */
  474. Request.prototype.clearTimeout = function(){
  475. this._timeout = 0;
  476. clearTimeout(this._timer);
  477. return this;
  478. };
  479. /**
  480. * Abort the request, and clear potential timeout.
  481. *
  482. * @return {Request}
  483. * @api public
  484. */
  485. Request.prototype.abort = function(){
  486. if (this.aborted) return;
  487. this.aborted = true;
  488. this.xhr.abort();
  489. this.clearTimeout();
  490. this.emit('abort');
  491. return this;
  492. };
  493. /**
  494. * Set header `field` to `val`, or multiple fields with one object.
  495. *
  496. * Examples:
  497. *
  498. * req.get('/')
  499. * .set('Accept', 'application/json')
  500. * .set('X-API-Key', 'foobar')
  501. * .end(callback);
  502. *
  503. * req.get('/')
  504. * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
  505. * .end(callback);
  506. *
  507. * @param {String|Object} field
  508. * @param {String} val
  509. * @return {Request} for chaining
  510. * @api public
  511. */
  512. Request.prototype.set = function(field, val){
  513. if (isObject(field)) {
  514. for (var key in field) {
  515. this.set(key, field[key]);
  516. }
  517. return this;
  518. }
  519. this._header[field.toLowerCase()] = val;
  520. this.header[field] = val;
  521. return this;
  522. };
  523. /**
  524. * Remove header `field`.
  525. *
  526. * Example:
  527. *
  528. * req.get('/')
  529. * .unset('User-Agent')
  530. * .end(callback);
  531. *
  532. * @param {String} field
  533. * @return {Request} for chaining
  534. * @api public
  535. */
  536. Request.prototype.unset = function(field){
  537. delete this._header[field.toLowerCase()];
  538. delete this.header[field];
  539. return this;
  540. };
  541. /**
  542. * Get case-insensitive header `field` value.
  543. *
  544. * @param {String} field
  545. * @return {String}
  546. * @api private
  547. */
  548. Request.prototype.getHeader = function(field){
  549. return this._header[field.toLowerCase()];
  550. };
  551. /**
  552. * Set Content-Type to `type`, mapping values from `request.types`.
  553. *
  554. * Examples:
  555. *
  556. * superagent.types.xml = 'application/xml';
  557. *
  558. * request.post('/')
  559. * .type('xml')
  560. * .send(xmlstring)
  561. * .end(callback);
  562. *
  563. * request.post('/')
  564. * .type('application/xml')
  565. * .send(xmlstring)
  566. * .end(callback);
  567. *
  568. * @param {String} type
  569. * @return {Request} for chaining
  570. * @api public
  571. */
  572. Request.prototype.type = function(type){
  573. this.set('Content-Type', request.types[type] || type);
  574. return this;
  575. };
  576. /**
  577. * Force given parser
  578. *
  579. * Sets the body parser no matter type.
  580. *
  581. * @param {Function}
  582. * @api public
  583. */
  584. Request.prototype.parse = function(fn){
  585. this._parser = fn;
  586. return this;
  587. };
  588. /**
  589. * Set Accept to `type`, mapping values from `request.types`.
  590. *
  591. * Examples:
  592. *
  593. * superagent.types.json = 'application/json';
  594. *
  595. * request.get('/agent')
  596. * .accept('json')
  597. * .end(callback);
  598. *
  599. * request.get('/agent')
  600. * .accept('application/json')
  601. * .end(callback);
  602. *
  603. * @param {String} accept
  604. * @return {Request} for chaining
  605. * @api public
  606. */
  607. Request.prototype.accept = function(type){
  608. this.set('Accept', request.types[type] || type);
  609. return this;
  610. };
  611. /**
  612. * Set Authorization field value with `user` and `pass`.
  613. *
  614. * @param {String} user
  615. * @param {String} pass
  616. * @return {Request} for chaining
  617. * @api public
  618. */
  619. Request.prototype.auth = function(user, pass){
  620. var str = btoa(user + ':' + pass);
  621. this.set('Authorization', 'Basic ' + str);
  622. return this;
  623. };
  624. /**
  625. * Add query-string `val`.
  626. *
  627. * Examples:
  628. *
  629. * request.get('/shoes')
  630. * .query('size=10')
  631. * .query({ color: 'blue' })
  632. *
  633. * @param {Object|String} val
  634. * @return {Request} for chaining
  635. * @api public
  636. */
  637. Request.prototype.query = function(val){
  638. if ('string' != typeof val) val = serialize(val);
  639. if (val) this._query.push(val);
  640. return this;
  641. };
  642. /**
  643. * Write the field `name` and `val` for "multipart/form-data"
  644. * request bodies.
  645. *
  646. * ``` js
  647. * request.post('/upload')
  648. * .field('foo', 'bar')
  649. * .end(callback);
  650. * ```
  651. *
  652. * @param {String} name
  653. * @param {String|Blob|File} val
  654. * @return {Request} for chaining
  655. * @api public
  656. */
  657. Request.prototype.field = function(name, val){
  658. if (!this._formData) this._formData = new root.FormData();
  659. this._formData.append(name, val);
  660. return this;
  661. };
  662. /**
  663. * Queue the given `file` as an attachment to the specified `field`,
  664. * with optional `filename`.
  665. *
  666. * ``` js
  667. * request.post('/upload')
  668. * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
  669. * .end(callback);
  670. * ```
  671. *
  672. * @param {String} field
  673. * @param {Blob|File} file
  674. * @param {String} filename
  675. * @return {Request} for chaining
  676. * @api public
  677. */
  678. Request.prototype.attach = function(field, file, filename){
  679. if (!this._formData) this._formData = new root.FormData();
  680. this._formData.append(field, file, filename);
  681. return this;
  682. };
  683. /**
  684. * Send `data`, defaulting the `.type()` to "json" when
  685. * an object is given.
  686. *
  687. * Examples:
  688. *
  689. * // querystring
  690. * request.get('/search')
  691. * .end(callback)
  692. *
  693. * // multiple data "writes"
  694. * request.get('/search')
  695. * .send({ search: 'query' })
  696. * .send({ range: '1..5' })
  697. * .send({ order: 'desc' })
  698. * .end(callback)
  699. *
  700. * // manual json
  701. * request.post('/user')
  702. * .type('json')
  703. * .send('{"name":"tj"}')
  704. * .end(callback)
  705. *
  706. * // auto json
  707. * request.post('/user')
  708. * .send({ name: 'tj' })
  709. * .end(callback)
  710. *
  711. * // manual x-www-form-urlencoded
  712. * request.post('/user')
  713. * .type('form')
  714. * .send('name=tj')
  715. * .end(callback)
  716. *
  717. * // auto x-www-form-urlencoded
  718. * request.post('/user')
  719. * .type('form')
  720. * .send({ name: 'tj' })
  721. * .end(callback)
  722. *
  723. * // defaults to x-www-form-urlencoded
  724. * request.post('/user')
  725. * .send('name=tobi')
  726. * .send('species=ferret')
  727. * .end(callback)
  728. *
  729. * @param {String|Object} data
  730. * @return {Request} for chaining
  731. * @api public
  732. */
  733. Request.prototype.send = function(data){
  734. var obj = isObject(data);
  735. var type = this.getHeader('Content-Type');
  736. // merge
  737. if (obj && isObject(this._data)) {
  738. for (var key in data) {
  739. this._data[key] = data[key];
  740. }
  741. } else if ('string' == typeof data) {
  742. if (!type) this.type('form');
  743. type = this.getHeader('Content-Type');
  744. if ('application/x-www-form-urlencoded' == type) {
  745. this._data = this._data
  746. ? this._data + '&' + data
  747. : data;
  748. } else {
  749. this._data = (this._data || '') + data;
  750. }
  751. } else {
  752. this._data = data;
  753. }
  754. if (!obj || isHost(data)) return this;
  755. if (!type) this.type('json');
  756. return this;
  757. };
  758. /**
  759. * Invoke the callback with `err` and `res`
  760. * and handle arity check.
  761. *
  762. * @param {Error} err
  763. * @param {Response} res
  764. * @api private
  765. */
  766. Request.prototype.callback = function(err, res){
  767. var fn = this._callback;
  768. this.clearTimeout();
  769. fn(err, res);
  770. };
  771. /**
  772. * Invoke callback with x-domain error.
  773. *
  774. * @api private
  775. */
  776. Request.prototype.crossDomainError = function(){
  777. var err = new Error('Origin is not allowed by Access-Control-Allow-Origin');
  778. err.crossDomain = true;
  779. this.callback(err);
  780. };
  781. /**
  782. * Invoke callback with timeout error.
  783. *
  784. * @api private
  785. */
  786. Request.prototype.timeoutError = function(){
  787. var timeout = this._timeout;
  788. var err = new Error('timeout of ' + timeout + 'ms exceeded');
  789. err.timeout = timeout;
  790. this.callback(err);
  791. };
  792. /**
  793. * Enable transmission of cookies with x-domain requests.
  794. *
  795. * Note that for this to work the origin must not be
  796. * using "Access-Control-Allow-Origin" with a wildcard,
  797. * and also must set "Access-Control-Allow-Credentials"
  798. * to "true".
  799. *
  800. * @api public
  801. */
  802. Request.prototype.withCredentials = function(){
  803. this._withCredentials = true;
  804. return this;
  805. };
  806. /**
  807. * Initiate request, invoking callback `fn(res)`
  808. * with an instanceof `Response`.
  809. *
  810. * @param {Function} fn
  811. * @return {Request} for chaining
  812. * @api public
  813. */
  814. Request.prototype.end = function(fn){
  815. var self = this;
  816. var xhr = this.xhr = request.getXHR();
  817. var query = this._query.join('&');
  818. var timeout = this._timeout;
  819. var data = this._formData || this._data;
  820. // store callback
  821. this._callback = fn || noop;
  822. // state change
  823. xhr.onreadystatechange = function(){
  824. if (4 != xhr.readyState) return;
  825. // In IE9, reads to any property (e.g. status) off of an aborted XHR will
  826. // result in the error "Could not complete the operation due to error c00c023f"
  827. var status;
  828. try { status = xhr.status } catch(e) { status = 0; }
  829. if (0 == status) {
  830. if (self.timedout) return self.timeoutError();
  831. if (self.aborted) return;
  832. return self.crossDomainError();
  833. }
  834. self.emit('end');
  835. };
  836. // progress
  837. var handleProgress = function(e){
  838. if (e.total > 0) {
  839. e.percent = e.loaded / e.total * 100;
  840. }
  841. self.emit('progress', e);
  842. };
  843. if (this.hasListeners('progress')) {
  844. xhr.onprogress = handleProgress;
  845. }
  846. try {
  847. if (xhr.upload && this.hasListeners('progress')) {
  848. xhr.upload.onprogress = handleProgress;
  849. }
  850. } catch(e) {
  851. // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
  852. // Reported here:
  853. // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
  854. }
  855. // timeout
  856. if (timeout && !this._timer) {
  857. this._timer = setTimeout(function(){
  858. self.timedout = true;
  859. self.abort();
  860. }, timeout);
  861. }
  862. // querystring
  863. if (query) {
  864. query = request.serializeObject(query);
  865. this.url += ~this.url.indexOf('?')
  866. ? '&' + query
  867. : '?' + query;
  868. }
  869. // initiate request
  870. xhr.open(this.method, this.url, true);
  871. // CORS
  872. if (this._withCredentials) xhr.withCredentials = true;
  873. // body
  874. if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) {
  875. // serialize stuff
  876. var contentType = this.getHeader('Content-Type');
  877. var serialize = this._parser || request.serialize[contentType ? contentType.split(';')[0] : ''];
  878. if (serialize) data = serialize(data);
  879. }
  880. // set header fields
  881. for (var field in this.header) {
  882. if (null == this.header[field]) continue;
  883. xhr.setRequestHeader(field, this.header[field]);
  884. }
  885. // send stuff
  886. this.emit('request', this);
  887. // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
  888. // We need null here if data is undefined
  889. xhr.send(typeof data !== 'undefined' ? data : null);
  890. return this;
  891. };
  892. /**
  893. * Faux promise support
  894. *
  895. * @param {Function} fulfill
  896. * @param {Function} reject
  897. * @return {Request}
  898. */
  899. Request.prototype.then = function (fulfill, reject) {
  900. return this.end(function(err, res) {
  901. err ? reject(err) : fulfill(res);
  902. });
  903. }
  904. /**
  905. * Expose `Request`.
  906. */
  907. request.Request = Request;
  908. /**
  909. * Issue a request:
  910. *
  911. * Examples:
  912. *
  913. * request('GET', '/users').end(callback)
  914. * request('/users').end(callback)
  915. * request('/users', callback)
  916. *
  917. * @param {String} method
  918. * @param {String|Function} url or callback
  919. * @return {Request}
  920. * @api public
  921. */
  922. function request(method, url) {
  923. // callback
  924. if ('function' == typeof url) {
  925. return new Request('GET', method).end(url);
  926. }
  927. // url first
  928. if (1 == arguments.length) {
  929. return new Request('GET', method);
  930. }
  931. return new Request(method, url);
  932. }
  933. /**
  934. * GET `url` with optional callback `fn(res)`.
  935. *
  936. * @param {String} url
  937. * @param {Mixed|Function} data or fn
  938. * @param {Function} fn
  939. * @return {Request}
  940. * @api public
  941. */
  942. request.get = function(url, data, fn){
  943. var req = request('GET', url);
  944. if ('function' == typeof data) fn = data, data = null;
  945. if (data) req.query(data);
  946. if (fn) req.end(fn);
  947. return req;
  948. };
  949. /**
  950. * HEAD `url` with optional callback `fn(res)`.
  951. *
  952. * @param {String} url
  953. * @param {Mixed|Function} data or fn
  954. * @param {Function} fn
  955. * @return {Request}
  956. * @api public
  957. */
  958. request.head = function(url, data, fn){
  959. var req = request('HEAD', url);
  960. if ('function' == typeof data) fn = data, data = null;
  961. if (data) req.send(data);
  962. if (fn) req.end(fn);
  963. return req;
  964. };
  965. /**
  966. * DELETE `url` with optional callback `fn(res)`.
  967. *
  968. * @param {String} url
  969. * @param {Function} fn
  970. * @return {Request}
  971. * @api public
  972. */
  973. function del(url, fn){
  974. var req = request('DELETE', url);
  975. if (fn) req.end(fn);
  976. return req;
  977. };
  978. request.del = del;
  979. request.delete = del;
  980. /**
  981. * PATCH `url` with optional `data` and callback `fn(res)`.
  982. *
  983. * @param {String} url
  984. * @param {Mixed} data
  985. * @param {Function} fn
  986. * @return {Request}
  987. * @api public
  988. */
  989. request.patch = function(url, data, fn){
  990. var req = request('PATCH', url);
  991. if ('function' == typeof data) fn = data, data = null;
  992. if (data) req.send(data);
  993. if (fn) req.end(fn);
  994. return req;
  995. };
  996. /**
  997. * POST `url` with optional `data` and callback `fn(res)`.
  998. *
  999. * @param {String} url
  1000. * @param {Mixed} data
  1001. * @param {Function} fn
  1002. * @return {Request}
  1003. * @api public
  1004. */
  1005. request.post = function(url, data, fn){
  1006. var req = request('POST', url);
  1007. if ('function' == typeof data) fn = data, data = null;
  1008. if (data) req.send(data);
  1009. if (fn) req.end(fn);
  1010. return req;
  1011. };
  1012. /**
  1013. * PUT `url` with optional `data` and callback `fn(res)`.
  1014. *
  1015. * @param {String} url
  1016. * @param {Mixed|Function} data or fn
  1017. * @param {Function} fn
  1018. * @return {Request}
  1019. * @api public
  1020. */
  1021. request.put = function(url, data, fn){
  1022. var req = request('PUT', url);
  1023. if ('function' == typeof data) fn = data, data = null;
  1024. if (data) req.send(data);
  1025. if (fn) req.end(fn);
  1026. return req;
  1027. };
  1028. /**
  1029. * Expose `request`.
  1030. */
  1031. module.exports = request;
  1032. },{"emitter":2,"reduce":3}],2:[function(require,module,exports){
  1033. /**
  1034. * Expose `Emitter`.
  1035. */
  1036. module.exports = Emitter;
  1037. /**
  1038. * Initialize a new `Emitter`.
  1039. *
  1040. * @api public
  1041. */
  1042. function Emitter(obj) {
  1043. if (obj) return mixin(obj);
  1044. };
  1045. /**
  1046. * Mixin the emitter properties.
  1047. *
  1048. * @param {Object} obj
  1049. * @return {Object}
  1050. * @api private
  1051. */
  1052. function mixin(obj) {
  1053. for (var key in Emitter.prototype) {
  1054. obj[key] = Emitter.prototype[key];
  1055. }
  1056. return obj;
  1057. }
  1058. /**
  1059. * Listen on the given `event` with `fn`.
  1060. *
  1061. * @param {String} event
  1062. * @param {Function} fn
  1063. * @return {Emitter}
  1064. * @api public
  1065. */
  1066. Emitter.prototype.on =
  1067. Emitter.prototype.addEventListener = function(event, fn){
  1068. this._callbacks = this._callbacks || {};
  1069. (this._callbacks[event] = this._callbacks[event] || [])
  1070. .push(fn);
  1071. return this;
  1072. };
  1073. /**
  1074. * Adds an `event` listener that will be invoked a single
  1075. * time then automatically removed.
  1076. *
  1077. * @param {String} event
  1078. * @param {Function} fn
  1079. * @return {Emitter}
  1080. * @api public
  1081. */
  1082. Emitter.prototype.once = function(event, fn){
  1083. var self = this;
  1084. this._callbacks = this._callbacks || {};
  1085. function on() {
  1086. self.off(event, on);
  1087. fn.apply(this, arguments);
  1088. }
  1089. on.fn = fn;
  1090. this.on(event, on);
  1091. return this;
  1092. };
  1093. /**
  1094. * Remove the given callback for `event` or all
  1095. * registered callbacks.
  1096. *
  1097. * @param {String} event
  1098. * @param {Function} fn
  1099. * @return {Emitter}
  1100. * @api public
  1101. */
  1102. Emitter.prototype.off =
  1103. Emitter.prototype.removeListener =
  1104. Emitter.prototype.removeAllListeners =
  1105. Emitter.prototype.removeEventListener = function(event, fn){
  1106. this._callbacks = this._callbacks || {};
  1107. // all
  1108. if (0 == arguments.length) {
  1109. this._callbacks = {};
  1110. return this;
  1111. }
  1112. // specific event
  1113. var callbacks = this._callbacks[event];
  1114. if (!callbacks) return this;
  1115. // remove all handlers
  1116. if (1 == arguments.length) {
  1117. delete this._callbacks[event];
  1118. return this;
  1119. }
  1120. // remove specific handler
  1121. var cb;
  1122. for (var i = 0; i < callbacks.length; i++) {
  1123. cb = callbacks[i];
  1124. if (cb === fn || cb.fn === fn) {
  1125. callbacks.splice(i, 1);
  1126. break;
  1127. }
  1128. }
  1129. return this;
  1130. };
  1131. /**
  1132. * Emit `event` with the given args.
  1133. *
  1134. * @param {String} event
  1135. * @param {Mixed} ...
  1136. * @return {Emitter}
  1137. */
  1138. Emitter.prototype.emit = function(event){
  1139. this._callbacks = this._callbacks || {};
  1140. var args = [].slice.call(arguments, 1)
  1141. , callbacks = this._callbacks[event];
  1142. if (callbacks) {
  1143. callbacks = callbacks.slice(0);
  1144. for (var i = 0, len = callbacks.length; i < len; ++i) {
  1145. callbacks[i].apply(this, args);
  1146. }
  1147. }
  1148. return this;
  1149. };
  1150. /**
  1151. * Return array of callbacks for `event`.
  1152. *
  1153. * @param {String} event
  1154. * @return {Array}
  1155. * @api public
  1156. */
  1157. Emitter.prototype.listeners = function(event){
  1158. this._callbacks = this._callbacks || {};
  1159. return this._callbacks[event] || [];
  1160. };
  1161. /**
  1162. * Check if this emitter has `event` handlers.
  1163. *
  1164. * @param {String} event
  1165. * @return {Boolean}
  1166. * @api public
  1167. */
  1168. Emitter.prototype.hasListeners = function(event){
  1169. return !! this.listeners(event).length;
  1170. };
  1171. },{}],3:[function(require,module,exports){
  1172. /**
  1173. * Reduce `arr` with `fn`.
  1174. *
  1175. * @param {Array} arr
  1176. * @param {Function} fn
  1177. * @param {Mixed} initial
  1178. *
  1179. * TODO: combatible error handling?
  1180. */
  1181. module.exports = function(arr, fn, initial){
  1182. var idx = 0;
  1183. var len = arr.length;
  1184. var curr = arguments.length == 3
  1185. ? initial
  1186. : arr[idx++];
  1187. while (idx < len) {
  1188. curr = fn.call(null, curr, arr[idx], ++idx, arr);
  1189. }
  1190. return curr;
  1191. };
  1192. },{}],4:[function(require,module,exports){
  1193. (function (global){
  1194. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.tus = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  1195. "use strict";
  1196. Object.defineProperty(exports, "__esModule", {
  1197. value: true
  1198. });
  1199. exports.default = fingerprint;
  1200. /**
  1201. * Generate a fingerprint for a file which will be used the store the endpoint
  1202. *
  1203. * @param {File} file
  1204. * @return {String}
  1205. */
  1206. function fingerprint(file) {
  1207. return ["tus", file.name, file.type, file.size, file.lastModified].join("-");
  1208. }
  1209. },{}],2:[function(_dereq_,module,exports){
  1210. "use strict";
  1211. var _upload = _dereq_("./upload");
  1212. var _upload2 = _interopRequireDefault(_upload);
  1213. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1214. var defaultOptions = _upload2.default.defaultOptions; /* global window */
  1215. var _window = window;
  1216. var XMLHttpRequest = _window.XMLHttpRequest;
  1217. var localStorage = _window.localStorage;
  1218. var Blob = _window.Blob;
  1219. var isSupported = XMLHttpRequest && localStorage && Blob && typeof Blob.prototype.slice === "function";
  1220. module.exports = {
  1221. Upload: _upload2.default,
  1222. isSupported: isSupported,
  1223. defaultOptions: defaultOptions
  1224. };
  1225. },{"./upload":3}],3:[function(_dereq_,module,exports){
  1226. "use strict";
  1227. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); /* global window, XMLHttpRequest */
  1228. Object.defineProperty(exports, "__esModule", {
  1229. value: true
  1230. });
  1231. var _fingerprint = _dereq_("./fingerprint");
  1232. var _fingerprint2 = _interopRequireDefault(_fingerprint);
  1233. var _extend = _dereq_("extend");
  1234. var _extend2 = _interopRequireDefault(_extend);
  1235. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1236. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1237. var _window = window;
  1238. var localStorage = _window.localStorage;
  1239. var btoa = _window.btoa;
  1240. var defaultOptions = {
  1241. endpoint: "",
  1242. fingerprint: _fingerprint2.default,
  1243. resume: true,
  1244. onProgress: null,
  1245. onChunkComplete: null,
  1246. onSuccess: null,
  1247. onError: null,
  1248. headers: {},
  1249. chunkSize: Infinity,
  1250. withCredentials: false
  1251. };
  1252. var Upload = (function () {
  1253. function Upload(file, options) {
  1254. _classCallCheck(this, Upload);
  1255. this.options = (0, _extend2.default)(true, {}, defaultOptions, options);
  1256. // The underlying File/Blob object
  1257. this.file = file;
  1258. // The URL against which the file will be uploaded
  1259. this.url = null;
  1260. // The underlying XHR object for the current PATCH request
  1261. this._xhr = null;
  1262. // The fingerpinrt for the current file (set after start())
  1263. this._fingerprint = null;
  1264. // The offset used in the current PATCH request
  1265. this._offset = null;
  1266. // True if the current PATCH request has been aborted
  1267. this._aborted = false;
  1268. }
  1269. _createClass(Upload, [{
  1270. key: "start",
  1271. value: function start() {
  1272. var file = this.file;
  1273. if (!file) {
  1274. this._emitError(new Error("tus: no file to upload provided"));
  1275. return;
  1276. }
  1277. if (!this.options.endpoint) {
  1278. this._emitError(new Error("tus: no endpoint provided"));
  1279. return;
  1280. }
  1281. // A URL has manually been specified, so we try to resume
  1282. if (this.url !== null) {
  1283. this._resumeUpload();
  1284. return;
  1285. }
  1286. // Try to find the endpoint for the file in the localStorage
  1287. if (this.options.resume) {
  1288. this._fingerprint = this.options.fingerprint(file);
  1289. var resumedUrl = localStorage.getItem(this._fingerprint);
  1290. if (resumedUrl != null) {
  1291. this.url = resumedUrl;
  1292. this._resumeUpload();
  1293. return;
  1294. }
  1295. }
  1296. // An upload has not started for the file yet, so we start a new one
  1297. this._createUpload();
  1298. }
  1299. }, {
  1300. key: "abort",
  1301. value: function abort() {
  1302. if (this._xhr !== null) {
  1303. this._xhr.abort();
  1304. this._aborted = true;
  1305. }
  1306. }
  1307. }, {
  1308. key: "_emitXhrError",
  1309. value: function _emitXhrError(xhr, err) {
  1310. err.originalRequest = xhr;
  1311. this._emitError(err);
  1312. }
  1313. }, {
  1314. key: "_emitError",
  1315. value: function _emitError(err) {
  1316. if (typeof this.options.onError === "function") {
  1317. this.options.onError(err);
  1318. } else {
  1319. throw err;
  1320. }
  1321. }
  1322. }, {
  1323. key: "_emitSuccess",
  1324. value: function _emitSuccess() {
  1325. if (typeof this.options.onSuccess === "function") {
  1326. this.options.onSuccess();
  1327. }
  1328. }
  1329. /**
  1330. * Publishes notification when data has been sent to the server. This
  1331. * data may not have been accepted by the server yet.
  1332. * @param {number} bytesSent Number of bytes sent to the server.
  1333. * @param {number} bytesTotal Total number of bytes to be sent to the server.
  1334. */
  1335. }, {
  1336. key: "_emitProgress",
  1337. value: function _emitProgress(bytesSent, bytesTotal) {
  1338. if (typeof this.options.onProgress === "function") {
  1339. this.options.onProgress(bytesSent, bytesTotal);
  1340. }
  1341. }
  1342. /**
  1343. * Publishes notification when a chunk of data has been sent to the server
  1344. * and accepted by the server.
  1345. * @param {number} chunkSize Size of the chunk that was accepted by the
  1346. * server.
  1347. * @param {number} bytesAccepted Total number of bytes that have been
  1348. * accepted by the server.
  1349. * @param {number} bytesTotal Total number of bytes to be sent to the server.
  1350. */
  1351. }, {
  1352. key: "_emitChunkComplete",
  1353. value: function _emitChunkComplete(chunkSize, bytesAccepted, bytesTotal) {
  1354. if (typeof this.options.onChunkComplete === "function") {
  1355. this.options.onChunkComplete(chunkSize, bytesAccepted, bytesTotal);
  1356. }
  1357. }
  1358. /**
  1359. * Set the headers used in the request and the withCredentials property
  1360. * as defined in the options
  1361. *
  1362. * @param {XMLHttpRequest} xhr
  1363. */
  1364. }, {
  1365. key: "_setupXHR",
  1366. value: function _setupXHR(xhr) {
  1367. xhr.setRequestHeader("Tus-Resumable", "1.0.0");
  1368. var headers = this.options.headers;
  1369. for (var name in headers) {
  1370. xhr.setRequestHeader(name, headers[name]);
  1371. }
  1372. xhr.withCredentials = this.options.withCredentials;
  1373. }
  1374. /**
  1375. * Create a new upload using the creation extension by sending a POST
  1376. * request to the endpoint. After successful creation the file will be
  1377. * uploaded
  1378. *
  1379. * @api private
  1380. */
  1381. }, {
  1382. key: "_createUpload",
  1383. value: function _createUpload() {
  1384. var _this = this;
  1385. var xhr = new XMLHttpRequest();
  1386. xhr.open("POST", this.options.endpoint, true);
  1387. xhr.onload = function () {
  1388. if (!(xhr.status >= 200 && xhr.status < 300)) {
  1389. _this._emitXhrError(xhr, new Error("tus: unexpected response while creating upload"));
  1390. return;
  1391. }
  1392. _this.url = xhr.getResponseHeader("Location");
  1393. if (_this.options.resume) {
  1394. localStorage.setItem(_this._fingerprint, _this.url);
  1395. }
  1396. _this._offset = 0;
  1397. _this._startUpload();
  1398. };
  1399. xhr.onerror = function () {
  1400. _this._emitXhrError(xhr, new Error("tus: failed to create upload"));
  1401. };
  1402. this._setupXHR(xhr);
  1403. xhr.setRequestHeader("Upload-Length", this.file.size);
  1404. // Add metadata if values have been added
  1405. var metadata = encodeMetadata(this.options.metadata);
  1406. if (metadata !== "") {
  1407. xhr.setRequestHeader("Upload-Metadata", metadata);
  1408. }
  1409. xhr.send(null);
  1410. }
  1411. /*
  1412. * Try to resume an existing upload. First a HEAD request will be sent
  1413. * to retrieve the offset. If the request fails a new upload will be
  1414. * created. In the case of a successful response the file will be uploaded.
  1415. *
  1416. * @api private
  1417. */
  1418. }, {
  1419. key: "_resumeUpload",
  1420. value: function _resumeUpload() {
  1421. var _this2 = this;
  1422. var xhr = new XMLHttpRequest();
  1423. xhr.open("HEAD", this.url, true);
  1424. xhr.onload = function () {
  1425. if (!(xhr.status >= 200 && xhr.status < 300)) {
  1426. if (_this2.options.resume) {
  1427. // Remove stored fingerprint and corresponding endpoint,
  1428. // since the file can not be found
  1429. localStorage.removeItem(_this2._fingerprint);
  1430. }
  1431. // Try to create a new upload
  1432. _this2.url = null;
  1433. _this2._createUpload();
  1434. return;
  1435. }
  1436. var offset = parseInt(xhr.getResponseHeader("Upload-Offset"), 10);
  1437. if (isNaN(offset)) {
  1438. _this2._emitXhrError(xhr, new Error("tus: invalid or missing offset value"));
  1439. return;
  1440. }
  1441. _this2._offset = offset;
  1442. _this2._startUpload();
  1443. };
  1444. xhr.onerror = function () {
  1445. _this2._emitXhrError(xhr, new Error("tus: failed to resume upload"));
  1446. };
  1447. this._setupXHR(xhr);
  1448. xhr.send(null);
  1449. }
  1450. /**
  1451. * Start uploading the file using PATCH requests. The file while be divided
  1452. * into chunks as specified in the chunkSize option. During the upload
  1453. * the onProgress event handler may be invoked multiple times.
  1454. *
  1455. * @api private
  1456. */
  1457. }, {
  1458. key: "_startUpload",
  1459. value: function _startUpload() {
  1460. var _this3 = this;
  1461. var xhr = this._xhr = new XMLHttpRequest();
  1462. xhr.open("PATCH", this.url, true);
  1463. xhr.onload = function () {
  1464. if (!(xhr.status >= 200 && xhr.status < 300)) {
  1465. _this3._emitXhrError(xhr, new Error("tus: unexpected response while creating upload"));
  1466. return;
  1467. }
  1468. var offset = parseInt(xhr.getResponseHeader("Upload-Offset"), 10);
  1469. if (isNaN(offset)) {
  1470. _this3._emitXhrError(xhr, new Error("tus: invalid or missing offset value"));
  1471. return;
  1472. }
  1473. _this3._emitChunkComplete(offset - _this3._offset, offset, _this3.file.size);
  1474. _this3._offset = offset;
  1475. if (offset == _this3.file.size) {
  1476. // Yay, finally done :)
  1477. // Emit a last progress event
  1478. _this3._emitProgress(offset, offset);
  1479. _this3._emitSuccess();
  1480. return;
  1481. }
  1482. _this3._startUpload();
  1483. };
  1484. xhr.onerror = function () {
  1485. // Don't emit an error if the upload was aborted manually
  1486. if (_this3._aborted) {
  1487. return;
  1488. }
  1489. _this3._emitXhrError(xhr, new Error("tus: failed to upload chunk at offset " + _this3._offset));
  1490. };
  1491. // Test support for progress events before attaching an event listener
  1492. if ("upload" in xhr) {
  1493. xhr.upload.onprogress = function (e) {
  1494. if (!e.lengthComputable) {
  1495. return;
  1496. }
  1497. _this3._emitProgress(start + e.loaded, _this3.file.size);
  1498. };
  1499. }
  1500. this._setupXHR(xhr);
  1501. xhr.setRequestHeader("Upload-Offset", this._offset);
  1502. xhr.setRequestHeader("Content-Type", "application/offset+octet-stream");
  1503. var start = this._offset;
  1504. var end = this._offset + this.options.chunkSize;
  1505. if (end === Infinity) {
  1506. end = this.file.size;
  1507. }
  1508. xhr.send(this.file.slice(start, end));
  1509. }
  1510. }]);
  1511. return Upload;
  1512. })();
  1513. function encodeMetadata(metadata) {
  1514. if (!("btoa" in window)) {
  1515. return "";
  1516. }
  1517. var encoded = [];
  1518. for (var key in metadata) {
  1519. encoded.push(key + " " + btoa(unescape(encodeURIComponent(metadata[key]))));
  1520. }
  1521. return encoded.join(",");
  1522. }
  1523. Upload.defaultOptions = defaultOptions;
  1524. exports.default = Upload;
  1525. },{"./fingerprint":1,"extend":4}],4:[function(_dereq_,module,exports){
  1526. 'use strict';
  1527. var hasOwn = Object.prototype.hasOwnProperty;
  1528. var toStr = Object.prototype.toString;
  1529. var isArray = function isArray(arr) {
  1530. if (typeof Array.isArray === 'function') {
  1531. return Array.isArray(arr);
  1532. }
  1533. return toStr.call(arr) === '[object Array]';
  1534. };
  1535. var isPlainObject = function isPlainObject(obj) {
  1536. if (!obj || toStr.call(obj) !== '[object Object]') {
  1537. return false;
  1538. }
  1539. var hasOwnConstructor = hasOwn.call(obj, 'constructor');
  1540. var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
  1541. // Not own constructor property must be Object
  1542. if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
  1543. return false;
  1544. }
  1545. // Own properties are enumerated firstly, so to speed up,
  1546. // if last one is own, then all properties are own.
  1547. var key;
  1548. for (key in obj) {/**/}
  1549. return typeof key === 'undefined' || hasOwn.call(obj, key);
  1550. };
  1551. module.exports = function extend() {
  1552. var options, name, src, copy, copyIsArray, clone,
  1553. target = arguments[0],
  1554. i = 1,
  1555. length = arguments.length,
  1556. deep = false;
  1557. // Handle a deep copy situation
  1558. if (typeof target === 'boolean') {
  1559. deep = target;
  1560. target = arguments[1] || {};
  1561. // skip the boolean and the target
  1562. i = 2;
  1563. } else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) {
  1564. target = {};
  1565. }
  1566. for (; i < length; ++i) {
  1567. options = arguments[i];
  1568. // Only deal with non-null/undefined values
  1569. if (options != null) {
  1570. // Extend the base object
  1571. for (name in options) {
  1572. src = target[name];
  1573. copy = options[name];
  1574. // Prevent never-ending loop
  1575. if (target !== copy) {
  1576. // Recurse if we're merging plain objects or arrays
  1577. if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
  1578. if (copyIsArray) {
  1579. copyIsArray = false;
  1580. clone = src && isArray(src) ? src : [];
  1581. } else {
  1582. clone = src && isPlainObject(src) ? src : {};
  1583. }
  1584. // Never move original objects, clone them
  1585. target[name] = extend(deep, clone, copy);
  1586. // Don't bring in undefined values
  1587. } else if (typeof copy !== 'undefined') {
  1588. target[name] = copy;
  1589. }
  1590. }
  1591. }
  1592. }
  1593. }
  1594. // Return the modified object
  1595. return target;
  1596. };
  1597. },{}]},{},[2])(2)
  1598. });
  1599. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1600. },{}],5:[function(require,module,exports){
  1601. 'use strict';
  1602. Object.defineProperty(exports, '__esModule', {
  1603. value: true
  1604. });
  1605. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  1606. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1607. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  1608. var _coreUtils = require('../core/Utils');
  1609. var _coreUtils2 = _interopRequireDefault(_coreUtils);
  1610. /**
  1611. * Main Uppy core
  1612. *
  1613. */
  1614. var Core = (function () {
  1615. function Core(opts) {
  1616. _classCallCheck(this, Core);
  1617. // Dictates in what order different plugin types are ran:
  1618. this.types = ['presetter', 'acquirer', 'uploader'];
  1619. this.type = 'core';
  1620. // Container for different types of plugins
  1621. this.plugins = {};
  1622. }
  1623. /**
  1624. * Registers a plugin with Core
  1625. *
  1626. * @param {Plugin} Plugin object
  1627. * @param {opts} options object that will be passed to Plugin later
  1628. * @returns {object} self for chaining
  1629. */
  1630. _createClass(Core, [{
  1631. key: 'use',
  1632. value: function use(Plugin, opts) {
  1633. // Instantiate
  1634. var plugin = new Plugin(this, opts);
  1635. this.plugins[plugin.type] = this.plugins[plugin.type] || [];
  1636. this.plugins[plugin.type].push(plugin);
  1637. return this;
  1638. }
  1639. /**
  1640. * Sets plugin’s progress, for uploads for example
  1641. *
  1642. * @param {plugin} plugin that want to set progress
  1643. * @param {percentage} integer
  1644. * @returns {object} self for chaining
  1645. */
  1646. }, {
  1647. key: 'setProgress',
  1648. value: function setProgress(plugin, percentage) {
  1649. // Any plugin can call this via `this.core.setProgress(this, precentage)`
  1650. console.log(plugin.type + ' plugin ' + plugin.name + ' set the progress to ' + percentage);
  1651. return this;
  1652. }
  1653. /**
  1654. * Runs all plugins of the same type in parallel
  1655. */
  1656. }, {
  1657. key: 'runType',
  1658. value: function runType(type, files) {
  1659. var methods = this.plugins[type].map(function (plugin) {
  1660. return plugin.run.call(plugin, files);
  1661. });
  1662. return Promise.all(methods);
  1663. }
  1664. /**
  1665. * Runs a waterfall of runType plugin packs, like so:
  1666. * All preseters(data) --> All acquirers(data) --> All uploaders(data) --> done
  1667. */
  1668. }, {
  1669. key: 'run',
  1670. value: function run() {
  1671. var _this = this;
  1672. console.log({
  1673. 'class': 'Core',
  1674. method: 'run'
  1675. });
  1676. // First we select only plugins of current type,
  1677. // then create an array of runType methods of this plugins
  1678. var typeMethods = this.types.filter(function (type) {
  1679. return _this.plugins[type];
  1680. }).map(function (type) {
  1681. return _this.runType.bind(_this, type);
  1682. });
  1683. _coreUtils2['default'].promiseWaterfall(typeMethods).then(function (result) {
  1684. return console.log(result);
  1685. })['catch'](function (error) {
  1686. return console.error(error);
  1687. });
  1688. }
  1689. }]);
  1690. return Core;
  1691. })();
  1692. exports['default'] = Core;
  1693. module.exports = exports['default'];
  1694. },{"../core/Utils":6}],6:[function(require,module,exports){
  1695. 'use strict';
  1696. Object.defineProperty(exports, '__esModule', {
  1697. value: true
  1698. });
  1699. function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
  1700. function promiseWaterfall(_ref) {
  1701. var _ref2 = _toArray(_ref);
  1702. var resolvedPromise = _ref2[0];
  1703. var tasks = _ref2.slice(1);
  1704. var finalTaskPromise = tasks.reduce(function (prevTaskPromise, task) {
  1705. return prevTaskPromise.then(task);
  1706. }, resolvedPromise(1)); // initial value
  1707. return finalTaskPromise;
  1708. }
  1709. // This is how we roll $('.element').toggleClass in non-jQuery world
  1710. function toggleClass(el, className) {
  1711. if (el.classList) {
  1712. el.classList.toggle(className);
  1713. } else {
  1714. var classes = el.className.split(' ');
  1715. var existingIndex = classes.indexOf(className);
  1716. if (existingIndex >= 0) {
  1717. classes.splice(existingIndex, 1);
  1718. } else {
  1719. classes.push(className);
  1720. el.className = classes.join(' ');
  1721. }
  1722. }
  1723. }
  1724. function addClass(el, className) {
  1725. if (el.classList) {
  1726. el.classList.add(className);
  1727. } else {
  1728. el.className += ' ' + className;
  1729. }
  1730. }
  1731. function removeClass(el, className) {
  1732. if (el.classList) {
  1733. el.classList.remove(className);
  1734. } else {
  1735. el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
  1736. }
  1737. }
  1738. // $form.on('drag dragstart dragend dragover dragenter dragleave drop');
  1739. function addListenerMulti(el, events, func) {
  1740. var eventsArray = events.split(' ');
  1741. for (var _event in eventsArray) {
  1742. el.addEventListener(eventsArray[_event], func, false);
  1743. }
  1744. }
  1745. exports['default'] = {
  1746. promiseWaterfall: promiseWaterfall,
  1747. toggleClass: toggleClass,
  1748. addClass: addClass,
  1749. removeClass: removeClass,
  1750. addListenerMulti: addListenerMulti
  1751. };
  1752. module.exports = exports['default'];
  1753. },{}],7:[function(require,module,exports){
  1754. 'use strict';
  1755. Object.defineProperty(exports, '__esModule', {
  1756. value: true
  1757. });
  1758. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1759. var _Core = require('./Core');
  1760. var _Core2 = _interopRequireDefault(_Core);
  1761. exports['default'] = _Core2['default'];
  1762. module.exports = exports['default'];
  1763. },{"./Core":5}],8:[function(require,module,exports){
  1764. 'use strict';
  1765. Object.defineProperty(exports, '__esModule', {
  1766. value: true
  1767. });
  1768. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1769. var _core = require('./core');
  1770. var _core2 = _interopRequireDefault(_core);
  1771. var _plugins = require('./plugins');
  1772. var _plugins2 = _interopRequireDefault(_plugins);
  1773. exports['default'] = {
  1774. Core: _core2['default'],
  1775. plugins: _plugins2['default']
  1776. };
  1777. module.exports = exports['default'];
  1778. },{"./core":7,"./plugins":16}],9:[function(require,module,exports){
  1779. 'use strict';
  1780. Object.defineProperty(exports, '__esModule', {
  1781. value: true
  1782. });
  1783. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  1784. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  1785. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1786. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  1787. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  1788. var _coreUtils = require('../core/Utils');
  1789. var _coreUtils2 = _interopRequireDefault(_coreUtils);
  1790. var _Plugin2 = require('./Plugin');
  1791. var _Plugin3 = _interopRequireDefault(_Plugin2);
  1792. /**
  1793. * Drag & Drop plugin
  1794. *
  1795. */
  1796. var DragDrop = (function (_Plugin) {
  1797. _inherits(DragDrop, _Plugin);
  1798. function DragDrop(core, opts) {
  1799. _classCallCheck(this, DragDrop);
  1800. _get(Object.getPrototypeOf(DragDrop.prototype), 'constructor', this).call(this, core, opts);
  1801. this.type = 'acquirer';
  1802. // set default options
  1803. var defaultOptions = {
  1804. bla: 'blabla',
  1805. autoSubmit: true,
  1806. modal: true
  1807. };
  1808. // merge default options with the ones set by user
  1809. this.opts = defaultOptions;
  1810. Object.assign(this.opts, opts);
  1811. // get the element where Drag & Drop event will occur
  1812. this.dropzone = document.querySelectorAll(this.opts.selector)[0];
  1813. this.dropzoneInput = document.querySelectorAll('.UppyDragDrop-input')[0];
  1814. this.status = document.querySelectorAll('.UppyDragDrop-status')[0];
  1815. this.isDragDropSupported = this.checkDragDropSupport();
  1816. // crazy stuff so that ‘this’ will behave in class
  1817. this.listenForEvents = this.listenForEvents.bind(this);
  1818. this.handleDrop = this.handleDrop.bind(this);
  1819. this.checkDragDropSupport = this.checkDragDropSupport.bind(this);
  1820. this.handleInputChange = this.handleInputChange.bind(this);
  1821. }
  1822. /**
  1823. * Checks if the browser supports Drag & Drop
  1824. * @returns {object} true if Drag & Drop is supported, false otherwise
  1825. */
  1826. _createClass(DragDrop, [{
  1827. key: 'checkDragDropSupport',
  1828. value: function checkDragDropSupport() {
  1829. var div = document.createElement('div');
  1830. if (!('draggable' in div) || !('ondragstart' in div && 'ondrop' in div)) {
  1831. return false;
  1832. }
  1833. if (!('FormData' in window)) {
  1834. return false;
  1835. }
  1836. if (!('FileReader' in window)) {
  1837. return false;
  1838. }
  1839. return true;
  1840. }
  1841. }, {
  1842. key: 'listenForEvents',
  1843. value: function listenForEvents() {
  1844. var _this = this;
  1845. console.log('waiting for some files to be dropped on ' + this.opts.selector);
  1846. if (this.isDragDropSupported) {
  1847. _coreUtils2['default'].addClass(this.dropzone, 'is-dragdrop-supported');
  1848. }
  1849. // prevent default actions for all drag & drop events
  1850. _coreUtils2['default'].addListenerMulti(this.dropzone, 'drag dragstart dragend dragover dragenter dragleave drop', function (e) {
  1851. e.preventDefault();
  1852. e.stopPropagation();
  1853. });
  1854. // Toggle is-dragover state when files are dragged over or dropped
  1855. _coreUtils2['default'].addListenerMulti(this.dropzone, 'dragover dragenter', function (e) {
  1856. _coreUtils2['default'].addClass(_this.dropzone, 'is-dragover');
  1857. });
  1858. _coreUtils2['default'].addListenerMulti(this.dropzone, 'dragleave dragend drop', function (e) {
  1859. _coreUtils2['default'].removeClass(_this.dropzone, 'is-dragover');
  1860. });
  1861. var onDrop = new Promise(function (resolve, reject) {
  1862. _this.dropzone.addEventListener('drop', function (e) {
  1863. resolve(_this.handleDrop.bind(null, e));
  1864. });
  1865. });
  1866. var onInput = new Promise(function (resolve, reject) {
  1867. _this.dropzoneInput.addEventListener('change', function (e) {
  1868. resolve(_this.handleInputChange.bind(null, e));
  1869. });
  1870. });
  1871. return Promise.race([onDrop, onInput]).then(function (handler) {
  1872. return handler();
  1873. });
  1874. // this.dropzone.addEventListener('drop', this.handleDrop);
  1875. // this.dropzoneInput.addEventListener('change', this.handleInputChange);
  1876. }
  1877. }, {
  1878. key: 'displayStatus',
  1879. value: function displayStatus(status) {
  1880. this.status.innerHTML = status;
  1881. }
  1882. }, {
  1883. key: 'handleDrop',
  1884. value: function handleDrop(e) {
  1885. console.log('all right, someone dropped something here...');
  1886. var files = e.dataTransfer.files;
  1887. // const formData = new FormData(this.dropzone);
  1888. // console.log('pizza', formData);
  1889. // for (var i = 0; i < files.length; i++) {
  1890. // formData.append('file', files[i]);
  1891. // console.log('pizza', files[i]);
  1892. // }
  1893. return Promise.resolve({ from: 'DragDrop', files: files });
  1894. }
  1895. }, {
  1896. key: 'handleInputChange',
  1897. value: function handleInputChange() {
  1898. // const fileInput = document.querySelectorAll('.UppyDragDrop-input')[0];
  1899. var formData = new FormData(this.dropzone);
  1900. console.log('@todo: No support for formData yet', formData);
  1901. var files = [];
  1902. return Promise.resolve(files);
  1903. }
  1904. }, {
  1905. key: 'run',
  1906. value: function run(results) {
  1907. console.log({
  1908. 'class': 'DragDrop',
  1909. method: 'run',
  1910. results: results
  1911. });
  1912. return this.listenForEvents();
  1913. }
  1914. }]);
  1915. return DragDrop;
  1916. })(_Plugin3['default']);
  1917. exports['default'] = DragDrop;
  1918. module.exports = exports['default'];
  1919. },{"../core/Utils":6,"./Plugin":13}],10:[function(require,module,exports){
  1920. 'use strict';
  1921. Object.defineProperty(exports, '__esModule', {
  1922. value: true
  1923. });
  1924. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  1925. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  1926. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1927. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  1928. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  1929. var _coreUtils = require('../core/Utils');
  1930. var _coreUtils2 = _interopRequireDefault(_coreUtils);
  1931. var _Plugin2 = require('./Plugin');
  1932. var _Plugin3 = _interopRequireDefault(_Plugin2);
  1933. var _superagent = require('superagent');
  1934. var _superagent2 = _interopRequireDefault(_superagent);
  1935. var Dropbox = (function (_Plugin) {
  1936. _inherits(Dropbox, _Plugin);
  1937. function Dropbox(core, opts) {
  1938. _classCallCheck(this, Dropbox);
  1939. _get(Object.getPrototypeOf(Dropbox.prototype), 'constructor', this).call(this, core, opts);
  1940. this.type = 'acquirer';
  1941. this.authenticate = this.authenticate.bind(this);
  1942. this.connect = this.connect.bind(this);
  1943. this.render = this.render.bind(this);
  1944. this.files = [];
  1945. this.currentDir = '/';
  1946. this.connect = this.connect.bind(this);
  1947. this.getDirectory();
  1948. }
  1949. _createClass(Dropbox, [{
  1950. key: 'connect',
  1951. value: function connect(target) {
  1952. this.getDirectory();
  1953. // this._target = document.getElementById(target);
  1954. // this.client = new Dropbox.Client({ key: 'b7dzc9ei5dv5hcv', token: '' });
  1955. // this.client.authDriver(new Dropbox.AuthDriver.Redirect());
  1956. // this.authenticate();
  1957. // if (this.client.credentials().token) {
  1958. // this.getDirectory();
  1959. // }
  1960. }
  1961. }, {
  1962. key: 'authenticate',
  1963. value: function authenticate() {
  1964. this.client.authenticate();
  1965. }
  1966. }, {
  1967. key: 'addFile',
  1968. value: function addFile() {}
  1969. }, {
  1970. key: 'getDirectory',
  1971. value: function getDirectory() {
  1972. var opts = {
  1973. dir: 'pizza'
  1974. };
  1975. _superagent2['default'].get('//localhost:3020/dropbox/readdir').query(opts).set('Content-Type', 'application/json').end(function (err, res) {
  1976. console.log(err);
  1977. console.log('yo!');
  1978. console.log(res);
  1979. });
  1980. }
  1981. }, {
  1982. key: 'run',
  1983. value: function run(results) {}
  1984. }, {
  1985. key: 'render',
  1986. value: function render(files) {
  1987. var _this = this;
  1988. // for each file in the directory, create a list item element
  1989. var elems = files.map(function (file, i) {
  1990. var icon = file.isFolder ? 'folder' : 'file';
  1991. return '<li data-type="' + icon + '" data-name="' + file.name + '"><span>' + icon + ' : </span><span> ' + file.name + '</span></li>';
  1992. });
  1993. // appends the list items to the target
  1994. this._target.innerHTML = elems.sort().join('');
  1995. if (this.currentDir.length > 1) {
  1996. var _parent = document.createElement('LI');
  1997. _parent.setAttribute('data-type', 'parent');
  1998. _parent.innerHTML = '<span>...</span>';
  1999. this._target.appendChild(_parent);
  2000. }
  2001. // add an onClick to each list item
  2002. var fileElems = this._target.querySelectorAll('li');
  2003. Array.prototype.forEach.call(fileElems, function (element) {
  2004. var type = element.getAttribute('data-type');
  2005. if (type === 'file') {
  2006. element.addEventListener('click', function () {
  2007. _this.files.push(element.getAttribute('data-name'));
  2008. console.log('files: ' + _this.files);
  2009. });
  2010. } else {
  2011. element.addEventListener('dblclick', function () {
  2012. var length = _this.currentDir.split('/').length;
  2013. if (type === 'folder') {
  2014. _this.currentDir = '' + _this.currentDir + element.getAttribute('data-name') + '/';
  2015. } else if (type === 'parent') {
  2016. _this.currentDir = _this.currentDir.split('/').slice(0, length - 2).join('/') + '/';
  2017. }
  2018. console.log(_this.currentDir);
  2019. _this.getDirectory();
  2020. });
  2021. }
  2022. });
  2023. }
  2024. }]);
  2025. return Dropbox;
  2026. })(_Plugin3['default']);
  2027. exports['default'] = Dropbox;
  2028. module.exports = exports['default'];
  2029. },{"../core/Utils":6,"./Plugin":13,"superagent":1}],11:[function(require,module,exports){
  2030. 'use strict';
  2031. Object.defineProperty(exports, '__esModule', {
  2032. value: true
  2033. });
  2034. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  2035. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  2036. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2037. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  2038. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  2039. var _Plugin2 = require('./Plugin');
  2040. var _Plugin3 = _interopRequireDefault(_Plugin2);
  2041. var Formtag = (function (_Plugin) {
  2042. _inherits(Formtag, _Plugin);
  2043. function Formtag(core, opts) {
  2044. _classCallCheck(this, Formtag);
  2045. _get(Object.getPrototypeOf(Formtag.prototype), 'constructor', this).call(this, core, opts);
  2046. this.type = 'acquirer';
  2047. }
  2048. _createClass(Formtag, [{
  2049. key: 'run',
  2050. value: function run(results) {
  2051. console.log({
  2052. 'class': 'Formtag',
  2053. method: 'run',
  2054. results: results
  2055. });
  2056. this.setProgress(0);
  2057. var button = document.querySelector(this.opts.doneButtonSelector);
  2058. var self = this;
  2059. return new Promise(function (resolve, reject) {
  2060. button.addEventListener('click', function (e) {
  2061. var fields = document.querySelectorAll(self.opts.selector);
  2062. var files = [];
  2063. var selected = [];
  2064. [].forEach.call(fields, function (field, i) {
  2065. [].forEach.call(field.files, function (file, j) {
  2066. selected.push({
  2067. from: 'Formtag',
  2068. file: file
  2069. });
  2070. });
  2071. });
  2072. // console.log(fields.length);
  2073. // for (var i in fields) {
  2074. // console.log('i');
  2075. // // console.log('i: ', i);
  2076. // for (var j in fields[i].files) {
  2077. // console.log('j');
  2078. // // console.log('i, j', i, j);
  2079. // console.log(fields[i].files);
  2080. // var file = fields[i].files.item(j);
  2081. // if (file) {
  2082. // selected.push({
  2083. // from: 'Formtag',
  2084. // file: fields[i].files.item(j)
  2085. // });
  2086. // }
  2087. // }
  2088. // }
  2089. self.setProgress(100);
  2090. console.log({
  2091. selected: selected,
  2092. fields: fields
  2093. });
  2094. resolve(selected);
  2095. });
  2096. });
  2097. }
  2098. }]);
  2099. return Formtag;
  2100. })(_Plugin3['default']);
  2101. exports['default'] = Formtag;
  2102. module.exports = exports['default'];
  2103. },{"./Plugin":13}],12:[function(require,module,exports){
  2104. 'use strict';
  2105. Object.defineProperty(exports, '__esModule', {
  2106. value: true
  2107. });
  2108. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  2109. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  2110. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2111. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  2112. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  2113. var _Plugin2 = require('./Plugin');
  2114. var _Plugin3 = _interopRequireDefault(_Plugin2);
  2115. var Multipart = (function (_Plugin) {
  2116. _inherits(Multipart, _Plugin);
  2117. function Multipart(core, opts) {
  2118. _classCallCheck(this, Multipart);
  2119. _get(Object.getPrototypeOf(Multipart.prototype), 'constructor', this).call(this, core, opts);
  2120. this.type = 'uploader';
  2121. if (!this.opts.fieldName === undefined) {
  2122. this.opts.fieldName = 'files[]';
  2123. }
  2124. if (this.opts.bundle === undefined) {
  2125. this.opts.bundle = true;
  2126. }
  2127. }
  2128. _createClass(Multipart, [{
  2129. key: 'run',
  2130. value: function run(results) {
  2131. console.log({
  2132. 'class': 'Multipart',
  2133. method: 'run',
  2134. results: results
  2135. });
  2136. var files = this.extractFiles(results);
  2137. this.setProgress(0);
  2138. var uploaders = [];
  2139. if (this.opts.bundle) {
  2140. uploaders.push(this.upload(files, 0, files.length));
  2141. } else {
  2142. for (var i in files) {
  2143. uploaders.push(this.upload(files, i, files.length));
  2144. }
  2145. }
  2146. return Promise.all(uploaders);
  2147. }
  2148. }, {
  2149. key: 'upload',
  2150. value: function upload(files, current, total) {
  2151. var _this = this;
  2152. var formPost = new FormData();
  2153. // turn file into an array so we can use bundle
  2154. if (!this.opts.bundle) {
  2155. files = [files[current]];
  2156. }
  2157. for (var i in files) {
  2158. formPost.append(this.opts.fieldName, files[i]);
  2159. }
  2160. var xhr = new XMLHttpRequest();
  2161. xhr.open('POST', this.opts.endpoint, true);
  2162. xhr.addEventListener('progress', function (e) {
  2163. var percentage = (e.loaded / e.total * 100).toFixed(2);
  2164. _this.setProgress(percentage, current, total);
  2165. });
  2166. xhr.addEventListener('load', function () {
  2167. var upload = {};
  2168. if (_this.opts.bundle) {
  2169. upload = { files: files };
  2170. } else {
  2171. upload = { file: files[current] };
  2172. }
  2173. return Promise.resolve(upload);
  2174. });
  2175. xhr.addEventListener('error', function () {
  2176. return Promise.reject('fucking error!');
  2177. });
  2178. xhr.send(formPost);
  2179. }
  2180. }]);
  2181. return Multipart;
  2182. })(_Plugin3['default']);
  2183. exports['default'] = Multipart;
  2184. module.exports = exports['default'];
  2185. },{"./Plugin":13}],13:[function(require,module,exports){
  2186. 'use strict';
  2187. Object.defineProperty(exports, '__esModule', {
  2188. value: true
  2189. });
  2190. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  2191. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  2192. var Plugin = (function () {
  2193. // This contains boilerplate that all Plugins share - and should not be used
  2194. // directly. It also shows which methods final plugins should implement/override,
  2195. // this deciding on structure.
  2196. function Plugin(core, opts) {
  2197. _classCallCheck(this, Plugin);
  2198. this.core = core;
  2199. this.opts = opts;
  2200. this.type = 'none';
  2201. this.name = this.constructor.name;
  2202. }
  2203. _createClass(Plugin, [{
  2204. key: 'setProgress',
  2205. value: function setProgress(percentage, current, total) {
  2206. var finalPercentage = percentage;
  2207. if (current !== undefined && total !== undefined) {
  2208. var percentageOfTotal = percentage / total;
  2209. finalPercentage = percentageOfTotal;
  2210. if (current > 0) {
  2211. finalPercentage = percentage + 100 / total * current;
  2212. } else {
  2213. finalPercentage = current * percentage;
  2214. }
  2215. }
  2216. this.core.setProgress(this, finalPercentage);
  2217. }
  2218. }, {
  2219. key: 'extractFiles',
  2220. value: function extractFiles(results) {
  2221. console.log({
  2222. 'class': 'Plugin',
  2223. method: 'extractFiles',
  2224. results: results
  2225. });
  2226. var files = [];
  2227. for (var i in results) {
  2228. for (var j in results[i].files) {
  2229. files.push(results[i].files.item(j));
  2230. }
  2231. }
  2232. return files;
  2233. }
  2234. }, {
  2235. key: 'run',
  2236. value: function run(results) {
  2237. return results;
  2238. }
  2239. }]);
  2240. return Plugin;
  2241. })();
  2242. exports['default'] = Plugin;
  2243. module.exports = exports['default'];
  2244. },{}],14:[function(require,module,exports){
  2245. 'use strict';
  2246. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  2247. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2248. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  2249. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  2250. var _Plugin2 = require('./Plugin');
  2251. var _Plugin3 = _interopRequireDefault(_Plugin2);
  2252. var TransloaditBasic = (function (_Plugin) {
  2253. _inherits(TransloaditBasic, _Plugin);
  2254. function TransloaditBasic(core, opts) {
  2255. _classCallCheck(this, TransloaditBasic);
  2256. _get(Object.getPrototypeOf(TransloaditBasic.prototype), 'constructor', this).call(this, core, opts);
  2257. this.type = 'presetter';
  2258. this.core.use(DragDrop, { modal: true, wait: true }).use(Tus10, { endpoint: 'http://master.tus.io:8080' });
  2259. }
  2260. return TransloaditBasic;
  2261. })(_Plugin3['default']);
  2262. },{"./Plugin":13}],15:[function(require,module,exports){
  2263. 'use strict';
  2264. Object.defineProperty(exports, '__esModule', {
  2265. value: true
  2266. });
  2267. var _createClass = (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, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  2268. var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
  2269. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2270. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  2271. function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  2272. var _Plugin2 = require('./Plugin');
  2273. var _Plugin3 = _interopRequireDefault(_Plugin2);
  2274. var _tusJsClient = require('tus-js-client');
  2275. var _tusJsClient2 = _interopRequireDefault(_tusJsClient);
  2276. var Tus10 = (function (_Plugin) {
  2277. _inherits(Tus10, _Plugin);
  2278. function Tus10(core, opts) {
  2279. _classCallCheck(this, Tus10);
  2280. _get(Object.getPrototypeOf(Tus10.prototype), 'constructor', this).call(this, core, opts);
  2281. this.type = 'uploader';
  2282. }
  2283. _createClass(Tus10, [{
  2284. key: 'run',
  2285. value: function run(results) {
  2286. console.log({
  2287. 'class': 'Tus10',
  2288. method: 'run',
  2289. results: results
  2290. });
  2291. var files = this.extractFiles(results);
  2292. this.setProgress(0);
  2293. var uploaded = [];
  2294. var uploaders = [];
  2295. for (var i in files) {
  2296. var file = files[i];
  2297. uploaders.push(this.upload(file, i, files.length));
  2298. }
  2299. return Promise.all(uploaders);
  2300. }
  2301. }, {
  2302. key: 'upload',
  2303. value: function upload(file, current, total) {
  2304. // Create a new tus upload
  2305. var self = this;
  2306. var upload = new _tusJsClient2['default'].Upload(file, {
  2307. endpoint: this.opts.endpoint,
  2308. onError: function onError(error) {
  2309. return Promise.reject('Failed because: ' + error);
  2310. },
  2311. onProgress: function onProgress(bytesUploaded, bytesTotal) {
  2312. var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
  2313. self.setProgress(percentage, current, total);
  2314. },
  2315. onSuccess: function onSuccess() {
  2316. console.log('Download ' + upload.file.name + ' from ' + upload.url);
  2317. return Promise.resolve(upload);
  2318. }
  2319. });
  2320. // Start the upload
  2321. upload.start();
  2322. }
  2323. }]);
  2324. return Tus10;
  2325. })(_Plugin3['default']);
  2326. exports['default'] = Tus10;
  2327. module.exports = exports['default'];
  2328. },{"./Plugin":13,"tus-js-client":4}],16:[function(require,module,exports){
  2329. // Parent
  2330. 'use strict';
  2331. Object.defineProperty(exports, '__esModule', {
  2332. value: true
  2333. });
  2334. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2335. var _Plugin = require('./Plugin');
  2336. var _Plugin2 = _interopRequireDefault(_Plugin);
  2337. // Acquirers
  2338. var _DragDrop = require('./DragDrop');
  2339. var _DragDrop2 = _interopRequireDefault(_DragDrop);
  2340. var _Dropbox = require('./Dropbox');
  2341. var _Dropbox2 = _interopRequireDefault(_Dropbox);
  2342. var _Formtag = require('./Formtag');
  2343. var _Formtag2 = _interopRequireDefault(_Formtag);
  2344. // Uploaders
  2345. var _Tus10 = require('./Tus10');
  2346. var _Tus102 = _interopRequireDefault(_Tus10);
  2347. var _Multipart = require('./Multipart');
  2348. var _Multipart2 = _interopRequireDefault(_Multipart);
  2349. // Presetters
  2350. var _TransloaditBasic = require('./TransloaditBasic');
  2351. var _TransloaditBasic2 = _interopRequireDefault(_TransloaditBasic);
  2352. exports['default'] = {
  2353. Plugin: _Plugin2['default'],
  2354. DragDrop: _DragDrop2['default'],
  2355. Dropbox: _Dropbox2['default'],
  2356. Formtag: _Formtag2['default'],
  2357. Tus10: _Tus102['default'],
  2358. Multipart: _Multipart2['default'],
  2359. TransloaditBasic: _TransloaditBasic2['default']
  2360. };
  2361. module.exports = exports['default'];
  2362. },{"./DragDrop":9,"./Dropbox":10,"./Formtag":11,"./Multipart":12,"./Plugin":13,"./TransloaditBasic":14,"./Tus10":15}]},{},[8])(8)
  2363. });