cos-js-sdk-v5

tencent-cos-js-sdk-v5

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/398294/782530/cos-js-sdk-v5.js

  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["COS"] = factory();
  8. else
  9. root["COS"] = factory();
  10. })(typeof self !== 'undefined' ? self : this, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, {
  50. /******/ configurable: false,
  51. /******/ enumerable: true,
  52. /******/ get: getter
  53. /******/ });
  54. /******/ }
  55. /******/ };
  56. /******/
  57. /******/ // getDefaultExport function for compatibility with non-harmony modules
  58. /******/ __webpack_require__.n = function(module) {
  59. /******/ var getter = module && module.__esModule ?
  60. /******/ function getDefault() { return module['default']; } :
  61. /******/ function getModuleExports() { return module; };
  62. /******/ __webpack_require__.d(getter, 'a', getter);
  63. /******/ return getter;
  64. /******/ };
  65. /******/
  66. /******/ // Object.prototype.hasOwnProperty.call
  67. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  68. /******/
  69. /******/ // __webpack_public_path__
  70. /******/ __webpack_require__.p = "/dist/";
  71. /******/
  72. /******/ // Load entry module and return exports
  73. /******/ return __webpack_require__(__webpack_require__.s = 3);
  74. /******/ })
  75. /************************************************************************/
  76. /******/ ([
  77. /* 0 */
  78. /***/ (function(module, exports, __webpack_require__) {
  79.  
  80. "use strict";
  81.  
  82.  
  83. var md5 = __webpack_require__(5);
  84. var CryptoJS = __webpack_require__(6);
  85. var xml2json = __webpack_require__(7);
  86. var json2xml = __webpack_require__(10);
  87.  
  88. function camSafeUrlEncode(str) {
  89. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
  90. }
  91.  
  92. //测试用的key后面可以去掉
  93. var getAuth = function (opt) {
  94. opt = opt || {};
  95.  
  96. var SecretId = opt.SecretId;
  97. var SecretKey = opt.SecretKey;
  98. var method = (opt.method || opt.Method || 'get').toLowerCase();
  99. var queryParams = clone(opt.Query || opt.params || {});
  100. var headers = clone(opt.Headers || opt.headers || {});
  101.  
  102. var Key = opt.Key || '';
  103. var pathname;
  104. if (opt.UseRawKey) {
  105. pathname = opt.Pathname || opt.pathname || '/' + Key;
  106. } else {
  107. pathname = opt.Pathname || opt.pathname || Key;
  108. pathname.indexOf('/') !== 0 && (pathname = '/' + pathname);
  109. }
  110.  
  111. if (!SecretId) return console.error('missing param SecretId');
  112. if (!SecretKey) return console.error('missing param SecretKey');
  113.  
  114. var getObjectKeys = function (obj) {
  115. var list = [];
  116. for (var key in obj) {
  117. if (obj.hasOwnProperty(key)) {
  118. list.push(key);
  119. }
  120. }
  121. return list.sort(function (a, b) {
  122. a = a.toLowerCase();
  123. b = b.toLowerCase();
  124. return a === b ? 0 : a > b ? 1 : -1;
  125. });
  126. };
  127.  
  128. var obj2str = function (obj) {
  129. var i, key, val;
  130. var list = [];
  131. var keyList = getObjectKeys(obj);
  132. for (i = 0; i < keyList.length; i++) {
  133. key = keyList[i];
  134. val = obj[key] === undefined || obj[key] === null ? '' : '' + obj[key];
  135. key = key.toLowerCase();
  136. key = camSafeUrlEncode(key);
  137. val = camSafeUrlEncode(val) || '';
  138. list.push(key + '=' + val);
  139. }
  140. return list.join('&');
  141. };
  142.  
  143. // 签名有效起止时间
  144. var now = Math.round(getSkewTime(opt.SystemClockOffset) / 1000) - 1;
  145. var exp = now;
  146.  
  147. var Expires = opt.Expires || opt.expires;
  148. if (Expires === undefined) {
  149. exp += 900; // 签名过期时间为当前 + 900s
  150. } else {
  151. exp += Expires * 1 || 0;
  152. }
  153.  
  154. // 要用到的 Authorization 参数列表
  155. var qSignAlgorithm = 'sha1';
  156. var qAk = SecretId;
  157. var qSignTime = now + ';' + exp;
  158. var qKeyTime = now + ';' + exp;
  159. var qHeaderList = getObjectKeys(headers).join(';').toLowerCase();
  160. var qUrlParamList = getObjectKeys(queryParams).join(';').toLowerCase();
  161.  
  162. // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
  163. // 步骤一:计算 SignKey
  164. var signKey = CryptoJS.HmacSHA1(qKeyTime, SecretKey).toString();
  165.  
  166. // 步骤二:构成 FormatString
  167. var formatString = [method, pathname, obj2str(queryParams), obj2str(headers), ''].join('\n');
  168.  
  169. // 步骤三:计算 StringToSign
  170. var stringToSign = ['sha1', qSignTime, CryptoJS.SHA1(formatString).toString(), ''].join('\n');
  171.  
  172. // 步骤四:计算 Signature
  173. var qSignature = CryptoJS.HmacSHA1(stringToSign, signKey).toString();
  174.  
  175. // 步骤五:构造 Authorization
  176. var authorization = ['q-sign-algorithm=' + qSignAlgorithm, 'q-ak=' + qAk, 'q-sign-time=' + qSignTime, 'q-key-time=' + qKeyTime, 'q-header-list=' + qHeaderList, 'q-url-param-list=' + qUrlParamList, 'q-signature=' + qSignature].join('&');
  177.  
  178. return authorization;
  179. };
  180.  
  181. var noop = function () {};
  182.  
  183. // 清除对象里值为的 undefined 或 null 的属性
  184. var clearKey = function (obj) {
  185. var retObj = {};
  186. for (var key in obj) {
  187. if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
  188. retObj[key] = obj[key];
  189. }
  190. }
  191. return retObj;
  192. };
  193.  
  194. var readAsBinaryString = function (blob, callback) {
  195. var readFun;
  196. var fr = new FileReader();
  197. if (FileReader.prototype.readAsBinaryString) {
  198. readFun = FileReader.prototype.readAsBinaryString;
  199. fr.onload = function () {
  200. callback(this.result);
  201. };
  202. } else if (FileReader.prototype.readAsArrayBuffer) {
  203. // 在 ie11 添加 readAsBinaryString 兼容
  204. readFun = function (fileData) {
  205. var binary = "";
  206. var pt = this;
  207. var reader = new FileReader();
  208. reader.onload = function (e) {
  209. var bytes = new Uint8Array(reader.result);
  210. var length = bytes.byteLength;
  211. for (var i = 0; i < length; i++) {
  212. binary += String.fromCharCode(bytes[i]);
  213. }
  214. callback(binary);
  215. };
  216. reader.readAsArrayBuffer(fileData);
  217. };
  218. } else {
  219. console.error('FileReader not support readAsBinaryString');
  220. }
  221. readFun.call(fr, blob);
  222. };
  223.  
  224. // 获取文件 md5 值
  225. var md5ChunkSize = 1024 * 1024;
  226. var getFileMd5 = function (blob, callback, onProgress) {
  227. var size = blob.size;
  228. var loaded = 0;
  229. var md5ctx = md5.getCtx();
  230. var next = function (start) {
  231. if (start >= size) {
  232. var hash = md5ctx.digest('hex');
  233. callback(null, hash);
  234. return;
  235. }
  236. var end = Math.min(size, start + md5ChunkSize);
  237. util.fileSlice(blob, start, end, false, function (chunk) {
  238. readAsBinaryString(chunk, function (content) {
  239. chunk = null;
  240. md5ctx = md5ctx.update(content, true);
  241. loaded += content.length;
  242. content = null;
  243. if (onProgress) onProgress({ loaded: loaded, total: size, percent: Math.round(loaded / size * 10000) / 10000 });
  244. next(start + md5ChunkSize);
  245. });
  246. });
  247. };
  248. next(0);
  249. };
  250.  
  251. function clone(obj) {
  252. return map(obj, function (v) {
  253. return typeof v === 'object' ? clone(v) : v;
  254. });
  255. }
  256.  
  257. function extend(target, source) {
  258. each(source, function (val, key) {
  259. target[key] = source[key];
  260. });
  261. return target;
  262. }
  263.  
  264. function isArray(arr) {
  265. return arr instanceof Array;
  266. }
  267.  
  268. function isInArray(arr, item) {
  269. var flag = false;
  270. for (var i = 0; i < arr.length; i++) {
  271. if (item === arr[i]) {
  272. flag = true;
  273. break;
  274. }
  275. }
  276. return flag;
  277. }
  278.  
  279. function each(obj, fn) {
  280. for (var i in obj) {
  281. if (obj.hasOwnProperty(i)) {
  282. fn(obj[i], i);
  283. }
  284. }
  285. }
  286.  
  287. function map(obj, fn) {
  288. var o = isArray(obj) ? [] : {};
  289. for (var i in obj) {
  290. if (obj.hasOwnProperty(i)) {
  291. o[i] = fn(obj[i], i);
  292. }
  293. }
  294. return o;
  295. }
  296.  
  297. function filter(obj, fn) {
  298. var iaArr = isArray(obj);
  299. var o = iaArr ? [] : {};
  300. for (var i in obj) {
  301. if (obj.hasOwnProperty(i)) {
  302. if (fn(obj[i], i)) {
  303. if (iaArr) {
  304. o.push(obj[i]);
  305. } else {
  306. o[i] = obj[i];
  307. }
  308. }
  309. }
  310. }
  311. return o;
  312. }
  313.  
  314. var binaryBase64 = function (str) {
  315. var i,
  316. len,
  317. char,
  318. res = '';
  319. for (i = 0, len = str.length / 2; i < len; i++) {
  320. char = parseInt(str[i * 2] + str[i * 2 + 1], 16);
  321. res += String.fromCharCode(char);
  322. }
  323. return btoa(res);
  324. };
  325. var uuid = function () {
  326. var S4 = function () {
  327. return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
  328. };
  329. return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4();
  330. };
  331.  
  332. var hasMissingParams = function (apiName, params) {
  333. var Bucket = params.Bucket;
  334. var Region = params.Region;
  335. var Key = params.Key;
  336. if (apiName.indexOf('Bucket') > -1 || apiName === 'deleteMultipleObject' || apiName === 'multipartList' || apiName === 'listObjectVersions') {
  337. if (!Bucket) return 'Bucket';
  338. if (!Region) return 'Region';
  339. } else if (apiName.indexOf('Object') > -1 || apiName.indexOf('multipart') > -1 || apiName === 'sliceUploadFile' || apiName === 'abortUploadTask') {
  340. if (!Bucket) return 'Bucket';
  341. if (!Region) return 'Region';
  342. if (!Key) return 'Key';
  343. }
  344. return false;
  345. };
  346.  
  347. var formatParams = function (apiName, params) {
  348.  
  349. // 复制参数对象
  350. params = extend({}, params);
  351.  
  352. // 统一处理 Headers
  353. if (apiName !== 'getAuth' && apiName !== 'getV4Auth' && apiName !== 'getObjectUrl') {
  354. var Headers = params.Headers || {};
  355. if (params && typeof params === 'object') {
  356. (function () {
  357. for (var key in params) {
  358. if (params.hasOwnProperty(key) && key.indexOf('x-cos-') > -1) {
  359. Headers[key] = params[key];
  360. }
  361. }
  362. })();
  363.  
  364. var headerMap = {
  365. // params headers
  366. 'x-cos-mfa': 'MFA',
  367. 'Content-MD5': 'ContentMD5',
  368. 'Content-Length': 'ContentLength',
  369. 'Content-Type': 'ContentType',
  370. 'Expect': 'Expect',
  371. 'Expires': 'Expires',
  372. 'Cache-Control': 'CacheControl',
  373. 'Content-Disposition': 'ContentDisposition',
  374. 'Content-Encoding': 'ContentEncoding',
  375. 'Range': 'Range',
  376. 'If-Modified-Since': 'IfModifiedSince',
  377. 'If-Unmodified-Since': 'IfUnmodifiedSince',
  378. 'If-Match': 'IfMatch',
  379. 'If-None-Match': 'IfNoneMatch',
  380. 'x-cos-copy-source': 'CopySource',
  381. 'x-cos-copy-source-Range': 'CopySourceRange',
  382. 'x-cos-metadata-directive': 'MetadataDirective',
  383. 'x-cos-copy-source-If-Modified-Since': 'CopySourceIfModifiedSince',
  384. 'x-cos-copy-source-If-Unmodified-Since': 'CopySourceIfUnmodifiedSince',
  385. 'x-cos-copy-source-If-Match': 'CopySourceIfMatch',
  386. 'x-cos-copy-source-If-None-Match': 'CopySourceIfNoneMatch',
  387. 'x-cos-acl': 'ACL',
  388. 'x-cos-grant-read': 'GrantRead',
  389. 'x-cos-grant-write': 'GrantWrite',
  390. 'x-cos-grant-full-control': 'GrantFullControl',
  391. 'x-cos-grant-read-acp': 'GrantReadAcp',
  392. 'x-cos-grant-write-acp': 'GrantWriteAcp',
  393. 'x-cos-storage-class': 'StorageClass',
  394. // SSE-C
  395. 'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm',
  396. 'x-cos-server-side-encryption-customer-key': 'SSECustomerKey',
  397. 'x-cos-server-side-encryption-customer-key-MD5': 'SSECustomerKeyMD5',
  398. // SSE-COS、SSE-KMS
  399. 'x-cos-server-side-encryption': 'ServerSideEncryption',
  400. 'x-cos-server-side-encryption-cos-kms-key-id': 'SSEKMSKeyId',
  401. 'x-cos-server-side-encryption-context': 'SSEContext'
  402. };
  403. util.each(headerMap, function (paramKey, headerKey) {
  404. if (params[paramKey] !== undefined) {
  405. Headers[headerKey] = params[paramKey];
  406. }
  407. });
  408.  
  409. params.Headers = clearKey(Headers);
  410. }
  411. }
  412.  
  413. return params;
  414. };
  415.  
  416. var apiWrapper = function (apiName, apiFn) {
  417. return function (params, callback) {
  418.  
  419. // 处理参数
  420. if (typeof params === 'function') {
  421. callback = params;
  422. params = {};
  423. }
  424.  
  425. // 整理参数格式
  426. params = formatParams(apiName, params);
  427.  
  428. // 代理回调函数
  429. var formatResult = function (result) {
  430. if (result && result.headers) {
  431. result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']);
  432. result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']);
  433. }
  434. return result;
  435. };
  436. var _callback = function (err, data) {
  437. callback && callback(formatResult(err), formatResult(data));
  438. };
  439.  
  440. if (apiName !== 'getService' && apiName !== 'abortUploadTask') {
  441. // 判断参数是否完整
  442. var missingResult;
  443. if (missingResult = hasMissingParams(apiName, params)) {
  444. _callback({ error: 'missing param ' + missingResult });
  445. return;
  446. }
  447. // 判断 region 格式
  448. if (params.Region) {
  449. if (params.Region.indexOf('cos.') > -1) {
  450. _callback({ error: 'param Region should not be start with "cos."' });
  451. return;
  452. } else if (!/^([a-z\d-]+)$/.test(params.Region)) {
  453. _callback({ error: 'Region format error.' });
  454. return;
  455. }
  456. // 判断 region 格式
  457. if (!this.options.CompatibilityMode && params.Region.indexOf('-') === -1 && params.Region !== 'yfb' && params.Region !== 'default') {
  458. console.warn('warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224');
  459. }
  460. }
  461. // 兼容不带 AppId 的 Bucket
  462. if (params.Bucket) {
  463. if (!/^([a-z\d-]+)-(\d+)$/.test(params.Bucket)) {
  464. if (params.AppId) {
  465. params.Bucket = params.Bucket + '-' + params.AppId;
  466. } else if (this.options.AppId) {
  467. params.Bucket = params.Bucket + '-' + this.options.AppId;
  468. } else {
  469. _callback({ error: 'Bucket should format as "test-1250000000".' });
  470. return;
  471. }
  472. }
  473. if (params.AppId) {
  474. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).');
  475. delete params.AppId;
  476. }
  477. }
  478. // 如果 Key 是 / 开头,强制去掉第一个 /
  479. if (!this.options.UseRawKey && params.Key && params.Key.substr(0, 1) === '/') {
  480. params.Key = params.Key.substr(1);
  481. }
  482. }
  483. var res = apiFn.call(this, params, _callback);
  484. if (apiName === 'getAuth' || apiName === 'getObjectUrl') {
  485. return res;
  486. }
  487. };
  488. };
  489.  
  490. var throttleOnProgress = function (total, onProgress) {
  491. var self = this;
  492. var size0 = 0;
  493. var size1 = 0;
  494. var time0 = Date.now();
  495. var time1;
  496. var timer;
  497.  
  498. function update() {
  499. timer = 0;
  500. if (onProgress && typeof onProgress === 'function') {
  501. time1 = Date.now();
  502. var speed = Math.max(0, Math.round((size1 - size0) / ((time1 - time0) / 1000) * 100) / 100);
  503. var percent;
  504. if (size1 === 0 && total === 0) {
  505. percent = 1;
  506. } else {
  507. percent = Math.round(size1 / total * 100) / 100 || 0;
  508. }
  509. time0 = time1;
  510. size0 = size1;
  511. try {
  512. onProgress({ loaded: size1, total: total, speed: speed, percent: percent });
  513. } catch (e) {}
  514. }
  515. }
  516.  
  517. return function (info, immediately) {
  518. if (info) {
  519. size1 = info.loaded;
  520. total = info.total;
  521. }
  522. if (immediately) {
  523. clearTimeout(timer);
  524. update();
  525. } else {
  526. if (timer) return;
  527. timer = setTimeout(update, self.options.ProgressInterval);
  528. }
  529. };
  530. };
  531.  
  532. var getFileSize = function (api, params, callback) {
  533. var size;
  534. if (typeof params.Body === 'string') {
  535. params.Body = new Blob([params.Body], { type: 'text/plain' });
  536. }
  537. if (params.Body && (params.Body instanceof Blob || params.Body.toString() === '[object File]' || params.Body.toString() === '[object Blob]')) {
  538. size = params.Body.size;
  539. } else {
  540. callback({ error: 'params body format error, Only allow File|Blob|String.' });
  541. return;
  542. }
  543. params.ContentLength = size;
  544. callback(null, size);
  545. };
  546.  
  547. var getSkewTime = function (offset) {
  548. return Date.now() + (offset || 0);
  549. };
  550.  
  551. var util = {
  552. noop: noop,
  553. formatParams: formatParams,
  554. apiWrapper: apiWrapper,
  555. xml2json: xml2json,
  556. json2xml: json2xml,
  557. md5: md5,
  558. clearKey: clearKey,
  559. getFileMd5: getFileMd5,
  560. binaryBase64: binaryBase64,
  561. extend: extend,
  562. isArray: isArray,
  563. isInArray: isInArray,
  564. each: each,
  565. map: map,
  566. filter: filter,
  567. clone: clone,
  568. uuid: uuid,
  569. camSafeUrlEncode: camSafeUrlEncode,
  570. throttleOnProgress: throttleOnProgress,
  571. getFileSize: getFileSize,
  572. getSkewTime: getSkewTime,
  573. getAuth: getAuth,
  574. isBrowser: true
  575. };
  576.  
  577. var fileSliceNeedCopy = function () {
  578. var compareVersion = function (a, b) {
  579. a = a.split('.');
  580. b = b.split('.');
  581. for (var i = 0; i < b.length; i++) {
  582. if (a[i] !== b[i]) {
  583. return parseInt(a[i]) > parseInt(b[i]) ? 1 : -1;
  584. }
  585. }
  586. return 0;
  587. };
  588. var check = function (ua) {
  589. var ChromeVersion = (ua.match(/Chrome\/([.\d]+)/) || [])[1];
  590. var QBCoreVersion = (ua.match(/QBCore\/([.\d]+)/) || [])[1];
  591. var QQBrowserVersion = (ua.match(/QQBrowser\/([.\d]+)/) || [])[1];
  592. var need = ChromeVersion && compareVersion(ChromeVersion, '53.0.2785.116') < 0 && QBCoreVersion && compareVersion(QBCoreVersion, '3.53.991.400') < 0 && QQBrowserVersion && compareVersion(QQBrowserVersion, '9.0.2524.400') <= 0 || false;
  593. return need;
  594. };
  595. return check(navigator && navigator.userAgent);
  596. }();
  597. util.fileSlice = function (file, start, end, isUseToUpload, callback) {
  598. var blob;
  599. if (file.slice) {
  600. blob = file.slice(start, end);
  601. } else if (file.mozSlice) {
  602. blob = file.mozSlice(start, end);
  603. } else if (file.webkitSlice) {
  604. blob = file.webkitSlice(start, end);
  605. }
  606. if (isUseToUpload && fileSliceNeedCopy) {
  607. var reader = new FileReader();
  608. reader.onload = function (e) {
  609. blob = null;
  610. callback(new Blob([reader.result]));
  611. };
  612. reader.readAsArrayBuffer(blob);
  613. } else {
  614. callback(blob);
  615. }
  616. };
  617. util.getFileUUID = function (file, ChunkSize) {
  618. // 如果信息不完整,不获取
  619. if (file.name && file.size && file.lastModifiedDate && ChunkSize) {
  620. return util.md5([file.name, file.size, file.lastModifiedDate, ChunkSize].join('::'));
  621. } else {
  622. return null;
  623. }
  624. };
  625. util.getBodyMd5 = function (UploadCheckContentMd5, Body, callback, onProgress) {
  626. callback = callback || noop;
  627. if (UploadCheckContentMd5) {
  628. if (typeof Body === 'string') {
  629. callback(util.md5(Body, true));
  630. } else if (Blob && Body instanceof Blob) {
  631. util.getFileMd5(Body, function (err, md5) {
  632. callback(md5);
  633. }, onProgress);
  634. } else {
  635. callback();
  636. }
  637. } else {
  638. callback();
  639. }
  640. };
  641.  
  642. module.exports = util;
  643.  
  644. /***/ }),
  645. /* 1 */
  646. /***/ (function(module, exports) {
  647.  
  648. /*
  649. * DOM Level 2
  650. * Object DOMException
  651. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  652. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  653. */
  654.  
  655. function copy(src,dest){
  656. for(var p in src){
  657. dest[p] = src[p];
  658. }
  659. }
  660. /**
  661. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  662. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  663. */
  664. function _extends(Class,Super){
  665. var pt = Class.prototype;
  666. if(Object.create){
  667. var ppt = Object.create(Super.prototype)
  668. pt.__proto__ = ppt;
  669. }
  670. if(!(pt instanceof Super)){
  671. function t(){};
  672. t.prototype = Super.prototype;
  673. t = new t();
  674. copy(pt,t);
  675. Class.prototype = pt = t;
  676. }
  677. if(pt.constructor != Class){
  678. if(typeof Class != 'function'){
  679. console.error("unknow Class:"+Class)
  680. }
  681. pt.constructor = Class
  682. }
  683. }
  684. var htmlns = 'http://www.w3.org/1999/xhtml' ;
  685. // Node Types
  686. var NodeType = {}
  687. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  688. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  689. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  690. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  691. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  692. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  693. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  694. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  695. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  696. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  697. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  698. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  699.  
  700. // ExceptionCode
  701. var ExceptionCode = {}
  702. var ExceptionMessage = {};
  703. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  704. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  705. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  706. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  707. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  708. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  709. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  710. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  711. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  712. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  713. //level2
  714. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  715. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  716. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  717. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  718. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  719.  
  720.  
  721. function DOMException(code, message) {
  722. if(message instanceof Error){
  723. var error = message;
  724. }else{
  725. error = this;
  726. Error.call(this, ExceptionMessage[code]);
  727. this.message = ExceptionMessage[code];
  728. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  729. }
  730. error.code = code;
  731. if(message) this.message = this.message + ": " + message;
  732. return error;
  733. };
  734. DOMException.prototype = Error.prototype;
  735. copy(ExceptionCode,DOMException)
  736. /**
  737. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  738. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  739. * The items in the NodeList are accessible via an integral index, starting from 0.
  740. */
  741. function NodeList() {
  742. };
  743. NodeList.prototype = {
  744. /**
  745. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  746. * @standard level1
  747. */
  748. length:0,
  749. /**
  750. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  751. * @standard level1
  752. * @param index unsigned long
  753. * Index into the collection.
  754. * @return Node
  755. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  756. */
  757. item: function(index) {
  758. return this[index] || null;
  759. },
  760. toString:function(isHTML,nodeFilter){
  761. for(var buf = [], i = 0;i<this.length;i++){
  762. serializeToString(this[i],buf,isHTML,nodeFilter);
  763. }
  764. return buf.join('');
  765. }
  766. };
  767. function LiveNodeList(node,refresh){
  768. this._node = node;
  769. this._refresh = refresh
  770. _updateLiveList(this);
  771. }
  772. function _updateLiveList(list){
  773. var inc = list._node._inc || list._node.ownerDocument._inc;
  774. if(list._inc != inc){
  775. var ls = list._refresh(list._node);
  776. //console.log(ls.length)
  777. __set__(list,'length',ls.length);
  778. copy(ls,list);
  779. list._inc = inc;
  780. }
  781. }
  782. LiveNodeList.prototype.item = function(i){
  783. _updateLiveList(this);
  784. return this[i];
  785. }
  786.  
  787. _extends(LiveNodeList,NodeList);
  788. /**
  789. *
  790. * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
  791. * NamedNodeMap objects in the DOM are live.
  792. * used for attributes or DocumentType entities
  793. */
  794. function NamedNodeMap() {
  795. };
  796.  
  797. function _findNodeIndex(list,node){
  798. var i = list.length;
  799. while(i--){
  800. if(list[i] === node){return i}
  801. }
  802. }
  803.  
  804. function _addNamedNode(el,list,newAttr,oldAttr){
  805. if(oldAttr){
  806. list[_findNodeIndex(list,oldAttr)] = newAttr;
  807. }else{
  808. list[list.length++] = newAttr;
  809. }
  810. if(el){
  811. newAttr.ownerElement = el;
  812. var doc = el.ownerDocument;
  813. if(doc){
  814. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  815. _onAddAttribute(doc,el,newAttr);
  816. }
  817. }
  818. }
  819. function _removeNamedNode(el,list,attr){
  820. //console.log('remove attr:'+attr)
  821. var i = _findNodeIndex(list,attr);
  822. if(i>=0){
  823. var lastIndex = list.length-1
  824. while(i<lastIndex){
  825. list[i] = list[++i]
  826. }
  827. list.length = lastIndex;
  828. if(el){
  829. var doc = el.ownerDocument;
  830. if(doc){
  831. _onRemoveAttribute(doc,el,attr);
  832. attr.ownerElement = null;
  833. }
  834. }
  835. }else{
  836. throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
  837. }
  838. }
  839. NamedNodeMap.prototype = {
  840. length:0,
  841. item:NodeList.prototype.item,
  842. getNamedItem: function(key) {
  843. // if(key.indexOf(':')>0 || key == 'xmlns'){
  844. // return null;
  845. // }
  846. //console.log()
  847. var i = this.length;
  848. while(i--){
  849. var attr = this[i];
  850. //console.log(attr.nodeName,key)
  851. if(attr.nodeName == key){
  852. return attr;
  853. }
  854. }
  855. },
  856. setNamedItem: function(attr) {
  857. var el = attr.ownerElement;
  858. if(el && el!=this._ownerElement){
  859. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  860. }
  861. var oldAttr = this.getNamedItem(attr.nodeName);
  862. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  863. return oldAttr;
  864. },
  865. /* returns Node */
  866. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  867. var el = attr.ownerElement, oldAttr;
  868. if(el && el!=this._ownerElement){
  869. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  870. }
  871. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  872. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  873. return oldAttr;
  874. },
  875.  
  876. /* returns Node */
  877. removeNamedItem: function(key) {
  878. var attr = this.getNamedItem(key);
  879. _removeNamedNode(this._ownerElement,this,attr);
  880. return attr;
  881. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  882. //for level2
  883. removeNamedItemNS:function(namespaceURI,localName){
  884. var attr = this.getNamedItemNS(namespaceURI,localName);
  885. _removeNamedNode(this._ownerElement,this,attr);
  886. return attr;
  887. },
  888. getNamedItemNS: function(namespaceURI, localName) {
  889. var i = this.length;
  890. while(i--){
  891. var node = this[i];
  892. if(node.localName == localName && node.namespaceURI == namespaceURI){
  893. return node;
  894. }
  895. }
  896. return null;
  897. }
  898. };
  899. /**
  900. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  901. */
  902. function DOMImplementation(/* Object */ features) {
  903. this._features = {};
  904. if (features) {
  905. for (var feature in features) {
  906. this._features = features[feature];
  907. }
  908. }
  909. };
  910.  
  911. DOMImplementation.prototype = {
  912. hasFeature: function(/* string */ feature, /* string */ version) {
  913. var versions = this._features[feature.toLowerCase()];
  914. if (versions && (!version || version in versions)) {
  915. return true;
  916. } else {
  917. return false;
  918. }
  919. },
  920. // Introduced in DOM Level 2:
  921. createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  922. var doc = new Document();
  923. doc.implementation = this;
  924. doc.childNodes = new NodeList();
  925. doc.doctype = doctype;
  926. if(doctype){
  927. doc.appendChild(doctype);
  928. }
  929. if(qualifiedName){
  930. var root = doc.createElementNS(namespaceURI,qualifiedName);
  931. doc.appendChild(root);
  932. }
  933. return doc;
  934. },
  935. // Introduced in DOM Level 2:
  936. createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  937. var node = new DocumentType();
  938. node.name = qualifiedName;
  939. node.nodeName = qualifiedName;
  940. node.publicId = publicId;
  941. node.systemId = systemId;
  942. // Introduced in DOM Level 2:
  943. //readonly attribute DOMString internalSubset;
  944. //TODO:..
  945. // readonly attribute NamedNodeMap entities;
  946. // readonly attribute NamedNodeMap notations;
  947. return node;
  948. }
  949. };
  950.  
  951.  
  952. /**
  953. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  954. */
  955.  
  956. function Node() {
  957. };
  958.  
  959. Node.prototype = {
  960. firstChild : null,
  961. lastChild : null,
  962. previousSibling : null,
  963. nextSibling : null,
  964. attributes : null,
  965. parentNode : null,
  966. childNodes : null,
  967. ownerDocument : null,
  968. nodeValue : null,
  969. namespaceURI : null,
  970. prefix : null,
  971. localName : null,
  972. // Modified in DOM Level 2:
  973. insertBefore:function(newChild, refChild){//raises
  974. return _insertBefore(this,newChild,refChild);
  975. },
  976. replaceChild:function(newChild, oldChild){//raises
  977. this.insertBefore(newChild,oldChild);
  978. if(oldChild){
  979. this.removeChild(oldChild);
  980. }
  981. },
  982. removeChild:function(oldChild){
  983. return _removeChild(this,oldChild);
  984. },
  985. appendChild:function(newChild){
  986. return this.insertBefore(newChild,null);
  987. },
  988. hasChildNodes:function(){
  989. return this.firstChild != null;
  990. },
  991. cloneNode:function(deep){
  992. return cloneNode(this.ownerDocument||this,this,deep);
  993. },
  994. // Modified in DOM Level 2:
  995. normalize:function(){
  996. var child = this.firstChild;
  997. while(child){
  998. var next = child.nextSibling;
  999. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  1000. this.removeChild(next);
  1001. child.appendData(next.data);
  1002. }else{
  1003. child.normalize();
  1004. child = next;
  1005. }
  1006. }
  1007. },
  1008. // Introduced in DOM Level 2:
  1009. isSupported:function(feature, version){
  1010. return this.ownerDocument.implementation.hasFeature(feature,version);
  1011. },
  1012. // Introduced in DOM Level 2:
  1013. hasAttributes:function(){
  1014. return this.attributes.length>0;
  1015. },
  1016. lookupPrefix:function(namespaceURI){
  1017. var el = this;
  1018. while(el){
  1019. var map = el._nsMap;
  1020. //console.dir(map)
  1021. if(map){
  1022. for(var n in map){
  1023. if(map[n] == namespaceURI){
  1024. return n;
  1025. }
  1026. }
  1027. }
  1028. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  1029. }
  1030. return null;
  1031. },
  1032. // Introduced in DOM Level 3:
  1033. lookupNamespaceURI:function(prefix){
  1034. var el = this;
  1035. while(el){
  1036. var map = el._nsMap;
  1037. //console.dir(map)
  1038. if(map){
  1039. if(prefix in map){
  1040. return map[prefix] ;
  1041. }
  1042. }
  1043. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  1044. }
  1045. return null;
  1046. },
  1047. // Introduced in DOM Level 3:
  1048. isDefaultNamespace:function(namespaceURI){
  1049. var prefix = this.lookupPrefix(namespaceURI);
  1050. return prefix == null;
  1051. }
  1052. };
  1053.  
  1054.  
  1055. function _xmlEncoder(c){
  1056. return c == '<' && '&lt;' ||
  1057. c == '>' && '&gt;' ||
  1058. c == '&' && '&amp;' ||
  1059. c == '"' && '&quot;' ||
  1060. '&#'+c.charCodeAt()+';'
  1061. }
  1062.  
  1063.  
  1064. copy(NodeType,Node);
  1065. copy(NodeType,Node.prototype);
  1066.  
  1067. /**
  1068. * @param callback return true for continue,false for break
  1069. * @return boolean true: break visit;
  1070. */
  1071. function _visitNode(node,callback){
  1072. if(callback(node)){
  1073. return true;
  1074. }
  1075. if(node = node.firstChild){
  1076. do{
  1077. if(_visitNode(node,callback)){return true}
  1078. }while(node=node.nextSibling)
  1079. }
  1080. }
  1081.  
  1082.  
  1083.  
  1084. function Document(){
  1085. }
  1086. function _onAddAttribute(doc,el,newAttr){
  1087. doc && doc._inc++;
  1088. var ns = newAttr.namespaceURI ;
  1089. if(ns == 'http://www.w3.org/2000/xmlns/'){
  1090. //update namespace
  1091. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  1092. }
  1093. }
  1094. function _onRemoveAttribute(doc,el,newAttr,remove){
  1095. doc && doc._inc++;
  1096. var ns = newAttr.namespaceURI ;
  1097. if(ns == 'http://www.w3.org/2000/xmlns/'){
  1098. //update namespace
  1099. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  1100. }
  1101. }
  1102. function _onUpdateChild(doc,el,newChild){
  1103. if(doc && doc._inc){
  1104. doc._inc++;
  1105. //update childNodes
  1106. var cs = el.childNodes;
  1107. if(newChild){
  1108. cs[cs.length++] = newChild;
  1109. }else{
  1110. //console.log(1)
  1111. var child = el.firstChild;
  1112. var i = 0;
  1113. while(child){
  1114. cs[i++] = child;
  1115. child =child.nextSibling;
  1116. }
  1117. cs.length = i;
  1118. }
  1119. }
  1120. }
  1121.  
  1122. /**
  1123. * attributes;
  1124. * children;
  1125. *
  1126. * writeable properties:
  1127. * nodeValue,Attr:value,CharacterData:data
  1128. * prefix
  1129. */
  1130. function _removeChild(parentNode,child){
  1131. var previous = child.previousSibling;
  1132. var next = child.nextSibling;
  1133. if(previous){
  1134. previous.nextSibling = next;
  1135. }else{
  1136. parentNode.firstChild = next
  1137. }
  1138. if(next){
  1139. next.previousSibling = previous;
  1140. }else{
  1141. parentNode.lastChild = previous;
  1142. }
  1143. _onUpdateChild(parentNode.ownerDocument,parentNode);
  1144. return child;
  1145. }
  1146. /**
  1147. * preformance key(refChild == null)
  1148. */
  1149. function _insertBefore(parentNode,newChild,nextChild){
  1150. var cp = newChild.parentNode;
  1151. if(cp){
  1152. cp.removeChild(newChild);//remove and update
  1153. }
  1154. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  1155. var newFirst = newChild.firstChild;
  1156. if (newFirst == null) {
  1157. return newChild;
  1158. }
  1159. var newLast = newChild.lastChild;
  1160. }else{
  1161. newFirst = newLast = newChild;
  1162. }
  1163. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  1164.  
  1165. newFirst.previousSibling = pre;
  1166. newLast.nextSibling = nextChild;
  1167. if(pre){
  1168. pre.nextSibling = newFirst;
  1169. }else{
  1170. parentNode.firstChild = newFirst;
  1171. }
  1172. if(nextChild == null){
  1173. parentNode.lastChild = newLast;
  1174. }else{
  1175. nextChild.previousSibling = newLast;
  1176. }
  1177. do{
  1178. newFirst.parentNode = parentNode;
  1179. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  1180. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  1181. //console.log(parentNode.lastChild.nextSibling == null)
  1182. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  1183. newChild.firstChild = newChild.lastChild = null;
  1184. }
  1185. return newChild;
  1186. }
  1187. function _appendSingleChild(parentNode,newChild){
  1188. var cp = newChild.parentNode;
  1189. if(cp){
  1190. var pre = parentNode.lastChild;
  1191. cp.removeChild(newChild);//remove and update
  1192. var pre = parentNode.lastChild;
  1193. }
  1194. var pre = parentNode.lastChild;
  1195. newChild.parentNode = parentNode;
  1196. newChild.previousSibling = pre;
  1197. newChild.nextSibling = null;
  1198. if(pre){
  1199. pre.nextSibling = newChild;
  1200. }else{
  1201. parentNode.firstChild = newChild;
  1202. }
  1203. parentNode.lastChild = newChild;
  1204. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  1205. return newChild;
  1206. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  1207. }
  1208. Document.prototype = {
  1209. //implementation : null,
  1210. nodeName : '#document',
  1211. nodeType : DOCUMENT_NODE,
  1212. doctype : null,
  1213. documentElement : null,
  1214. _inc : 1,
  1215. insertBefore : function(newChild, refChild){//raises
  1216. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  1217. var child = newChild.firstChild;
  1218. while(child){
  1219. var next = child.nextSibling;
  1220. this.insertBefore(child,refChild);
  1221. child = next;
  1222. }
  1223. return newChild;
  1224. }
  1225. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  1226. this.documentElement = newChild;
  1227. }
  1228. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  1229. },
  1230. removeChild : function(oldChild){
  1231. if(this.documentElement == oldChild){
  1232. this.documentElement = null;
  1233. }
  1234. return _removeChild(this,oldChild);
  1235. },
  1236. // Introduced in DOM Level 2:
  1237. importNode : function(importedNode,deep){
  1238. return importNode(this,importedNode,deep);
  1239. },
  1240. // Introduced in DOM Level 2:
  1241. getElementById : function(id){
  1242. var rtv = null;
  1243. _visitNode(this.documentElement,function(node){
  1244. if(node.nodeType == ELEMENT_NODE){
  1245. if(node.getAttribute('id') == id){
  1246. rtv = node;
  1247. return true;
  1248. }
  1249. }
  1250. })
  1251. return rtv;
  1252. },
  1253. //document factory method:
  1254. createElement : function(tagName){
  1255. var node = new Element();
  1256. node.ownerDocument = this;
  1257. node.nodeName = tagName;
  1258. node.tagName = tagName;
  1259. node.childNodes = new NodeList();
  1260. var attrs = node.attributes = new NamedNodeMap();
  1261. attrs._ownerElement = node;
  1262. return node;
  1263. },
  1264. createDocumentFragment : function(){
  1265. var node = new DocumentFragment();
  1266. node.ownerDocument = this;
  1267. node.childNodes = new NodeList();
  1268. return node;
  1269. },
  1270. createTextNode : function(data){
  1271. var node = new Text();
  1272. node.ownerDocument = this;
  1273. node.appendData(data)
  1274. return node;
  1275. },
  1276. createComment : function(data){
  1277. var node = new Comment();
  1278. node.ownerDocument = this;
  1279. node.appendData(data)
  1280. return node;
  1281. },
  1282. createCDATASection : function(data){
  1283. var node = new CDATASection();
  1284. node.ownerDocument = this;
  1285. node.appendData(data)
  1286. return node;
  1287. },
  1288. createProcessingInstruction : function(target,data){
  1289. var node = new ProcessingInstruction();
  1290. node.ownerDocument = this;
  1291. node.tagName = node.target = target;
  1292. node.nodeValue= node.data = data;
  1293. return node;
  1294. },
  1295. createAttribute : function(name){
  1296. var node = new Attr();
  1297. node.ownerDocument = this;
  1298. node.name = name;
  1299. node.nodeName = name;
  1300. node.localName = name;
  1301. node.specified = true;
  1302. return node;
  1303. },
  1304. createEntityReference : function(name){
  1305. var node = new EntityReference();
  1306. node.ownerDocument = this;
  1307. node.nodeName = name;
  1308. return node;
  1309. },
  1310. // Introduced in DOM Level 2:
  1311. createElementNS : function(namespaceURI,qualifiedName){
  1312. var node = new Element();
  1313. var pl = qualifiedName.split(':');
  1314. var attrs = node.attributes = new NamedNodeMap();
  1315. node.childNodes = new NodeList();
  1316. node.ownerDocument = this;
  1317. node.nodeName = qualifiedName;
  1318. node.tagName = qualifiedName;
  1319. node.namespaceURI = namespaceURI;
  1320. if(pl.length == 2){
  1321. node.prefix = pl[0];
  1322. node.localName = pl[1];
  1323. }else{
  1324. //el.prefix = null;
  1325. node.localName = qualifiedName;
  1326. }
  1327. attrs._ownerElement = node;
  1328. return node;
  1329. },
  1330. // Introduced in DOM Level 2:
  1331. createAttributeNS : function(namespaceURI,qualifiedName){
  1332. var node = new Attr();
  1333. var pl = qualifiedName.split(':');
  1334. node.ownerDocument = this;
  1335. node.nodeName = qualifiedName;
  1336. node.name = qualifiedName;
  1337. node.namespaceURI = namespaceURI;
  1338. node.specified = true;
  1339. if(pl.length == 2){
  1340. node.prefix = pl[0];
  1341. node.localName = pl[1];
  1342. }else{
  1343. //el.prefix = null;
  1344. node.localName = qualifiedName;
  1345. }
  1346. return node;
  1347. }
  1348. };
  1349. _extends(Document,Node);
  1350.  
  1351.  
  1352. function Element() {
  1353. this._nsMap = {};
  1354. };
  1355. Element.prototype = {
  1356. nodeType : ELEMENT_NODE,
  1357. hasAttribute : function(name){
  1358. return this.getAttributeNode(name)!=null;
  1359. },
  1360. getAttribute : function(name){
  1361. var attr = this.getAttributeNode(name);
  1362. return attr && attr.value || '';
  1363. },
  1364. getAttributeNode : function(name){
  1365. return this.attributes.getNamedItem(name);
  1366. },
  1367. setAttribute : function(name, value){
  1368. var attr = this.ownerDocument.createAttribute(name);
  1369. attr.value = attr.nodeValue = "" + value;
  1370. this.setAttributeNode(attr)
  1371. },
  1372. removeAttribute : function(name){
  1373. var attr = this.getAttributeNode(name)
  1374. attr && this.removeAttributeNode(attr);
  1375. },
  1376. //four real opeartion method
  1377. appendChild:function(newChild){
  1378. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  1379. return this.insertBefore(newChild,null);
  1380. }else{
  1381. return _appendSingleChild(this,newChild);
  1382. }
  1383. },
  1384. setAttributeNode : function(newAttr){
  1385. return this.attributes.setNamedItem(newAttr);
  1386. },
  1387. setAttributeNodeNS : function(newAttr){
  1388. return this.attributes.setNamedItemNS(newAttr);
  1389. },
  1390. removeAttributeNode : function(oldAttr){
  1391. //console.log(this == oldAttr.ownerElement)
  1392. return this.attributes.removeNamedItem(oldAttr.nodeName);
  1393. },
  1394. //get real attribute name,and remove it by removeAttributeNode
  1395. removeAttributeNS : function(namespaceURI, localName){
  1396. var old = this.getAttributeNodeNS(namespaceURI, localName);
  1397. old && this.removeAttributeNode(old);
  1398. },
  1399. hasAttributeNS : function(namespaceURI, localName){
  1400. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  1401. },
  1402. getAttributeNS : function(namespaceURI, localName){
  1403. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  1404. return attr && attr.value || '';
  1405. },
  1406. setAttributeNS : function(namespaceURI, qualifiedName, value){
  1407. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  1408. attr.value = attr.nodeValue = "" + value;
  1409. this.setAttributeNode(attr)
  1410. },
  1411. getAttributeNodeNS : function(namespaceURI, localName){
  1412. return this.attributes.getNamedItemNS(namespaceURI, localName);
  1413. },
  1414. getElementsByTagName : function(tagName){
  1415. return new LiveNodeList(this,function(base){
  1416. var ls = [];
  1417. _visitNode(base,function(node){
  1418. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  1419. ls.push(node);
  1420. }
  1421. });
  1422. return ls;
  1423. });
  1424. },
  1425. getElementsByTagNameNS : function(namespaceURI, localName){
  1426. return new LiveNodeList(this,function(base){
  1427. var ls = [];
  1428. _visitNode(base,function(node){
  1429. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  1430. ls.push(node);
  1431. }
  1432. });
  1433. return ls;
  1434. });
  1435. }
  1436. };
  1437. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  1438. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  1439.  
  1440.  
  1441. _extends(Element,Node);
  1442. function Attr() {
  1443. };
  1444. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  1445. _extends(Attr,Node);
  1446.  
  1447.  
  1448. function CharacterData() {
  1449. };
  1450. CharacterData.prototype = {
  1451. data : '',
  1452. substringData : function(offset, count) {
  1453. return this.data.substring(offset, offset+count);
  1454. },
  1455. appendData: function(text) {
  1456. text = this.data+text;
  1457. this.nodeValue = this.data = text;
  1458. this.length = text.length;
  1459. },
  1460. insertData: function(offset,text) {
  1461. this.replaceData(offset,0,text);
  1462. },
  1463. appendChild:function(newChild){
  1464. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  1465. },
  1466. deleteData: function(offset, count) {
  1467. this.replaceData(offset,count,"");
  1468. },
  1469. replaceData: function(offset, count, text) {
  1470. var start = this.data.substring(0,offset);
  1471. var end = this.data.substring(offset+count);
  1472. text = start + text + end;
  1473. this.nodeValue = this.data = text;
  1474. this.length = text.length;
  1475. }
  1476. }
  1477. _extends(CharacterData,Node);
  1478. function Text() {
  1479. };
  1480. Text.prototype = {
  1481. nodeName : "#text",
  1482. nodeType : TEXT_NODE,
  1483. splitText : function(offset) {
  1484. var text = this.data;
  1485. var newText = text.substring(offset);
  1486. text = text.substring(0, offset);
  1487. this.data = this.nodeValue = text;
  1488. this.length = text.length;
  1489. var newNode = this.ownerDocument.createTextNode(newText);
  1490. if(this.parentNode){
  1491. this.parentNode.insertBefore(newNode, this.nextSibling);
  1492. }
  1493. return newNode;
  1494. }
  1495. }
  1496. _extends(Text,CharacterData);
  1497. function Comment() {
  1498. };
  1499. Comment.prototype = {
  1500. nodeName : "#comment",
  1501. nodeType : COMMENT_NODE
  1502. }
  1503. _extends(Comment,CharacterData);
  1504.  
  1505. function CDATASection() {
  1506. };
  1507. CDATASection.prototype = {
  1508. nodeName : "#cdata-section",
  1509. nodeType : CDATA_SECTION_NODE
  1510. }
  1511. _extends(CDATASection,CharacterData);
  1512.  
  1513.  
  1514. function DocumentType() {
  1515. };
  1516. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  1517. _extends(DocumentType,Node);
  1518.  
  1519. function Notation() {
  1520. };
  1521. Notation.prototype.nodeType = NOTATION_NODE;
  1522. _extends(Notation,Node);
  1523.  
  1524. function Entity() {
  1525. };
  1526. Entity.prototype.nodeType = ENTITY_NODE;
  1527. _extends(Entity,Node);
  1528.  
  1529. function EntityReference() {
  1530. };
  1531. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  1532. _extends(EntityReference,Node);
  1533.  
  1534. function DocumentFragment() {
  1535. };
  1536. DocumentFragment.prototype.nodeName = "#document-fragment";
  1537. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  1538. _extends(DocumentFragment,Node);
  1539.  
  1540.  
  1541. function ProcessingInstruction() {
  1542. }
  1543. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  1544. _extends(ProcessingInstruction,Node);
  1545. function XMLSerializer(){}
  1546. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  1547. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  1548. }
  1549. Node.prototype.toString = nodeSerializeToString;
  1550. function nodeSerializeToString(isHtml,nodeFilter){
  1551. var buf = [];
  1552. var refNode = this.nodeType == 9?this.documentElement:this;
  1553. var prefix = refNode.prefix;
  1554. var uri = refNode.namespaceURI;
  1555. if(uri && prefix == null){
  1556. //console.log(prefix)
  1557. var prefix = refNode.lookupPrefix(uri);
  1558. if(prefix == null){
  1559. //isHTML = true;
  1560. var visibleNamespaces=[
  1561. {namespace:uri,prefix:null}
  1562. //{namespace:uri,prefix:''}
  1563. ]
  1564. }
  1565. }
  1566. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  1567. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  1568. return buf.join('');
  1569. }
  1570. function needNamespaceDefine(node,isHTML, visibleNamespaces) {
  1571. var prefix = node.prefix||'';
  1572. var uri = node.namespaceURI;
  1573. if (!prefix && !uri){
  1574. return false;
  1575. }
  1576. if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
  1577. || uri == 'http://www.w3.org/2000/xmlns/'){
  1578. return false;
  1579. }
  1580. var i = visibleNamespaces.length
  1581. //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
  1582. while (i--) {
  1583. var ns = visibleNamespaces[i];
  1584. // get namespace prefix
  1585. //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
  1586. if (ns.prefix == prefix){
  1587. return ns.namespace != uri;
  1588. }
  1589. }
  1590. //console.log(isHTML,uri,prefix=='')
  1591. //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  1592. // return false;
  1593. //}
  1594. //node.flag = '11111'
  1595. //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
  1596. return true;
  1597. }
  1598. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  1599. if(nodeFilter){
  1600. node = nodeFilter(node);
  1601. if(node){
  1602. if(typeof node == 'string'){
  1603. buf.push(node);
  1604. return;
  1605. }
  1606. }else{
  1607. return;
  1608. }
  1609. //buf.sort.apply(attrs, attributeSorter);
  1610. }
  1611. switch(node.nodeType){
  1612. case ELEMENT_NODE:
  1613. if (!visibleNamespaces) visibleNamespaces = [];
  1614. var startVisibleNamespaces = visibleNamespaces.length;
  1615. var attrs = node.attributes;
  1616. var len = attrs.length;
  1617. var child = node.firstChild;
  1618. var nodeName = node.tagName;
  1619. isHTML = (htmlns === node.namespaceURI) ||isHTML
  1620. buf.push('<',nodeName);
  1621. for(var i=0;i<len;i++){
  1622. // add namespaces for attributes
  1623. var attr = attrs.item(i);
  1624. if (attr.prefix == 'xmlns') {
  1625. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  1626. }else if(attr.nodeName == 'xmlns'){
  1627. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  1628. }
  1629. }
  1630. for(var i=0;i<len;i++){
  1631. var attr = attrs.item(i);
  1632. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  1633. var prefix = attr.prefix||'';
  1634. var uri = attr.namespaceURI;
  1635. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1636. buf.push(ns, '="' , uri , '"');
  1637. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1638. }
  1639. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  1640. }
  1641. // add namespace for current node
  1642. if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
  1643. var prefix = node.prefix||'';
  1644. var uri = node.namespaceURI;
  1645. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1646. buf.push(ns, '="' , uri , '"');
  1647. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1648. }
  1649. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  1650. buf.push('>');
  1651. //if is cdata child node
  1652. if(isHTML && /^script$/i.test(nodeName)){
  1653. while(child){
  1654. if(child.data){
  1655. buf.push(child.data);
  1656. }else{
  1657. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1658. }
  1659. child = child.nextSibling;
  1660. }
  1661. }else
  1662. {
  1663. while(child){
  1664. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1665. child = child.nextSibling;
  1666. }
  1667. }
  1668. buf.push('</',nodeName,'>');
  1669. }else{
  1670. buf.push('/>');
  1671. }
  1672. // remove added visible namespaces
  1673. //visibleNamespaces.length = startVisibleNamespaces;
  1674. return;
  1675. case DOCUMENT_NODE:
  1676. case DOCUMENT_FRAGMENT_NODE:
  1677. var child = node.firstChild;
  1678. while(child){
  1679. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1680. child = child.nextSibling;
  1681. }
  1682. return;
  1683. case ATTRIBUTE_NODE:
  1684. return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
  1685. case TEXT_NODE:
  1686. return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
  1687. case CDATA_SECTION_NODE:
  1688. return buf.push( '<![CDATA[',node.data,']]>');
  1689. case COMMENT_NODE:
  1690. return buf.push( "<!--",node.data,"-->");
  1691. case DOCUMENT_TYPE_NODE:
  1692. var pubid = node.publicId;
  1693. var sysid = node.systemId;
  1694. buf.push('<!DOCTYPE ',node.name);
  1695. if(pubid){
  1696. buf.push(' PUBLIC "',pubid);
  1697. if (sysid && sysid!='.') {
  1698. buf.push( '" "',sysid);
  1699. }
  1700. buf.push('">');
  1701. }else if(sysid && sysid!='.'){
  1702. buf.push(' SYSTEM "',sysid,'">');
  1703. }else{
  1704. var sub = node.internalSubset;
  1705. if(sub){
  1706. buf.push(" [",sub,"]");
  1707. }
  1708. buf.push(">");
  1709. }
  1710. return;
  1711. case PROCESSING_INSTRUCTION_NODE:
  1712. return buf.push( "<?",node.target," ",node.data,"?>");
  1713. case ENTITY_REFERENCE_NODE:
  1714. return buf.push( '&',node.nodeName,';');
  1715. //case ENTITY_NODE:
  1716. //case NOTATION_NODE:
  1717. default:
  1718. buf.push('??',node.nodeName);
  1719. }
  1720. }
  1721. function importNode(doc,node,deep){
  1722. var node2;
  1723. switch (node.nodeType) {
  1724. case ELEMENT_NODE:
  1725. node2 = node.cloneNode(false);
  1726. node2.ownerDocument = doc;
  1727. //var attrs = node2.attributes;
  1728. //var len = attrs.length;
  1729. //for(var i=0;i<len;i++){
  1730. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  1731. //}
  1732. case DOCUMENT_FRAGMENT_NODE:
  1733. break;
  1734. case ATTRIBUTE_NODE:
  1735. deep = true;
  1736. break;
  1737. //case ENTITY_REFERENCE_NODE:
  1738. //case PROCESSING_INSTRUCTION_NODE:
  1739. ////case TEXT_NODE:
  1740. //case CDATA_SECTION_NODE:
  1741. //case COMMENT_NODE:
  1742. // deep = false;
  1743. // break;
  1744. //case DOCUMENT_NODE:
  1745. //case DOCUMENT_TYPE_NODE:
  1746. //cannot be imported.
  1747. //case ENTITY_NODE:
  1748. //case NOTATION_NODE:
  1749. //can not hit in level3
  1750. //default:throw e;
  1751. }
  1752. if(!node2){
  1753. node2 = node.cloneNode(false);//false
  1754. }
  1755. node2.ownerDocument = doc;
  1756. node2.parentNode = null;
  1757. if(deep){
  1758. var child = node.firstChild;
  1759. while(child){
  1760. node2.appendChild(importNode(doc,child,deep));
  1761. child = child.nextSibling;
  1762. }
  1763. }
  1764. return node2;
  1765. }
  1766. //
  1767. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  1768. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  1769. function cloneNode(doc,node,deep){
  1770. var node2 = new node.constructor();
  1771. for(var n in node){
  1772. var v = node[n];
  1773. if(typeof v != 'object' ){
  1774. if(v != node2[n]){
  1775. node2[n] = v;
  1776. }
  1777. }
  1778. }
  1779. if(node.childNodes){
  1780. node2.childNodes = new NodeList();
  1781. }
  1782. node2.ownerDocument = doc;
  1783. switch (node2.nodeType) {
  1784. case ELEMENT_NODE:
  1785. var attrs = node.attributes;
  1786. var attrs2 = node2.attributes = new NamedNodeMap();
  1787. var len = attrs.length
  1788. attrs2._ownerElement = node2;
  1789. for(var i=0;i<len;i++){
  1790. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  1791. }
  1792. break;;
  1793. case ATTRIBUTE_NODE:
  1794. deep = true;
  1795. }
  1796. if(deep){
  1797. var child = node.firstChild;
  1798. while(child){
  1799. node2.appendChild(cloneNode(doc,child,deep));
  1800. child = child.nextSibling;
  1801. }
  1802. }
  1803. return node2;
  1804. }
  1805.  
  1806. function __set__(object,key,value){
  1807. object[key] = value
  1808. }
  1809. //do dynamic
  1810. try{
  1811. if(Object.defineProperty){
  1812. Object.defineProperty(LiveNodeList.prototype,'length',{
  1813. get:function(){
  1814. _updateLiveList(this);
  1815. return this.$$length;
  1816. }
  1817. });
  1818. Object.defineProperty(Node.prototype,'textContent',{
  1819. get:function(){
  1820. return getTextContent(this);
  1821. },
  1822. set:function(data){
  1823. switch(this.nodeType){
  1824. case ELEMENT_NODE:
  1825. case DOCUMENT_FRAGMENT_NODE:
  1826. while(this.firstChild){
  1827. this.removeChild(this.firstChild);
  1828. }
  1829. if(data || String(data)){
  1830. this.appendChild(this.ownerDocument.createTextNode(data));
  1831. }
  1832. break;
  1833. default:
  1834. //TODO:
  1835. this.data = data;
  1836. this.value = data;
  1837. this.nodeValue = data;
  1838. }
  1839. }
  1840. })
  1841. function getTextContent(node){
  1842. switch(node.nodeType){
  1843. case ELEMENT_NODE:
  1844. case DOCUMENT_FRAGMENT_NODE:
  1845. var buf = [];
  1846. node = node.firstChild;
  1847. while(node){
  1848. if(node.nodeType!==7 && node.nodeType !==8){
  1849. buf.push(getTextContent(node));
  1850. }
  1851. node = node.nextSibling;
  1852. }
  1853. return buf.join('');
  1854. default:
  1855. return node.nodeValue;
  1856. }
  1857. }
  1858. __set__ = function(object,key,value){
  1859. //console.log(value)
  1860. object['$$'+key] = value
  1861. }
  1862. }
  1863. }catch(e){//ie8
  1864. }
  1865.  
  1866. //if(typeof require == 'function'){
  1867. exports.DOMImplementation = DOMImplementation;
  1868. exports.XMLSerializer = XMLSerializer;
  1869. //}
  1870.  
  1871.  
  1872. /***/ }),
  1873. /* 2 */
  1874. /***/ (function(module, exports) {
  1875.  
  1876. var initEvent = function (cos) {
  1877. var listeners = {};
  1878. var getList = function (action) {
  1879. !listeners[action] && (listeners[action] = []);
  1880. return listeners[action];
  1881. };
  1882. cos.on = function (action, callback) {
  1883. if (action === 'task-list-update') {
  1884. console.warn('warning: Event "' + action + '" has been deprecated. Please use "list-update" instead.');
  1885. }
  1886. getList(action).push(callback);
  1887. };
  1888. cos.off = function (action, callback) {
  1889. var list = getList(action);
  1890. for (var i = list.length - 1; i >= 0; i--) {
  1891. callback === list[i] && list.splice(i, 1);
  1892. }
  1893. };
  1894. cos.emit = function (action, data) {
  1895. var list = getList(action).map(function (cb) {
  1896. return cb;
  1897. });
  1898. for (var i = 0; i < list.length; i++) {
  1899. list[i](data);
  1900. }
  1901. };
  1902. };
  1903.  
  1904. var EventProxy = function () {
  1905. initEvent(this);
  1906. };
  1907.  
  1908. module.exports.init = initEvent;
  1909. module.exports.EventProxy = EventProxy;
  1910.  
  1911. /***/ }),
  1912. /* 3 */
  1913. /***/ (function(module, exports, __webpack_require__) {
  1914.  
  1915. var COS = __webpack_require__(4);
  1916. module.exports = COS;
  1917.  
  1918. /***/ }),
  1919. /* 4 */
  1920. /***/ (function(module, exports, __webpack_require__) {
  1921.  
  1922. "use strict";
  1923.  
  1924.  
  1925. var util = __webpack_require__(0);
  1926. var event = __webpack_require__(2);
  1927. var task = __webpack_require__(11);
  1928. var base = __webpack_require__(12);
  1929. var advance = __webpack_require__(14);
  1930.  
  1931. var defaultOptions = {
  1932. AppId: '', // AppId 已废弃,请拼接到 Bucket 后传入,例如:test-1250000000
  1933. SecretId: '',
  1934. SecretKey: '',
  1935. XCosSecurityToken: '', // 使用临时密钥需要注意自行刷新 Token
  1936. ChunkRetryTimes: 2,
  1937. FileParallelLimit: 3,
  1938. ChunkParallelLimit: 3,
  1939. ChunkSize: 1024 * 1024,
  1940. SliceSize: 1024 * 1024,
  1941. CopyChunkParallelLimit: 20,
  1942. CopyChunkSize: 1024 * 1024 * 10,
  1943. CopySliceSize: 1024 * 1024 * 10,
  1944. MaxPartNumber: 10000,
  1945. ProgressInterval: 1000,
  1946. UploadQueueSize: 10000,
  1947. Domain: '',
  1948. ServiceDomain: '',
  1949. Protocol: '',
  1950. CompatibilityMode: false,
  1951. ForcePathStyle: false,
  1952. UseRawKey: false,
  1953. Timeout: 0, // 单位毫秒,0 代表不设置超时时间
  1954. CorrectClockSkew: true,
  1955. SystemClockOffset: 0, // 单位毫秒,ms
  1956. UploadCheckContentMd5: false,
  1957. UploadAddMetaMd5: false,
  1958. UploadIdCacheLimit: 50
  1959. };
  1960.  
  1961. // 对外暴露的类
  1962. var COS = function (options) {
  1963. this.options = util.extend(util.clone(defaultOptions), options || {});
  1964. this.options.FileParallelLimit = Math.max(1, this.options.FileParallelLimit);
  1965. this.options.ChunkParallelLimit = Math.max(1, this.options.ChunkParallelLimit);
  1966. this.options.ChunkRetryTimes = Math.max(0, this.options.ChunkRetryTimes);
  1967. this.options.ChunkSize = Math.max(1024 * 1024, this.options.ChunkSize);
  1968. this.options.CopyChunkParallelLimit = Math.max(1, this.options.CopyChunkParallelLimit);
  1969. this.options.CopyChunkSize = Math.max(1024 * 1024, this.options.CopyChunkSize);
  1970. this.options.CopySliceSize = Math.max(0, this.options.CopySliceSize);
  1971. this.options.MaxPartNumber = Math.max(1024, Math.min(10000, this.options.MaxPartNumber));
  1972. this.options.Timeout = Math.max(0, this.options.Timeout);
  1973. if (this.options.AppId) {
  1974. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").');
  1975. }
  1976. event.init(this);
  1977. task.init(this);
  1978. };
  1979.  
  1980. base.init(COS, task);
  1981. advance.init(COS, task);
  1982.  
  1983. COS.getAuthorization = util.getAuth;
  1984. COS.version = '0.5.22';
  1985.  
  1986. module.exports = COS;
  1987.  
  1988. /***/ }),
  1989. /* 5 */
  1990. /***/ (function(module, exports) {
  1991.  
  1992. function md5cycle(x, k) {
  1993. var a = x[0],
  1994. b = x[1],
  1995. c = x[2],
  1996. d = x[3];
  1997.  
  1998. a = ff(a, b, c, d, k[0], 7, -680876936);
  1999. d = ff(d, a, b, c, k[1], 12, -389564586);
  2000. c = ff(c, d, a, b, k[2], 17, 606105819);
  2001. b = ff(b, c, d, a, k[3], 22, -1044525330);
  2002. a = ff(a, b, c, d, k[4], 7, -176418897);
  2003. d = ff(d, a, b, c, k[5], 12, 1200080426);
  2004. c = ff(c, d, a, b, k[6], 17, -1473231341);
  2005. b = ff(b, c, d, a, k[7], 22, -45705983);
  2006. a = ff(a, b, c, d, k[8], 7, 1770035416);
  2007. d = ff(d, a, b, c, k[9], 12, -1958414417);
  2008. c = ff(c, d, a, b, k[10], 17, -42063);
  2009. b = ff(b, c, d, a, k[11], 22, -1990404162);
  2010. a = ff(a, b, c, d, k[12], 7, 1804603682);
  2011. d = ff(d, a, b, c, k[13], 12, -40341101);
  2012. c = ff(c, d, a, b, k[14], 17, -1502002290);
  2013. b = ff(b, c, d, a, k[15], 22, 1236535329);
  2014.  
  2015. a = gg(a, b, c, d, k[1], 5, -165796510);
  2016. d = gg(d, a, b, c, k[6], 9, -1069501632);
  2017. c = gg(c, d, a, b, k[11], 14, 643717713);
  2018. b = gg(b, c, d, a, k[0], 20, -373897302);
  2019. a = gg(a, b, c, d, k[5], 5, -701558691);
  2020. d = gg(d, a, b, c, k[10], 9, 38016083);
  2021. c = gg(c, d, a, b, k[15], 14, -660478335);
  2022. b = gg(b, c, d, a, k[4], 20, -405537848);
  2023. a = gg(a, b, c, d, k[9], 5, 568446438);
  2024. d = gg(d, a, b, c, k[14], 9, -1019803690);
  2025. c = gg(c, d, a, b, k[3], 14, -187363961);
  2026. b = gg(b, c, d, a, k[8], 20, 1163531501);
  2027. a = gg(a, b, c, d, k[13], 5, -1444681467);
  2028. d = gg(d, a, b, c, k[2], 9, -51403784);
  2029. c = gg(c, d, a, b, k[7], 14, 1735328473);
  2030. b = gg(b, c, d, a, k[12], 20, -1926607734);
  2031.  
  2032. a = hh(a, b, c, d, k[5], 4, -378558);
  2033. d = hh(d, a, b, c, k[8], 11, -2022574463);
  2034. c = hh(c, d, a, b, k[11], 16, 1839030562);
  2035. b = hh(b, c, d, a, k[14], 23, -35309556);
  2036. a = hh(a, b, c, d, k[1], 4, -1530992060);
  2037. d = hh(d, a, b, c, k[4], 11, 1272893353);
  2038. c = hh(c, d, a, b, k[7], 16, -155497632);
  2039. b = hh(b, c, d, a, k[10], 23, -1094730640);
  2040. a = hh(a, b, c, d, k[13], 4, 681279174);
  2041. d = hh(d, a, b, c, k[0], 11, -358537222);
  2042. c = hh(c, d, a, b, k[3], 16, -722521979);
  2043. b = hh(b, c, d, a, k[6], 23, 76029189);
  2044. a = hh(a, b, c, d, k[9], 4, -640364487);
  2045. d = hh(d, a, b, c, k[12], 11, -421815835);
  2046. c = hh(c, d, a, b, k[15], 16, 530742520);
  2047. b = hh(b, c, d, a, k[2], 23, -995338651);
  2048.  
  2049. a = ii(a, b, c, d, k[0], 6, -198630844);
  2050. d = ii(d, a, b, c, k[7], 10, 1126891415);
  2051. c = ii(c, d, a, b, k[14], 15, -1416354905);
  2052. b = ii(b, c, d, a, k[5], 21, -57434055);
  2053. a = ii(a, b, c, d, k[12], 6, 1700485571);
  2054. d = ii(d, a, b, c, k[3], 10, -1894986606);
  2055. c = ii(c, d, a, b, k[10], 15, -1051523);
  2056. b = ii(b, c, d, a, k[1], 21, -2054922799);
  2057. a = ii(a, b, c, d, k[8], 6, 1873313359);
  2058. d = ii(d, a, b, c, k[15], 10, -30611744);
  2059. c = ii(c, d, a, b, k[6], 15, -1560198380);
  2060. b = ii(b, c, d, a, k[13], 21, 1309151649);
  2061. a = ii(a, b, c, d, k[4], 6, -145523070);
  2062. d = ii(d, a, b, c, k[11], 10, -1120210379);
  2063. c = ii(c, d, a, b, k[2], 15, 718787259);
  2064. b = ii(b, c, d, a, k[9], 21, -343485551);
  2065.  
  2066. x[0] = add32(a, x[0]);
  2067. x[1] = add32(b, x[1]);
  2068. x[2] = add32(c, x[2]);
  2069. x[3] = add32(d, x[3]);
  2070. }
  2071.  
  2072. function cmn(q, a, b, x, s, t) {
  2073. a = add32(add32(a, q), add32(x, t));
  2074. return add32(a << s | a >>> 32 - s, b);
  2075. }
  2076.  
  2077. function ff(a, b, c, d, x, s, t) {
  2078. return cmn(b & c | ~b & d, a, b, x, s, t);
  2079. }
  2080.  
  2081. function gg(a, b, c, d, x, s, t) {
  2082. return cmn(b & d | c & ~d, a, b, x, s, t);
  2083. }
  2084.  
  2085. function hh(a, b, c, d, x, s, t) {
  2086. return cmn(b ^ c ^ d, a, b, x, s, t);
  2087. }
  2088.  
  2089. function ii(a, b, c, d, x, s, t) {
  2090. return cmn(c ^ (b | ~d), a, b, x, s, t);
  2091. }
  2092.  
  2093. function md51(s) {
  2094. var n = s.length,
  2095. state = [1732584193, -271733879, -1732584194, 271733878],
  2096. i;
  2097. for (i = 64; i <= s.length; i += 64) {
  2098. md5cycle(state, md5blk(s.substring(i - 64, i)));
  2099. }
  2100. s = s.substring(i - 64);
  2101. var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  2102. for (i = 0; i < s.length; i++) tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
  2103. tail[i >> 2] |= 0x80 << (i % 4 << 3);
  2104. if (i > 55) {
  2105. md5cycle(state, tail);
  2106. for (i = 0; i < 16; i++) tail[i] = 0;
  2107. }
  2108. tail[14] = n * 8;
  2109. md5cycle(state, tail);
  2110. return state;
  2111. }
  2112.  
  2113. var binaryBase64 = function (str) {
  2114. var i,
  2115. len,
  2116. char,
  2117. res = '';
  2118. for (i = 0, len = str.length / 2; i < len; i++) {
  2119. char = parseInt(str[i * 2] + str[i * 2 + 1], 16);
  2120. res += String.fromCharCode(char);
  2121. }
  2122. return btoa(res);
  2123. };
  2124. function getCtx() {
  2125. var ctx = {};
  2126. ctx.state = [1732584193, -271733879, -1732584194, 271733878];
  2127. ctx.tail = '';
  2128. ctx.size = 0;
  2129. ctx.update = function (s, isBinaryString) {
  2130. if (!isBinaryString) s = Utf8Encode(s);
  2131. ctx.size += s.length;
  2132. s = ctx.tail + s;
  2133. var i,
  2134. state = ctx.state;
  2135. for (i = 64; i <= s.length; i += 64) {
  2136. md5cycle(state, md5blk(s.substring(i - 64, i)));
  2137. }
  2138. ctx.tail = s.substring(i - 64);
  2139. return ctx;
  2140. };
  2141. ctx.digest = function (encode) {
  2142. var i,
  2143. n = ctx.size,
  2144. state = ctx.state,
  2145. s = ctx.tail,
  2146. tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  2147. for (i = 0; i < s.length; i++) tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
  2148. tail[i >> 2] |= 0x80 << (i % 4 << 3);
  2149. if (i > 55) {
  2150. md5cycle(state, tail);
  2151. for (i = 0; i < 16; i++) tail[i] = 0;
  2152. }
  2153. tail[14] = n * 8;
  2154. md5cycle(state, tail);
  2155. return encode === 'hex' ? hex(state) : encode === 'base64' ? binaryBase64(hex(state)) : state;
  2156. };
  2157. return ctx;
  2158. }
  2159.  
  2160. /* there needs to be support for Unicode here,
  2161. * unless we pretend that we can redefine the MD-5
  2162. * algorithm for multi-byte characters (perhaps
  2163. * by adding every four 16-bit characters and
  2164. * shortening the sum to 32 bits). Otherwise
  2165. * I suggest performing MD-5 as if every character
  2166. * was two bytes--e.g., 0040 0025 = @%--but then
  2167. * how will an ordinary MD-5 sum be matched?
  2168. * There is no way to standardize text to something
  2169. * like UTF-8 before transformation; speed cost is
  2170. * utterly prohibitive. The JavaScript standard
  2171. * itself needs to look at this: it should start
  2172. * providing access to strings as preformed UTF-8
  2173. * 8-bit unsigned value arrays.
  2174. */
  2175. function md5blk(s) {
  2176. /* I figured global was faster. */
  2177. var md5blks = [],
  2178. i; /* Andy King said do it this way. */
  2179. for (i = 0; i < 64; i += 4) {
  2180. md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
  2181. }
  2182. return md5blks;
  2183. }
  2184.  
  2185. var hex_chr = '0123456789abcdef'.split('');
  2186.  
  2187. function rhex(n) {
  2188. var s = '',
  2189. j = 0;
  2190. for (; j < 4; j++) s += hex_chr[n >> j * 8 + 4 & 0x0F] + hex_chr[n >> j * 8 & 0x0F];
  2191. return s;
  2192. }
  2193.  
  2194. function hex(x) {
  2195. for (var i = 0; i < x.length; i++) x[i] = rhex(x[i]);
  2196. return x.join('');
  2197. }
  2198.  
  2199. function Utf8Encode(string) {
  2200. string = string.replace(/\r\n/g, "\n");
  2201. var utftext = "";
  2202. for (var n = 0; n < string.length; n++) {
  2203. var c = string.charCodeAt(n);
  2204. if (c < 128) {
  2205. utftext += String.fromCharCode(c);
  2206. } else if (c > 127 && c < 2048) {
  2207. utftext += String.fromCharCode(c >> 6 | 192);
  2208. utftext += String.fromCharCode(c & 63 | 128);
  2209. } else {
  2210. utftext += String.fromCharCode(c >> 12 | 224);
  2211. utftext += String.fromCharCode(c >> 6 & 63 | 128);
  2212. utftext += String.fromCharCode(c & 63 | 128);
  2213. }
  2214. }
  2215. return utftext;
  2216. }
  2217.  
  2218. function md5(s, isBinaryString) {
  2219. if (!isBinaryString) {
  2220. s = Utf8Encode(s);
  2221. }
  2222. return hex(md51(s));
  2223. }
  2224.  
  2225. /* this function is much faster,
  2226. so if possible we use it. Some IEs
  2227. are the only ones I know of that
  2228. need the idiotic second function,
  2229. generated by an if clause. */
  2230.  
  2231. var add32 = function (a, b) {
  2232. return a + b & 0xFFFFFFFF;
  2233. };
  2234. if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
  2235. add32 = function (x, y) {
  2236. var lsw = (x & 0xFFFF) + (y & 0xFFFF),
  2237. msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  2238. return msw << 16 | lsw & 0xFFFF;
  2239. };
  2240. }
  2241.  
  2242. md5.getCtx = getCtx;
  2243.  
  2244. module.exports = md5;
  2245.  
  2246. /***/ }),
  2247. /* 6 */
  2248. /***/ (function(module, exports, __webpack_require__) {
  2249.  
  2250. /*
  2251. CryptoJS v3.1.2
  2252. code.google.com/p/crypto-js
  2253. (c) 2009-2013 by Jeff Mott. All rights reserved.
  2254. code.google.com/p/crypto-js/wiki/License
  2255. */
  2256. var CryptoJS = CryptoJS || function (g, l) {
  2257. var e = {},
  2258. d = e.lib = {},
  2259. m = function () {},
  2260. k = d.Base = { extend: function (a) {
  2261. m.prototype = this;var c = new m();a && c.mixIn(a);c.hasOwnProperty("init") || (c.init = function () {
  2262. c.$super.init.apply(this, arguments);
  2263. });c.init.prototype = c;c.$super = this;return c;
  2264. }, create: function () {
  2265. var a = this.extend();a.init.apply(a, arguments);return a;
  2266. }, init: function () {}, mixIn: function (a) {
  2267. for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]);a.hasOwnProperty("toString") && (this.toString = a.toString);
  2268. }, clone: function () {
  2269. return this.init.prototype.extend(this);
  2270. } },
  2271. p = d.WordArray = k.extend({ init: function (a, c) {
  2272. a = this.words = a || [];this.sigBytes = c != l ? c : 4 * a.length;
  2273. }, toString: function (a) {
  2274. return (a || n).stringify(this);
  2275. }, concat: function (a) {
  2276. var c = this.words,
  2277. q = a.words,
  2278. f = this.sigBytes;a = a.sigBytes;this.clamp();if (f % 4) for (var b = 0; b < a; b++) c[f + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((f + b) % 4);else if (65535 < q.length) for (b = 0; b < a; b += 4) c[f + b >>> 2] = q[b >>> 2];else c.push.apply(c, q);this.sigBytes += a;return this;
  2279. }, clamp: function () {
  2280. var a = this.words,
  2281. c = this.sigBytes;a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4);a.length = g.ceil(c / 4);
  2282. }, clone: function () {
  2283. var a = k.clone.call(this);a.words = this.words.slice(0);return a;
  2284. }, random: function (a) {
  2285. for (var c = [], b = 0; b < a; b += 4) c.push(4294967296 * g.random() | 0);return new p.init(c, a);
  2286. } }),
  2287. b = e.enc = {},
  2288. n = b.Hex = { stringify: function (a) {
  2289. var c = a.words;a = a.sigBytes;for (var b = [], f = 0; f < a; f++) {
  2290. var d = c[f >>> 2] >>> 24 - 8 * (f % 4) & 255;b.push((d >>> 4).toString(16));b.push((d & 15).toString(16));
  2291. }return b.join("");
  2292. }, parse: function (a) {
  2293. for (var c = a.length, b = [], f = 0; f < c; f += 2) b[f >>> 3] |= parseInt(a.substr(f, 2), 16) << 24 - 4 * (f % 8);return new p.init(b, c / 2);
  2294. } },
  2295. j = b.Latin1 = { stringify: function (a) {
  2296. var c = a.words;a = a.sigBytes;for (var b = [], f = 0; f < a; f++) b.push(String.fromCharCode(c[f >>> 2] >>> 24 - 8 * (f % 4) & 255));return b.join("");
  2297. }, parse: function (a) {
  2298. for (var c = a.length, b = [], f = 0; f < c; f++) b[f >>> 2] |= (a.charCodeAt(f) & 255) << 24 - 8 * (f % 4);return new p.init(b, c);
  2299. } },
  2300. h = b.Utf8 = { stringify: function (a) {
  2301. try {
  2302. return decodeURIComponent(escape(j.stringify(a)));
  2303. } catch (c) {
  2304. throw Error("Malformed UTF-8 data");
  2305. }
  2306. }, parse: function (a) {
  2307. return j.parse(unescape(encodeURIComponent(a)));
  2308. } },
  2309. r = d.BufferedBlockAlgorithm = k.extend({ reset: function () {
  2310. this._data = new p.init();this._nDataBytes = 0;
  2311. }, _append: function (a) {
  2312. "string" == typeof a && (a = h.parse(a));this._data.concat(a);this._nDataBytes += a.sigBytes;
  2313. }, _process: function (a) {
  2314. var c = this._data,
  2315. b = c.words,
  2316. f = c.sigBytes,
  2317. d = this.blockSize,
  2318. e = f / (4 * d),
  2319. e = a ? g.ceil(e) : g.max((e | 0) - this._minBufferSize, 0);a = e * d;f = g.min(4 * a, f);if (a) {
  2320. for (var k = 0; k < a; k += d) this._doProcessBlock(b, k);k = b.splice(0, a);c.sigBytes -= f;
  2321. }return new p.init(k, f);
  2322. }, clone: function () {
  2323. var a = k.clone.call(this);
  2324. a._data = this._data.clone();return a;
  2325. }, _minBufferSize: 0 });d.Hasher = r.extend({ cfg: k.extend(), init: function (a) {
  2326. this.cfg = this.cfg.extend(a);this.reset();
  2327. }, reset: function () {
  2328. r.reset.call(this);this._doReset();
  2329. }, update: function (a) {
  2330. this._append(a);this._process();return this;
  2331. }, finalize: function (a) {
  2332. a && this._append(a);return this._doFinalize();
  2333. }, blockSize: 16, _createHelper: function (a) {
  2334. return function (b, d) {
  2335. return new a.init(d).finalize(b);
  2336. };
  2337. }, _createHmacHelper: function (a) {
  2338. return function (b, d) {
  2339. return new s.HMAC.init(a, d).finalize(b);
  2340. };
  2341. } });var s = e.algo = {};return e;
  2342. }(Math);
  2343. (function () {
  2344. var g = CryptoJS,
  2345. l = g.lib,
  2346. e = l.WordArray,
  2347. d = l.Hasher,
  2348. m = [],
  2349. l = g.algo.SHA1 = d.extend({ _doReset: function () {
  2350. this._hash = new e.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
  2351. }, _doProcessBlock: function (d, e) {
  2352. for (var b = this._hash.words, n = b[0], j = b[1], h = b[2], g = b[3], l = b[4], a = 0; 80 > a; a++) {
  2353. if (16 > a) m[a] = d[e + a] | 0;else {
  2354. var c = m[a - 3] ^ m[a - 8] ^ m[a - 14] ^ m[a - 16];m[a] = c << 1 | c >>> 31;
  2355. }c = (n << 5 | n >>> 27) + l + m[a];c = 20 > a ? c + ((j & h | ~j & g) + 1518500249) : 40 > a ? c + ((j ^ h ^ g) + 1859775393) : 60 > a ? c + ((j & h | j & g | h & g) - 1894007588) : c + ((j ^ h ^ g) - 899497514);l = g;g = h;h = j << 30 | j >>> 2;j = n;n = c;
  2356. }b[0] = b[0] + n | 0;b[1] = b[1] + j | 0;b[2] = b[2] + h | 0;b[3] = b[3] + g | 0;b[4] = b[4] + l | 0;
  2357. }, _doFinalize: function () {
  2358. var d = this._data,
  2359. e = d.words,
  2360. b = 8 * this._nDataBytes,
  2361. g = 8 * d.sigBytes;e[g >>> 5] |= 128 << 24 - g % 32;e[(g + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296);e[(g + 64 >>> 9 << 4) + 15] = b;d.sigBytes = 4 * e.length;this._process();return this._hash;
  2362. }, clone: function () {
  2363. var e = d.clone.call(this);e._hash = this._hash.clone();return e;
  2364. } });g.SHA1 = d._createHelper(l);g.HmacSHA1 = d._createHmacHelper(l);
  2365. })();
  2366. (function () {
  2367. var g = CryptoJS,
  2368. l = g.enc.Utf8;g.algo.HMAC = g.lib.Base.extend({ init: function (e, d) {
  2369. e = this._hasher = new e.init();"string" == typeof d && (d = l.parse(d));var g = e.blockSize,
  2370. k = 4 * g;d.sigBytes > k && (d = e.finalize(d));d.clamp();for (var p = this._oKey = d.clone(), b = this._iKey = d.clone(), n = p.words, j = b.words, h = 0; h < g; h++) n[h] ^= 1549556828, j[h] ^= 909522486;p.sigBytes = b.sigBytes = k;this.reset();
  2371. }, reset: function () {
  2372. var e = this._hasher;e.reset();e.update(this._iKey);
  2373. }, update: function (e) {
  2374. this._hasher.update(e);return this;
  2375. }, finalize: function (e) {
  2376. var d = this._hasher;e = d.finalize(e);d.reset();return d.finalize(this._oKey.clone().concat(e));
  2377. } });
  2378. })();
  2379.  
  2380. (function () {
  2381. // Shortcuts
  2382. var C = CryptoJS;
  2383. var C_lib = C.lib;
  2384. var WordArray = C_lib.WordArray;
  2385. var C_enc = C.enc;
  2386.  
  2387. /**
  2388. * Base64 encoding strategy.
  2389. */
  2390. var Base64 = C_enc.Base64 = {
  2391. /**
  2392. * Converts a word array to a Base64 string.
  2393. *
  2394. * @param {WordArray} wordArray The word array.
  2395. *
  2396. * @return {string} The Base64 string.
  2397. *
  2398. * @static
  2399. *
  2400. * @example
  2401. *
  2402. * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
  2403. */
  2404. stringify: function (wordArray) {
  2405. // Shortcuts
  2406. var words = wordArray.words;
  2407. var sigBytes = wordArray.sigBytes;
  2408. var map = this._map;
  2409.  
  2410. // Clamp excess bits
  2411. wordArray.clamp();
  2412.  
  2413. // Convert
  2414. var base64Chars = [];
  2415. for (var i = 0; i < sigBytes; i += 3) {
  2416. var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
  2417. var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 0xff;
  2418. var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 0xff;
  2419.  
  2420. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  2421.  
  2422. for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) {
  2423. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 0x3f));
  2424. }
  2425. }
  2426.  
  2427. // Add padding
  2428. var paddingChar = map.charAt(64);
  2429. if (paddingChar) {
  2430. while (base64Chars.length % 4) {
  2431. base64Chars.push(paddingChar);
  2432. }
  2433. }
  2434.  
  2435. return base64Chars.join('');
  2436. },
  2437.  
  2438. /**
  2439. * Converts a Base64 string to a word array.
  2440. *
  2441. * @param {string} base64Str The Base64 string.
  2442. *
  2443. * @return {WordArray} The word array.
  2444. *
  2445. * @static
  2446. *
  2447. * @example
  2448. *
  2449. * var wordArray = CryptoJS.enc.Base64.parse(base64String);
  2450. */
  2451. parse: function (base64Str) {
  2452. // Shortcuts
  2453. var base64StrLength = base64Str.length;
  2454. var map = this._map;
  2455.  
  2456. // Ignore padding
  2457. var paddingChar = map.charAt(64);
  2458. if (paddingChar) {
  2459. var paddingIndex = base64Str.indexOf(paddingChar);
  2460. if (paddingIndex != -1) {
  2461. base64StrLength = paddingIndex;
  2462. }
  2463. }
  2464.  
  2465. // Convert
  2466. var words = [];
  2467. var nBytes = 0;
  2468. for (var i = 0; i < base64StrLength; i++) {
  2469. if (i % 4) {
  2470. var bits1 = map.indexOf(base64Str.charAt(i - 1)) << i % 4 * 2;
  2471. var bits2 = map.indexOf(base64Str.charAt(i)) >>> 6 - i % 4 * 2;
  2472. words[nBytes >>> 2] |= (bits1 | bits2) << 24 - nBytes % 4 * 8;
  2473. nBytes++;
  2474. }
  2475. }
  2476.  
  2477. return WordArray.create(words, nBytes);
  2478. },
  2479.  
  2480. _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  2481. };
  2482. })();
  2483.  
  2484. if (true) {
  2485. module.exports = CryptoJS;
  2486. } else {
  2487. window.CryptoJS = CryptoJS;
  2488. }
  2489.  
  2490. /***/ }),
  2491. /* 7 */
  2492. /***/ (function(module, exports, __webpack_require__) {
  2493.  
  2494. /* Copyright 2015 William Summers, MetaTribal LLC
  2495. * adapted from https://developer.mozilla.org/en-US/docs/JXON
  2496. *
  2497. * Licensed under the MIT License, Version 2.0 (the "License");
  2498. * you may not use this file except in compliance with the License.
  2499. * You may obtain a copy of the License at
  2500. *
  2501. * https://opensource.org/licenses/MIT
  2502. *
  2503. * Unless required by applicable law or agreed to in writing, software
  2504. * distributed under the License is distributed on an "AS IS" BASIS,
  2505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2506. * See the License for the specific language governing permissions and
  2507. * limitations under the License.
  2508. */
  2509. /**
  2510. * @author William Summers
  2511. * https://github.com/metatribal/xmlToJSON
  2512. */
  2513. var DOMParser = __webpack_require__(8).DOMParser;
  2514.  
  2515. var xmlToJSON = function () {
  2516.  
  2517. this.version = "1.3.5";
  2518.  
  2519. var options = { // set up the default options
  2520. mergeCDATA: true, // extract cdata and merge with text
  2521. normalize: true, // collapse multiple spaces to single space
  2522. stripElemPrefix: true // for elements of same name in diff namespaces, you can enable namespaces and access the nskey property
  2523. };
  2524.  
  2525. var prefixMatch = new RegExp(/(?!xmlns)^.*:/);
  2526. var trimMatch = new RegExp(/^\s+|\s+$/g);
  2527.  
  2528. this.grokType = function (sValue) {
  2529. if (/^\s*$/.test(sValue)) {
  2530. return null;
  2531. }
  2532. if (/^(?:true|false)$/i.test(sValue)) {
  2533. return sValue.toLowerCase() === "true";
  2534. }
  2535. if (isFinite(sValue)) {
  2536. return parseFloat(sValue);
  2537. }
  2538. return sValue;
  2539. };
  2540.  
  2541. this.parseString = function (xmlString, opt) {
  2542. if (xmlString) {
  2543. var xml = this.stringToXML(xmlString);
  2544. if (xml.getElementsByTagName('parsererror').length) {
  2545. return null;
  2546. } else {
  2547. return this.parseXML(xml, opt);
  2548. }
  2549. } else {
  2550. return null;
  2551. }
  2552. };
  2553.  
  2554. this.parseXML = function (oXMLParent, opt) {
  2555.  
  2556. // initialize options
  2557. for (var key in opt) {
  2558. options[key] = opt[key];
  2559. }
  2560.  
  2561. var vResult = {},
  2562. nLength = 0,
  2563. sCollectedTxt = "";
  2564.  
  2565. // iterate over the children
  2566. var childNum = oXMLParent.childNodes.length;
  2567. if (childNum) {
  2568. for (var oNode, sProp, vContent, nItem = 0; nItem < oXMLParent.childNodes.length; nItem++) {
  2569. oNode = oXMLParent.childNodes.item(nItem);
  2570.  
  2571. if (oNode.nodeType === 4) {
  2572. if (options.mergeCDATA) {
  2573. sCollectedTxt += oNode.nodeValue;
  2574. }
  2575. } /* nodeType is "CDATASection" (4) */
  2576. else if (oNode.nodeType === 3) {
  2577. sCollectedTxt += oNode.nodeValue;
  2578. } /* nodeType is "Text" (3) */
  2579. else if (oNode.nodeType === 1) {
  2580. /* nodeType is "Element" (1) */
  2581.  
  2582. if (nLength === 0) {
  2583. vResult = {};
  2584. }
  2585.  
  2586. // using nodeName to support browser (IE) implementation with no 'localName' property
  2587. if (options.stripElemPrefix) {
  2588. sProp = oNode.nodeName.replace(prefixMatch, '');
  2589. } else {
  2590. sProp = oNode.nodeName;
  2591. }
  2592.  
  2593. vContent = xmlToJSON.parseXML(oNode);
  2594.  
  2595. if (vResult.hasOwnProperty(sProp)) {
  2596. if (vResult[sProp].constructor !== Array) {
  2597. vResult[sProp] = [vResult[sProp]];
  2598. }
  2599. vResult[sProp].push(vContent);
  2600. } else {
  2601. vResult[sProp] = vContent;
  2602. nLength++;
  2603. }
  2604. }
  2605. }
  2606. }
  2607.  
  2608. if (!Object.keys(vResult).length) {
  2609. // vResult = sCollectedTxt.replace(trimMatch, '') || ''; // by carsonxu 修复 getBucket返回的 Key 是 " /" 这种场景
  2610. vResult = sCollectedTxt || '';
  2611. }
  2612.  
  2613. return vResult;
  2614. };
  2615.  
  2616. // Convert xmlDocument to a string
  2617. // Returns null on failure
  2618. this.xmlToString = function (xmlDoc) {
  2619. try {
  2620. var xmlString = xmlDoc.xml ? xmlDoc.xml : new XMLSerializer().serializeToString(xmlDoc);
  2621. return xmlString;
  2622. } catch (err) {
  2623. return null;
  2624. }
  2625. };
  2626.  
  2627. // Convert a string to XML Node Structure
  2628. // Returns null on failure
  2629. this.stringToXML = function (xmlString) {
  2630. try {
  2631. var xmlDoc = null;
  2632.  
  2633. if (window.DOMParser) {
  2634.  
  2635. var parser = new DOMParser();
  2636. xmlDoc = parser.parseFromString(xmlString, "text/xml");
  2637.  
  2638. return xmlDoc;
  2639. } else {
  2640. xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  2641. xmlDoc.async = false;
  2642. xmlDoc.loadXML(xmlString);
  2643.  
  2644. return xmlDoc;
  2645. }
  2646. } catch (e) {
  2647. return null;
  2648. }
  2649. };
  2650.  
  2651. return this;
  2652. }.call({});
  2653.  
  2654. var xml2json = function (xmlString) {
  2655. return xmlToJSON.parseString(xmlString);
  2656. };
  2657.  
  2658. module.exports = xml2json;
  2659.  
  2660. /***/ }),
  2661. /* 8 */
  2662. /***/ (function(module, exports, __webpack_require__) {
  2663.  
  2664. function DOMParser(options){
  2665. this.options = options ||{locator:{}};
  2666. }
  2667. DOMParser.prototype.parseFromString = function(source,mimeType){
  2668. var options = this.options;
  2669. var sax = new XMLReader();
  2670. var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
  2671. var errorHandler = options.errorHandler;
  2672. var locator = options.locator;
  2673. var defaultNSMap = options.xmlns||{};
  2674. var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
  2675. if(locator){
  2676. domBuilder.setDocumentLocator(locator)
  2677. }
  2678. sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
  2679. sax.domBuilder = options.domBuilder || domBuilder;
  2680. if(/\/x?html?$/.test(mimeType)){
  2681. entityMap.nbsp = '\xa0';
  2682. entityMap.copy = '\xa9';
  2683. defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
  2684. }
  2685. defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
  2686. if(source){
  2687. sax.parse(source,defaultNSMap,entityMap);
  2688. }else{
  2689. sax.errorHandler.error("invalid doc source");
  2690. }
  2691. return domBuilder.doc;
  2692. }
  2693. function buildErrorHandler(errorImpl,domBuilder,locator){
  2694. if(!errorImpl){
  2695. if(domBuilder instanceof DOMHandler){
  2696. return domBuilder;
  2697. }
  2698. errorImpl = domBuilder ;
  2699. }
  2700. var errorHandler = {}
  2701. var isCallback = errorImpl instanceof Function;
  2702. locator = locator||{}
  2703. function build(key){
  2704. var fn = errorImpl[key];
  2705. if(!fn && isCallback){
  2706. fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
  2707. }
  2708. errorHandler[key] = fn && function(msg){
  2709. fn('[xmldom '+key+']\t'+msg+_locator(locator));
  2710. }||function(){};
  2711. }
  2712. build('warning');
  2713. build('error');
  2714. build('fatalError');
  2715. return errorHandler;
  2716. }
  2717.  
  2718. //console.log('#\n\n\n\n\n\n\n####')
  2719. /**
  2720. * +ContentHandler+ErrorHandler
  2721. * +LexicalHandler+EntityResolver2
  2722. * -DeclHandler-DTDHandler
  2723. *
  2724. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  2725. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  2726. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  2727. */
  2728. function DOMHandler() {
  2729. this.cdata = false;
  2730. }
  2731. function position(locator,node){
  2732. node.lineNumber = locator.lineNumber;
  2733. node.columnNumber = locator.columnNumber;
  2734. }
  2735. /**
  2736. * @see org.xml.sax.ContentHandler#startDocument
  2737. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  2738. */
  2739. DOMHandler.prototype = {
  2740. startDocument : function() {
  2741. this.doc = new DOMImplementation().createDocument(null, null, null);
  2742. if (this.locator) {
  2743. this.doc.documentURI = this.locator.systemId;
  2744. }
  2745. },
  2746. startElement:function(namespaceURI, localName, qName, attrs) {
  2747. var doc = this.doc;
  2748. var el = doc.createElementNS(namespaceURI, qName||localName);
  2749. var len = attrs.length;
  2750. appendElement(this, el);
  2751. this.currentElement = el;
  2752. this.locator && position(this.locator,el)
  2753. for (var i = 0 ; i < len; i++) {
  2754. var namespaceURI = attrs.getURI(i);
  2755. var value = attrs.getValue(i);
  2756. var qName = attrs.getQName(i);
  2757. var attr = doc.createAttributeNS(namespaceURI, qName);
  2758. this.locator &&position(attrs.getLocator(i),attr);
  2759. attr.value = attr.nodeValue = value;
  2760. el.setAttributeNode(attr)
  2761. }
  2762. },
  2763. endElement:function(namespaceURI, localName, qName) {
  2764. var current = this.currentElement
  2765. var tagName = current.tagName;
  2766. this.currentElement = current.parentNode;
  2767. },
  2768. startPrefixMapping:function(prefix, uri) {
  2769. },
  2770. endPrefixMapping:function(prefix) {
  2771. },
  2772. processingInstruction:function(target, data) {
  2773. var ins = this.doc.createProcessingInstruction(target, data);
  2774. this.locator && position(this.locator,ins)
  2775. appendElement(this, ins);
  2776. },
  2777. ignorableWhitespace:function(ch, start, length) {
  2778. },
  2779. characters:function(chars, start, length) {
  2780. chars = _toString.apply(this,arguments)
  2781. //console.log(chars)
  2782. if(chars){
  2783. if (this.cdata) {
  2784. var charNode = this.doc.createCDATASection(chars);
  2785. } else {
  2786. var charNode = this.doc.createTextNode(chars);
  2787. }
  2788. if(this.currentElement){
  2789. this.currentElement.appendChild(charNode);
  2790. }else if(/^\s*$/.test(chars)){
  2791. this.doc.appendChild(charNode);
  2792. //process xml
  2793. }
  2794. this.locator && position(this.locator,charNode)
  2795. }
  2796. },
  2797. skippedEntity:function(name) {
  2798. },
  2799. endDocument:function() {
  2800. this.doc.normalize();
  2801. },
  2802. setDocumentLocator:function (locator) {
  2803. if(this.locator = locator){// && !('lineNumber' in locator)){
  2804. locator.lineNumber = 0;
  2805. }
  2806. },
  2807. //LexicalHandler
  2808. comment:function(chars, start, length) {
  2809. chars = _toString.apply(this,arguments)
  2810. var comm = this.doc.createComment(chars);
  2811. this.locator && position(this.locator,comm)
  2812. appendElement(this, comm);
  2813. },
  2814. startCDATA:function() {
  2815. //used in characters() methods
  2816. this.cdata = true;
  2817. },
  2818. endCDATA:function() {
  2819. this.cdata = false;
  2820. },
  2821. startDTD:function(name, publicId, systemId) {
  2822. var impl = this.doc.implementation;
  2823. if (impl && impl.createDocumentType) {
  2824. var dt = impl.createDocumentType(name, publicId, systemId);
  2825. this.locator && position(this.locator,dt)
  2826. appendElement(this, dt);
  2827. }
  2828. },
  2829. /**
  2830. * @see org.xml.sax.ErrorHandler
  2831. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  2832. */
  2833. warning:function(error) {
  2834. console.warn('[xmldom warning]\t'+error,_locator(this.locator));
  2835. },
  2836. error:function(error) {
  2837. console.error('[xmldom error]\t'+error,_locator(this.locator));
  2838. },
  2839. fatalError:function(error) {
  2840. console.error('[xmldom fatalError]\t'+error,_locator(this.locator));
  2841. throw error;
  2842. }
  2843. }
  2844. function _locator(l){
  2845. if(l){
  2846. return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
  2847. }
  2848. }
  2849. function _toString(chars,start,length){
  2850. if(typeof chars == 'string'){
  2851. return chars.substr(start,length)
  2852. }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  2853. if(chars.length >= start+length || start){
  2854. return new java.lang.String(chars,start,length)+'';
  2855. }
  2856. return chars;
  2857. }
  2858. }
  2859.  
  2860. /*
  2861. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  2862. * used method of org.xml.sax.ext.LexicalHandler:
  2863. * #comment(chars, start, length)
  2864. * #startCDATA()
  2865. * #endCDATA()
  2866. * #startDTD(name, publicId, systemId)
  2867. *
  2868. *
  2869. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  2870. * #endDTD()
  2871. * #startEntity(name)
  2872. * #endEntity(name)
  2873. *
  2874. *
  2875. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  2876. * IGNORED method of org.xml.sax.ext.DeclHandler
  2877. * #attributeDecl(eName, aName, type, mode, value)
  2878. * #elementDecl(name, model)
  2879. * #externalEntityDecl(name, publicId, systemId)
  2880. * #internalEntityDecl(name, value)
  2881. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  2882. * IGNORED method of org.xml.sax.EntityResolver2
  2883. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  2884. * #resolveEntity(publicId, systemId)
  2885. * #getExternalSubset(name, baseURI)
  2886. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  2887. * IGNORED method of org.xml.sax.DTDHandler
  2888. * #notationDecl(name, publicId, systemId) {};
  2889. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  2890. */
  2891. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
  2892. DOMHandler.prototype[key] = function(){return null}
  2893. })
  2894.  
  2895. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  2896. function appendElement (hander,node) {
  2897. if (!hander.currentElement) {
  2898. hander.doc.appendChild(node);
  2899. } else {
  2900. hander.currentElement.appendChild(node);
  2901. }
  2902. }//appendChild and setAttributeNS are preformance key
  2903.  
  2904. //if(typeof require == 'function'){
  2905. var XMLReader = __webpack_require__(9).XMLReader;
  2906. var DOMImplementation = exports.DOMImplementation = __webpack_require__(1).DOMImplementation;
  2907. exports.XMLSerializer = __webpack_require__(1).XMLSerializer ;
  2908. exports.DOMParser = DOMParser;
  2909. //}
  2910.  
  2911.  
  2912. /***/ }),
  2913. /* 9 */
  2914. /***/ (function(module, exports) {
  2915.  
  2916. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  2917. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  2918. //[5] Name ::= NameStartChar (NameChar)*
  2919. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
  2920. var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  2921. var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
  2922. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  2923. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  2924.  
  2925. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  2926. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  2927. var S_TAG = 0;//tag name offerring
  2928. var S_ATTR = 1;//attr name offerring
  2929. var S_ATTR_SPACE=2;//attr name end and space offer
  2930. var S_EQ = 3;//=space?
  2931. var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
  2932. var S_ATTR_END = 5;//attr value end and no space(quot end)
  2933. var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
  2934. var S_TAG_CLOSE = 7;//closed el<el />
  2935.  
  2936. function XMLReader(){
  2937. }
  2938.  
  2939. XMLReader.prototype = {
  2940. parse:function(source,defaultNSMap,entityMap){
  2941. var domBuilder = this.domBuilder;
  2942. domBuilder.startDocument();
  2943. _copy(defaultNSMap ,defaultNSMap = {})
  2944. parse(source,defaultNSMap,entityMap,
  2945. domBuilder,this.errorHandler);
  2946. domBuilder.endDocument();
  2947. }
  2948. }
  2949. function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
  2950. function fixedFromCharCode(code) {
  2951. // String.prototype.fromCharCode does not supports
  2952. // > 2 bytes unicode chars directly
  2953. if (code > 0xffff) {
  2954. code -= 0x10000;
  2955. var surrogate1 = 0xd800 + (code >> 10)
  2956. , surrogate2 = 0xdc00 + (code & 0x3ff);
  2957.  
  2958. return String.fromCharCode(surrogate1, surrogate2);
  2959. } else {
  2960. return String.fromCharCode(code);
  2961. }
  2962. }
  2963. function entityReplacer(a){
  2964. var k = a.slice(1,-1);
  2965. if(k in entityMap){
  2966. return entityMap[k];
  2967. }else if(k.charAt(0) === '#'){
  2968. return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
  2969. }else{
  2970. errorHandler.error('entity not found:'+a);
  2971. return a;
  2972. }
  2973. }
  2974. function appendText(end){//has some bugs
  2975. if(end>start){
  2976. var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
  2977. locator&&position(start);
  2978. domBuilder.characters(xt,0,end-start);
  2979. start = end
  2980. }
  2981. }
  2982. function position(p,m){
  2983. while(p>=lineEnd && (m = linePattern.exec(source))){
  2984. lineStart = m.index;
  2985. lineEnd = lineStart + m[0].length;
  2986. locator.lineNumber++;
  2987. //console.log('line++:',locator,startPos,endPos)
  2988. }
  2989. locator.columnNumber = p-lineStart+1;
  2990. }
  2991. var lineStart = 0;
  2992. var lineEnd = 0;
  2993. var linePattern = /.*(?:\r\n?|\n)|.*$/g
  2994. var locator = domBuilder.locator;
  2995. var parseStack = [{currentNSMap:defaultNSMapCopy}]
  2996. var closeMap = {};
  2997. var start = 0;
  2998. while(true){
  2999. try{
  3000. var tagStart = source.indexOf('<',start);
  3001. if(tagStart<0){
  3002. if(!source.substr(start).match(/^\s*$/)){
  3003. var doc = domBuilder.doc;
  3004. var text = doc.createTextNode(source.substr(start));
  3005. doc.appendChild(text);
  3006. domBuilder.currentElement = text;
  3007. }
  3008. return;
  3009. }
  3010. if(tagStart>start){
  3011. appendText(tagStart);
  3012. }
  3013. switch(source.charAt(tagStart+1)){
  3014. case '/':
  3015. var end = source.indexOf('>',tagStart+3);
  3016. var tagName = source.substring(tagStart+2,end);
  3017. var config = parseStack.pop();
  3018. if(end<0){
  3019. tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
  3020. //console.error('#@@@@@@'+tagName)
  3021. errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
  3022. end = tagStart+1+tagName.length;
  3023. }else if(tagName.match(/\s</)){
  3024. tagName = tagName.replace(/[\s<].*/,'');
  3025. errorHandler.error("end tag name: "+tagName+' maybe not complete');
  3026. end = tagStart+1+tagName.length;
  3027. }
  3028. //console.error(parseStack.length,parseStack)
  3029. //console.error(config);
  3030. var localNSMap = config.localNSMap;
  3031. var endMatch = config.tagName == tagName;
  3032. var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
  3033. if(endIgnoreCaseMach){
  3034. domBuilder.endElement(config.uri,config.localName,tagName);
  3035. if(localNSMap){
  3036. for(var prefix in localNSMap){
  3037. domBuilder.endPrefixMapping(prefix) ;
  3038. }
  3039. }
  3040. if(!endMatch){
  3041. errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
  3042. }
  3043. }else{
  3044. parseStack.push(config)
  3045. }
  3046. end++;
  3047. break;
  3048. // end elment
  3049. case '?':// <?...?>
  3050. locator&&position(tagStart);
  3051. end = parseInstruction(source,tagStart,domBuilder);
  3052. break;
  3053. case '!':// <!doctype,<![CDATA,<!--
  3054. locator&&position(tagStart);
  3055. end = parseDCC(source,tagStart,domBuilder,errorHandler);
  3056. break;
  3057. default:
  3058. locator&&position(tagStart);
  3059. var el = new ElementAttributes();
  3060. var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  3061. //elStartEnd
  3062. var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
  3063. var len = el.length;
  3064. if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
  3065. el.closed = true;
  3066. if(!entityMap.nbsp){
  3067. errorHandler.warning('unclosed xml attribute');
  3068. }
  3069. }
  3070. if(locator && len){
  3071. var locator2 = copyLocator(locator,{});
  3072. //try{//attribute position fixed
  3073. for(var i = 0;i<len;i++){
  3074. var a = el[i];
  3075. position(a.offset);
  3076. a.locator = copyLocator(locator,{});
  3077. }
  3078. //}catch(e){console.error('@@@@@'+e)}
  3079. domBuilder.locator = locator2
  3080. if(appendElement(el,domBuilder,currentNSMap)){
  3081. parseStack.push(el)
  3082. }
  3083. domBuilder.locator = locator;
  3084. }else{
  3085. if(appendElement(el,domBuilder,currentNSMap)){
  3086. parseStack.push(el)
  3087. }
  3088. }
  3089. if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
  3090. end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
  3091. }else{
  3092. end++;
  3093. }
  3094. }
  3095. }catch(e){
  3096. errorHandler.error('element parse error: '+e)
  3097. //errorHandler.error('element parse error: '+e);
  3098. end = -1;
  3099. //throw e;
  3100. }
  3101. if(end>start){
  3102. start = end;
  3103. }else{
  3104. //TODO: 这里有可能sax回退,有位置错误风险
  3105. appendText(Math.max(tagStart,start)+1);
  3106. }
  3107. }
  3108. }
  3109. function copyLocator(f,t){
  3110. t.lineNumber = f.lineNumber;
  3111. t.columnNumber = f.columnNumber;
  3112. return t;
  3113. }
  3114.  
  3115. /**
  3116. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  3117. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  3118. */
  3119. function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
  3120. var attrName;
  3121. var value;
  3122. var p = ++start;
  3123. var s = S_TAG;//status
  3124. while(true){
  3125. var c = source.charAt(p);
  3126. switch(c){
  3127. case '=':
  3128. if(s === S_ATTR){//attrName
  3129. attrName = source.slice(start,p);
  3130. s = S_EQ;
  3131. }else if(s === S_ATTR_SPACE){
  3132. s = S_EQ;
  3133. }else{
  3134. //fatalError: equal must after attrName or space after attrName
  3135. throw new Error('attribute equal must after attrName');
  3136. }
  3137. break;
  3138. case '\'':
  3139. case '"':
  3140. if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  3141. ){//equal
  3142. if(s === S_ATTR){
  3143. errorHandler.warning('attribute value must after "="')
  3144. attrName = source.slice(start,p)
  3145. }
  3146. start = p+1;
  3147. p = source.indexOf(c,start)
  3148. if(p>0){
  3149. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  3150. el.add(attrName,value,start-1);
  3151. s = S_ATTR_END;
  3152. }else{
  3153. //fatalError: no end quot match
  3154. throw new Error('attribute value no end \''+c+'\' match');
  3155. }
  3156. }else if(s == S_ATTR_NOQUOT_VALUE){
  3157. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  3158. //console.log(attrName,value,start,p)
  3159. el.add(attrName,value,start);
  3160. //console.dir(el)
  3161. errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
  3162. start = p+1;
  3163. s = S_ATTR_END
  3164. }else{
  3165. //fatalError: no equal before
  3166. throw new Error('attribute value must after "="');
  3167. }
  3168. break;
  3169. case '/':
  3170. switch(s){
  3171. case S_TAG:
  3172. el.setTagName(source.slice(start,p));
  3173. case S_ATTR_END:
  3174. case S_TAG_SPACE:
  3175. case S_TAG_CLOSE:
  3176. s =S_TAG_CLOSE;
  3177. el.closed = true;
  3178. case S_ATTR_NOQUOT_VALUE:
  3179. case S_ATTR:
  3180. case S_ATTR_SPACE:
  3181. break;
  3182. //case S_EQ:
  3183. default:
  3184. throw new Error("attribute invalid close char('/')")
  3185. }
  3186. break;
  3187. case ''://end document
  3188. //throw new Error('unexpected end of input')
  3189. errorHandler.error('unexpected end of input');
  3190. if(s == S_TAG){
  3191. el.setTagName(source.slice(start,p));
  3192. }
  3193. return p;
  3194. case '>':
  3195. switch(s){
  3196. case S_TAG:
  3197. el.setTagName(source.slice(start,p));
  3198. case S_ATTR_END:
  3199. case S_TAG_SPACE:
  3200. case S_TAG_CLOSE:
  3201. break;//normal
  3202. case S_ATTR_NOQUOT_VALUE://Compatible state
  3203. case S_ATTR:
  3204. value = source.slice(start,p);
  3205. if(value.slice(-1) === '/'){
  3206. el.closed = true;
  3207. value = value.slice(0,-1)
  3208. }
  3209. case S_ATTR_SPACE:
  3210. if(s === S_ATTR_SPACE){
  3211. value = attrName;
  3212. }
  3213. if(s == S_ATTR_NOQUOT_VALUE){
  3214. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  3215. el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
  3216. }else{
  3217. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
  3218. errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
  3219. }
  3220. el.add(value,value,start)
  3221. }
  3222. break;
  3223. case S_EQ:
  3224. throw new Error('attribute value missed!!');
  3225. }
  3226. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  3227. return p;
  3228. /*xml space '\x20' | #x9 | #xD | #xA; */
  3229. case '\u0080':
  3230. c = ' ';
  3231. default:
  3232. if(c<= ' '){//space
  3233. switch(s){
  3234. case S_TAG:
  3235. el.setTagName(source.slice(start,p));//tagName
  3236. s = S_TAG_SPACE;
  3237. break;
  3238. case S_ATTR:
  3239. attrName = source.slice(start,p)
  3240. s = S_ATTR_SPACE;
  3241. break;
  3242. case S_ATTR_NOQUOT_VALUE:
  3243. var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  3244. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  3245. el.add(attrName,value,start)
  3246. case S_ATTR_END:
  3247. s = S_TAG_SPACE;
  3248. break;
  3249. //case S_TAG_SPACE:
  3250. //case S_EQ:
  3251. //case S_ATTR_SPACE:
  3252. // void();break;
  3253. //case S_TAG_CLOSE:
  3254. //ignore warning
  3255. }
  3256. }else{//not space
  3257. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  3258. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  3259. switch(s){
  3260. //case S_TAG:void();break;
  3261. //case S_ATTR:void();break;
  3262. //case S_ATTR_NOQUOT_VALUE:void();break;
  3263. case S_ATTR_SPACE:
  3264. var tagName = el.tagName;
  3265. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
  3266. errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
  3267. }
  3268. el.add(attrName,attrName,start);
  3269. start = p;
  3270. s = S_ATTR;
  3271. break;
  3272. case S_ATTR_END:
  3273. errorHandler.warning('attribute space is required"'+attrName+'"!!')
  3274. case S_TAG_SPACE:
  3275. s = S_ATTR;
  3276. start = p;
  3277. break;
  3278. case S_EQ:
  3279. s = S_ATTR_NOQUOT_VALUE;
  3280. start = p;
  3281. break;
  3282. case S_TAG_CLOSE:
  3283. throw new Error("elements closed character '/' and '>' must be connected to");
  3284. }
  3285. }
  3286. }//end outer switch
  3287. //console.log('p++',p)
  3288. p++;
  3289. }
  3290. }
  3291. /**
  3292. * @return true if has new namespace define
  3293. */
  3294. function appendElement(el,domBuilder,currentNSMap){
  3295. var tagName = el.tagName;
  3296. var localNSMap = null;
  3297. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  3298. var i = el.length;
  3299. while(i--){
  3300. var a = el[i];
  3301. var qName = a.qName;
  3302. var value = a.value;
  3303. var nsp = qName.indexOf(':');
  3304. if(nsp>0){
  3305. var prefix = a.prefix = qName.slice(0,nsp);
  3306. var localName = qName.slice(nsp+1);
  3307. var nsPrefix = prefix === 'xmlns' && localName
  3308. }else{
  3309. localName = qName;
  3310. prefix = null
  3311. nsPrefix = qName === 'xmlns' && ''
  3312. }
  3313. //can not set prefix,because prefix !== ''
  3314. a.localName = localName ;
  3315. //prefix == null for no ns prefix attribute
  3316. if(nsPrefix !== false){//hack!!
  3317. if(localNSMap == null){
  3318. localNSMap = {}
  3319. //console.log(currentNSMap,0)
  3320. _copy(currentNSMap,currentNSMap={})
  3321. //console.log(currentNSMap,1)
  3322. }
  3323. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  3324. a.uri = 'http://www.w3.org/2000/xmlns/'
  3325. domBuilder.startPrefixMapping(nsPrefix, value)
  3326. }
  3327. }
  3328. var i = el.length;
  3329. while(i--){
  3330. a = el[i];
  3331. var prefix = a.prefix;
  3332. if(prefix){//no prefix attribute has no namespace
  3333. if(prefix === 'xml'){
  3334. a.uri = 'http://www.w3.org/XML/1998/namespace';
  3335. }if(prefix !== 'xmlns'){
  3336. a.uri = currentNSMap[prefix || '']
  3337. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  3338. }
  3339. }
  3340. }
  3341. var nsp = tagName.indexOf(':');
  3342. if(nsp>0){
  3343. prefix = el.prefix = tagName.slice(0,nsp);
  3344. localName = el.localName = tagName.slice(nsp+1);
  3345. }else{
  3346. prefix = null;//important!!
  3347. localName = el.localName = tagName;
  3348. }
  3349. //no prefix element has default namespace
  3350. var ns = el.uri = currentNSMap[prefix || ''];
  3351. domBuilder.startElement(ns,localName,tagName,el);
  3352. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  3353. //localNSMap = null
  3354. if(el.closed){
  3355. domBuilder.endElement(ns,localName,tagName);
  3356. if(localNSMap){
  3357. for(prefix in localNSMap){
  3358. domBuilder.endPrefixMapping(prefix)
  3359. }
  3360. }
  3361. }else{
  3362. el.currentNSMap = currentNSMap;
  3363. el.localNSMap = localNSMap;
  3364. //parseStack.push(el);
  3365. return true;
  3366. }
  3367. }
  3368. function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
  3369. if(/^(?:script|textarea)$/i.test(tagName)){
  3370. var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
  3371. var text = source.substring(elStartEnd+1,elEndStart);
  3372. if(/[&<]/.test(text)){
  3373. if(/^script$/i.test(tagName)){
  3374. //if(!/\]\]>/.test(text)){
  3375. //lexHandler.startCDATA();
  3376. domBuilder.characters(text,0,text.length);
  3377. //lexHandler.endCDATA();
  3378. return elEndStart;
  3379. //}
  3380. }//}else{//text area
  3381. text = text.replace(/&#?\w+;/g,entityReplacer);
  3382. domBuilder.characters(text,0,text.length);
  3383. return elEndStart;
  3384. //}
  3385. }
  3386. }
  3387. return elStartEnd+1;
  3388. }
  3389. function fixSelfClosed(source,elStartEnd,tagName,closeMap){
  3390. //if(tagName in closeMap){
  3391. var pos = closeMap[tagName];
  3392. if(pos == null){
  3393. //console.log(tagName)
  3394. pos = source.lastIndexOf('</'+tagName+'>')
  3395. if(pos<elStartEnd){//忘记闭合
  3396. pos = source.lastIndexOf('</'+tagName)
  3397. }
  3398. closeMap[tagName] =pos
  3399. }
  3400. return pos<elStartEnd;
  3401. //}
  3402. }
  3403. function _copy(source,target){
  3404. for(var n in source){target[n] = source[n]}
  3405. }
  3406. function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
  3407. var next= source.charAt(start+2)
  3408. switch(next){
  3409. case '-':
  3410. if(source.charAt(start + 3) === '-'){
  3411. var end = source.indexOf('-->',start+4);
  3412. //append comment source.substring(4,end)//<!--
  3413. if(end>start){
  3414. domBuilder.comment(source,start+4,end-start-4);
  3415. return end+3;
  3416. }else{
  3417. errorHandler.error("Unclosed comment");
  3418. return -1;
  3419. }
  3420. }else{
  3421. //error
  3422. return -1;
  3423. }
  3424. default:
  3425. if(source.substr(start+3,6) == 'CDATA['){
  3426. var end = source.indexOf(']]>',start+9);
  3427. domBuilder.startCDATA();
  3428. domBuilder.characters(source,start+9,end-start-9);
  3429. domBuilder.endCDATA()
  3430. return end+3;
  3431. }
  3432. //<!DOCTYPE
  3433. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  3434. var matchs = split(source,start);
  3435. var len = matchs.length;
  3436. if(len>1 && /!doctype/i.test(matchs[0][0])){
  3437. var name = matchs[1][0];
  3438. var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
  3439. var sysid = len>4 && matchs[4][0];
  3440. var lastMatch = matchs[len-1]
  3441. domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
  3442. sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
  3443. domBuilder.endDTD();
  3444. return lastMatch.index+lastMatch[0].length
  3445. }
  3446. }
  3447. return -1;
  3448. }
  3449.  
  3450.  
  3451.  
  3452. function parseInstruction(source,start,domBuilder){
  3453. var end = source.indexOf('?>',start);
  3454. if(end){
  3455. var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  3456. if(match){
  3457. var len = match[0].length;
  3458. domBuilder.processingInstruction(match[1], match[2]) ;
  3459. return end+2;
  3460. }else{//error
  3461. return -1;
  3462. }
  3463. }
  3464. return -1;
  3465. }
  3466.  
  3467. /**
  3468. * @param source
  3469. */
  3470. function ElementAttributes(source){
  3471. }
  3472. ElementAttributes.prototype = {
  3473. setTagName:function(tagName){
  3474. if(!tagNamePattern.test(tagName)){
  3475. throw new Error('invalid tagName:'+tagName)
  3476. }
  3477. this.tagName = tagName
  3478. },
  3479. add:function(qName,value,offset){
  3480. if(!tagNamePattern.test(qName)){
  3481. throw new Error('invalid attribute:'+qName)
  3482. }
  3483. this[this.length++] = {qName:qName,value:value,offset:offset}
  3484. },
  3485. length:0,
  3486. getLocalName:function(i){return this[i].localName},
  3487. getLocator:function(i){return this[i].locator},
  3488. getQName:function(i){return this[i].qName},
  3489. getURI:function(i){return this[i].uri},
  3490. getValue:function(i){return this[i].value}
  3491. // ,getIndex:function(uri, localName)){
  3492. // if(localName){
  3493. //
  3494. // }else{
  3495. // var qName = uri
  3496. // }
  3497. // },
  3498. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  3499. // getType:function(uri,localName){}
  3500. // getType:function(i){},
  3501. }
  3502.  
  3503.  
  3504.  
  3505.  
  3506. function _set_proto_(thiz,parent){
  3507. thiz.__proto__ = parent;
  3508. return thiz;
  3509. }
  3510. if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
  3511. _set_proto_ = function(thiz,parent){
  3512. function p(){};
  3513. p.prototype = parent;
  3514. p = new p();
  3515. for(parent in thiz){
  3516. p[parent] = thiz[parent];
  3517. }
  3518. return p;
  3519. }
  3520. }
  3521.  
  3522. function split(source,start){
  3523. var match;
  3524. var buf = [];
  3525. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  3526. reg.lastIndex = start;
  3527. reg.exec(source);//skip <
  3528. while(match = reg.exec(source)){
  3529. buf.push(match);
  3530. if(match[1])return buf;
  3531. }
  3532. }
  3533.  
  3534. exports.XMLReader = XMLReader;
  3535.  
  3536.  
  3537.  
  3538. /***/ }),
  3539. /* 10 */
  3540. /***/ (function(module, exports) {
  3541.  
  3542. //copyright Ryan Day 2010 <http://ryanday.org>, Joscha Feth 2013 <http://www.feth.com> [MIT Licensed]
  3543.  
  3544. var element_start_char = "a-zA-Z_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FFF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD";
  3545. var element_non_start_char = "\-.0-9\u00B7\u0300-\u036F\u203F\u2040";
  3546. var element_replace = new RegExp("^([^" + element_start_char + "])|^((x|X)(m|M)(l|L))|([^" + element_start_char + element_non_start_char + "])", "g");
  3547. var not_safe_in_xml = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm;
  3548.  
  3549. var objKeys = function (obj) {
  3550. var l = [];
  3551. if (obj instanceof Object) {
  3552. for (var k in obj) {
  3553. if (obj.hasOwnProperty(k)) {
  3554. l.push(k);
  3555. }
  3556. }
  3557. }
  3558. return l;
  3559. };
  3560. var process_to_xml = function (node_data, options) {
  3561.  
  3562. var makeNode = function (name, content, attributes, level, hasSubNodes) {
  3563. var indent_value = options.indent !== undefined ? options.indent : "\t";
  3564. var indent = options.prettyPrint ? '\n' + new Array(level).join(indent_value) : '';
  3565. if (options.removeIllegalNameCharacters) {
  3566. name = name.replace(element_replace, '_');
  3567. }
  3568.  
  3569. var node = [indent, '<', name, attributes || ''];
  3570. if (content && content.length > 0) {
  3571. node.push('>');
  3572. node.push(content);
  3573. hasSubNodes && node.push(indent);
  3574. node.push('</');
  3575. node.push(name);
  3576. node.push('>');
  3577. } else {
  3578. node.push('/>');
  3579. }
  3580. return node.join('');
  3581. };
  3582.  
  3583. return function fn(node_data, node_descriptor, level) {
  3584. var type = typeof node_data;
  3585. if (Array.isArray ? Array.isArray(node_data) : node_data instanceof Array) {
  3586. type = 'array';
  3587. } else if (node_data instanceof Date) {
  3588. type = 'date';
  3589. }
  3590.  
  3591. switch (type) {
  3592. //if value is an array create child nodes from values
  3593. case 'array':
  3594. var ret = [];
  3595. node_data.map(function (v) {
  3596. ret.push(fn(v, 1, level + 1));
  3597. //entries that are values of an array are the only ones that can be special node descriptors
  3598. });
  3599. options.prettyPrint && ret.push('\n');
  3600. return ret.join('');
  3601. break;
  3602.  
  3603. case 'date':
  3604. // cast dates to ISO 8601 date (soap likes it)
  3605. return node_data.toJSON ? node_data.toJSON() : node_data + '';
  3606. break;
  3607.  
  3608. case 'object':
  3609. var nodes = [];
  3610. for (var name in node_data) {
  3611. if (node_data.hasOwnProperty(name)) {
  3612. if (node_data[name] instanceof Array) {
  3613. for (var j = 0; j < node_data[name].length; j++) {
  3614. if (node_data[name].hasOwnProperty(j)) {
  3615. nodes.push(makeNode(name, fn(node_data[name][j], 0, level + 1), null, level + 1, objKeys(node_data[name][j]).length));
  3616. }
  3617. }
  3618. } else {
  3619. nodes.push(makeNode(name, fn(node_data[name], 0, level + 1), null, level + 1));
  3620. }
  3621. }
  3622. }
  3623. options.prettyPrint && nodes.length > 0 && nodes.push('\n');
  3624. return nodes.join('');
  3625. break;
  3626.  
  3627. case 'function':
  3628. return node_data();
  3629. break;
  3630.  
  3631. default:
  3632. return options.escape ? esc(node_data) : '' + node_data;
  3633. }
  3634. }(node_data, 0, 0);
  3635. };
  3636.  
  3637. var xml_header = function (standalone) {
  3638. var ret = ['<?xml version="1.0" encoding="UTF-8"'];
  3639.  
  3640. if (standalone) {
  3641. ret.push(' standalone="yes"');
  3642. }
  3643. ret.push('?>');
  3644.  
  3645. return ret.join('');
  3646. };
  3647.  
  3648. function esc(str) {
  3649. return ('' + str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(not_safe_in_xml, '');
  3650. }
  3651.  
  3652. module.exports = function (obj, options) {
  3653. if (!options) {
  3654. options = {
  3655. xmlHeader: {
  3656. standalone: true
  3657. },
  3658. prettyPrint: true,
  3659. indent: " ",
  3660. escape: true
  3661. };
  3662. }
  3663.  
  3664. if (typeof obj == 'string') {
  3665. try {
  3666. obj = JSON.parse(obj.toString());
  3667. } catch (e) {
  3668. return false;
  3669. }
  3670. }
  3671.  
  3672. var xmlheader = '';
  3673. var docType = '';
  3674. if (options) {
  3675. if (typeof options == 'object') {
  3676. // our config is an object
  3677.  
  3678. if (options.xmlHeader) {
  3679. // the user wants an xml header
  3680. xmlheader = xml_header(!!options.xmlHeader.standalone);
  3681. }
  3682.  
  3683. if (typeof options.docType != 'undefined') {
  3684. docType = '<!DOCTYPE ' + options.docType + '>';
  3685. }
  3686. } else {
  3687. // our config is a boolean value, so just add xml header
  3688. xmlheader = xml_header();
  3689. }
  3690. }
  3691. options = options || {};
  3692.  
  3693. var ret = [xmlheader, options.prettyPrint && docType ? '\n' : '', docType, process_to_xml(obj, options)];
  3694. return ret.join('').replace(/\n{2,}/g, '\n').replace(/\s+$/g, '');
  3695. };
  3696.  
  3697. /***/ }),
  3698. /* 11 */
  3699. /***/ (function(module, exports, __webpack_require__) {
  3700.  
  3701. var util = __webpack_require__(0);
  3702.  
  3703. var originApiMap = {};
  3704. var transferToTaskMethod = function (apiMap, apiName) {
  3705. originApiMap[apiName] = apiMap[apiName];
  3706. apiMap[apiName] = function (params, callback) {
  3707. if (params.SkipTask) {
  3708. originApiMap[apiName].call(this, params, callback);
  3709. } else {
  3710. this._addTask(apiName, params, callback);
  3711. }
  3712. };
  3713. };
  3714.  
  3715. var initTask = function (cos) {
  3716.  
  3717. var queue = [];
  3718. var tasks = {};
  3719. var uploadingFileCount = 0;
  3720. var nextUploadIndex = 0;
  3721.  
  3722. // 接口返回简略的任务信息
  3723. var formatTask = function (task) {
  3724. var t = {
  3725. id: task.id,
  3726. Bucket: task.Bucket,
  3727. Region: task.Region,
  3728. Key: task.Key,
  3729. FilePath: task.FilePath,
  3730. state: task.state,
  3731. loaded: task.loaded,
  3732. size: task.size,
  3733. speed: task.speed,
  3734. percent: task.percent,
  3735. hashPercent: task.hashPercent,
  3736. error: task.error
  3737. };
  3738. if (task.FilePath) t.FilePath = task.FilePath;
  3739. if (task._custom) t._custom = task._custom;
  3740. return t;
  3741. };
  3742.  
  3743. var emitListUpdate = function () {
  3744. var timer;
  3745. var emit = function () {
  3746. timer = 0;
  3747. cos.emit('task-list-update', { list: util.map(queue, formatTask) });
  3748. cos.emit('list-update', { list: util.map(queue, formatTask) });
  3749. };
  3750. return function () {
  3751. if (!timer) timer = setTimeout(emit);
  3752. };
  3753. }();
  3754.  
  3755. var clearQueue = function () {
  3756. if (queue.length <= cos.options.UploadQueueSize) return;
  3757. for (var i = 0; i < nextUploadIndex && // 小于当前操作的 index 才清理
  3758. i < queue.length && // 大于队列才清理
  3759. queue.length > cos.options.UploadQueueSize // 如果还太多,才继续清理
  3760. ;) {
  3761. var isActive = queue[i].state === 'waiting' || queue[i].state === 'checking' || queue[i].state === 'uploading';
  3762. if (!queue[i] || !isActive) {
  3763. tasks[queue[i].id] && delete tasks[queue[i].id];
  3764. queue.splice(i, 1);
  3765. nextUploadIndex--;
  3766. } else {
  3767. i++;
  3768. }
  3769. }
  3770. emitListUpdate();
  3771. };
  3772.  
  3773. var startNextTask = function () {
  3774. // 检查是否允许增加执行进程
  3775. if (uploadingFileCount >= cos.options.FileParallelLimit) return;
  3776. // 跳过不可执行的任务
  3777. while (queue[nextUploadIndex] && queue[nextUploadIndex].state !== 'waiting') nextUploadIndex++;
  3778. // 检查是否已遍历结束
  3779. if (nextUploadIndex >= queue.length) return;
  3780. // 上传该遍历到的任务
  3781. var task = queue[nextUploadIndex];
  3782. nextUploadIndex++;
  3783. uploadingFileCount++;
  3784. task.state = 'checking';
  3785. task.params.onTaskStart && task.params.onTaskStart(formatTask(task));
  3786. !task.params.UploadData && (task.params.UploadData = {});
  3787. var apiParams = util.formatParams(task.api, task.params);
  3788. originApiMap[task.api].call(cos, apiParams, function (err, data) {
  3789. if (!cos._isRunningTask(task.id)) return;
  3790. if (task.state === 'checking' || task.state === 'uploading') {
  3791. task.state = err ? 'error' : 'success';
  3792. err && (task.error = err);
  3793. uploadingFileCount--;
  3794. emitListUpdate();
  3795. startNextTask();
  3796. task.callback && task.callback(err, data);
  3797. if (task.state === 'success') {
  3798. if (task.params) {
  3799. delete task.params.UploadData;
  3800. delete task.params.Body;
  3801. delete task.params;
  3802. }
  3803. delete task.callback;
  3804. }
  3805. }
  3806. clearQueue();
  3807. });
  3808. emitListUpdate();
  3809. // 异步执行下一个任务
  3810. setTimeout(startNextTask);
  3811. };
  3812.  
  3813. var killTask = function (id, switchToState) {
  3814. var task = tasks[id];
  3815. if (!task) return;
  3816. var waiting = task && task.state === 'waiting';
  3817. var running = task && (task.state === 'checking' || task.state === 'uploading');
  3818. if (switchToState === 'canceled' && task.state !== 'canceled' || switchToState === 'paused' && waiting || switchToState === 'paused' && running) {
  3819. if (switchToState === 'paused' && task.params.Body && typeof task.params.Body.pipe === 'function') {
  3820. console.error('stream not support pause');
  3821. return;
  3822. }
  3823. task.state = switchToState;
  3824. cos.emit('inner-kill-task', { TaskId: id, toState: switchToState });
  3825. emitListUpdate();
  3826. if (running) {
  3827. uploadingFileCount--;
  3828. startNextTask();
  3829. }
  3830. if (switchToState === 'canceled') {
  3831. if (task.params) {
  3832. delete task.params.UploadData;
  3833. delete task.params.Body;
  3834. delete task.params;
  3835. }
  3836. delete task.callback;
  3837. }
  3838. }
  3839. clearQueue();
  3840. };
  3841.  
  3842. cos._addTasks = function (taskList) {
  3843. util.each(taskList, function (task) {
  3844. cos._addTask(task.api, task.params, task.callback, true);
  3845. });
  3846. emitListUpdate();
  3847. };
  3848.  
  3849. var isTaskReadyWarning = true;
  3850. cos._addTask = function (api, params, callback, ignoreAddEvent) {
  3851.  
  3852. // 复制参数对象
  3853. params = util.formatParams(api, params);
  3854.  
  3855. // 生成 id
  3856. var id = util.uuid();
  3857. params.TaskId = id;
  3858. params.onTaskReady && params.onTaskReady(id);
  3859. if (params.TaskReady) {
  3860. params.TaskReady(id);
  3861. isTaskReadyWarning && console.warn('warning: Param "TaskReady" has been deprecated. Please use "onTaskReady" instead.');
  3862. isTaskReadyWarning = false;
  3863. }
  3864.  
  3865. var task = {
  3866. // env
  3867. params: params,
  3868. callback: callback,
  3869. api: api,
  3870. index: queue.length,
  3871. // task
  3872. id: id,
  3873. Bucket: params.Bucket,
  3874. Region: params.Region,
  3875. Key: params.Key,
  3876. FilePath: params.FilePath || '',
  3877. state: 'waiting',
  3878. loaded: 0,
  3879. size: 0,
  3880. speed: 0,
  3881. percent: 0,
  3882. hashPercent: 0,
  3883. error: null,
  3884. _custom: params._custom
  3885. };
  3886. var onHashProgress = params.onHashProgress;
  3887. params.onHashProgress = function (info) {
  3888. if (!cos._isRunningTask(task.id)) return;
  3889. task.hashPercent = info.percent;
  3890. onHashProgress && onHashProgress(info);
  3891. emitListUpdate();
  3892. };
  3893. var onProgress = params.onProgress;
  3894. params.onProgress = function (info) {
  3895. if (!cos._isRunningTask(task.id)) return;
  3896. task.state === 'checking' && (task.state = 'uploading');
  3897. task.loaded = info.loaded;
  3898. task.speed = info.speed;
  3899. task.percent = info.percent;
  3900. onProgress && onProgress(info);
  3901. emitListUpdate();
  3902. };
  3903.  
  3904. // 异步获取 filesize
  3905. util.getFileSize(api, params, function (err, size) {
  3906. // 开始处理上传
  3907. if (err) {
  3908. // 如果获取大小出错,不加入队列
  3909. callback(err);
  3910. return;
  3911. }
  3912. // 获取完文件大小再把任务加入队列
  3913. tasks[id] = task;
  3914. queue.push(task);
  3915. task.size = size;
  3916. !ignoreAddEvent && emitListUpdate();
  3917. startNextTask();
  3918. clearQueue();
  3919. });
  3920. return id;
  3921. };
  3922. cos._isRunningTask = function (id) {
  3923. var task = tasks[id];
  3924. return !!(task && (task.state === 'checking' || task.state === 'uploading'));
  3925. };
  3926. cos.getTaskList = function () {
  3927. return util.map(queue, formatTask);
  3928. };
  3929. cos.cancelTask = function (id) {
  3930. var options = (typeof id === 'string' ? { id: id } : id) || {};
  3931. killTask(id, 'canceled', options.IgnoreListUpdate);
  3932. };
  3933. cos.pauseTask = function (id) {
  3934. var options = (typeof id === 'string' ? { id: id } : id) || {};
  3935. killTask(id, 'paused', options.IgnoreListUpdate);
  3936. };
  3937. cos.restartTask = function (id) {
  3938. var options = (typeof id === 'string' ? { id: id } : id) || {};
  3939. var task = tasks[id];
  3940. if (task && (task.state === 'paused' || task.state === 'error')) {
  3941. task.state = 'waiting';
  3942. options && emitListUpdate();
  3943. nextUploadIndex = 0;
  3944. startNextTask();
  3945. }
  3946. };
  3947. cos.isUploadRunning = function () {
  3948. return uploadingFileCount || nextUploadIndex < queue.length;
  3949. };
  3950. };
  3951.  
  3952. module.exports.transferToTaskMethod = transferToTaskMethod;
  3953. module.exports.init = initTask;
  3954.  
  3955. /***/ }),
  3956. /* 12 */
  3957. /***/ (function(module, exports, __webpack_require__) {
  3958.  
  3959. var REQUEST = __webpack_require__(13);
  3960. var util = __webpack_require__(0);
  3961.  
  3962. // Bucket 相关
  3963.  
  3964. /**
  3965. * 查看是否存在该Bucket,是否有权限访问
  3966. * @param {Object} params 参数对象,必须
  3967. * @param {String} params.Bucket Bucket名称,必须
  3968. * @param {String} params.Region 地域名称,必须
  3969. * @param {Function} callback 回调函数,必须
  3970. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  3971. * @return {Object} data 返回的数据
  3972. * @return {Boolean} data.BucketExist Bucket是否存在
  3973. * @return {Boolean} data.BucketAuth 是否有 Bucket 的访问权限
  3974. */
  3975. function headBucket(params, callback) {
  3976. submitRequest.call(this, {
  3977. Action: 'name/cos:HeadBucket',
  3978. Bucket: params.Bucket,
  3979. Region: params.Region,
  3980. headers: params.Headers,
  3981. method: 'HEAD'
  3982. }, function (err, data) {
  3983. callback(err, data);
  3984. });
  3985. }
  3986.  
  3987. /**
  3988. * 获取 Bucket 下的 object 列表
  3989. * @param {Object} params 参数对象,必须
  3990. * @param {String} params.Bucket Bucket名称,必须
  3991. * @param {String} params.Region 地域名称,必须
  3992. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  3993. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,非必须
  3994. * @param {String} params.Marker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  3995. * @param {String} params.MaxKeys 单次返回最大的条目数量,默认1000,非必须
  3996. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  3997. * @param {Function} callback 回调函数,必须
  3998. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  3999. * @return {Object} data 返回的数据
  4000. * @return {Object} data.ListBucketResult 返回的 object 列表信息
  4001. */
  4002. function getBucket(params, callback) {
  4003. var reqParams = {};
  4004. reqParams['prefix'] = params['Prefix'] || '';
  4005. reqParams['delimiter'] = params['Delimiter'];
  4006. reqParams['marker'] = params['Marker'];
  4007. reqParams['max-keys'] = params['MaxKeys'];
  4008. reqParams['encoding-type'] = params['EncodingType'];
  4009.  
  4010. submitRequest.call(this, {
  4011. Action: 'name/cos:GetBucket',
  4012. ResourceKey: reqParams['prefix'],
  4013. method: 'GET',
  4014. Bucket: params.Bucket,
  4015. Region: params.Region,
  4016. headers: params.Headers,
  4017. qs: reqParams
  4018. }, function (err, data) {
  4019. if (err) {
  4020. return callback(err);
  4021. }
  4022. var ListBucketResult = data.ListBucketResult || {};
  4023. var Contents = ListBucketResult.Contents || [];
  4024. var CommonPrefixes = ListBucketResult.CommonPrefixes || [];
  4025.  
  4026. Contents = util.isArray(Contents) ? Contents : [Contents];
  4027. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  4028.  
  4029. var result = util.clone(ListBucketResult);
  4030. util.extend(result, {
  4031. Contents: Contents,
  4032. CommonPrefixes: CommonPrefixes,
  4033. statusCode: data.statusCode,
  4034. headers: data.headers
  4035. });
  4036.  
  4037. callback(null, result);
  4038. });
  4039. }
  4040.  
  4041. /**
  4042. * 删除 Bucket
  4043. * @param {Object} params 参数对象,必须
  4044. * @param {String} params.Bucket Bucket名称,必须
  4045. * @param {String} params.Region 地域名称,必须
  4046. * @param {Function} callback 回调函数,必须
  4047. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4048. * @return {Object} data 返回的数据
  4049. * @return {String} data.Location 操作地址
  4050. */
  4051. function deleteBucket(params, callback) {
  4052. submitRequest.call(this, {
  4053. Action: 'name/cos:DeleteBucket',
  4054. Bucket: params.Bucket,
  4055. Region: params.Region,
  4056. headers: params.Headers,
  4057. method: 'DELETE'
  4058. }, function (err, data) {
  4059. if (err && err.statusCode === 204) {
  4060. return callback(null, { statusCode: err.statusCode });
  4061. } else if (err) {
  4062. return callback(err);
  4063. }
  4064. callback(null, {
  4065. statusCode: data.statusCode,
  4066. headers: data.headers
  4067. });
  4068. });
  4069. }
  4070.  
  4071. /**
  4072. * 设置 Bucket 的 权限列表
  4073. * @param {Object} params 参数对象,必须
  4074. * @param {String} params.Bucket Bucket名称,必须
  4075. * @param {String} params.Region 地域名称,必须
  4076. * @param {String} params.ACL 用户自定义文件权限,可以设置:private,public-read;默认值:private,非必须
  4077. * @param {String} params.GrantRead 赋予被授权者读的权限,格式x-cos-grant-read: uin=" ",uin=" ",非必须
  4078. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式x-cos-grant-write: uin=" ",uin=" ",非必须
  4079. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式x-cos-grant-full-control: uin=" ",uin=" ",非必须
  4080. * @param {Function} callback 回调函数,必须
  4081. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4082. * @return {Object} data 返回的数据
  4083. */
  4084. function putBucketAcl(params, callback) {
  4085. var headers = params.Headers;
  4086.  
  4087. var xml = '';
  4088. if (params['AccessControlPolicy']) {
  4089. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  4090. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  4091. Grants = util.isArray(Grants) ? Grants : [Grants];
  4092. delete AccessControlPolicy.Grant;
  4093. delete AccessControlPolicy.Grants;
  4094. AccessControlPolicy.AccessControlList = { Grant: Grants };
  4095. xml = util.json2xml({ AccessControlPolicy: AccessControlPolicy });
  4096.  
  4097. headers['Content-Type'] = 'application/xml';
  4098. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  4099. }
  4100.  
  4101. // Grant Header 去重
  4102. util.each(headers, function (val, key) {
  4103. if (key.indexOf('x-cos-grant-') === 0) {
  4104. headers[key] = uniqGrant(headers[key]);
  4105. }
  4106. });
  4107.  
  4108. submitRequest.call(this, {
  4109. Action: 'name/cos:PutBucketACL',
  4110. method: 'PUT',
  4111. Bucket: params.Bucket,
  4112. Region: params.Region,
  4113. headers: headers,
  4114. action: 'acl',
  4115. body: xml
  4116. }, function (err, data) {
  4117. if (err) {
  4118. return callback(err);
  4119. }
  4120. callback(null, {
  4121. statusCode: data.statusCode,
  4122. headers: data.headers
  4123. });
  4124. });
  4125. }
  4126.  
  4127. /**
  4128. * 获取 Bucket 的 权限列表
  4129. * @param {Object} params 参数对象,必须
  4130. * @param {String} params.Bucket Bucket名称,必须
  4131. * @param {String} params.Region 地域名称,必须
  4132. * @param {Function} callback 回调函数,必须
  4133. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4134. * @return {Object} data 返回的数据
  4135. * @return {Object} data.AccessControlPolicy 访问权限信息
  4136. */
  4137. function getBucketAcl(params, callback) {
  4138. submitRequest.call(this, {
  4139. Action: 'name/cos:GetBucketACL',
  4140. method: 'GET',
  4141. Bucket: params.Bucket,
  4142. Region: params.Region,
  4143. headers: params.Headers,
  4144. action: 'acl'
  4145. }, function (err, data) {
  4146. if (err) {
  4147. return callback(err);
  4148. }
  4149. var AccessControlPolicy = data.AccessControlPolicy || {};
  4150. var Owner = AccessControlPolicy.Owner || {};
  4151. var Grant = AccessControlPolicy.AccessControlList.Grant || [];
  4152. Grant = util.isArray(Grant) ? Grant : [Grant];
  4153. var result = decodeAcl(AccessControlPolicy);
  4154. if (data.headers && data.headers['x-cos-acl']) {
  4155. result.ACL = data.headers['x-cos-acl'];
  4156. }
  4157. result = util.extend(result, {
  4158. Owner: Owner,
  4159. Grants: Grant,
  4160. statusCode: data.statusCode,
  4161. headers: data.headers
  4162. });
  4163. callback(null, result);
  4164. });
  4165. }
  4166.  
  4167. /**
  4168. * 设置 Bucket 的 跨域设置
  4169. * @param {Object} params 参数对象,必须
  4170. * @param {String} params.Bucket Bucket名称,必须
  4171. * @param {String} params.Region 地域名称,必须
  4172. * @param {Object} params.CORSConfiguration 相关的跨域设置,必须
  4173. * @param {Array} params.CORSConfiguration.CORSRules 对应的跨域规则
  4174. * @param {Function} callback 回调函数,必须
  4175. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4176. * @return {Object} data 返回的数据
  4177. */
  4178. function putBucketCors(params, callback) {
  4179.  
  4180. var CORSConfiguration = params['CORSConfiguration'] || {};
  4181. var CORSRules = CORSConfiguration['CORSRules'] || params['CORSRules'] || [];
  4182. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  4183. util.each(CORSRules, function (rule) {
  4184. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key, k) {
  4185. var sKey = key + 's';
  4186. var val = rule[sKey] || rule[key] || [];
  4187. delete rule[sKey];
  4188. rule[key] = util.isArray(val) ? val : [val];
  4189. });
  4190. });
  4191.  
  4192. var xml = util.json2xml({ CORSConfiguration: { CORSRule: CORSRules } });
  4193.  
  4194. var headers = params.Headers;
  4195. headers['Content-Type'] = 'application/xml';
  4196. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  4197.  
  4198. submitRequest.call(this, {
  4199. Action: 'name/cos:PutBucketCORS',
  4200. method: 'PUT',
  4201. Bucket: params.Bucket,
  4202. Region: params.Region,
  4203. body: xml,
  4204. action: 'cors',
  4205. headers: headers
  4206. }, function (err, data) {
  4207. if (err) {
  4208. return callback(err);
  4209. }
  4210. callback(null, {
  4211. statusCode: data.statusCode,
  4212. headers: data.headers
  4213. });
  4214. });
  4215. }
  4216.  
  4217. /**
  4218. * 获取 Bucket 的 跨域设置
  4219. * @param {Object} params 参数对象,必须
  4220. * @param {String} params.Bucket Bucket名称,必须
  4221. * @param {String} params.Region 地域名称,必须
  4222. * @param {Function} callback 回调函数,必须
  4223. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4224. * @return {Object} data 返回的数据
  4225. * @return {Object} data.CORSRules Bucket的跨域设置
  4226. */
  4227. function getBucketCors(params, callback) {
  4228. submitRequest.call(this, {
  4229. Action: 'name/cos:GetBucketCORS',
  4230. method: 'GET',
  4231. Bucket: params.Bucket,
  4232. Region: params.Region,
  4233. headers: params.Headers,
  4234. action: 'cors'
  4235. }, function (err, data) {
  4236. if (err) {
  4237. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchCORSConfiguration') {
  4238. var result = {
  4239. CORSRules: [],
  4240. statusCode: err.statusCode
  4241. };
  4242. err.headers && (result.headers = err.headers);
  4243. callback(null, result);
  4244. } else {
  4245. callback(err);
  4246. }
  4247. return;
  4248. }
  4249. var CORSConfiguration = data.CORSConfiguration || {};
  4250. var CORSRules = CORSConfiguration.CORSRules || CORSConfiguration.CORSRule || [];
  4251. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  4252.  
  4253. util.each(CORSRules, function (rule) {
  4254. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key, j) {
  4255. var sKey = key + 's';
  4256. var val = rule[sKey] || rule[key] || [];
  4257. delete rule[key];
  4258. rule[sKey] = util.isArray(val) ? val : [val];
  4259. });
  4260. });
  4261.  
  4262. callback(null, {
  4263. CORSRules: CORSRules,
  4264. statusCode: data.statusCode,
  4265. headers: data.headers
  4266. });
  4267. });
  4268. }
  4269.  
  4270. /**
  4271. * 删除 Bucket 的 跨域设置
  4272. * @param {Object} params 参数对象,必须
  4273. * @param {String} params.Bucket Bucket名称,必须
  4274. * @param {String} params.Region 地域名称,必须
  4275. * @param {Function} callback 回调函数,必须
  4276. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4277. * @return {Object} data 返回的数据
  4278. */
  4279. function deleteBucketCors(params, callback) {
  4280. submitRequest.call(this, {
  4281. Action: 'name/cos:DeleteBucketCORS',
  4282. method: 'DELETE',
  4283. Bucket: params.Bucket,
  4284. Region: params.Region,
  4285. headers: params.Headers,
  4286. action: 'cors'
  4287. }, function (err, data) {
  4288. if (err && err.statusCode === 204) {
  4289. return callback(null, { statusCode: err.statusCode });
  4290. } else if (err) {
  4291. return callback(err);
  4292. }
  4293. callback(null, {
  4294. statusCode: data.statusCode || err.statusCode,
  4295. headers: data.headers
  4296. });
  4297. });
  4298. }
  4299.  
  4300. /**
  4301. * 获取 Bucket 的 地域信息
  4302. * @param {Object} params 参数对象,必须
  4303. * @param {String} params.Bucket Bucket名称,必须
  4304. * @param {String} params.Region 地域名称,必须
  4305. * @param {Function} callback 回调函数,必须
  4306. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4307. * @return {Object} data 返回数据,包含地域信息 LocationConstraint
  4308. */
  4309. function getBucketLocation(params, callback) {
  4310. submitRequest.call(this, {
  4311. Action: 'name/cos:GetBucketLocation',
  4312. method: 'GET',
  4313. Bucket: params.Bucket,
  4314. Region: params.Region,
  4315. headers: params.Headers,
  4316. action: 'location'
  4317. }, function (err, data) {
  4318. if (err) {
  4319. return callback(err);
  4320. }
  4321. callback(null, data);
  4322. });
  4323. }
  4324.  
  4325. function putBucketPolicy(params, callback) {
  4326. var Policy = params['Policy'];
  4327. var PolicyStr = Policy;
  4328. try {
  4329. if (typeof Policy === 'string') {
  4330. Policy = JSON.parse(PolicyStr);
  4331. } else {
  4332. PolicyStr = JSON.stringify(Policy);
  4333. }
  4334. } catch (e) {
  4335. callback({ error: 'Policy format error' });
  4336. }
  4337.  
  4338. var headers = params.Headers;
  4339. headers['Content-Type'] = 'application/json';
  4340. headers['Content-MD5'] = util.binaryBase64(util.md5(PolicyStr));
  4341.  
  4342. submitRequest.call(this, {
  4343. Action: 'name/cos:PutBucketPolicy',
  4344. method: 'PUT',
  4345. Bucket: params.Bucket,
  4346. Region: params.Region,
  4347. action: 'policy',
  4348. body: util.isBrowser ? PolicyStr : Policy,
  4349. headers: headers,
  4350. json: true
  4351. }, function (err, data) {
  4352. if (err && err.statusCode === 204) {
  4353. return callback(null, { statusCode: err.statusCode });
  4354. } else if (err) {
  4355. return callback(err);
  4356. }
  4357. callback(null, {
  4358. statusCode: data.statusCode,
  4359. headers: data.headers
  4360. });
  4361. });
  4362. }
  4363.  
  4364. /**
  4365. * 获取 Bucket 的读取权限策略
  4366. * @param {Object} params 参数对象,必须
  4367. * @param {String} params.Bucket Bucket名称,必须
  4368. * @param {String} params.Region 地域名称,必须
  4369. * @param {Function} callback 回调函数,必须
  4370. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4371. * @return {Object} data 返回数据
  4372. */
  4373. function getBucketPolicy(params, callback) {
  4374. submitRequest.call(this, {
  4375. Action: 'name/cos:GetBucketPolicy',
  4376. method: 'GET',
  4377. Bucket: params.Bucket,
  4378. Region: params.Region,
  4379. headers: params.Headers,
  4380. action: 'policy',
  4381. rawBody: true
  4382. }, function (err, data) {
  4383. if (err) {
  4384. if (err.statusCode && err.statusCode === 403) {
  4385. return callback({ ErrorStatus: 'Access Denied' });
  4386. }
  4387. if (err.statusCode && err.statusCode === 405) {
  4388. return callback({ ErrorStatus: 'Method Not Allowed' });
  4389. }
  4390. if (err.statusCode && err.statusCode === 404) {
  4391. return callback({ ErrorStatus: 'Policy Not Found' });
  4392. }
  4393. return callback(err);
  4394. }
  4395. var Policy = {};
  4396. try {
  4397. Policy = JSON.parse(data.body);
  4398. } catch (e) {}
  4399. callback(null, {
  4400. Policy: Policy,
  4401. statusCode: data.statusCode,
  4402. headers: data.headers
  4403. });
  4404. });
  4405. }
  4406.  
  4407. /**
  4408. * 删除 Bucket 的 跨域设置
  4409. * @param {Object} params 参数对象,必须
  4410. * @param {String} params.Bucket Bucket名称,必须
  4411. * @param {String} params.Region 地域名称,必须
  4412. * @param {Function} callback 回调函数,必须
  4413. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4414. * @return {Object} data 返回的数据
  4415. */
  4416. function deleteBucketPolicy(params, callback) {
  4417. submitRequest.call(this, {
  4418. Action: 'name/cos:DeleteBucketPolicy',
  4419. method: 'DELETE',
  4420. Bucket: params.Bucket,
  4421. Region: params.Region,
  4422. headers: params.Headers,
  4423. action: 'policy'
  4424. }, function (err, data) {
  4425. if (err && err.statusCode === 204) {
  4426. return callback(null, { statusCode: err.statusCode });
  4427. } else if (err) {
  4428. return callback(err);
  4429. }
  4430. callback(null, {
  4431. statusCode: data.statusCode || err.statusCode,
  4432. headers: data.headers
  4433. });
  4434. });
  4435. }
  4436.  
  4437. /**
  4438. * 设置 Bucket 的标签
  4439. * @param {Object} params 参数对象,必须
  4440. * @param {String} params.Bucket Bucket名称,必须
  4441. * @param {String} params.Region 地域名称,必须
  4442. * @param {Array} params.TagSet 标签设置,必须
  4443. * @param {Function} callback 回调函数,必须
  4444. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4445. * @return {Object} data 返回数据
  4446. */
  4447. function putBucketTagging(params, callback) {
  4448.  
  4449. var Tagging = params['Tagging'] || {};
  4450. var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];
  4451. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  4452. var xml = util.json2xml({ Tagging: { TagSet: { Tag: Tags } } });
  4453.  
  4454. var headers = params.Headers;
  4455. headers['Content-Type'] = 'application/xml';
  4456. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  4457.  
  4458. submitRequest.call(this, {
  4459. Action: 'name/cos:PutBucketTagging',
  4460. method: 'PUT',
  4461. Bucket: params.Bucket,
  4462. Region: params.Region,
  4463. body: xml,
  4464. action: 'tagging',
  4465. headers: headers
  4466. }, function (err, data) {
  4467. if (err && err.statusCode === 204) {
  4468. return callback(null, { statusCode: err.statusCode });
  4469. } else if (err) {
  4470. return callback(err);
  4471. }
  4472. callback(null, {
  4473. statusCode: data.statusCode,
  4474. headers: data.headers
  4475. });
  4476. });
  4477. }
  4478.  
  4479. /**
  4480. * 获取 Bucket 的标签设置
  4481. * @param {Object} params 参数对象,必须
  4482. * @param {String} params.Bucket Bucket名称,必须
  4483. * @param {String} params.Region 地域名称,必须
  4484. * @param {Function} callback 回调函数,必须
  4485. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4486. * @return {Object} data 返回数据
  4487. */
  4488. function getBucketTagging(params, callback) {
  4489. submitRequest.call(this, {
  4490. Action: 'name/cos:GetBucketTagging',
  4491. method: 'GET',
  4492. Bucket: params.Bucket,
  4493. Region: params.Region,
  4494. headers: params.Headers,
  4495. action: 'tagging'
  4496. }, function (err, data) {
  4497. if (err) {
  4498. if (err.statusCode === 404 && err.error && (err.error === "Not Found" || err.error.Code === 'NoSuchTagSet')) {
  4499. var result = {
  4500. Tags: [],
  4501. statusCode: err.statusCode
  4502. };
  4503. err.headers && (result.headers = err.headers);
  4504. callback(null, result);
  4505. } else {
  4506. callback(err);
  4507. }
  4508. return;
  4509. }
  4510. var Tags = [];
  4511. try {
  4512. Tags = data.Tagging.TagSet.Tag || [];
  4513. } catch (e) {}
  4514. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  4515. callback(null, {
  4516. Tags: Tags,
  4517. statusCode: data.statusCode,
  4518. headers: data.headers
  4519. });
  4520. });
  4521. }
  4522.  
  4523. /**
  4524. * 删除 Bucket 的 标签设置
  4525. * @param {Object} params 参数对象,必须
  4526. * @param {String} params.Bucket Bucket名称,必须
  4527. * @param {String} params.Region 地域名称,必须
  4528. * @param {Function} callback 回调函数,必须
  4529. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4530. * @return {Object} data 返回的数据
  4531. */
  4532. function deleteBucketTagging(params, callback) {
  4533. submitRequest.call(this, {
  4534. Action: 'name/cos:DeleteBucketTagging',
  4535. method: 'DELETE',
  4536. Bucket: params.Bucket,
  4537. Region: params.Region,
  4538. headers: params.Headers,
  4539. action: 'tagging'
  4540. }, function (err, data) {
  4541. if (err && err.statusCode === 204) {
  4542. return callback(null, { statusCode: err.statusCode });
  4543. } else if (err) {
  4544. return callback(err);
  4545. }
  4546. callback(null, {
  4547. statusCode: data.statusCode,
  4548. headers: data.headers
  4549. });
  4550. });
  4551. }
  4552.  
  4553. function putBucketLifecycle(params, callback) {
  4554.  
  4555. var LifecycleConfiguration = params['LifecycleConfiguration'] || {};
  4556. var Rules = LifecycleConfiguration.Rules || params.Rules || [];
  4557. Rules = util.clone(Rules);
  4558. var xml = util.json2xml({ LifecycleConfiguration: { Rule: Rules } });
  4559.  
  4560. var headers = params.Headers;
  4561. headers['Content-Type'] = 'application/xml';
  4562. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  4563.  
  4564. submitRequest.call(this, {
  4565. Action: 'name/cos:PutBucketLifecycle',
  4566. method: 'PUT',
  4567. Bucket: params.Bucket,
  4568. Region: params.Region,
  4569. body: xml,
  4570. action: 'lifecycle',
  4571. headers: headers
  4572. }, function (err, data) {
  4573. if (err && err.statusCode === 204) {
  4574. return callback(null, { statusCode: err.statusCode });
  4575. } else if (err) {
  4576. return callback(err);
  4577. }
  4578. callback(null, {
  4579. statusCode: data.statusCode,
  4580. headers: data.headers
  4581. });
  4582. });
  4583. }
  4584.  
  4585. function getBucketLifecycle(params, callback) {
  4586. submitRequest.call(this, {
  4587. Action: 'name/cos:GetBucketLifecycle',
  4588. method: 'GET',
  4589. Bucket: params.Bucket,
  4590. Region: params.Region,
  4591. headers: params.Headers,
  4592. action: 'lifecycle'
  4593. }, function (err, data) {
  4594. if (err) {
  4595. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchLifecycleConfiguration') {
  4596. var result = {
  4597. Rules: [],
  4598. statusCode: err.statusCode
  4599. };
  4600. err.headers && (result.headers = err.headers);
  4601. callback(null, result);
  4602. } else {
  4603. callback(err);
  4604. }
  4605. return;
  4606. }
  4607. var Rules = [];
  4608. try {
  4609. Rules = data.LifecycleConfiguration.Rule || [];
  4610. } catch (e) {}
  4611. Rules = util.clone(util.isArray(Rules) ? Rules : [Rules]);
  4612. callback(null, {
  4613. Rules: Rules,
  4614. statusCode: data.statusCode,
  4615. headers: data.headers
  4616. });
  4617. });
  4618. }
  4619.  
  4620. function deleteBucketLifecycle(params, callback) {
  4621. submitRequest.call(this, {
  4622. Action: 'name/cos:DeleteBucketLifecycle',
  4623. method: 'DELETE',
  4624. Bucket: params.Bucket,
  4625. Region: params.Region,
  4626. headers: params.Headers,
  4627. action: 'lifecycle'
  4628. }, function (err, data) {
  4629. if (err && err.statusCode === 204) {
  4630. return callback(null, { statusCode: err.statusCode });
  4631. } else if (err) {
  4632. return callback(err);
  4633. }
  4634. callback(null, {
  4635. statusCode: data.statusCode,
  4636. headers: data.headers
  4637. });
  4638. });
  4639. }
  4640.  
  4641. function putBucketVersioning(params, callback) {
  4642.  
  4643. if (!params['VersioningConfiguration']) {
  4644. callback({ error: 'missing param VersioningConfiguration' });
  4645. return;
  4646. }
  4647. var VersioningConfiguration = params['VersioningConfiguration'] || {};
  4648. var xml = util.json2xml({ VersioningConfiguration: VersioningConfiguration });
  4649.  
  4650. var headers = params.Headers;
  4651. headers['Content-Type'] = 'application/xml';
  4652. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  4653.  
  4654. submitRequest.call(this, {
  4655. Action: 'name/cos:PutBucketVersioning',
  4656. method: 'PUT',
  4657. Bucket: params.Bucket,
  4658. Region: params.Region,
  4659. body: xml,
  4660. action: 'versioning',
  4661. headers: headers
  4662. }, function (err, data) {
  4663. if (err && err.statusCode === 204) {
  4664. return callback(null, { statusCode: err.statusCode });
  4665. } else if (err) {
  4666. return callback(err);
  4667. }
  4668. callback(null, {
  4669. statusCode: data.statusCode,
  4670. headers: data.headers
  4671. });
  4672. });
  4673. }
  4674.  
  4675. function getBucketVersioning(params, callback) {
  4676. submitRequest.call(this, {
  4677. Action: 'name/cos:GetBucketVersioning',
  4678. method: 'GET',
  4679. Bucket: params.Bucket,
  4680. Region: params.Region,
  4681. headers: params.Headers,
  4682. action: 'versioning'
  4683. }, function (err, data) {
  4684. if (!err) {
  4685. !data.VersioningConfiguration && (data.VersioningConfiguration = {});
  4686. }
  4687. callback(err, data);
  4688. });
  4689. }
  4690.  
  4691. function putBucketReplication(params, callback) {
  4692. var ReplicationConfiguration = util.clone(params.ReplicationConfiguration);
  4693. var xml = util.json2xml({ ReplicationConfiguration: ReplicationConfiguration });
  4694. xml = xml.replace(/<(\/?)Rules>/ig, '<$1Rule>');
  4695. xml = xml.replace(/<(\/?)Tags>/ig, '<$1Tag>');
  4696.  
  4697. var headers = params.Headers;
  4698. headers['Content-Type'] = 'application/xml';
  4699. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  4700.  
  4701. submitRequest.call(this, {
  4702. Action: 'name/cos:PutBucketReplication',
  4703. method: 'PUT',
  4704. Bucket: params.Bucket,
  4705. Region: params.Region,
  4706. body: xml,
  4707. action: 'replication',
  4708. headers: headers
  4709. }, function (err, data) {
  4710. if (err && err.statusCode === 204) {
  4711. return callback(null, { statusCode: err.statusCode });
  4712. } else if (err) {
  4713. return callback(err);
  4714. }
  4715. callback(null, {
  4716. statusCode: data.statusCode,
  4717. headers: data.headers
  4718. });
  4719. });
  4720. }
  4721.  
  4722. function getBucketReplication(params, callback) {
  4723. submitRequest.call(this, {
  4724. Action: 'name/cos:GetBucketReplication',
  4725. method: 'GET',
  4726. Bucket: params.Bucket,
  4727. Region: params.Region,
  4728. headers: params.Headers,
  4729. action: 'replication'
  4730. }, function (err, data) {
  4731. if (err) {
  4732. if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'ReplicationConfigurationnotFoundError')) {
  4733. var result = {
  4734. ReplicationConfiguration: { Rules: [] },
  4735. statusCode: err.statusCode
  4736. };
  4737. err.headers && (result.headers = err.headers);
  4738. callback(null, result);
  4739. } else {
  4740. callback(err);
  4741. }
  4742. return;
  4743. }
  4744. if (!err) {
  4745. !data.ReplicationConfiguration && (data.ReplicationConfiguration = {});
  4746. }
  4747. if (data.ReplicationConfiguration.Rule) {
  4748. data.ReplicationConfiguration.Rules = data.ReplicationConfiguration.Rule;
  4749. delete data.ReplicationConfiguration.Rule;
  4750. }
  4751. callback(err, data);
  4752. });
  4753. }
  4754.  
  4755. function deleteBucketReplication(params, callback) {
  4756. submitRequest.call(this, {
  4757. Action: 'name/cos:DeleteBucketReplication',
  4758. method: 'DELETE',
  4759. Bucket: params.Bucket,
  4760. Region: params.Region,
  4761. headers: params.Headers,
  4762. action: 'replication'
  4763. }, function (err, data) {
  4764. if (err && err.statusCode === 204) {
  4765. return callback(null, { statusCode: err.statusCode });
  4766. } else if (err) {
  4767. return callback(err);
  4768. }
  4769. callback(null, {
  4770. statusCode: data.statusCode,
  4771. headers: data.headers
  4772. });
  4773. });
  4774. }
  4775.  
  4776. /**
  4777. * 设置 Bucket 静态网站配置信息
  4778. * @param {Object} params 参数对象,必须
  4779. * @param {String} params.Bucket Bucket名称,必须
  4780. * @param {String} params.Region 地域名称,必须
  4781. * @param {Object} params.WebsiteConfiguration 地域名称,必须
  4782. * @param {Object} WebsiteConfiguration.IndexDocument 索引文档,必须
  4783. * @param {Object} WebsiteConfiguration.ErrorDocument 错误文档,非必须
  4784. * @param {Object} WebsiteConfiguration.RedirectAllRequestsTo 重定向所有请求,非必须
  4785. * @param {Array} params.RoutingRules 重定向规则,非必须
  4786. * @param {Function} callback 回调函数,必须
  4787. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4788. * @return {Object} data 返回数据
  4789. */
  4790. function putBucketWebsite(params, callback) {
  4791.  
  4792. if (!params['WebsiteConfiguration']) {
  4793. callback({ error: 'missing param WebsiteConfiguration' });
  4794. return;
  4795. }
  4796.  
  4797. var WebsiteConfiguration = util.clone(params['WebsiteConfiguration'] || {});
  4798. var RoutingRules = WebsiteConfiguration['RoutingRules'] || WebsiteConfiguration['RoutingRule'] || [];
  4799. RoutingRules = util.isArray(RoutingRules) ? RoutingRules : [RoutingRules];
  4800. delete WebsiteConfiguration.RoutingRule;
  4801. delete WebsiteConfiguration.RoutingRules;
  4802. RoutingRules.length > 0 && (WebsiteConfiguration.RoutingRules = { RoutingRule: RoutingRules });
  4803. var xml = util.json2xml({ WebsiteConfiguration: WebsiteConfiguration });
  4804.  
  4805. var headers = params.Headers;
  4806. headers['Content-Type'] = 'application/xml';
  4807. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  4808.  
  4809. submitRequest.call(this, {
  4810. Action: 'name/cos:PutBucketWebsite',
  4811. method: 'PUT',
  4812. Bucket: params.Bucket,
  4813. Region: params.Region,
  4814. body: xml,
  4815. action: 'website',
  4816. headers: headers
  4817. }, function (err, data) {
  4818. if (err && err.statusCode === 204) {
  4819. return callback(null, { statusCode: err.statusCode });
  4820. } else if (err) {
  4821. return callback(err);
  4822. }
  4823. callback(null, {
  4824. statusCode: data.statusCode,
  4825. headers: data.headers
  4826. });
  4827. });
  4828. }
  4829.  
  4830. /**
  4831. * 获取 Bucket 的静态网站配置信息
  4832. * @param {Object} params 参数对象,必须
  4833. * @param {String} params.Bucket Bucket名称,必须
  4834. * @param {String} params.Region 地域名称,必须
  4835. * @param {Function} callback 回调函数,必须
  4836. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4837. * @return {Object} data 返回数据
  4838. */
  4839. function getBucketWebsite(params, callback) {
  4840.  
  4841. submitRequest.call(this, {
  4842. Action: 'name/cos:GetBucketWebsite',
  4843. method: 'GET',
  4844. Bucket: params.Bucket,
  4845. Region: params.Region,
  4846. Key: params.Key,
  4847. headers: params.Headers,
  4848. action: 'website'
  4849. }, function (err, data) {
  4850. if (err) {
  4851. if (err.statusCode === 404 && err.error.Code === 'NoSuchWebsiteConfiguration') {
  4852. var result = {
  4853. WebsiteConfiguration: {},
  4854. statusCode: err.statusCode
  4855. };
  4856. err.headers && (result.headers = err.headers);
  4857. callback(null, result);
  4858. } else {
  4859. callback(err);
  4860. }
  4861. return;
  4862. }
  4863.  
  4864. var WebsiteConfiguration = data.WebsiteConfiguration || {};
  4865. if (WebsiteConfiguration['RoutingRules']) {
  4866. var RoutingRules = util.clone(WebsiteConfiguration['RoutingRules'].RoutingRule || []);
  4867. RoutingRules = util.makeArray(RoutingRules);
  4868. WebsiteConfiguration.RoutingRules = RoutingRules;
  4869. }
  4870.  
  4871. callback(null, {
  4872. WebsiteConfiguration: WebsiteConfiguration,
  4873. statusCode: data.statusCode,
  4874. headers: data.headers
  4875. });
  4876. });
  4877. }
  4878.  
  4879. /**
  4880. * 删除 Bucket 的静态网站配置
  4881. * @param {Object} params 参数对象,必须
  4882. * @param {String} params.Bucket Bucket名称,必须
  4883. * @param {String} params.Region 地域名称,必须
  4884. * @param {Function} callback 回调函数,必须
  4885. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4886. * @return {Object} data 返回数据
  4887. */
  4888. function deleteBucketWebsite(params, callback) {
  4889.  
  4890. submitRequest.call(this, {
  4891. Action: 'name/cos:DeleteBucketWebsite',
  4892. method: 'DELETE',
  4893. Bucket: params.Bucket,
  4894. Region: params.Region,
  4895. headers: params.Headers,
  4896. action: 'website'
  4897. }, function (err, data) {
  4898. if (err && err.statusCode === 204) {
  4899. return callback(null, { statusCode: err.statusCode });
  4900. } else if (err) {
  4901. return callback(err);
  4902. }
  4903. callback(null, {
  4904. statusCode: data.statusCode,
  4905. headers: data.headers
  4906. });
  4907. });
  4908. }
  4909.  
  4910. // Object 相关
  4911.  
  4912. /**
  4913. * 取回对应Object的元数据,Head的权限与Get的权限一致
  4914. * @param {Object} params 参数对象,必须
  4915. * @param {String} params.Bucket Bucket名称,必须
  4916. * @param {String} params.Region 地域名称,必须
  4917. * @param {String} params.Key 文件名称,必须
  4918. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  4919. * @param {Function} callback 回调函数,必须
  4920. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  4921. * @return {Object} data 为指定 object 的元数据,如果设置了 IfModifiedSince ,且文件未修改,则返回一个对象,NotModified 属性为 true
  4922. * @return {Boolean} data.NotModified 是否在 IfModifiedSince 时间点之后未修改该 object,则为 true
  4923. */
  4924. function headObject(params, callback) {
  4925. submitRequest.call(this, {
  4926. Action: 'name/cos:HeadObject',
  4927. method: 'HEAD',
  4928. Bucket: params.Bucket,
  4929. Region: params.Region,
  4930. Key: params.Key,
  4931. VersionId: params.VersionId,
  4932. headers: params.Headers
  4933. }, function (err, data) {
  4934. if (err) {
  4935. var statusCode = err.statusCode;
  4936. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  4937. return callback(null, {
  4938. NotModified: true,
  4939. statusCode: statusCode
  4940. });
  4941. }
  4942. return callback(err);
  4943. }
  4944. if (data.headers && data.headers.etag) {
  4945. data.ETag = data.headers && data.headers.etag;
  4946. }
  4947. callback(null, data);
  4948. });
  4949. }
  4950.  
  4951. function listObjectVersions(params, callback) {
  4952. var reqParams = {};
  4953. reqParams['prefix'] = params['Prefix'] || '';
  4954. reqParams['delimiter'] = params['Delimiter'];
  4955. reqParams['key-marker'] = params['KeyMarker'];
  4956. reqParams['version-id-marker'] = params['VersionIdMarker'];
  4957. reqParams['max-keys'] = params['MaxKeys'];
  4958. reqParams['encoding-type'] = params['EncodingType'];
  4959.  
  4960. submitRequest.call(this, {
  4961. Action: 'name/cos:GetBucketObjectVersions',
  4962. ResourceKey: reqParams['prefix'],
  4963. method: 'GET',
  4964. Bucket: params.Bucket,
  4965. Region: params.Region,
  4966. headers: params.Headers,
  4967. qs: reqParams,
  4968. action: 'versions'
  4969. }, function (err, data) {
  4970. if (err) {
  4971. return callback(err);
  4972. }
  4973. var ListVersionsResult = data.ListVersionsResult || {};
  4974. var DeleteMarkers = ListVersionsResult.DeleteMarker || [];
  4975. DeleteMarkers = util.isArray(DeleteMarkers) ? DeleteMarkers : [DeleteMarkers];
  4976. var Versions = ListVersionsResult.Version || [];
  4977. Versions = util.isArray(Versions) ? Versions : [Versions];
  4978.  
  4979. var result = util.clone(ListVersionsResult);
  4980. delete result.DeleteMarker;
  4981. delete result.Version;
  4982. util.extend(result, {
  4983. DeleteMarkers: DeleteMarkers,
  4984. Versions: Versions,
  4985. statusCode: data.statusCode,
  4986. headers: data.headers
  4987. });
  4988.  
  4989. callback(null, result);
  4990. });
  4991. }
  4992.  
  4993. /**
  4994. * 下载 object
  4995. * @param {Object} params 参数对象,必须
  4996. * @param {String} params.Bucket Bucket名称,必须
  4997. * @param {String} params.Region 地域名称,必须
  4998. * @param {String} params.Key 文件名称,必须
  4999. * @param {WriteStream} params.Output 文件写入流,非必须
  5000. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  5001. * @param {String} params.IfUnmodifiedSince 如果文件修改时间早于或等于指定时间,才返回文件内容。否则返回 412 (precondition failed),非必须
  5002. * @param {String} params.IfMatch 当 ETag 与指定的内容一致,才返回文件。否则返回 412 (precondition failed),非必须
  5003. * @param {String} params.IfNoneMatch 当 ETag 与指定的内容不一致,才返回文件。否则返回304 (not modified),非必须
  5004. * @param {String} params.ResponseContentType 设置返回头部中的 Content-Type 参数,非必须
  5005. * @param {String} params.ResponseContentLanguage 设置返回头部中的 Content-Language 参数,非必须
  5006. * @param {String} params.ResponseExpires 设置返回头部中的 Content-Expires 参数,非必须
  5007. * @param {String} params.ResponseCacheControl 设置返回头部中的 Cache-Control 参数,非必须
  5008. * @param {String} params.ResponseContentDisposition 设置返回头部中的 Content-Disposition 参数,非必须
  5009. * @param {String} params.ResponseContentEncoding 设置返回头部中的 Content-Encoding 参数,非必须
  5010. * @param {Function} callback 回调函数,必须
  5011. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5012. * @param {Object} data 为对应的 object 数据,包括 body 和 headers
  5013. */
  5014. function getObject(params, callback) {
  5015. var reqParams = {};
  5016.  
  5017. reqParams['response-content-type'] = params['ResponseContentType'];
  5018. reqParams['response-content-language'] = params['ResponseContentLanguage'];
  5019. reqParams['response-expires'] = params['ResponseExpires'];
  5020. reqParams['response-cache-control'] = params['ResponseCacheControl'];
  5021. reqParams['response-content-disposition'] = params['ResponseContentDisposition'];
  5022. reqParams['response-content-encoding'] = params['ResponseContentEncoding'];
  5023.  
  5024. // 如果用户自己传入了 output
  5025. submitRequest.call(this, {
  5026. Action: 'name/cos:GetObject',
  5027. method: 'GET',
  5028. Bucket: params.Bucket,
  5029. Region: params.Region,
  5030. Key: params.Key,
  5031. VersionId: params.VersionId,
  5032. headers: params.Headers,
  5033. qs: reqParams,
  5034. rawBody: true
  5035. }, function (err, data) {
  5036. if (err) {
  5037. var statusCode = err.statusCode;
  5038. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  5039. return callback(null, {
  5040. NotModified: true
  5041. });
  5042. }
  5043. return callback(err);
  5044. }
  5045. var result = {};
  5046. result.Body = data.body;
  5047. if (data.headers && data.headers.etag) {
  5048. result.ETag = data.headers && data.headers.etag;
  5049. }
  5050. util.extend(result, {
  5051. statusCode: data.statusCode,
  5052. headers: data.headers
  5053. });
  5054. callback(null, result);
  5055. });
  5056. }
  5057.  
  5058. /**
  5059. * 上传 object
  5060. * @param {Object} params 参数对象,必须
  5061. * @param {String} params.Bucket Bucket名称,必须
  5062. * @param {String} params.Region 地域名称,必须
  5063. * @param {String} params.Key 文件名称,必须
  5064. * @param {File || Blob || String} params.Body 上传文件对象或字符串,必须
  5065. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  5066. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存,非必须
  5067. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  5068. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),必须
  5069. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  5070. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  5071. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  5072. * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须
  5073. * @param {String} params.GrantRead 赋予被授权者读取对象的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  5074. * @param {String} params.GrantReadAcp 赋予被授权者读取对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  5075. * @param {String} params.GrantWriteAcp 赋予被授权者写入对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  5076. * @param {String} params.GrantFullControl 赋予被授权者操作对象的所有权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  5077. * @param {String} params.StorageClass 设置对象的存储级别,枚举值:STANDARD、STANDARD_IA、ARCHIVE,默认值:STANDARD,非必须
  5078. * @param {String} params.x-cos-meta-* 允许用户自定义的头部信息,将作为对象的元数据保存。大小限制2KB,非必须
  5079. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须
  5080. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  5081. * @param {Function} params.onProgress 上传进度回调函数
  5082. * @param {Function} callback 回调函数,必须
  5083. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5084. * @return {Object} data 为对应的 object 数据
  5085. * @return {String} data.ETag 为对应上传文件的 ETag 值
  5086. */
  5087. function putObject(params, callback) {
  5088. var self = this;
  5089. var FileSize = params.ContentLength;
  5090. var onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  5091.  
  5092. // 特殊处理 Cache-Control
  5093. var headers = params.Headers;
  5094. !headers['Cache-Control'] && (headers['Cache-Control'] = '');
  5095.  
  5096. // 获取 File 或 Blob 的 type 属性,如果有,作为文件 Content-Type
  5097. var ContentType = headers['Content-Type'] || params.Body && params.Body.type;
  5098. !headers['Content-Type'] && ContentType && (headers['Content-Type'] = ContentType);
  5099.  
  5100. var needCalcMd5 = params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5 || self.options.UploadCheckContentMd5;
  5101. util.getBodyMd5(needCalcMd5, params.Body, function (md5) {
  5102. if (md5) {
  5103. if (self.options.UploadCheckContentMd5) params.Headers['Content-MD5'] = util.binaryBase64(md5);
  5104. if (params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5) params.Headers['x-cos-meta-md5'] = md5;
  5105. }
  5106.  
  5107. if (params.ContentLength !== undefined) {
  5108. params.Headers['Content-Length'] = params.ContentLength;
  5109. }
  5110. onProgress(null, true); // 任务状态开始 uploading
  5111. submitRequest.call(self, {
  5112. Action: 'name/cos:PutObject',
  5113. TaskId: params.TaskId,
  5114. method: 'PUT',
  5115. Bucket: params.Bucket,
  5116. Region: params.Region,
  5117. Key: params.Key,
  5118. headers: params.Headers,
  5119. body: params.Body,
  5120. onProgress: onProgress
  5121. }, function (err, data) {
  5122. if (err) {
  5123. onProgress(null, true);
  5124. return callback(err);
  5125. }
  5126. onProgress({ loaded: FileSize, total: FileSize }, true);
  5127. if (data) {
  5128. var url = getUrl({
  5129. ForcePathStyle: self.options.ForcePathStyle,
  5130. protocol: self.options.Protocol,
  5131. domain: self.options.Domain,
  5132. bucket: params.Bucket,
  5133. region: params.Region,
  5134. object: params.Key
  5135. });
  5136. url = url.substr(url.indexOf('://') + 3);
  5137. var result = {
  5138. Location: url,
  5139. statusCode: data.statusCode,
  5140. headers: data.headers
  5141. };
  5142. if (data.headers && data.headers.etag) {
  5143. result.ETag = data.headers.etag;
  5144. }
  5145. return callback(null, result);
  5146. }
  5147. callback(null, data);
  5148. });
  5149. }, params.onHashProgress);
  5150. }
  5151.  
  5152. /**
  5153. * 删除 object
  5154. * @param {Object} params 参数对象,必须
  5155. * @param {String} params.Bucket Bucket名称,必须
  5156. * @param {String} params.Region 地域名称,必须
  5157. * @param {String} params.Key object名称,必须
  5158. * @param {Function} callback 回调函数,必须
  5159. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5160. * @param {Object} data 删除操作成功之后返回的数据
  5161. */
  5162. function deleteObject(params, callback) {
  5163. submitRequest.call(this, {
  5164. Action: 'name/cos:DeleteObject',
  5165. method: 'DELETE',
  5166. Bucket: params.Bucket,
  5167. Region: params.Region,
  5168. Key: params.Key,
  5169. headers: params.Headers,
  5170. VersionId: params.VersionId
  5171. }, function (err, data) {
  5172. if (err) {
  5173. var statusCode = err.statusCode;
  5174. if (statusCode && statusCode === 204) {
  5175. return callback(null, { statusCode: statusCode });
  5176. } else if (statusCode && statusCode === 404) {
  5177. return callback(null, { BucketNotFound: true, statusCode: statusCode });
  5178. } else {
  5179. return callback(err);
  5180. }
  5181. }
  5182. callback(null, {
  5183. statusCode: data.statusCode,
  5184. headers: data.headers
  5185. });
  5186. });
  5187. }
  5188.  
  5189. /**
  5190. * 获取 object 的 权限列表
  5191. * @param {Object} params 参数对象,必须
  5192. * @param {String} params.Bucket Bucket名称,必须
  5193. * @param {String} params.Region 地域名称,必须
  5194. * @param {String} params.Key object名称,必须
  5195. * @param {Function} callback 回调函数,必须
  5196. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5197. * @return {Object} data 返回的数据
  5198. * @return {Object} data.AccessControlPolicy 权限列表
  5199. */
  5200. function getObjectAcl(params, callback) {
  5201.  
  5202. submitRequest.call(this, {
  5203. Action: 'name/cos:GetObjectACL',
  5204. method: 'GET',
  5205. Bucket: params.Bucket,
  5206. Region: params.Region,
  5207. Key: params.Key,
  5208. headers: params.Headers,
  5209. action: 'acl'
  5210. }, function (err, data) {
  5211. if (err) {
  5212. return callback(err);
  5213. }
  5214. var AccessControlPolicy = data.AccessControlPolicy || {};
  5215. var Owner = AccessControlPolicy.Owner || {};
  5216. var Grant = AccessControlPolicy.AccessControlList && AccessControlPolicy.AccessControlList.Grant || [];
  5217. Grant = util.isArray(Grant) ? Grant : [Grant];
  5218. var result = decodeAcl(AccessControlPolicy);
  5219. if (data.headers && data.headers['x-cos-acl']) {
  5220. result.ACL = data.headers['x-cos-acl'];
  5221. }
  5222. result = util.extend(result, {
  5223. Owner: Owner,
  5224. Grants: Grant,
  5225. statusCode: data.statusCode,
  5226. headers: data.headers
  5227. });
  5228. callback(null, result);
  5229. });
  5230. }
  5231.  
  5232. /**
  5233. * 设置 object 的 权限列表
  5234. * @param {Object} params 参数对象,必须
  5235. * @param {String} params.Bucket Bucket名称,必须
  5236. * @param {String} params.Region 地域名称,必须
  5237. * @param {String} params.Key object名称,必须
  5238. * @param {Function} callback 回调函数,必须
  5239. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5240. * @return {Object} data 返回的数据
  5241. */
  5242. function putObjectAcl(params, callback) {
  5243. var headers = params.Headers;
  5244.  
  5245. var xml = '';
  5246. if (params['AccessControlPolicy']) {
  5247. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  5248. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  5249. Grants = util.isArray(Grants) ? Grants : [Grants];
  5250. delete AccessControlPolicy.Grant;
  5251. delete AccessControlPolicy.Grants;
  5252. AccessControlPolicy.AccessControlList = { Grant: Grants };
  5253. xml = util.json2xml({ AccessControlPolicy: AccessControlPolicy });
  5254.  
  5255. headers['Content-Type'] = 'application/xml';
  5256. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5257. }
  5258.  
  5259. // Grant Header 去重
  5260. util.each(headers, function (val, key) {
  5261. if (key.indexOf('x-cos-grant-') === 0) {
  5262. headers[key] = uniqGrant(headers[key]);
  5263. }
  5264. });
  5265.  
  5266. submitRequest.call(this, {
  5267. Action: 'name/cos:PutObjectACL',
  5268. method: 'PUT',
  5269. Bucket: params.Bucket,
  5270. Region: params.Region,
  5271. Key: params.Key,
  5272. action: 'acl',
  5273. headers: headers,
  5274. body: xml
  5275. }, function (err, data) {
  5276. if (err) {
  5277. return callback(err);
  5278. }
  5279. callback(null, {
  5280. statusCode: data.statusCode,
  5281. headers: data.headers
  5282. });
  5283. });
  5284. }
  5285.  
  5286. /**
  5287. * Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
  5288. * @param {Object} params 参数对象,必须
  5289. * @param {String} params.Bucket Bucket名称,必须
  5290. * @param {String} params.Region 地域名称,必须
  5291. * @param {String} params.Key object名称,必须
  5292. * @param {Function} callback 回调函数,必须
  5293. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5294. * @return {Object} data 返回的数据
  5295. */
  5296. function optionsObject(params, callback) {
  5297.  
  5298. var headers = params.Headers;
  5299. headers['Origin'] = params['Origin'];
  5300. headers['Access-Control-Request-Method'] = params['AccessControlRequestMethod'];
  5301. headers['Access-Control-Request-Headers'] = params['AccessControlRequestHeaders'];
  5302.  
  5303. submitRequest.call(this, {
  5304. Action: 'name/cos:OptionsObject',
  5305. method: 'OPTIONS',
  5306. Bucket: params.Bucket,
  5307. Region: params.Region,
  5308. Key: params.Key,
  5309. headers: headers
  5310. }, function (err, data) {
  5311. if (err) {
  5312. if (err.statusCode && err.statusCode === 403) {
  5313. return callback(null, {
  5314. OptionsForbidden: true,
  5315. statusCode: err.statusCode
  5316. });
  5317. }
  5318. return callback(err);
  5319. }
  5320.  
  5321. var headers = data.headers || {};
  5322. callback(null, {
  5323. AccessControlAllowOrigin: headers['access-control-allow-origin'],
  5324. AccessControlAllowMethods: headers['access-control-allow-methods'],
  5325. AccessControlAllowHeaders: headers['access-control-allow-headers'],
  5326. AccessControlExposeHeaders: headers['access-control-expose-headers'],
  5327. AccessControlMaxAge: headers['access-control-max-age'],
  5328. statusCode: data.statusCode,
  5329. headers: data.headers
  5330. });
  5331. });
  5332. }
  5333.  
  5334. /**
  5335. * @param {Object} 参数列表
  5336. * @param {String} Bucket Bucket 名称
  5337. * @param {String} Region 地域名称
  5338. * @param {String} Key 文件名称
  5339. * @param {String} CopySource 源文件URL绝对路径,可以通过versionid子资源指定历史版本
  5340. * @param {String} ACL 允许用户自定义文件权限。有效值:private,public-read默认值:private。
  5341. * @param {String} GrantRead 赋予被授权者读的权限,格式 x-cos-grant-read: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  5342. * @param {String} GrantWrite 赋予被授权者写的权限,格式 x-cos-grant-write: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  5343. * @param {String} GrantFullControl 赋予被授权者读写权限,格式 x-cos-grant-full-control: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  5344. * @param {String} MetadataDirective 是否拷贝元数据,枚举值:Copy, Replaced,默认值Copy。假如标记为Copy,忽略Header中的用户元数据信息直接复制;假如标记为Replaced,按Header信息修改元数据。当目标路径和原路径一致,即用户试图修改元数据时,必须为Replaced
  5345. * @param {String} CopySourceIfModifiedSince 当Object在指定时间后被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-None-Match一起使用,与其他条件联合使用返回冲突。
  5346. * @param {String} CopySourceIfUnmodifiedSince 当Object在指定时间后未被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-Match一起使用,与其他条件联合使用返回冲突。
  5347. * @param {String} CopySourceIfMatch 当Object的Etag和给定一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Unmodified-Since一起使用,与其他条件联合使用返回冲突。
  5348. * @param {String} CopySourceIfNoneMatch 当Object的Etag和给定不一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Modified-Since一起使用,与其他条件联合使用返回冲突。
  5349. * @param {String} StorageClass 存储级别,枚举值:存储级别,枚举值:Standard, Standard_IA,Archive;默认值:Standard
  5350. * @param {String} CacheControl 指定所有缓存机制在整个请求/响应链中必须服从的指令。
  5351. * @param {String} ContentDisposition MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件
  5352. * @param {String} ContentEncoding HTTP 中用来对「采用何种编码格式传输正文」进行协定的一对头部字段
  5353. * @param {String} ContentLength 设置响应消息的实体内容的大小,单位为字节
  5354. * @param {String} ContentType RFC 2616 中定义的 HTTP 请求内容类型(MIME),例如text/plain
  5355. * @param {String} Expect 请求的特定的服务器行为
  5356. * @param {String} Expires 响应过期的日期和时间
  5357. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  5358. * @param {String} ContentLanguage 指定内容语言
  5359. * @param {String} x-cos-meta-* 允许用户自定义的头部信息,将作为 Object 元数据返回。大小限制2K。
  5360. */
  5361. function putObjectCopy(params, callback) {
  5362.  
  5363. // 特殊处理 Cache-Control
  5364. var headers = params.Headers;
  5365. !headers['Cache-Control'] && (headers['Cache-Control'] = '');
  5366.  
  5367. var CopySource = params.CopySource || '';
  5368. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  5369. if (!m) {
  5370. callback({ error: 'CopySource format error' });
  5371. return;
  5372. }
  5373.  
  5374. var SourceBucket = m[1];
  5375. var SourceRegion = m[3];
  5376. var SourceKey = decodeURIComponent(m[4]);
  5377.  
  5378. submitRequest.call(this, {
  5379. Scope: [{
  5380. action: 'name/cos:GetObject',
  5381. bucket: SourceBucket,
  5382. region: SourceRegion,
  5383. prefix: SourceKey
  5384. }, {
  5385. action: 'name/cos:PutObject',
  5386. bucket: params.Bucket,
  5387. region: params.Region,
  5388. prefix: params.Key
  5389. }],
  5390. method: 'PUT',
  5391. Bucket: params.Bucket,
  5392. Region: params.Region,
  5393. Key: params.Key,
  5394. VersionId: params.VersionId,
  5395. headers: params.Headers
  5396. }, function (err, data) {
  5397. if (err) {
  5398. return callback(err);
  5399. }
  5400. var result = util.clone(data.CopyObjectResult || {});
  5401. util.extend(result, {
  5402. statusCode: data.statusCode,
  5403. headers: data.headers
  5404. });
  5405. callback(null, result);
  5406. });
  5407. }
  5408.  
  5409. function uploadPartCopy(params, callback) {
  5410.  
  5411. var CopySource = params.CopySource || '';
  5412. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  5413. if (!m) {
  5414. callback({ error: 'CopySource format error' });
  5415. return;
  5416. }
  5417.  
  5418. var SourceBucket = m[1];
  5419. var SourceRegion = m[3];
  5420. var SourceKey = decodeURIComponent(m[4]);
  5421.  
  5422. submitRequest.call(this, {
  5423. Scope: [{
  5424. action: 'name/cos:GetObject',
  5425. bucket: SourceBucket,
  5426. region: SourceRegion,
  5427. prefix: SourceKey
  5428. }, {
  5429. action: 'name/cos:PutObject',
  5430. bucket: params.Bucket,
  5431. region: params.Region,
  5432. prefix: params.Key
  5433. }],
  5434. method: 'PUT',
  5435. Bucket: params.Bucket,
  5436. Region: params.Region,
  5437. Key: params.Key,
  5438. VersionId: params.VersionId,
  5439. qs: {
  5440. partNumber: params['PartNumber'],
  5441. uploadId: params['UploadId']
  5442. },
  5443. headers: params.Headers
  5444. }, function (err, data) {
  5445. if (err) {
  5446. return callback(err);
  5447. }
  5448. var result = util.clone(data.CopyPartResult || {});
  5449. util.extend(result, {
  5450. statusCode: data.statusCode,
  5451. headers: data.headers
  5452. });
  5453. callback(null, result);
  5454. });
  5455. }
  5456.  
  5457. function deleteMultipleObject(params, callback) {
  5458. var Objects = params.Objects || [];
  5459. var Quiet = params.Quiet;
  5460. Objects = util.isArray(Objects) ? Objects : [Objects];
  5461.  
  5462. var xml = util.json2xml({ Delete: { Object: Objects, Quiet: Quiet || false } });
  5463.  
  5464. var headers = params.Headers;
  5465. headers['Content-Type'] = 'application/xml';
  5466. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5467.  
  5468. var Scope = util.map(Objects, function (v) {
  5469. return {
  5470. action: 'name/cos:DeleteObject',
  5471. bucket: params.Bucket,
  5472. region: params.Region,
  5473. prefix: v.Key
  5474. };
  5475. });
  5476.  
  5477. submitRequest.call(this, {
  5478. Scope: Scope,
  5479. method: 'POST',
  5480. Bucket: params.Bucket,
  5481. Region: params.Region,
  5482. body: xml,
  5483. action: 'delete',
  5484. headers: headers
  5485. }, function (err, data) {
  5486. if (err) {
  5487. return callback(err);
  5488. }
  5489. var DeleteResult = data.DeleteResult || {};
  5490. var Deleted = DeleteResult.Deleted || [];
  5491. var Errors = DeleteResult.Error || [];
  5492.  
  5493. Deleted = util.isArray(Deleted) ? Deleted : [Deleted];
  5494. Errors = util.isArray(Errors) ? Errors : [Errors];
  5495.  
  5496. var result = util.clone(DeleteResult);
  5497. util.extend(result, {
  5498. Error: Errors,
  5499. Deleted: Deleted,
  5500. statusCode: data.statusCode,
  5501. headers: data.headers
  5502. });
  5503. callback(null, result);
  5504. });
  5505. }
  5506.  
  5507. function restoreObject(params, callback) {
  5508. var headers = params.Headers;
  5509. if (!params['RestoreRequest']) {
  5510. callback({ error: 'missing param RestoreRequest' });
  5511. return;
  5512. }
  5513.  
  5514. var RestoreRequest = params.RestoreRequest || {};
  5515. var xml = util.json2xml({ RestoreRequest: RestoreRequest });
  5516.  
  5517. headers['Content-Type'] = 'application/xml';
  5518. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5519.  
  5520. submitRequest.call(this, {
  5521. Action: 'name/cos:RestoreObject',
  5522. method: 'POST',
  5523. Bucket: params.Bucket,
  5524. Region: params.Region,
  5525. Key: params.Key,
  5526. VersionId: params.VersionId,
  5527. body: xml,
  5528. action: 'restore',
  5529. headers: headers
  5530. }, function (err, data) {
  5531. callback(err, data);
  5532. });
  5533. }
  5534.  
  5535. // 分块上传
  5536.  
  5537.  
  5538. /**
  5539. * 初始化分块上传
  5540. * @param {Object} params 参数对象,必须
  5541. * @param {String} params.Bucket Bucket名称,必须
  5542. * @param {String} params.Region 地域名称,必须
  5543. * @param {String} params.Key object名称,必须
  5544. * @param {String} params.UploadId object名称,必须
  5545. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  5546. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存 ,非必须
  5547. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  5548. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  5549. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  5550. * @param {String} params.ACL 允许用户自定义文件权限,非必须
  5551. * @param {String} params.GrantRead 赋予被授权者读的权限 ,非必须
  5552. * @param {String} params.GrantWrite 赋予被授权者写的权限 ,非必须
  5553. * @param {String} params.GrantFullControl 赋予被授权者读写权限 ,非必须
  5554. * @param {String} params.StorageClass 设置Object的存储级别,枚举值:Standard,Standard_IA,Archive,非必须
  5555. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  5556. * @param {Function} callback 回调函数,必须
  5557. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5558. * @return {Object} data 返回的数据
  5559. */
  5560. function multipartInit(params, callback) {
  5561.  
  5562. var self = this;
  5563. var headers = params.Headers;
  5564.  
  5565. // 特殊处理 Cache-Control
  5566. !headers['Cache-Control'] && (headers['Cache-Control'] = '');
  5567. util.getBodyMd5(params.Body && (params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5), params.Body, function (md5) {
  5568. if (md5) params.Headers['x-cos-meta-md5'] = md5;
  5569. submitRequest.call(self, {
  5570. Action: 'name/cos:InitiateMultipartUpload',
  5571. method: 'POST',
  5572. Bucket: params.Bucket,
  5573. Region: params.Region,
  5574. Key: params.Key,
  5575. action: 'uploads',
  5576. headers: params.Headers
  5577. }, function (err, data) {
  5578. if (err) {
  5579. return callback(err);
  5580. }
  5581. data = util.clone(data || {});
  5582. if (data && data.InitiateMultipartUploadResult) {
  5583. return callback(null, util.extend(data.InitiateMultipartUploadResult, {
  5584. statusCode: data.statusCode,
  5585. headers: data.headers
  5586. }));
  5587. }
  5588. callback(null, data);
  5589. });
  5590. }, params.onHashProgress);
  5591. }
  5592.  
  5593. /**
  5594. * 分块上传
  5595. * @param {Object} params 参数对象,必须
  5596. * @param {String} params.Bucket Bucket名称,必须
  5597. * @param {String} params.Region 地域名称,必须
  5598. * @param {String} params.Key object名称,必须
  5599. * @param {File || Blob || String} params.Body 上传文件对象或字符串
  5600. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),非必须
  5601. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  5602. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  5603. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验值,非必须
  5604. * @param {Function} callback 回调函数,必须
  5605. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5606. * @return {Object} data 返回的数据
  5607. * @return {Object} data.ETag 返回的文件分块 sha1 值
  5608. */
  5609. function multipartUpload(params, callback) {
  5610.  
  5611. var self = this;
  5612. util.getFileSize('multipartUpload', params, function () {
  5613. util.getBodyMd5(self.options.UploadCheckContentMd5, params.Body, function (md5) {
  5614. if (md5) params.Headers['Content-MD5'] = util.binaryBase64(md5);
  5615. submitRequest.call(self, {
  5616. Action: 'name/cos:UploadPart',
  5617. TaskId: params.TaskId,
  5618. method: 'PUT',
  5619. Bucket: params.Bucket,
  5620. Region: params.Region,
  5621. Key: params.Key,
  5622. qs: {
  5623. partNumber: params['PartNumber'],
  5624. uploadId: params['UploadId']
  5625. },
  5626. headers: params.Headers,
  5627. onProgress: params.onProgress,
  5628. body: params.Body || null
  5629. }, function (err, data) {
  5630. if (err) {
  5631. return callback(err);
  5632. }
  5633. data['headers'] = data['headers'] || {};
  5634. callback(null, {
  5635. ETag: data['headers']['etag'] || '',
  5636. statusCode: data.statusCode,
  5637. headers: data.headers
  5638. });
  5639. });
  5640. });
  5641. });
  5642. }
  5643.  
  5644. /**
  5645. * 完成分块上传
  5646. * @param {Object} params 参数对象,必须
  5647. * @param {String} params.Bucket Bucket名称,必须
  5648. * @param {String} params.Region 地域名称,必须
  5649. * @param {String} params.Key object名称,必须
  5650. * @param {Array} params.Parts 分块信息列表,必须
  5651. * @param {String} params.Parts[i].PartNumber 块编号,必须
  5652. * @param {String} params.Parts[i].ETag 分块的 sha1 校验值
  5653. * @param {Function} callback 回调函数,必须
  5654. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5655. * @return {Object} data 返回的数据
  5656. * @return {Object} data.CompleteMultipartUpload 完成分块上传后的文件信息,包括Location, Bucket, Key 和 ETag
  5657. */
  5658. function multipartComplete(params, callback) {
  5659. var self = this;
  5660.  
  5661. var UploadId = params.UploadId;
  5662.  
  5663. var Parts = params['Parts'];
  5664.  
  5665. for (var i = 0, len = Parts.length; i < len; i++) {
  5666. if (Parts[i]['ETag'].indexOf('"') === 0) {
  5667. continue;
  5668. }
  5669. Parts[i]['ETag'] = '"' + Parts[i]['ETag'] + '"';
  5670. }
  5671.  
  5672. var xml = util.json2xml({ CompleteMultipartUpload: { Part: Parts } });
  5673.  
  5674. var headers = params.Headers;
  5675. headers['Content-Type'] = 'application/xml';
  5676. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5677.  
  5678. submitRequest.call(this, {
  5679. Action: 'name/cos:CompleteMultipartUpload',
  5680. method: 'POST',
  5681. Bucket: params.Bucket,
  5682. Region: params.Region,
  5683. Key: params.Key,
  5684. qs: {
  5685. uploadId: UploadId
  5686. },
  5687. body: xml,
  5688. headers: headers
  5689. }, function (err, data) {
  5690. if (err) {
  5691. return callback(err);
  5692. }
  5693. var url = getUrl({
  5694. ForcePathStyle: self.options.ForcePathStyle,
  5695. protocol: self.options.Protocol,
  5696. domain: self.options.Domain,
  5697. bucket: params.Bucket,
  5698. region: params.Region,
  5699. object: params.Key,
  5700. isLocation: true
  5701. });
  5702. var CompleteMultipartUploadResult = data.CompleteMultipartUploadResult || {};
  5703. var result = util.extend(CompleteMultipartUploadResult, {
  5704. Location: url,
  5705. statusCode: data.statusCode,
  5706. headers: data.headers
  5707. });
  5708. callback(null, result);
  5709. });
  5710. }
  5711.  
  5712. /**
  5713. * 分块上传任务列表查询
  5714. * @param {Object} params 参数对象,必须
  5715. * @param {String} params.Bucket Bucket名称,必须
  5716. * @param {String} params.Region 地域名称,必须
  5717. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,定义为Common Prefix,然后列出所有Common Prefix。如果没有Prefix,则从路径起点开始,非必须
  5718. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  5719. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  5720. * @param {String} params.MaxUploads 单次返回最大的条目数量,默认1000,非必须
  5721. * @param {String} params.KeyMarker 与upload-id-marker一起使用 </Br>当upload-id-marker未被指定时,ObjectName字母顺序大于key-marker的条目将被列出 </Br>当upload-id-marker被指定时,ObjectName字母顺序大于key-marker的条目被列出,ObjectName字母顺序等于key-marker同时UploadId大于upload-id-marker的条目将被列出,非必须
  5722. * @param {String} params.UploadIdMarker 与key-marker一起使用 </Br>当key-marker未被指定时,upload-id-marker将被忽略 </Br>当key-marker被指定时,ObjectName字母顺序大于key-marker的条目被列出,ObjectName字母顺序等于key-marker同时UploadId大于upload-id-marker的条目将被列出,非必须
  5723. * @param {Function} callback 回调函数,必须
  5724. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5725. * @return {Object} data 返回的数据
  5726. * @return {Object} data.ListMultipartUploadsResult 分块上传任务信息
  5727. */
  5728. function multipartList(params, callback) {
  5729. var reqParams = {};
  5730.  
  5731. reqParams['delimiter'] = params['Delimiter'];
  5732. reqParams['encoding-type'] = params['EncodingType'];
  5733. reqParams['prefix'] = params['Prefix'] || '';
  5734.  
  5735. reqParams['max-uploads'] = params['MaxUploads'];
  5736.  
  5737. reqParams['key-marker'] = params['KeyMarker'];
  5738. reqParams['upload-id-marker'] = params['UploadIdMarker'];
  5739.  
  5740. reqParams = util.clearKey(reqParams);
  5741.  
  5742. submitRequest.call(this, {
  5743. Action: 'name/cos:ListMultipartUploads',
  5744. ResourceKey: reqParams['prefix'],
  5745. method: 'GET',
  5746. Bucket: params.Bucket,
  5747. Region: params.Region,
  5748. headers: params.Headers,
  5749. qs: reqParams,
  5750. action: 'uploads'
  5751. }, function (err, data) {
  5752. if (err) {
  5753. return callback(err);
  5754. }
  5755.  
  5756. if (data && data.ListMultipartUploadsResult) {
  5757. var Upload = data.ListMultipartUploadsResult.Upload || [];
  5758.  
  5759. var CommonPrefixes = data.ListMultipartUploadsResult.CommonPrefixes || [];
  5760.  
  5761. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  5762. Upload = util.isArray(Upload) ? Upload : [Upload];
  5763.  
  5764. data.ListMultipartUploadsResult.Upload = Upload;
  5765. data.ListMultipartUploadsResult.CommonPrefixes = CommonPrefixes;
  5766. }
  5767. var result = util.clone(data.ListMultipartUploadsResult || {});
  5768. util.extend(result, {
  5769. statusCode: data.statusCode,
  5770. headers: data.headers
  5771. });
  5772. callback(null, result);
  5773. });
  5774. }
  5775.  
  5776. /**
  5777. * 上传的分块列表查询
  5778. * @param {Object} params 参数对象,必须
  5779. * @param {String} params.Bucket Bucket名称,必须
  5780. * @param {String} params.Region 地域名称,必须
  5781. * @param {String} params.Key object名称,必须
  5782. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  5783. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  5784. * @param {String} params.MaxParts 单次返回最大的条目数量,默认1000,非必须
  5785. * @param {String} params.PartNumberMarker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  5786. * @param {Function} callback 回调函数,必须
  5787. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5788. * @return {Object} data 返回的数据
  5789. * @return {Object} data.ListMultipartUploadsResult 分块信息
  5790. */
  5791. function multipartListPart(params, callback) {
  5792. var reqParams = {};
  5793.  
  5794. reqParams['uploadId'] = params['UploadId'];
  5795. reqParams['encoding-type'] = params['EncodingType'];
  5796. reqParams['max-parts'] = params['MaxParts'];
  5797. reqParams['part-number-marker'] = params['PartNumberMarker'];
  5798.  
  5799. submitRequest.call(this, {
  5800. Action: 'name/cos:ListParts',
  5801. method: 'GET',
  5802. Bucket: params.Bucket,
  5803. Region: params.Region,
  5804. Key: params.Key,
  5805. headers: params.Headers,
  5806. qs: reqParams
  5807. }, function (err, data) {
  5808. if (err) {
  5809. return callback(err);
  5810. }
  5811. var ListPartsResult = data.ListPartsResult || {};
  5812. var Part = ListPartsResult.Part || [];
  5813. Part = util.isArray(Part) ? Part : [Part];
  5814.  
  5815. ListPartsResult.Part = Part;
  5816. var result = util.clone(ListPartsResult);
  5817. util.extend(result, {
  5818. statusCode: data.statusCode,
  5819. headers: data.headers
  5820. });
  5821. callback(null, result);
  5822. });
  5823. }
  5824.  
  5825. /**
  5826. * 抛弃分块上传
  5827. * @param {Object} params 参数对象,必须
  5828. * @param {String} params.Bucket Bucket名称,必须
  5829. * @param {String} params.Region 地域名称,必须
  5830. * @param {String} params.Key object名称,必须
  5831. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  5832. * @param {Function} callback 回调函数,必须
  5833. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5834. * @return {Object} data 返回的数据
  5835. */
  5836. function multipartAbort(params, callback) {
  5837. var reqParams = {};
  5838.  
  5839. reqParams['uploadId'] = params['UploadId'];
  5840. submitRequest.call(this, {
  5841. Action: 'name/cos:AbortMultipartUpload',
  5842. method: 'DELETE',
  5843. Bucket: params.Bucket,
  5844. Region: params.Region,
  5845. Key: params.Key,
  5846. headers: params.Headers,
  5847. qs: reqParams
  5848. }, function (err, data) {
  5849. if (err) {
  5850. return callback(err);
  5851. }
  5852. callback(null, {
  5853. statusCode: data.statusCode,
  5854. headers: data.headers
  5855. });
  5856. });
  5857. }
  5858.  
  5859. /**
  5860. * 获取签名
  5861. * @param {Object} params 参数对象,必须
  5862. * @param {String} params.Method 请求方法,必须
  5863. * @param {String} params.Key object名称,必须
  5864. * @param {String} params.Expires 名超时时间,单位秒,可选
  5865. * @return {String} data 返回签名字符串
  5866. */
  5867. function getAuth(params) {
  5868. var self = this;
  5869. return util.getAuth({
  5870. SecretId: params.SecretId || this.options.SecretId || '',
  5871. SecretKey: params.SecretKey || this.options.SecretKey || '',
  5872. Method: params.Method,
  5873. Key: params.Key,
  5874. Query: params.Query,
  5875. Headers: params.Headers,
  5876. Expires: params.Expires,
  5877. UseRawKey: self.options.UseRawKey,
  5878. SystemClockOffset: self.options.SystemClockOffset
  5879. });
  5880. }
  5881.  
  5882. /**
  5883. * 获取文件下载链接
  5884. * @param {Object} params 参数对象,必须
  5885. * @param {String} params.Bucket Bucket名称,必须
  5886. * @param {String} params.Region 地域名称,必须
  5887. * @param {String} params.Key object名称,必须
  5888. * @param {String} params.Method 请求的方法,可选
  5889. * @param {String} params.Expires 签名超时时间,单位秒,可选
  5890. * @param {Function} callback 回调函数,必须
  5891. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5892. * @return {Object} data 返回的数据
  5893. */
  5894. function getObjectUrl(params, callback) {
  5895. var self = this;
  5896. var url = getUrl({
  5897. ForcePathStyle: self.options.ForcePathStyle,
  5898. protocol: params.Protocol || self.options.Protocol,
  5899. domain: self.options.Domain,
  5900. bucket: params.Bucket,
  5901. region: params.Region,
  5902. object: params.Key
  5903. });
  5904. if (params.Sign !== undefined && !params.Sign) {
  5905. callback(null, { Url: url });
  5906. return url;
  5907. }
  5908. var AuthData = getAuthorizationAsync.call(this, {
  5909. Action: (params.Method || '').toUpperCase() === 'PUT' ? 'name/cos:PutObject' : 'name/cos:GetObject',
  5910. Bucket: params.Bucket || '',
  5911. Region: params.Region || '',
  5912. Method: params.Method || 'get',
  5913. Key: params.Key,
  5914. Expires: params.Expires
  5915. }, function (err, AuthData) {
  5916. if (!callback) return;
  5917. if (err) {
  5918. callback(err);
  5919. return;
  5920. }
  5921. var signUrl = url;
  5922. signUrl += '?' + (AuthData.Authorization.indexOf('q-signature') > -1 ? AuthData.Authorization : 'sign=' + encodeURIComponent(AuthData.Authorization));
  5923. AuthData.XCosSecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.XCosSecurityToken);
  5924. AuthData.ClientIP && (signUrl += '&clientIP=' + AuthData.ClientIP);
  5925. AuthData.ClientUA && (signUrl += '&clientUA=' + AuthData.ClientUA);
  5926. AuthData.Token && (signUrl += '&token=' + AuthData.Token);
  5927. setTimeout(function () {
  5928. callback(null, { Url: signUrl });
  5929. });
  5930. });
  5931. if (AuthData) {
  5932. return url + '?' + AuthData.Authorization + (AuthData.XCosSecurityToken ? '&x-cos-security-token=' + AuthData.XCosSecurityToken : '');
  5933. } else {
  5934. return url;
  5935. }
  5936. }
  5937.  
  5938. /**
  5939. * 私有方法
  5940. */
  5941. function decodeAcl(AccessControlPolicy) {
  5942. var result = {
  5943. GrantFullControl: [],
  5944. GrantWrite: [],
  5945. GrantRead: [],
  5946. GrantReadAcp: [],
  5947. GrantWriteAcp: [],
  5948. ACL: ''
  5949. };
  5950. var GrantMap = {
  5951. 'FULL_CONTROL': 'GrantFullControl',
  5952. 'WRITE': 'GrantWrite',
  5953. 'READ': 'GrantRead',
  5954. 'READ_ACP': 'GrantReadAcp',
  5955. 'WRITE_ACP': 'GrantWriteAcp'
  5956. };
  5957. var Grant = AccessControlPolicy.AccessControlList.Grant;
  5958. if (Grant) {
  5959. Grant = util.isArray(Grant) ? Grant : [Grant];
  5960. }
  5961. var PublicAcl = { READ: 0, WRITE: 0, FULL_CONTROL: 0 };
  5962. Grant.length && util.each(Grant, function (item) {
  5963. if (item.Grantee.ID === 'qcs::cam::anyone:anyone' || item.Grantee.URI === 'http://cam.qcloud.com/groups/global/AllUsers') {
  5964. PublicAcl[item.Permission] = 1;
  5965. } else if (item.Grantee.ID !== AccessControlPolicy.Owner.ID) {
  5966. result[GrantMap[item.Permission]].push('id="' + item.Grantee.ID + '"');
  5967. }
  5968. });
  5969. if (PublicAcl.FULL_CONTROL || PublicAcl.WRITE && PublicAcl.READ) {
  5970. result.ACL = 'public-read-write';
  5971. } else if (PublicAcl.READ) {
  5972. result.ACL = 'public-read';
  5973. } else {
  5974. result.ACL = 'private';
  5975. }
  5976. util.each(GrantMap, function (item) {
  5977. result[item] = uniqGrant(result[item].join(','));
  5978. });
  5979. return result;
  5980. }
  5981.  
  5982. // Grant 去重
  5983. function uniqGrant(str) {
  5984. var arr = str.split(',');
  5985. var exist = {};
  5986. var i, item;
  5987. for (i = 0; i < arr.length;) {
  5988. item = arr[i].trim();
  5989. if (exist[item]) {
  5990. arr.splice(i, 1);
  5991. } else {
  5992. exist[item] = true;
  5993. arr[i] = item;
  5994. i++;
  5995. }
  5996. }
  5997. return arr.join(',');
  5998. }
  5999.  
  6000. // 生成操作 url
  6001. function getUrl(params) {
  6002. var longBucket = params.bucket;
  6003. var shortBucket = longBucket.substr(0, longBucket.lastIndexOf('-'));
  6004. var appId = longBucket.substr(longBucket.lastIndexOf('-') + 1);
  6005. var domain = params.domain;
  6006. var region = params.region;
  6007. var object = params.object;
  6008. var protocol = params.protocol || (util.isBrowser && location.protocol === 'http:' ? 'http:' : 'https:');
  6009. if (!domain) {
  6010. if (['cn-south', 'cn-south-2', 'cn-north', 'cn-east', 'cn-southwest', 'sg'].indexOf(region) > -1) {
  6011. domain = '{Region}.myqcloud.com';
  6012. } else {
  6013. domain = 'cos.{Region}.myqcloud.com';
  6014. }
  6015. if (!params.ForcePathStyle) {
  6016. domain = '{Bucket}.' + domain;
  6017. }
  6018. }
  6019. domain = domain.replace(/\{\{AppId\}\}/ig, appId).replace(/\{\{Bucket\}\}/ig, shortBucket).replace(/\{\{Region\}\}/ig, region).replace(/\{\{.*?\}\}/ig, '');
  6020. domain = domain.replace(/\{AppId\}/ig, appId).replace(/\{BucketName\}/ig, shortBucket).replace(/\{Bucket\}/ig, longBucket).replace(/\{Region\}/ig, region).replace(/\{.*?\}/ig, '');
  6021. if (!/^[a-zA-Z]+:\/\//.test(domain)) {
  6022. domain = protocol + '//' + domain;
  6023. }
  6024.  
  6025. // 去掉域名最后的斜杆
  6026. if (domain.slice(-1) === '/') {
  6027. domain = domain.slice(0, -1);
  6028. }
  6029. var url = domain;
  6030.  
  6031. if (params.ForcePathStyle) {
  6032. url += '/' + longBucket;
  6033. }
  6034. url += '/';
  6035. if (object) {
  6036. url += util.camSafeUrlEncode(object).replace(/%2F/g, '/');
  6037. }
  6038.  
  6039. if (params.isLocation) {
  6040. url = url.replace(/^https?:\/\//, '');
  6041. }
  6042. return url;
  6043. }
  6044.  
  6045. // 异步获取签名
  6046. function getAuthorizationAsync(params, callback) {
  6047.  
  6048. var headers = util.clone(params.Headers);
  6049. delete headers['Content-Type'];
  6050. delete headers['Cache-Control'];
  6051. util.each(headers, function (v, k) {
  6052. v === '' && delete headers[k];
  6053. });
  6054.  
  6055. var cb = function (AuthData) {
  6056.  
  6057. // 检查签名格式
  6058. var formatAllow = false;
  6059. var auth = AuthData.Authorization;
  6060. if (auth) {
  6061. if (auth.indexOf(' ') > -1) {
  6062. formatAllow = false;
  6063. } else if (auth.indexOf('q-sign-algorithm=') > -1 && auth.indexOf('q-ak=') > -1 && auth.indexOf('q-sign-time=') > -1 && auth.indexOf('q-key-time=') > -1 && auth.indexOf('q-url-param-list=') > -1) {
  6064. formatAllow = true;
  6065. } else {
  6066. try {
  6067. auth = atob(auth);
  6068. if (auth.indexOf('a=') > -1 && auth.indexOf('k=') > -1 && auth.indexOf('t=') > -1 && auth.indexOf('r=') > -1 && auth.indexOf('b=') > -1) {
  6069. formatAllow = true;
  6070. }
  6071. } catch (e) {}
  6072. }
  6073. }
  6074. if (formatAllow) {
  6075. callback && callback(null, AuthData);
  6076. } else {
  6077. callback && callback('authorization error');
  6078. }
  6079. };
  6080.  
  6081. var self = this;
  6082. var Bucket = params.Bucket || '';
  6083. var Region = params.Region || '';
  6084.  
  6085. // PathName
  6086. var KeyName = params.Key || '';
  6087. if (self.options.ForcePathStyle && Bucket) {
  6088. KeyName = Bucket + '/' + KeyName;
  6089. }
  6090. var Pathname = '/' + KeyName;
  6091.  
  6092. // Action、ResourceKey
  6093. var StsData = {};
  6094. var Scope = params.Scope;
  6095. if (!Scope) {
  6096. var Action = params.Action || '';
  6097. var ResourceKey = params.ResourceKey || params.Key || '';
  6098. Scope = params.Scope || [{
  6099. action: Action,
  6100. bucket: Bucket,
  6101. region: Region,
  6102. prefix: ResourceKey
  6103. }];
  6104. }
  6105. var ScopeKey = util.md5(JSON.stringify(Scope));
  6106.  
  6107. // STS
  6108. self._StsCache = self._StsCache || [];
  6109. (function () {
  6110. var i, AuthData;
  6111. for (i = self._StsCache.length - 1; i >= 0; i--) {
  6112. AuthData = self._StsCache[i];
  6113. var compareTime = Math.round(util.getSkewTime(self.options.SystemClockOffset) / 1000) + 30;
  6114. if (AuthData.StartTime && compareTime < AuthData.StartTime || compareTime >= AuthData.ExpiredTime) {
  6115. self._StsCache.splice(i, 1);
  6116. continue;
  6117. }
  6118. if (!AuthData.ScopeLimit || AuthData.ScopeLimit && AuthData.ScopeKey === ScopeKey) {
  6119. StsData = AuthData;
  6120. break;
  6121. }
  6122. }
  6123. })();
  6124.  
  6125. var calcAuthByTmpKey = function () {
  6126. var Authorization = util.getAuth({
  6127. SecretId: StsData.TmpSecretId,
  6128. SecretKey: StsData.TmpSecretKey,
  6129. Method: params.Method,
  6130. Pathname: Pathname,
  6131. Query: params.Query,
  6132. Headers: headers,
  6133. Expires: params.Expires,
  6134. UseRawKey: self.options.UseRawKey,
  6135. SystemClockOffset: self.options.SystemClockOffset
  6136. });
  6137. var AuthData = {
  6138. Authorization: Authorization,
  6139. XCosSecurityToken: StsData.XCosSecurityToken || '',
  6140. Token: StsData.Token || '',
  6141. ClientIP: StsData.ClientIP || '',
  6142. ClientUA: StsData.ClientUA || ''
  6143. };
  6144. cb(AuthData);
  6145. };
  6146.  
  6147. // 先判断是否有临时密钥
  6148. if (StsData.ExpiredTime && StsData.ExpiredTime - util.getSkewTime(self.options.SystemClockOffset) / 1000 > 60) {
  6149. // 如果缓存的临时密钥有效,并还有超过60秒有效期就直接使用
  6150. calcAuthByTmpKey();
  6151. } else if (self.options.getAuthorization) {
  6152. // 外部计算签名或获取临时密钥
  6153. self.options.getAuthorization.call(self, {
  6154. Bucket: Bucket,
  6155. Region: Region,
  6156. Method: params.Method,
  6157. Key: KeyName,
  6158. Pathname: Pathname,
  6159. Query: params.Query,
  6160. Headers: headers,
  6161. Scope: Scope
  6162. }, function (AuthData) {
  6163. if (typeof AuthData === 'string') {
  6164. AuthData = { Authorization: AuthData };
  6165. }
  6166. if (AuthData.TmpSecretId && AuthData.TmpSecretKey && AuthData.XCosSecurityToken && AuthData.ExpiredTime) {
  6167. StsData = AuthData || {};
  6168. StsData.Scope = Scope;
  6169. StsData.ScopeKey = ScopeKey;
  6170. self._StsCache.push(StsData);
  6171. calcAuthByTmpKey();
  6172. } else {
  6173. cb(AuthData);
  6174. }
  6175. });
  6176. } else if (self.options.getSTS) {
  6177. // 外部获取临时密钥
  6178. self.options.getSTS.call(self, {
  6179. Bucket: Bucket,
  6180. Region: Region
  6181. }, function (data) {
  6182. StsData = data || {};
  6183. StsData.Scope = Scope;
  6184. StsData.ScopeKey = ScopeKey;
  6185. StsData.TmpSecretId = StsData.SecretId;
  6186. StsData.TmpSecretKey = StsData.SecretKey;
  6187. self._StsCache.push(StsData);
  6188. calcAuthByTmpKey();
  6189. });
  6190. } else {
  6191. // 内部计算获取签名
  6192. return function () {
  6193. var Authorization = util.getAuth({
  6194. SecretId: params.SecretId || self.options.SecretId,
  6195. SecretKey: params.SecretKey || self.options.SecretKey,
  6196. Method: params.Method,
  6197. Pathname: Pathname,
  6198. Query: params.Query,
  6199. Headers: headers,
  6200. Expires: params.Expires,
  6201. UseRawKey: self.options.UseRawKey,
  6202. SystemClockOffset: self.options.SystemClockOffset
  6203. });
  6204. var AuthData = {
  6205. Authorization: Authorization,
  6206. XCosSecurityToken: self.options.XCosSecurityToken
  6207. };
  6208. cb(AuthData);
  6209. return AuthData;
  6210. }();
  6211. }
  6212. return '';
  6213. }
  6214.  
  6215. // 调整时间偏差
  6216. function allowRetry(err) {
  6217. var allowRetry = false;
  6218. var isTimeError = false;
  6219. var serverDate = err.headers && (err.headers.date || err.headers.Date) || err.error && err.error.ServerTime;
  6220. try {
  6221. var errorCode = err.error.Code;
  6222. var errorMessage = err.error.Message;
  6223. if (errorCode === 'RequestTimeTooSkewed' || errorCode === 'AccessDenied' && errorMessage === 'Request has expired') {
  6224. isTimeError = true;
  6225. }
  6226. } catch (e) {}
  6227. if (err) {
  6228. if (isTimeError && serverDate) {
  6229. var serverTime = Date.parse(serverDate);
  6230. if (this.options.CorrectClockSkew && Math.abs(util.getSkewTime(this.options.SystemClockOffset) - serverTime) >= 30000) {
  6231. console.error('error: Local time is too skewed.');
  6232. this.options.SystemClockOffset = serverTime - Date.now();
  6233. allowRetry = true;
  6234. }
  6235. } else if (Math.round(err.statusCode / 100) === 5) {
  6236. allowRetry = true;
  6237. }
  6238. }
  6239. return allowRetry;
  6240. }
  6241.  
  6242. // 获取签名并发起请求
  6243. function submitRequest(params, callback) {
  6244. var self = this;
  6245.  
  6246. // 处理 headers
  6247. !params.headers && (params.headers = {});
  6248.  
  6249. // 处理 query
  6250. !params.qs && (params.qs = {});
  6251. params.VersionId && (params.qs.versionId = params.VersionId);
  6252. params.qs = util.clearKey(params.qs);
  6253.  
  6254. // 清理 undefined 和 null 字段
  6255. params.headers && (params.headers = util.clearKey(params.headers));
  6256. params.qs && (params.qs = util.clearKey(params.qs));
  6257.  
  6258. var Query = util.clone(params.qs);
  6259. params.action && (Query[params.action] = '');
  6260.  
  6261. var next = function (tryTimes) {
  6262. var oldClockOffset = self.options.SystemClockOffset;
  6263. getAuthorizationAsync.call(self, {
  6264. Bucket: params.Bucket || '',
  6265. Region: params.Region || '',
  6266. Method: params.method,
  6267. Key: params.Key,
  6268. Query: Query,
  6269. Headers: params.headers,
  6270. Action: params.Action,
  6271. ResourceKey: params.ResourceKey,
  6272. Scope: params.Scope
  6273. }, function (err, AuthData) {
  6274. if (err) {
  6275. callback(err);
  6276. return;
  6277. }
  6278. params.AuthData = AuthData;
  6279. _submitRequest.call(self, params, function (err, data) {
  6280. if (err && tryTimes < 2 && (oldClockOffset !== self.options.SystemClockOffset || allowRetry.call(self, err))) {
  6281. if (params.headers) {
  6282. delete params.headers.Authorization;
  6283. delete params.headers['token'];
  6284. delete params.headers['clientIP'];
  6285. delete params.headers['clientUA'];
  6286. delete params.headers['x-cos-security-token'];
  6287. }
  6288. next(tryTimes + 1);
  6289. } else {
  6290. callback(err, data);
  6291. }
  6292. });
  6293. });
  6294. };
  6295. next(1);
  6296. }
  6297.  
  6298. // 发起请求
  6299. function _submitRequest(params, callback) {
  6300. var self = this;
  6301. var TaskId = params.TaskId;
  6302. if (TaskId && !self._isRunningTask(TaskId)) return;
  6303.  
  6304. var bucket = params.Bucket;
  6305. var region = params.Region;
  6306. var object = params.Key;
  6307. var method = params.method || 'GET';
  6308. var url = params.url;
  6309. var body = params.body;
  6310. var json = params.json;
  6311. var rawBody = params.rawBody;
  6312.  
  6313. // url
  6314. url = url || getUrl({
  6315. ForcePathStyle: self.options.ForcePathStyle,
  6316. protocol: self.options.Protocol,
  6317. domain: self.options.Domain,
  6318. bucket: bucket,
  6319. region: region,
  6320. object: object
  6321. });
  6322. if (params.action) {
  6323. url = url + '?' + params.action;
  6324. }
  6325.  
  6326. var opt = {
  6327. method: method,
  6328. url: url,
  6329. headers: params.headers,
  6330. qs: params.qs,
  6331. body: body,
  6332. json: json
  6333. };
  6334.  
  6335. // 获取签名
  6336. opt.headers.Authorization = params.AuthData.Authorization;
  6337. params.AuthData.Token && (opt.headers['token'] = params.AuthData.Token);
  6338. params.AuthData.ClientIP && (opt.headers['clientIP'] = params.AuthData.ClientIP);
  6339. params.AuthData.ClientUA && (opt.headers['clientUA'] = params.AuthData.ClientUA);
  6340. params.AuthData.XCosSecurityToken && (opt.headers['x-cos-security-token'] = params.AuthData.XCosSecurityToken);
  6341.  
  6342. // 清理 undefined 和 null 字段
  6343. opt.headers && (opt.headers = util.clearKey(opt.headers));
  6344. opt = util.clearKey(opt);
  6345.  
  6346. // progress
  6347. if (params.onProgress && typeof params.onProgress === 'function') {
  6348. var contentLength = body && (body.size || body.length) || 0;
  6349. opt.onProgress = function (e) {
  6350. if (TaskId && !self._isRunningTask(TaskId)) return;
  6351. var loaded = e ? e.loaded : 0;
  6352. params.onProgress({ loaded: loaded, total: contentLength });
  6353. };
  6354. }
  6355. if (this.options.Timeout) {
  6356. opt.timeout = this.options.Timeout;
  6357. }
  6358.  
  6359. self.emit('before-send', opt);
  6360. var sender = REQUEST(opt, function (err, response, body) {
  6361. if (err === 'abort') return;
  6362.  
  6363. // 返回内容添加 状态码 和 headers
  6364. var hasReturned;
  6365. var cb = function (err, data) {
  6366. TaskId && self.off('inner-kill-task', killTask);
  6367. if (hasReturned) return;
  6368. hasReturned = true;
  6369. var attrs = {};
  6370. response && response.statusCode && (attrs.statusCode = response.statusCode);
  6371. response && response.headers && (attrs.headers = response.headers);
  6372.  
  6373. if (err) {
  6374. err = util.extend(err || {}, attrs);
  6375. callback(err, null);
  6376. } else {
  6377. data = util.extend(data || {}, attrs);
  6378. callback(null, data);
  6379. }
  6380. sender = null;
  6381. };
  6382.  
  6383. // 请求错误,发生网络错误
  6384. if (err) {
  6385. cb({ error: err });
  6386. return;
  6387. }
  6388.  
  6389. var jsonRes;
  6390.  
  6391. // 不对 body 进行转换,body 直接挂载返回
  6392. if (rawBody) {
  6393. jsonRes = {};
  6394. jsonRes.body = body;
  6395. } else {
  6396. try {
  6397. jsonRes = body && body.indexOf('<') > -1 && body.indexOf('>') > -1 && util.xml2json(body) || {};
  6398. } catch (e) {
  6399. jsonRes = body || {};
  6400. }
  6401. }
  6402.  
  6403. // 请求返回码不为 200
  6404. var statusCode = response.statusCode;
  6405. var statusSuccess = Math.floor(statusCode / 100) === 2; // 200 202 204 206
  6406. if (!statusSuccess) {
  6407. cb({ error: jsonRes.Error || jsonRes });
  6408. return;
  6409. }
  6410.  
  6411. if (jsonRes.Error) {
  6412. cb({ error: jsonRes.Error });
  6413. return;
  6414. }
  6415. cb(null, jsonRes);
  6416. });
  6417.  
  6418. // kill task
  6419. var killTask = function (data) {
  6420. if (data.TaskId === TaskId) {
  6421. sender && sender.abort && sender.abort();
  6422. self.off('inner-kill-task', killTask);
  6423. }
  6424. };
  6425. TaskId && self.on('inner-kill-task', killTask);
  6426. }
  6427.  
  6428. var API_MAP = {
  6429. // Bucket 相关方法
  6430. headBucket: headBucket, // Bucket
  6431. getBucket: getBucket,
  6432. deleteBucket: deleteBucket,
  6433. putBucketAcl: putBucketAcl, // BucketACL
  6434. getBucketAcl: getBucketAcl,
  6435. putBucketCors: putBucketCors, // BucketCors
  6436. getBucketCors: getBucketCors,
  6437. deleteBucketCors: deleteBucketCors,
  6438. getBucketLocation: getBucketLocation, // BucketLocation
  6439. getBucketPolicy: getBucketPolicy, // BucketPolicy
  6440. putBucketPolicy: putBucketPolicy,
  6441. deleteBucketPolicy: deleteBucketPolicy,
  6442. putBucketTagging: putBucketTagging, // BucketTagging
  6443. getBucketTagging: getBucketTagging,
  6444. deleteBucketTagging: deleteBucketTagging,
  6445. putBucketLifecycle: putBucketLifecycle, // BucketLifecycle
  6446. getBucketLifecycle: getBucketLifecycle,
  6447. deleteBucketLifecycle: deleteBucketLifecycle,
  6448. putBucketVersioning: putBucketVersioning, // BucketVersioning
  6449. getBucketVersioning: getBucketVersioning,
  6450. putBucketReplication: putBucketReplication, // BucketReplication
  6451. getBucketReplication: getBucketReplication,
  6452. deleteBucketReplication: deleteBucketReplication,
  6453. putBucketWebsite: putBucketWebsite, // BucketWebsite
  6454. getBucketWebsite: getBucketWebsite,
  6455. deleteBucketWebsite: deleteBucketWebsite,
  6456.  
  6457. // Object 相关方法
  6458. getObject: getObject,
  6459. headObject: headObject,
  6460. listObjectVersions: listObjectVersions,
  6461. putObject: putObject,
  6462. deleteObject: deleteObject,
  6463. getObjectAcl: getObjectAcl,
  6464. putObjectAcl: putObjectAcl,
  6465. optionsObject: optionsObject,
  6466. putObjectCopy: putObjectCopy,
  6467. deleteMultipleObject: deleteMultipleObject,
  6468. restoreObject: restoreObject,
  6469.  
  6470. // 分块上传相关方法
  6471. uploadPartCopy: uploadPartCopy,
  6472. multipartInit: multipartInit,
  6473. multipartUpload: multipartUpload,
  6474. multipartComplete: multipartComplete,
  6475. multipartList: multipartList,
  6476. multipartListPart: multipartListPart,
  6477. multipartAbort: multipartAbort,
  6478.  
  6479. // 工具方法
  6480. getObjectUrl: getObjectUrl,
  6481. getAuth: getAuth
  6482. };
  6483.  
  6484. function warnOldApi(apiName, fn, proto) {
  6485. util.each(['Cors', 'Acl'], function (suffix) {
  6486. if (apiName.slice(-suffix.length) === suffix) {
  6487. var oldName = apiName.slice(0, -suffix.length) + suffix.toUpperCase();
  6488. var apiFn = util.apiWrapper(apiName, fn);
  6489. var warned = false;
  6490. proto[oldName] = function () {
  6491. !warned && console.warn('warning: cos.' + oldName + ' has been deprecated. Please Use cos.' + apiName + ' instead.');
  6492. warned = true;
  6493. apiFn.apply(this, arguments);
  6494. };
  6495. }
  6496. });
  6497. }
  6498.  
  6499. module.exports.init = function (COS, task) {
  6500. task.transferToTaskMethod(API_MAP, 'putObject');
  6501. util.each(API_MAP, function (fn, apiName) {
  6502. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  6503. warnOldApi(apiName, fn, COS.prototype);
  6504. });
  6505. };
  6506.  
  6507. /***/ }),
  6508. /* 13 */
  6509. /***/ (function(module, exports) {
  6510.  
  6511. var $ = function () {
  6512. var deletedIds = [];
  6513.  
  6514. var slice = deletedIds.slice;
  6515.  
  6516. var concat = deletedIds.concat;
  6517.  
  6518. var push = deletedIds.push;
  6519.  
  6520. var indexOf = deletedIds.indexOf;
  6521.  
  6522. var class2type = {};
  6523.  
  6524. var toString = class2type.toString;
  6525.  
  6526. var hasOwn = class2type.hasOwnProperty;
  6527.  
  6528. var support = {};
  6529.  
  6530. var version = "1.11.1 -css,-css/addGetHookIf,-css/curCSS,-css/defaultDisplay,-css/hiddenVisibleSelectors,-css/support,-css/swap,-css/var/cssExpand,-css/var/isHidden,-css/var/rmargin,-css/var/rnumnonpx,-effects,-effects/Tween,-effects/animatedSelector,-effects/support,-dimensions,-offset,-deprecated,-event-alias,-wrap",
  6531.  
  6532.  
  6533. // Define a local copy of jQuery
  6534. jQuery = function (selector, context) {
  6535. // The jQuery object is actually just the init constructor 'enhanced'
  6536. // Need init if jQuery is called (just allow error to be thrown if not included)
  6537. return new jQuery.fn.init(selector, context);
  6538. },
  6539.  
  6540.  
  6541. // Support: Android<4.1, IE<9
  6542. // Make sure we trim BOM and NBSP
  6543. rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
  6544.  
  6545.  
  6546. // Matches dashed string for camelizing
  6547. rmsPrefix = /^-ms-/,
  6548. rdashAlpha = /-([\da-z])/gi,
  6549.  
  6550.  
  6551. // Used by jQuery.camelCase as callback to replace()
  6552. fcamelCase = function (all, letter) {
  6553. return letter.toUpperCase();
  6554. };
  6555.  
  6556. jQuery.fn = jQuery.prototype = {
  6557. // The current version of jQuery being used
  6558. jquery: version,
  6559.  
  6560. constructor: jQuery,
  6561.  
  6562. // Start with an empty selector
  6563. selector: "",
  6564.  
  6565. // The default length of a jQuery object is 0
  6566. length: 0,
  6567.  
  6568. toArray: function () {
  6569. return slice.call(this);
  6570. },
  6571.  
  6572. // Get the Nth element in the matched element set OR
  6573. // Get the whole matched element set as a clean array
  6574. get: function (num) {
  6575. return num != null ?
  6576.  
  6577. // Return just the one element from the set
  6578. num < 0 ? this[num + this.length] : this[num] :
  6579.  
  6580. // Return all the elements in a clean array
  6581. slice.call(this);
  6582. },
  6583.  
  6584. // Take an array of elements and push it onto the stack
  6585. // (returning the new matched element set)
  6586. pushStack: function (elems) {
  6587.  
  6588. // Build a new jQuery matched element set
  6589. var ret = jQuery.merge(this.constructor(), elems);
  6590.  
  6591. // Add the old object onto the stack (as a reference)
  6592. ret.prevObject = this;
  6593. ret.context = this.context;
  6594.  
  6595. // Return the newly-formed element set
  6596. return ret;
  6597. },
  6598.  
  6599. // Execute a callback for every element in the matched set.
  6600. // (You can seed the arguments with an array of args, but this is
  6601. // only used internally.)
  6602. each: function (callback, args) {
  6603. return jQuery.each(this, callback, args);
  6604. },
  6605.  
  6606. map: function (callback) {
  6607. return this.pushStack(jQuery.map(this, function (elem, i) {
  6608. return callback.call(elem, i, elem);
  6609. }));
  6610. },
  6611.  
  6612. slice: function () {
  6613. return this.pushStack(slice.apply(this, arguments));
  6614. },
  6615.  
  6616. first: function () {
  6617. return this.eq(0);
  6618. },
  6619.  
  6620. last: function () {
  6621. return this.eq(-1);
  6622. },
  6623.  
  6624. eq: function (i) {
  6625. var len = this.length,
  6626. j = +i + (i < 0 ? len : 0);
  6627. return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
  6628. },
  6629.  
  6630. end: function () {
  6631. return this.prevObject || this.constructor(null);
  6632. },
  6633.  
  6634. // For internal use only.
  6635. // Behaves like an Array's method, not like a jQuery method.
  6636. push: push,
  6637. sort: deletedIds.sort,
  6638. splice: deletedIds.splice
  6639. };
  6640.  
  6641. jQuery.extend = jQuery.fn.extend = function () {
  6642. var src,
  6643. copyIsArray,
  6644. copy,
  6645. name,
  6646. options,
  6647. clone,
  6648. target = arguments[0] || {},
  6649. i = 1,
  6650. length = arguments.length,
  6651. deep = false;
  6652.  
  6653. // Handle a deep copy situation
  6654. if (typeof target === "boolean") {
  6655. deep = target;
  6656.  
  6657. // skip the boolean and the target
  6658. target = arguments[i] || {};
  6659. i++;
  6660. }
  6661.  
  6662. // Handle case when target is a string or something (possible in deep copy)
  6663. if (typeof target !== "object" && !jQuery.isFunction(target)) {
  6664. target = {};
  6665. }
  6666.  
  6667. // extend jQuery itself if only one argument is passed
  6668. if (i === length) {
  6669. target = this;
  6670. i--;
  6671. }
  6672.  
  6673. for (; i < length; i++) {
  6674. // Only deal with non-null/undefined values
  6675. if ((options = arguments[i]) != null) {
  6676. // Extend the base object
  6677. for (name in options) {
  6678. src = target[name];
  6679. copy = options[name];
  6680.  
  6681. // Prevent never-ending loop
  6682. if (target === copy) {
  6683. continue;
  6684. }
  6685.  
  6686. // Recurse if we're merging plain objects or arrays
  6687. if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) {
  6688. if (copyIsArray) {
  6689. copyIsArray = false;
  6690. clone = src && jQuery.isArray(src) ? src : [];
  6691. } else {
  6692. clone = src && jQuery.isPlainObject(src) ? src : {};
  6693. }
  6694.  
  6695. // Never move original objects, clone them
  6696. target[name] = jQuery.extend(deep, clone, copy);
  6697.  
  6698. // Don't bring in undefined values
  6699. } else if (copy !== undefined) {
  6700. target[name] = copy;
  6701. }
  6702. }
  6703. }
  6704. }
  6705.  
  6706. // Return the modified object
  6707. return target;
  6708. };
  6709.  
  6710. jQuery.extend({
  6711. // Unique for each copy of jQuery on the page
  6712. expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),
  6713.  
  6714. // Assume jQuery is ready without the ready module
  6715. isReady: true,
  6716.  
  6717. error: function (msg) {
  6718. throw new Error(msg);
  6719. },
  6720.  
  6721. noop: function () {},
  6722.  
  6723. // See test/unit/core.js for details concerning isFunction.
  6724. // Since version 1.3, DOM methods and functions like alert
  6725. // aren't supported. They return false on IE (#2968).
  6726. isFunction: function (obj) {
  6727. return jQuery.type(obj) === "function";
  6728. },
  6729.  
  6730. isArray: Array.isArray || function (obj) {
  6731. return jQuery.type(obj) === "array";
  6732. },
  6733.  
  6734. isWindow: function (obj) {
  6735. /* jshint eqeqeq: false */
  6736. return obj != null && obj == obj.window;
  6737. },
  6738.  
  6739. isNumeric: function (obj) {
  6740. // parseFloat NaNs numeric-cast false positives (null|true|false|"")
  6741. // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  6742. // subtraction forces infinities to NaN
  6743. return !jQuery.isArray(obj) && obj - parseFloat(obj) >= 0;
  6744. },
  6745.  
  6746. isEmptyObject: function (obj) {
  6747. var name;
  6748. for (name in obj) {
  6749. return false;
  6750. }
  6751. return true;
  6752. },
  6753.  
  6754. isPlainObject: function (obj) {
  6755. var key;
  6756.  
  6757. // Must be an Object.
  6758. // Because of IE, we also have to check the presence of the constructor property.
  6759. // Make sure that DOM nodes and window objects don't pass through, as well
  6760. if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
  6761. return false;
  6762. }
  6763.  
  6764. try {
  6765. // Not own constructor property must be Object
  6766. if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
  6767. return false;
  6768. }
  6769. } catch (e) {
  6770. // IE8,9 Will throw exceptions on certain host objects #9897
  6771. return false;
  6772. }
  6773.  
  6774. // Support: IE<9
  6775. // Handle iteration over inherited properties before own properties.
  6776. if (support.ownLast) {
  6777. for (key in obj) {
  6778. return hasOwn.call(obj, key);
  6779. }
  6780. }
  6781.  
  6782. // Own properties are enumerated firstly, so to speed up,
  6783. // if last one is own, then all properties are own.
  6784. for (key in obj) {}
  6785.  
  6786. return key === undefined || hasOwn.call(obj, key);
  6787. },
  6788.  
  6789. type: function (obj) {
  6790. if (obj == null) {
  6791. return obj + "";
  6792. }
  6793. return typeof obj === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj;
  6794. },
  6795.  
  6796. // Evaluates a script in a global context
  6797. // Workarounds based on findings by Jim Driscoll
  6798. // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
  6799. globalEval: function (data) {
  6800. if (data && jQuery.trim(data)) {
  6801. // We use execScript on Internet Explorer
  6802. // We use an anonymous function so that context is window
  6803. // rather than jQuery in Firefox
  6804. (window.execScript || function (data) {
  6805. window["eval"].call(window, data);
  6806. })(data);
  6807. }
  6808. },
  6809.  
  6810. // Convert dashed to camelCase; used by the css and data modules
  6811. // Microsoft forgot to hump their vendor prefix (#9572)
  6812. camelCase: function (string) {
  6813. return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
  6814. },
  6815.  
  6816. nodeName: function (elem, name) {
  6817. return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
  6818. },
  6819.  
  6820. // args is for internal usage only
  6821. each: function (obj, callback, args) {
  6822. var value,
  6823. i = 0,
  6824. length = obj.length,
  6825. isArray = isArraylike(obj);
  6826.  
  6827. if (args) {
  6828. if (isArray) {
  6829. for (; i < length; i++) {
  6830. value = callback.apply(obj[i], args);
  6831.  
  6832. if (value === false) {
  6833. break;
  6834. }
  6835. }
  6836. } else {
  6837. for (i in obj) {
  6838. value = callback.apply(obj[i], args);
  6839.  
  6840. if (value === false) {
  6841. break;
  6842. }
  6843. }
  6844. }
  6845.  
  6846. // A special, fast, case for the most common use of each
  6847. } else {
  6848. if (isArray) {
  6849. for (; i < length; i++) {
  6850. value = callback.call(obj[i], i, obj[i]);
  6851.  
  6852. if (value === false) {
  6853. break;
  6854. }
  6855. }
  6856. } else {
  6857. for (i in obj) {
  6858. value = callback.call(obj[i], i, obj[i]);
  6859.  
  6860. if (value === false) {
  6861. break;
  6862. }
  6863. }
  6864. }
  6865. }
  6866.  
  6867. return obj;
  6868. },
  6869.  
  6870. // Support: Android<4.1, IE<9
  6871. trim: function (text) {
  6872. return text == null ? "" : (text + "").replace(rtrim, "");
  6873. },
  6874.  
  6875. // results is for internal usage only
  6876. makeArray: function (arr, results) {
  6877. var ret = results || [];
  6878.  
  6879. if (arr != null) {
  6880. if (isArraylike(Object(arr))) {
  6881. jQuery.merge(ret, typeof arr === "string" ? [arr] : arr);
  6882. } else {
  6883. push.call(ret, arr);
  6884. }
  6885. }
  6886.  
  6887. return ret;
  6888. },
  6889.  
  6890. inArray: function (elem, arr, i) {
  6891. var len;
  6892.  
  6893. if (arr) {
  6894. if (indexOf) {
  6895. return indexOf.call(arr, elem, i);
  6896. }
  6897.  
  6898. len = arr.length;
  6899. i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
  6900.  
  6901. for (; i < len; i++) {
  6902. // Skip accessing in sparse arrays
  6903. if (i in arr && arr[i] === elem) {
  6904. return i;
  6905. }
  6906. }
  6907. }
  6908.  
  6909. return -1;
  6910. },
  6911.  
  6912. merge: function (first, second) {
  6913. var len = +second.length,
  6914. j = 0,
  6915. i = first.length;
  6916.  
  6917. while (j < len) {
  6918. first[i++] = second[j++];
  6919. }
  6920.  
  6921. // Support: IE<9
  6922. // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
  6923. if (len !== len) {
  6924. while (second[j] !== undefined) {
  6925. first[i++] = second[j++];
  6926. }
  6927. }
  6928.  
  6929. first.length = i;
  6930.  
  6931. return first;
  6932. },
  6933.  
  6934. grep: function (elems, callback, invert) {
  6935. var callbackInverse,
  6936. matches = [],
  6937. i = 0,
  6938. length = elems.length,
  6939. callbackExpect = !invert;
  6940.  
  6941. // Go through the array, only saving the items
  6942. // that pass the validator function
  6943. for (; i < length; i++) {
  6944. callbackInverse = !callback(elems[i], i);
  6945. if (callbackInverse !== callbackExpect) {
  6946. matches.push(elems[i]);
  6947. }
  6948. }
  6949.  
  6950. return matches;
  6951. },
  6952.  
  6953. // arg is for internal usage only
  6954. map: function (elems, callback, arg) {
  6955. var value,
  6956. i = 0,
  6957. length = elems.length,
  6958. isArray = isArraylike(elems),
  6959. ret = [];
  6960.  
  6961. // Go through the array, translating each of the items to their new values
  6962. if (isArray) {
  6963. for (; i < length; i++) {
  6964. value = callback(elems[i], i, arg);
  6965.  
  6966. if (value != null) {
  6967. ret.push(value);
  6968. }
  6969. }
  6970.  
  6971. // Go through every key on the object,
  6972. } else {
  6973. for (i in elems) {
  6974. value = callback(elems[i], i, arg);
  6975.  
  6976. if (value != null) {
  6977. ret.push(value);
  6978. }
  6979. }
  6980. }
  6981.  
  6982. // Flatten any nested arrays
  6983. return concat.apply([], ret);
  6984. },
  6985.  
  6986. // A global GUID counter for objects
  6987. guid: 1,
  6988.  
  6989. // Bind a function to a context, optionally partially applying any
  6990. // arguments.
  6991. proxy: function (fn, context) {
  6992. var args, proxy, tmp;
  6993.  
  6994. if (typeof context === "string") {
  6995. tmp = fn[context];
  6996. context = fn;
  6997. fn = tmp;
  6998. }
  6999.  
  7000. // Quick check to determine if target is callable, in the spec
  7001. // this throws a TypeError, but we will just return undefined.
  7002. if (!jQuery.isFunction(fn)) {
  7003. return undefined;
  7004. }
  7005.  
  7006. // Simulated bind
  7007. args = slice.call(arguments, 2);
  7008. proxy = function () {
  7009. return fn.apply(context || this, args.concat(slice.call(arguments)));
  7010. };
  7011.  
  7012. // Set the guid of unique handler to the same of original handler, so it can be removed
  7013. proxy.guid = fn.guid = fn.guid || jQuery.guid++;
  7014.  
  7015. return proxy;
  7016. },
  7017.  
  7018. now: function () {
  7019. return +new Date();
  7020. },
  7021.  
  7022. // jQuery.support is not used in Core but other projects attach their
  7023. // properties to it so it needs to exist.
  7024. support: support
  7025. });
  7026.  
  7027. // Populate the class2type map
  7028. jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) {
  7029. class2type["[object " + name + "]"] = name.toLowerCase();
  7030. });
  7031.  
  7032. function isArraylike(obj) {
  7033. var length = obj.length,
  7034. type = jQuery.type(obj);
  7035.  
  7036. if (type === "function" || jQuery.isWindow(obj)) {
  7037. return false;
  7038. }
  7039.  
  7040. if (obj.nodeType === 1 && length) {
  7041. return true;
  7042. }
  7043.  
  7044. return type === "array" || length === 0 || typeof length === "number" && length > 0 && length - 1 in obj;
  7045. }
  7046.  
  7047. // Initialize a jQuery object
  7048.  
  7049.  
  7050. // A central reference to the root jQuery(document)
  7051. var rootjQuery,
  7052.  
  7053.  
  7054. // Use the correct document accordingly with window argument (sandbox)
  7055. document = window.document,
  7056.  
  7057.  
  7058. // A simple way to check for HTML strings
  7059. // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
  7060. // Strict HTML recognition (#11290: must start with <)
  7061. rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
  7062. init = jQuery.fn.init = function (selector, context) {
  7063. var match, elem;
  7064.  
  7065. // HANDLE: $(""), $(null), $(undefined), $(false)
  7066. if (!selector) {
  7067. return this;
  7068. }
  7069.  
  7070. // Handle HTML strings
  7071. if (typeof selector === "string") {
  7072. if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) {
  7073. // Assume that strings that start and end with <> are HTML and skip the regex check
  7074. match = [null, selector, null];
  7075. } else {
  7076. match = rquickExpr.exec(selector);
  7077. }
  7078.  
  7079. // Match html or make sure no context is specified for #id
  7080. if (match && (match[1] || !context)) {
  7081.  
  7082. // HANDLE: $(html) -> $(array)
  7083. if (match[1]) {
  7084. context = context instanceof jQuery ? context[0] : context;
  7085.  
  7086. // scripts is true for back-compat
  7087. // Intentionally let the error be thrown if parseHTML is not present
  7088. jQuery.merge(this, jQuery.parseHTML(match[1], context && context.nodeType ? context.ownerDocument || context : document, true));
  7089.  
  7090. // HANDLE: $(html, props)
  7091. if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
  7092. for (match in context) {
  7093. // Properties of context are called as methods if possible
  7094. if (jQuery.isFunction(this[match])) {
  7095. this[match](context[match]);
  7096.  
  7097. // ...and otherwise set as attributes
  7098. } else {
  7099. this.attr(match, context[match]);
  7100. }
  7101. }
  7102. }
  7103.  
  7104. return this;
  7105.  
  7106. // HANDLE: $(#id)
  7107. } else {
  7108. elem = document.getElementById(match[2]);
  7109.  
  7110. // Check parentNode to catch when Blackberry 4.6 returns
  7111. // nodes that are no longer in the document #6963
  7112. if (elem && elem.parentNode) {
  7113. // Handle the case where IE and Opera return items
  7114. // by name instead of ID
  7115. if (elem.id !== match[2]) {
  7116. return rootjQuery.find(selector);
  7117. }
  7118.  
  7119. // Otherwise, we inject the element directly into the jQuery object
  7120. this.length = 1;
  7121. this[0] = elem;
  7122. }
  7123.  
  7124. this.context = document;
  7125. this.selector = selector;
  7126. return this;
  7127. }
  7128.  
  7129. // HANDLE: $(expr, $(...))
  7130. } else if (!context || context.jquery) {
  7131. return (context || rootjQuery).find(selector);
  7132.  
  7133. // HANDLE: $(expr, context)
  7134. // (which is just equivalent to: $(context).find(expr)
  7135. } else {
  7136. return this.constructor(context).find(selector);
  7137. }
  7138.  
  7139. // HANDLE: $(DOMElement)
  7140. } else if (selector.nodeType) {
  7141. this.context = this[0] = selector;
  7142. this.length = 1;
  7143. return this;
  7144.  
  7145. // HANDLE: $(function)
  7146. // Shortcut for document ready
  7147. } else if (jQuery.isFunction(selector)) {
  7148. return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready(selector) :
  7149. // Execute immediately if ready is not present
  7150. selector(jQuery);
  7151. }
  7152.  
  7153. if (selector.selector !== undefined) {
  7154. this.selector = selector.selector;
  7155. this.context = selector.context;
  7156. }
  7157.  
  7158. return jQuery.makeArray(selector, this);
  7159. };
  7160.  
  7161. // Give the init function the jQuery prototype for later instantiation
  7162. init.prototype = jQuery.fn;
  7163.  
  7164. // Initialize central reference
  7165. rootjQuery = jQuery(document);
  7166.  
  7167. var rnotwhite = /\S+/g;
  7168.  
  7169. // String to Object options format cache
  7170. var optionsCache = {};
  7171.  
  7172. // Convert String-formatted options into Object-formatted ones and store in cache
  7173. function createOptions(options) {
  7174. var object = optionsCache[options] = {};
  7175. jQuery.each(options.match(rnotwhite) || [], function (_, flag) {
  7176. object[flag] = true;
  7177. });
  7178. return object;
  7179. }
  7180.  
  7181. /*
  7182. * Create a callback list using the following parameters:
  7183. *
  7184. * options: an optional list of space-separated options that will change how
  7185. * the callback list behaves or a more traditional option object
  7186. *
  7187. * By default a callback list will act like an event callback list and can be
  7188. * "fired" multiple times.
  7189. *
  7190. * Possible options:
  7191. *
  7192. * once: will ensure the callback list can only be fired once (like a Deferred)
  7193. *
  7194. * memory: will keep track of previous values and will call any callback added
  7195. * after the list has been fired right away with the latest "memorized"
  7196. * values (like a Deferred)
  7197. *
  7198. * unique: will ensure a callback can only be added once (no duplicate in the list)
  7199. *
  7200. * stopOnFalse: interrupt callings when a callback returns false
  7201. *
  7202. */
  7203. jQuery.Callbacks = function (options) {
  7204.  
  7205. // Convert options from String-formatted to Object-formatted if needed
  7206. // (we check in cache first)
  7207. options = typeof options === "string" ? optionsCache[options] || createOptions(options) : jQuery.extend({}, options);
  7208.  
  7209. var // Flag to know if list is currently firing
  7210. firing,
  7211.  
  7212. // Last fire value (for non-forgettable lists)
  7213. memory,
  7214.  
  7215. // Flag to know if list was already fired
  7216. fired,
  7217.  
  7218. // End of the loop when firing
  7219. firingLength,
  7220.  
  7221. // Index of currently firing callback (modified by remove if needed)
  7222. firingIndex,
  7223.  
  7224. // First callback to fire (used internally by add and fireWith)
  7225. firingStart,
  7226.  
  7227. // Actual callback list
  7228. list = [],
  7229.  
  7230. // Stack of fire calls for repeatable lists
  7231. stack = !options.once && [],
  7232.  
  7233. // Fire callbacks
  7234. fire = function (data) {
  7235. memory = options.memory && data;
  7236. fired = true;
  7237. firingIndex = firingStart || 0;
  7238. firingStart = 0;
  7239. firingLength = list.length;
  7240. firing = true;
  7241. for (; list && firingIndex < firingLength; firingIndex++) {
  7242. if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) {
  7243. memory = false; // To prevent further calls using add
  7244. break;
  7245. }
  7246. }
  7247. firing = false;
  7248. if (list) {
  7249. if (stack) {
  7250. if (stack.length) {
  7251. fire(stack.shift());
  7252. }
  7253. } else if (memory) {
  7254. list = [];
  7255. } else {
  7256. self.disable();
  7257. }
  7258. }
  7259. },
  7260.  
  7261. // Actual Callbacks object
  7262. self = {
  7263. // Add a callback or a collection of callbacks to the list
  7264. add: function () {
  7265. if (list) {
  7266. // First, we save the current length
  7267. var start = list.length;
  7268. (function add(args) {
  7269. jQuery.each(args, function (_, arg) {
  7270. var type = jQuery.type(arg);
  7271. if (type === "function") {
  7272. if (!options.unique || !self.has(arg)) {
  7273. list.push(arg);
  7274. }
  7275. } else if (arg && arg.length && type !== "string") {
  7276. // Inspect recursively
  7277. add(arg);
  7278. }
  7279. });
  7280. })(arguments);
  7281. // Do we need to add the callbacks to the
  7282. // current firing batch?
  7283. if (firing) {
  7284. firingLength = list.length;
  7285. // With memory, if we're not firing then
  7286. // we should call right away
  7287. } else if (memory) {
  7288. firingStart = start;
  7289. fire(memory);
  7290. }
  7291. }
  7292. return this;
  7293. },
  7294. // Remove a callback from the list
  7295. remove: function () {
  7296. if (list) {
  7297. jQuery.each(arguments, function (_, arg) {
  7298. var index;
  7299. while ((index = jQuery.inArray(arg, list, index)) > -1) {
  7300. list.splice(index, 1);
  7301. // Handle firing indexes
  7302. if (firing) {
  7303. if (index <= firingLength) {
  7304. firingLength--;
  7305. }
  7306. if (index <= firingIndex) {
  7307. firingIndex--;
  7308. }
  7309. }
  7310. }
  7311. });
  7312. }
  7313. return this;
  7314. },
  7315. // Check if a given callback is in the list.
  7316. // If no argument is given, return whether or not list has callbacks attached.
  7317. has: function (fn) {
  7318. return fn ? jQuery.inArray(fn, list) > -1 : !!(list && list.length);
  7319. },
  7320. // Remove all callbacks from the list
  7321. empty: function () {
  7322. list = [];
  7323. firingLength = 0;
  7324. return this;
  7325. },
  7326. // Have the list do nothing anymore
  7327. disable: function () {
  7328. list = stack = memory = undefined;
  7329. return this;
  7330. },
  7331. // Is it disabled?
  7332. disabled: function () {
  7333. return !list;
  7334. },
  7335. // Lock the list in its current state
  7336. lock: function () {
  7337. stack = undefined;
  7338. if (!memory) {
  7339. self.disable();
  7340. }
  7341. return this;
  7342. },
  7343. // Is it locked?
  7344. locked: function () {
  7345. return !stack;
  7346. },
  7347. // Call all callbacks with the given context and arguments
  7348. fireWith: function (context, args) {
  7349. if (list && (!fired || stack)) {
  7350. args = args || [];
  7351. args = [context, args.slice ? args.slice() : args];
  7352. if (firing) {
  7353. stack.push(args);
  7354. } else {
  7355. fire(args);
  7356. }
  7357. }
  7358. return this;
  7359. },
  7360. // Call all the callbacks with the given arguments
  7361. fire: function () {
  7362. self.fireWith(this, arguments);
  7363. return this;
  7364. },
  7365. // To know if the callbacks have already been called at least once
  7366. fired: function () {
  7367. return !!fired;
  7368. }
  7369. };
  7370.  
  7371. return self;
  7372. };
  7373.  
  7374. jQuery.extend({
  7375.  
  7376. Deferred: function (func) {
  7377. var tuples = [
  7378. // action, add listener, listener list, final state
  7379. ["resolve", "done", jQuery.Callbacks("once memory"), "resolved"], ["reject", "fail", jQuery.Callbacks("once memory"), "rejected"], ["notify", "progress", jQuery.Callbacks("memory")]],
  7380. state = "pending",
  7381. promise = {
  7382. state: function () {
  7383. return state;
  7384. },
  7385. always: function () {
  7386. deferred.done(arguments).fail(arguments);
  7387. return this;
  7388. },
  7389. then: function () /* fnDone, fnFail, fnProgress */{
  7390. var fns = arguments;
  7391. return jQuery.Deferred(function (newDefer) {
  7392. jQuery.each(tuples, function (i, tuple) {
  7393. var fn = jQuery.isFunction(fns[i]) && fns[i];
  7394. // deferred[ done | fail | progress ] for forwarding actions to newDefer
  7395. deferred[tuple[1]](function () {
  7396. var returned = fn && fn.apply(this, arguments);
  7397. if (returned && jQuery.isFunction(returned.promise)) {
  7398. returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify);
  7399. } else {
  7400. newDefer[tuple[0] + "With"](this === promise ? newDefer.promise() : this, fn ? [returned] : arguments);
  7401. }
  7402. });
  7403. });
  7404. fns = null;
  7405. }).promise();
  7406. },
  7407. // Get a promise for this deferred
  7408. // If obj is provided, the promise aspect is added to the object
  7409. promise: function (obj) {
  7410. return obj != null ? jQuery.extend(obj, promise) : promise;
  7411. }
  7412. },
  7413. deferred = {};
  7414.  
  7415. // Keep pipe for back-compat
  7416. promise.pipe = promise.then;
  7417.  
  7418. // Add list-specific methods
  7419. jQuery.each(tuples, function (i, tuple) {
  7420. var list = tuple[2],
  7421. stateString = tuple[3];
  7422.  
  7423. // promise[ done | fail | progress ] = list.add
  7424. promise[tuple[1]] = list.add;
  7425.  
  7426. // Handle state
  7427. if (stateString) {
  7428. list.add(function () {
  7429. // state = [ resolved | rejected ]
  7430. state = stateString;
  7431.  
  7432. // [ reject_list | resolve_list ].disable; progress_list.lock
  7433. }, tuples[i ^ 1][2].disable, tuples[2][2].lock);
  7434. }
  7435.  
  7436. // deferred[ resolve | reject | notify ]
  7437. deferred[tuple[0]] = function () {
  7438. deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments);
  7439. return this;
  7440. };
  7441. deferred[tuple[0] + "With"] = list.fireWith;
  7442. });
  7443.  
  7444. // Make the deferred a promise
  7445. promise.promise(deferred);
  7446.  
  7447. // Call given func if any
  7448. if (func) {
  7449. func.call(deferred, deferred);
  7450. }
  7451.  
  7452. // All done!
  7453. return deferred;
  7454. },
  7455.  
  7456. // Deferred helper
  7457. when: function (subordinate /* , ..., subordinateN */) {
  7458. var i = 0,
  7459. resolveValues = slice.call(arguments),
  7460. length = resolveValues.length,
  7461.  
  7462.  
  7463. // the count of uncompleted subordinates
  7464. remaining = length !== 1 || subordinate && jQuery.isFunction(subordinate.promise) ? length : 0,
  7465.  
  7466.  
  7467. // the master Deferred. If resolveValues consist of only a single Deferred, just use that.
  7468. deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
  7469.  
  7470.  
  7471. // Update function for both resolve and progress values
  7472. updateFunc = function (i, contexts, values) {
  7473. return function (value) {
  7474. contexts[i] = this;
  7475. values[i] = arguments.length > 1 ? slice.call(arguments) : value;
  7476. if (values === progressValues) {
  7477. deferred.notifyWith(contexts, values);
  7478. } else if (! --remaining) {
  7479. deferred.resolveWith(contexts, values);
  7480. }
  7481. };
  7482. },
  7483. progressValues,
  7484. progressContexts,
  7485. resolveContexts;
  7486.  
  7487. // add listeners to Deferred subordinates; treat others as resolved
  7488. if (length > 1) {
  7489. progressValues = new Array(length);
  7490. progressContexts = new Array(length);
  7491. resolveContexts = new Array(length);
  7492. for (; i < length; i++) {
  7493. if (resolveValues[i] && jQuery.isFunction(resolveValues[i].promise)) {
  7494. resolveValues[i].promise().done(updateFunc(i, resolveContexts, resolveValues)).fail(deferred.reject).progress(updateFunc(i, progressContexts, progressValues));
  7495. } else {
  7496. --remaining;
  7497. }
  7498. }
  7499. }
  7500.  
  7501. // if we're not waiting on anything, resolve the master
  7502. if (!remaining) {
  7503. deferred.resolveWith(resolveContexts, resolveValues);
  7504. }
  7505.  
  7506. return deferred.promise();
  7507. }
  7508. });
  7509.  
  7510. // The deferred used on DOM ready
  7511. var readyList;
  7512.  
  7513. jQuery.fn.ready = function (fn) {
  7514. // Add the callback
  7515. jQuery.ready.promise().done(fn);
  7516.  
  7517. return this;
  7518. };
  7519.  
  7520. jQuery.extend({
  7521. // Is the DOM ready to be used? Set to true once it occurs.
  7522. isReady: false,
  7523.  
  7524. // A counter to track how many items to wait for before
  7525. // the ready event fires. See #6781
  7526. readyWait: 1,
  7527.  
  7528. // Hold (or release) the ready event
  7529. holdReady: function (hold) {
  7530. if (hold) {
  7531. jQuery.readyWait++;
  7532. } else {
  7533. jQuery.ready(true);
  7534. }
  7535. },
  7536.  
  7537. // Handle when the DOM is ready
  7538. ready: function (wait) {
  7539.  
  7540. // Abort if there are pending holds or we're already ready
  7541. if (wait === true ? --jQuery.readyWait : jQuery.isReady) {
  7542. return;
  7543. }
  7544.  
  7545. // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
  7546. if (!document.body) {
  7547. return setTimeout(jQuery.ready);
  7548. }
  7549.  
  7550. // Remember that the DOM is ready
  7551. jQuery.isReady = true;
  7552.  
  7553. // If a normal DOM Ready event fired, decrement, and wait if need be
  7554. if (wait !== true && --jQuery.readyWait > 0) {
  7555. return;
  7556. }
  7557.  
  7558. // If there are functions bound, to execute
  7559. readyList.resolveWith(document, [jQuery]);
  7560.  
  7561. // Trigger any bound ready events
  7562. if (jQuery.fn.triggerHandler) {
  7563. jQuery(document).triggerHandler("ready");
  7564. jQuery(document).off("ready");
  7565. }
  7566. }
  7567. });
  7568.  
  7569. /**
  7570. * Clean-up method for dom ready events
  7571. */
  7572. function detach() {
  7573. if (document.addEventListener) {
  7574. document.removeEventListener("DOMContentLoaded", completed, false);
  7575. window.removeEventListener("load", completed, false);
  7576. } else {
  7577. document.detachEvent("onreadystatechange", completed);
  7578. window.detachEvent("onload", completed);
  7579. }
  7580. }
  7581.  
  7582. /**
  7583. * The ready event handler and self cleanup method
  7584. */
  7585. function completed() {
  7586. // readyState === "complete" is good enough for us to call the dom ready in oldIE
  7587. if (document.addEventListener || event.type === "load" || document.readyState === "complete") {
  7588. detach();
  7589. jQuery.ready();
  7590. }
  7591. }
  7592.  
  7593. jQuery.ready.promise = function (obj) {
  7594. if (!readyList) {
  7595.  
  7596. readyList = jQuery.Deferred();
  7597.  
  7598. // Catch cases where $(document).ready() is called after the browser event has already occurred.
  7599. // we once tried to use readyState "interactive" here, but it caused issues like the one
  7600. // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
  7601. if (document.readyState === "complete") {
  7602. // Handle it asynchronously to allow scripts the opportunity to delay ready
  7603. setTimeout(jQuery.ready);
  7604.  
  7605. // Standards-based browsers support DOMContentLoaded
  7606. } else if (document.addEventListener) {
  7607. // Use the handy event callback
  7608. document.addEventListener("DOMContentLoaded", completed, false);
  7609.  
  7610. // A fallback to window.onload, that will always work
  7611. window.addEventListener("load", completed, false);
  7612.  
  7613. // If IE event model is used
  7614. } else {
  7615. // Ensure firing before onload, maybe late but safe also for iframes
  7616. document.attachEvent("onreadystatechange", completed);
  7617.  
  7618. // A fallback to window.onload, that will always work
  7619. window.attachEvent("onload", completed);
  7620.  
  7621. // If IE and not a frame
  7622. // continually check to see if the document is ready
  7623. var top = false;
  7624.  
  7625. try {
  7626. top = window.frameElement == null && document.documentElement;
  7627. } catch (e) {}
  7628.  
  7629. if (top && top.doScroll) {
  7630. (function doScrollCheck() {
  7631. if (!jQuery.isReady) {
  7632.  
  7633. try {
  7634. // Use the trick by Diego Perini
  7635. // http://javascript.nwbox.com/IEContentLoaded/
  7636. top.doScroll("left");
  7637. } catch (e) {
  7638. return setTimeout(doScrollCheck, 50);
  7639. }
  7640.  
  7641. // detach all dom ready events
  7642. detach();
  7643.  
  7644. // and execute any waiting functions
  7645. jQuery.ready();
  7646. }
  7647. })();
  7648. }
  7649. }
  7650. }
  7651. return readyList.promise(obj);
  7652. };
  7653.  
  7654. var strundefined = typeof undefined;
  7655.  
  7656. // Support: IE<9
  7657. // Iteration over object's inherited properties before its own
  7658. var i;
  7659. for (i in jQuery(support)) {
  7660. break;
  7661. }
  7662. support.ownLast = i !== "0";
  7663.  
  7664. // Note: most support tests are defined in their respective modules.
  7665. // false until the test is run
  7666. support.inlineBlockNeedsLayout = false;
  7667.  
  7668. // Execute ASAP in case we need to set body.style.zoom
  7669. jQuery(function () {
  7670. // Minified: var a,b,c,d
  7671. var val, div, body, container;
  7672.  
  7673. body = document.getElementsByTagName("body")[0];
  7674. if (!body || !body.style) {
  7675. // Return for frameset docs that don't have a body
  7676. return;
  7677. }
  7678.  
  7679. // Setup
  7680. div = document.createElement("div");
  7681. container = document.createElement("div");
  7682. container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
  7683. body.appendChild(container).appendChild(div);
  7684.  
  7685. if (typeof div.style.zoom !== strundefined) {
  7686. // Support: IE<8
  7687. // Check if natively block-level elements act like inline-block
  7688. // elements when setting their display to 'inline' and giving
  7689. // them layout
  7690. div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
  7691.  
  7692. support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
  7693. if (val) {
  7694. // Prevent IE 6 from affecting layout for positioned elements #11048
  7695. // Prevent IE from shrinking the body in IE 7 mode #12869
  7696. // Support: IE<8
  7697. body.style.zoom = 1;
  7698. }
  7699. }
  7700.  
  7701. body.removeChild(container);
  7702. });
  7703.  
  7704. (function () {
  7705. var div = document.createElement("div");
  7706.  
  7707. // Execute the test only if not already executed in another module.
  7708. if (support.deleteExpando == null) {
  7709. // Support: IE<9
  7710. support.deleteExpando = true;
  7711. try {
  7712. delete div.test;
  7713. } catch (e) {
  7714. support.deleteExpando = false;
  7715. }
  7716. }
  7717.  
  7718. // Null elements to avoid leaks in IE.
  7719. div = null;
  7720. })();
  7721.  
  7722. /**
  7723. * Determines whether an object can have data
  7724. */
  7725. jQuery.acceptData = function (elem) {
  7726. var noData = jQuery.noData[(elem.nodeName + " ").toLowerCase()],
  7727. nodeType = +elem.nodeType || 1;
  7728.  
  7729. // Do not set data on non-element DOM nodes because it will not be cleared (#8335).
  7730. return nodeType !== 1 && nodeType !== 9 ? false :
  7731.  
  7732. // Nodes accept data unless otherwise specified; rejection can be conditional
  7733. !noData || noData !== true && elem.getAttribute("classid") === noData;
  7734. };
  7735.  
  7736. var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
  7737. rmultiDash = /([A-Z])/g;
  7738.  
  7739. function dataAttr(elem, key, data) {
  7740. // If nothing was found internally, try to fetch any
  7741. // data from the HTML5 data-* attribute
  7742. if (data === undefined && elem.nodeType === 1) {
  7743.  
  7744. var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase();
  7745.  
  7746. data = elem.getAttribute(name);
  7747.  
  7748. if (typeof data === "string") {
  7749. try {
  7750. data = data === "true" ? true : data === "false" ? false : data === "null" ? null :
  7751. // Only convert to a number if it doesn't change the string
  7752. +data + "" === data ? +data : rbrace.test(data) ? jQuery.parseJSON(data) : data;
  7753. } catch (e) {}
  7754.  
  7755. // Make sure we set the data so it isn't changed later
  7756. jQuery.data(elem, key, data);
  7757. } else {
  7758. data = undefined;
  7759. }
  7760. }
  7761.  
  7762. return data;
  7763. }
  7764.  
  7765. // checks a cache object for emptiness
  7766. function isEmptyDataObject(obj) {
  7767. var name;
  7768. for (name in obj) {
  7769.  
  7770. // if the public data object is empty, the private is still empty
  7771. if (name === "data" && jQuery.isEmptyObject(obj[name])) {
  7772. continue;
  7773. }
  7774. if (name !== "toJSON") {
  7775. return false;
  7776. }
  7777. }
  7778.  
  7779. return true;
  7780. }
  7781.  
  7782. function internalData(elem, name, data, pvt /* Internal Use Only */) {
  7783. if (!jQuery.acceptData(elem)) {
  7784. return;
  7785. }
  7786.  
  7787. var ret,
  7788. thisCache,
  7789. internalKey = jQuery.expando,
  7790.  
  7791.  
  7792. // We have to handle DOM nodes and JS objects differently because IE6-7
  7793. // can't GC object references properly across the DOM-JS boundary
  7794. isNode = elem.nodeType,
  7795.  
  7796.  
  7797. // Only DOM nodes need the global jQuery cache; JS object data is
  7798. // attached directly to the object so GC can occur automatically
  7799. cache = isNode ? jQuery.cache : elem,
  7800.  
  7801.  
  7802. // Only defining an ID for JS objects if its cache already exists allows
  7803. // the code to shortcut on the same path as a DOM node with no cache
  7804. id = isNode ? elem[internalKey] : elem[internalKey] && internalKey;
  7805.  
  7806. // Avoid doing any more work than we need to when trying to get data on an
  7807. // object that has no data at all
  7808. if ((!id || !cache[id] || !pvt && !cache[id].data) && data === undefined && typeof name === "string") {
  7809. return;
  7810. }
  7811.  
  7812. if (!id) {
  7813. // Only DOM nodes need a new unique ID for each element since their data
  7814. // ends up in the global cache
  7815. if (isNode) {
  7816. id = elem[internalKey] = deletedIds.pop() || jQuery.guid++;
  7817. } else {
  7818. id = internalKey;
  7819. }
  7820. }
  7821.  
  7822. if (!cache[id]) {
  7823. // Avoid exposing jQuery metadata on plain JS objects when the object
  7824. // is serialized using JSON.stringify
  7825. cache[id] = isNode ? {} : { toJSON: jQuery.noop };
  7826. }
  7827.  
  7828. // An object can be passed to jQuery.data instead of a key/value pair; this gets
  7829. // shallow copied over onto the existing cache
  7830. if (typeof name === "object" || typeof name === "function") {
  7831. if (pvt) {
  7832. cache[id] = jQuery.extend(cache[id], name);
  7833. } else {
  7834. cache[id].data = jQuery.extend(cache[id].data, name);
  7835. }
  7836. }
  7837.  
  7838. thisCache = cache[id];
  7839.  
  7840. // jQuery data() is stored in a separate object inside the object's internal data
  7841. // cache in order to avoid key collisions between internal data and user-defined
  7842. // data.
  7843. if (!pvt) {
  7844. if (!thisCache.data) {
  7845. thisCache.data = {};
  7846. }
  7847.  
  7848. thisCache = thisCache.data;
  7849. }
  7850.  
  7851. if (data !== undefined) {
  7852. thisCache[jQuery.camelCase(name)] = data;
  7853. }
  7854.  
  7855. // Check for both converted-to-camel and non-converted data property names
  7856. // If a data property was specified
  7857. if (typeof name === "string") {
  7858.  
  7859. // First Try to find as-is property data
  7860. ret = thisCache[name];
  7861.  
  7862. // Test for null|undefined property data
  7863. if (ret == null) {
  7864.  
  7865. // Try to find the camelCased property
  7866. ret = thisCache[jQuery.camelCase(name)];
  7867. }
  7868. } else {
  7869. ret = thisCache;
  7870. }
  7871.  
  7872. return ret;
  7873. }
  7874.  
  7875. function internalRemoveData(elem, name, pvt) {
  7876. if (!jQuery.acceptData(elem)) {
  7877. return;
  7878. }
  7879.  
  7880. var thisCache,
  7881. i,
  7882. isNode = elem.nodeType,
  7883.  
  7884.  
  7885. // See jQuery.data for more information
  7886. cache = isNode ? jQuery.cache : elem,
  7887. id = isNode ? elem[jQuery.expando] : jQuery.expando;
  7888.  
  7889. // If there is already no cache entry for this object, there is no
  7890. // purpose in continuing
  7891. if (!cache[id]) {
  7892. return;
  7893. }
  7894.  
  7895. if (name) {
  7896.  
  7897. thisCache = pvt ? cache[id] : cache[id].data;
  7898.  
  7899. if (thisCache) {
  7900.  
  7901. // Support array or space separated string names for data keys
  7902. if (!jQuery.isArray(name)) {
  7903.  
  7904. // try the string as a key before any manipulation
  7905. if (name in thisCache) {
  7906. name = [name];
  7907. } else {
  7908.  
  7909. // split the camel cased version by spaces unless a key with the spaces exists
  7910. name = jQuery.camelCase(name);
  7911. if (name in thisCache) {
  7912. name = [name];
  7913. } else {
  7914. name = name.split(" ");
  7915. }
  7916. }
  7917. } else {
  7918. // If "name" is an array of keys...
  7919. // When data is initially created, via ("key", "val") signature,
  7920. // keys will be converted to camelCase.
  7921. // Since there is no way to tell _how_ a key was added, remove
  7922. // both plain key and camelCase key. #12786
  7923. // This will only penalize the array argument path.
  7924. name = name.concat(jQuery.map(name, jQuery.camelCase));
  7925. }
  7926.  
  7927. i = name.length;
  7928. while (i--) {
  7929. delete thisCache[name[i]];
  7930. }
  7931.  
  7932. // If there is no data left in the cache, we want to continue
  7933. // and let the cache object itself get destroyed
  7934. if (pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache)) {
  7935. return;
  7936. }
  7937. }
  7938. }
  7939.  
  7940. // See jQuery.data for more information
  7941. if (!pvt) {
  7942. delete cache[id].data;
  7943.  
  7944. // Don't destroy the parent cache unless the internal data object
  7945. // had been the only thing left in it
  7946. if (!isEmptyDataObject(cache[id])) {
  7947. return;
  7948. }
  7949. }
  7950.  
  7951. // Destroy the cache
  7952. if (isNode) {
  7953. jQuery.cleanData([elem], true);
  7954.  
  7955. // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
  7956. /* jshint eqeqeq: false */
  7957. } else if (support.deleteExpando || cache != cache.window) {
  7958. /* jshint eqeqeq: true */
  7959. delete cache[id];
  7960.  
  7961. // When all else fails, null
  7962. } else {
  7963. cache[id] = null;
  7964. }
  7965. }
  7966.  
  7967. jQuery.extend({
  7968. cache: {},
  7969.  
  7970. // The following elements (space-suffixed to avoid Object.prototype collisions)
  7971. // throw uncatchable exceptions if you attempt to set expando properties
  7972. noData: {
  7973. "applet ": true,
  7974. "embed ": true,
  7975. // ...but Flash objects (which have this classid) *can* handle expandos
  7976. "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
  7977. },
  7978.  
  7979. hasData: function (elem) {
  7980. elem = elem.nodeType ? jQuery.cache[elem[jQuery.expando]] : elem[jQuery.expando];
  7981. return !!elem && !isEmptyDataObject(elem);
  7982. },
  7983.  
  7984. data: function (elem, name, data) {
  7985. return internalData(elem, name, data);
  7986. },
  7987.  
  7988. removeData: function (elem, name) {
  7989. return internalRemoveData(elem, name);
  7990. },
  7991.  
  7992. // For internal use only.
  7993. _data: function (elem, name, data) {
  7994. return internalData(elem, name, data, true);
  7995. },
  7996.  
  7997. _removeData: function (elem, name) {
  7998. return internalRemoveData(elem, name, true);
  7999. }
  8000. });
  8001.  
  8002. jQuery.fn.extend({
  8003. data: function (key, value) {
  8004. var i,
  8005. name,
  8006. data,
  8007. elem = this[0],
  8008. attrs = elem && elem.attributes;
  8009.  
  8010. // Special expections of .data basically thwart jQuery.access,
  8011. // so implement the relevant behavior ourselves
  8012.  
  8013. // Gets all values
  8014. if (key === undefined) {
  8015. if (this.length) {
  8016. data = jQuery.data(elem);
  8017.  
  8018. if (elem.nodeType === 1 && !jQuery._data(elem, "parsedAttrs")) {
  8019. i = attrs.length;
  8020. while (i--) {
  8021.  
  8022. // Support: IE11+
  8023. // The attrs elements can be null (#14894)
  8024. if (attrs[i]) {
  8025. name = attrs[i].name;
  8026. if (name.indexOf("data-") === 0) {
  8027. name = jQuery.camelCase(name.slice(5));
  8028. dataAttr(elem, name, data[name]);
  8029. }
  8030. }
  8031. }
  8032. jQuery._data(elem, "parsedAttrs", true);
  8033. }
  8034. }
  8035.  
  8036. return data;
  8037. }
  8038.  
  8039. // Sets multiple values
  8040. if (typeof key === "object") {
  8041. return this.each(function () {
  8042. jQuery.data(this, key);
  8043. });
  8044. }
  8045.  
  8046. return arguments.length > 1 ?
  8047.  
  8048. // Sets one value
  8049. this.each(function () {
  8050. jQuery.data(this, key, value);
  8051. }) :
  8052.  
  8053. // Gets one value
  8054. // Try to fetch any internally stored data first
  8055. elem ? dataAttr(elem, key, jQuery.data(elem, key)) : undefined;
  8056. },
  8057.  
  8058. removeData: function (key) {
  8059. return this.each(function () {
  8060. jQuery.removeData(this, key);
  8061. });
  8062. }
  8063. });
  8064.  
  8065. jQuery.extend({
  8066. queue: function (elem, type, data) {
  8067. var queue;
  8068.  
  8069. if (elem) {
  8070. type = (type || "fx") + "queue";
  8071. queue = jQuery._data(elem, type);
  8072.  
  8073. // Speed up dequeue by getting out quickly if this is just a lookup
  8074. if (data) {
  8075. if (!queue || jQuery.isArray(data)) {
  8076. queue = jQuery._data(elem, type, jQuery.makeArray(data));
  8077. } else {
  8078. queue.push(data);
  8079. }
  8080. }
  8081. return queue || [];
  8082. }
  8083. },
  8084.  
  8085. dequeue: function (elem, type) {
  8086. type = type || "fx";
  8087.  
  8088. var queue = jQuery.queue(elem, type),
  8089. startLength = queue.length,
  8090. fn = queue.shift(),
  8091. hooks = jQuery._queueHooks(elem, type),
  8092. next = function () {
  8093. jQuery.dequeue(elem, type);
  8094. };
  8095.  
  8096. // If the fx queue is dequeued, always remove the progress sentinel
  8097. if (fn === "inprogress") {
  8098. fn = queue.shift();
  8099. startLength--;
  8100. }
  8101.  
  8102. if (fn) {
  8103.  
  8104. // Add a progress sentinel to prevent the fx queue from being
  8105. // automatically dequeued
  8106. if (type === "fx") {
  8107. queue.unshift("inprogress");
  8108. }
  8109.  
  8110. // clear up the last queue stop function
  8111. delete hooks.stop;
  8112. fn.call(elem, next, hooks);
  8113. }
  8114.  
  8115. if (!startLength && hooks) {
  8116. hooks.empty.fire();
  8117. }
  8118. },
  8119.  
  8120. // not intended for public consumption - generates a queueHooks object, or returns the current one
  8121. _queueHooks: function (elem, type) {
  8122. var key = type + "queueHooks";
  8123. return jQuery._data(elem, key) || jQuery._data(elem, key, {
  8124. empty: jQuery.Callbacks("once memory").add(function () {
  8125. jQuery._removeData(elem, type + "queue");
  8126. jQuery._removeData(elem, key);
  8127. })
  8128. });
  8129. }
  8130. });
  8131.  
  8132. jQuery.fn.extend({
  8133. queue: function (type, data) {
  8134. var setter = 2;
  8135.  
  8136. if (typeof type !== "string") {
  8137. data = type;
  8138. type = "fx";
  8139. setter--;
  8140. }
  8141.  
  8142. if (arguments.length < setter) {
  8143. return jQuery.queue(this[0], type);
  8144. }
  8145.  
  8146. return data === undefined ? this : this.each(function () {
  8147. var queue = jQuery.queue(this, type, data);
  8148.  
  8149. // ensure a hooks for this queue
  8150. jQuery._queueHooks(this, type);
  8151.  
  8152. if (type === "fx" && queue[0] !== "inprogress") {
  8153. jQuery.dequeue(this, type);
  8154. }
  8155. });
  8156. },
  8157. dequeue: function (type) {
  8158. return this.each(function () {
  8159. jQuery.dequeue(this, type);
  8160. });
  8161. },
  8162. clearQueue: function (type) {
  8163. return this.queue(type || "fx", []);
  8164. },
  8165. // Get a promise resolved when queues of a certain type
  8166. // are emptied (fx is the type by default)
  8167. promise: function (type, obj) {
  8168. var tmp,
  8169. count = 1,
  8170. defer = jQuery.Deferred(),
  8171. elements = this,
  8172. i = this.length,
  8173. resolve = function () {
  8174. if (! --count) {
  8175. defer.resolveWith(elements, [elements]);
  8176. }
  8177. };
  8178.  
  8179. if (typeof type !== "string") {
  8180. obj = type;
  8181. type = undefined;
  8182. }
  8183. type = type || "fx";
  8184.  
  8185. while (i--) {
  8186. tmp = jQuery._data(elements[i], type + "queueHooks");
  8187. if (tmp && tmp.empty) {
  8188. count++;
  8189. tmp.empty.add(resolve);
  8190. }
  8191. }
  8192. resolve();
  8193. return defer.promise(obj);
  8194. }
  8195. });
  8196.  
  8197. /*
  8198. * Helper functions for managing events -- not part of the public interface.
  8199. * Props to Dean Edwards' addEvent library for many of the ideas.
  8200. */
  8201. jQuery.event = {
  8202.  
  8203. global: {},
  8204.  
  8205. add: function (elem, types, handler, data, selector) {
  8206. var tmp,
  8207. events,
  8208. t,
  8209. handleObjIn,
  8210. special,
  8211. eventHandle,
  8212. handleObj,
  8213. handlers,
  8214. type,
  8215. namespaces,
  8216. origType,
  8217. elemData = jQuery._data(elem);
  8218.  
  8219. // Don't attach events to noData or text/comment nodes (but allow plain objects)
  8220. if (!elemData) {
  8221. return;
  8222. }
  8223.  
  8224. // Caller can pass in an object of custom data in lieu of the handler
  8225. if (handler.handler) {
  8226. handleObjIn = handler;
  8227. handler = handleObjIn.handler;
  8228. selector = handleObjIn.selector;
  8229. }
  8230.  
  8231. // Make sure that the handler has a unique ID, used to find/remove it later
  8232. if (!handler.guid) {
  8233. handler.guid = jQuery.guid++;
  8234. }
  8235.  
  8236. // Init the element's event structure and main handler, if this is the first
  8237. if (!(events = elemData.events)) {
  8238. events = elemData.events = {};
  8239. }
  8240. if (!(eventHandle = elemData.handle)) {
  8241. eventHandle = elemData.handle = function (e) {
  8242. // Discard the second event of a jQuery.event.trigger() and
  8243. // when an event is called after a page has unloaded
  8244. return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply(eventHandle.elem, arguments) : undefined;
  8245. };
  8246. // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
  8247. eventHandle.elem = elem;
  8248. }
  8249.  
  8250. // Handle multiple events separated by a space
  8251. types = (types || "").match(rnotwhite) || [""];
  8252. t = types.length;
  8253. while (t--) {
  8254. tmp = rtypenamespace.exec(types[t]) || [];
  8255. type = origType = tmp[1];
  8256. namespaces = (tmp[2] || "").split(".").sort();
  8257.  
  8258. // There *must* be a type, no attaching namespace-only handlers
  8259. if (!type) {
  8260. continue;
  8261. }
  8262.  
  8263. // If event changes its type, use the special event handlers for the changed type
  8264. special = jQuery.event.special[type] || {};
  8265.  
  8266. // If selector defined, determine special event api type, otherwise given type
  8267. type = (selector ? special.delegateType : special.bindType) || type;
  8268.  
  8269. // Update special based on newly reset type
  8270. special = jQuery.event.special[type] || {};
  8271.  
  8272. // handleObj is passed to all event handlers
  8273. handleObj = jQuery.extend({
  8274. type: type,
  8275. origType: origType,
  8276. data: data,
  8277. handler: handler,
  8278. guid: handler.guid,
  8279. selector: selector,
  8280. needsContext: selector && jQuery.expr.match.needsContext.test(selector),
  8281. namespace: namespaces.join(".")
  8282. }, handleObjIn);
  8283.  
  8284. // Init the event handler queue if we're the first
  8285. if (!(handlers = events[type])) {
  8286. handlers = events[type] = [];
  8287. handlers.delegateCount = 0;
  8288.  
  8289. // Only use addEventListener/attachEvent if the special events handler returns false
  8290. if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
  8291. // Bind the global event handler to the element
  8292. if (elem.addEventListener) {
  8293. elem.addEventListener(type, eventHandle, false);
  8294. } else if (elem.attachEvent) {
  8295. elem.attachEvent("on" + type, eventHandle);
  8296. }
  8297. }
  8298. }
  8299.  
  8300. if (special.add) {
  8301. special.add.call(elem, handleObj);
  8302.  
  8303. if (!handleObj.handler.guid) {
  8304. handleObj.handler.guid = handler.guid;
  8305. }
  8306. }
  8307.  
  8308. // Add to the element's handler list, delegates in front
  8309. if (selector) {
  8310. handlers.splice(handlers.delegateCount++, 0, handleObj);
  8311. } else {
  8312. handlers.push(handleObj);
  8313. }
  8314.  
  8315. // Keep track of which events have ever been used, for event optimization
  8316. jQuery.event.global[type] = true;
  8317. }
  8318.  
  8319. // Nullify elem to prevent memory leaks in IE
  8320. elem = null;
  8321. },
  8322.  
  8323. // Detach an event or set of events from an element
  8324. remove: function (elem, types, handler, selector, mappedTypes) {
  8325. var j,
  8326. handleObj,
  8327. tmp,
  8328. origCount,
  8329. t,
  8330. events,
  8331. special,
  8332. handlers,
  8333. type,
  8334. namespaces,
  8335. origType,
  8336. elemData = jQuery.hasData(elem) && jQuery._data(elem);
  8337.  
  8338. if (!elemData || !(events = elemData.events)) {
  8339. return;
  8340. }
  8341.  
  8342. // Once for each type.namespace in types; type may be omitted
  8343. types = (types || "").match(rnotwhite) || [""];
  8344. t = types.length;
  8345. while (t--) {
  8346. tmp = rtypenamespace.exec(types[t]) || [];
  8347. type = origType = tmp[1];
  8348. namespaces = (tmp[2] || "").split(".").sort();
  8349.  
  8350. // Unbind all events (on this namespace, if provided) for the element
  8351. if (!type) {
  8352. for (type in events) {
  8353. jQuery.event.remove(elem, type + types[t], handler, selector, true);
  8354. }
  8355. continue;
  8356. }
  8357.  
  8358. special = jQuery.event.special[type] || {};
  8359. type = (selector ? special.delegateType : special.bindType) || type;
  8360. handlers = events[type] || [];
  8361. tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");
  8362.  
  8363. // Remove matching events
  8364. origCount = j = handlers.length;
  8365. while (j--) {
  8366. handleObj = handlers[j];
  8367.  
  8368. if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) {
  8369. handlers.splice(j, 1);
  8370.  
  8371. if (handleObj.selector) {
  8372. handlers.delegateCount--;
  8373. }
  8374. if (special.remove) {
  8375. special.remove.call(elem, handleObj);
  8376. }
  8377. }
  8378. }
  8379.  
  8380. // Remove generic event handler if we removed something and no more handlers exist
  8381. // (avoids potential for endless recursion during removal of special event handlers)
  8382. if (origCount && !handlers.length) {
  8383. if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
  8384. jQuery.removeEvent(elem, type, elemData.handle);
  8385. }
  8386.  
  8387. delete events[type];
  8388. }
  8389. }
  8390.  
  8391. // Remove the expando if it's no longer used
  8392. if (jQuery.isEmptyObject(events)) {
  8393. delete elemData.handle;
  8394.  
  8395. // removeData also checks for emptiness and clears the expando if empty
  8396. // so use it instead of delete
  8397. jQuery._removeData(elem, "events");
  8398. }
  8399. },
  8400.  
  8401. trigger: function (event, data, elem, onlyHandlers) {
  8402. var handle,
  8403. ontype,
  8404. cur,
  8405. bubbleType,
  8406. special,
  8407. tmp,
  8408. i,
  8409. eventPath = [elem || document],
  8410. type = hasOwn.call(event, "type") ? event.type : event,
  8411. namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
  8412.  
  8413. cur = tmp = elem = elem || document;
  8414.  
  8415. // Don't do events on text and comment nodes
  8416. if (elem.nodeType === 3 || elem.nodeType === 8) {
  8417. return;
  8418. }
  8419.  
  8420. // focus/blur morphs to focusin/out; ensure we're not firing them right now
  8421. if (rfocusMorph.test(type + jQuery.event.triggered)) {
  8422. return;
  8423. }
  8424.  
  8425. if (type.indexOf(".") >= 0) {
  8426. // Namespaced trigger; create a regexp to match event type in handle()
  8427. namespaces = type.split(".");
  8428. type = namespaces.shift();
  8429. namespaces.sort();
  8430. }
  8431. ontype = type.indexOf(":") < 0 && "on" + type;
  8432.  
  8433. // Caller can pass in a jQuery.Event object, Object, or just an event type string
  8434. event = event[jQuery.expando] ? event : new jQuery.Event(type, typeof event === "object" && event);
  8435.  
  8436. // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
  8437. event.isTrigger = onlyHandlers ? 2 : 3;
  8438. event.namespace = namespaces.join(".");
  8439. event.namespace_re = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
  8440.  
  8441. // Clean up the event in case it is being reused
  8442. event.result = undefined;
  8443. if (!event.target) {
  8444. event.target = elem;
  8445. }
  8446.  
  8447. // Clone any incoming data and prepend the event, creating the handler arg list
  8448. data = data == null ? [event] : jQuery.makeArray(data, [event]);
  8449.  
  8450. // Allow special events to draw outside the lines
  8451. special = jQuery.event.special[type] || {};
  8452. if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
  8453. return;
  8454. }
  8455.  
  8456. // Determine event propagation path in advance, per W3C events spec (#9951)
  8457. // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
  8458. if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {
  8459.  
  8460. bubbleType = special.delegateType || type;
  8461. if (!rfocusMorph.test(bubbleType + type)) {
  8462. cur = cur.parentNode;
  8463. }
  8464. for (; cur; cur = cur.parentNode) {
  8465. eventPath.push(cur);
  8466. tmp = cur;
  8467. }
  8468.  
  8469. // Only add window if we got to document (e.g., not plain obj or detached DOM)
  8470. if (tmp === (elem.ownerDocument || document)) {
  8471. eventPath.push(tmp.defaultView || tmp.parentWindow || window);
  8472. }
  8473. }
  8474.  
  8475. // Fire handlers on the event path
  8476. i = 0;
  8477. while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {
  8478.  
  8479. event.type = i > 1 ? bubbleType : special.bindType || type;
  8480.  
  8481. // jQuery handler
  8482. handle = (jQuery._data(cur, "events") || {})[event.type] && jQuery._data(cur, "handle");
  8483. if (handle) {
  8484. handle.apply(cur, data);
  8485. }
  8486.  
  8487. // Native handler
  8488. handle = ontype && cur[ontype];
  8489. if (handle && handle.apply && jQuery.acceptData(cur)) {
  8490. event.result = handle.apply(cur, data);
  8491. if (event.result === false) {
  8492. event.preventDefault();
  8493. }
  8494. }
  8495. }
  8496. event.type = type;
  8497.  
  8498. // If nobody prevented the default action, do it now
  8499. if (!onlyHandlers && !event.isDefaultPrevented()) {
  8500.  
  8501. if ((!special._default || special._default.apply(eventPath.pop(), data) === false) && jQuery.acceptData(elem)) {
  8502.  
  8503. // Call a native DOM method on the target with the same name name as the event.
  8504. // Can't use an .isFunction() check here because IE6/7 fails that test.
  8505. // Don't do default actions on window, that's where global variables be (#6170)
  8506. if (ontype && elem[type] && !jQuery.isWindow(elem)) {
  8507.  
  8508. // Don't re-trigger an onFOO event when we call its FOO() method
  8509. tmp = elem[ontype];
  8510.  
  8511. if (tmp) {
  8512. elem[ontype] = null;
  8513. }
  8514.  
  8515. // Prevent re-triggering of the same event, since we already bubbled it above
  8516. jQuery.event.triggered = type;
  8517. try {
  8518. elem[type]();
  8519. } catch (e) {
  8520. // IE<9 dies on focus/blur to hidden element (#1486,#12518)
  8521. // only reproducible on winXP IE8 native, not IE9 in IE8 mode
  8522. }
  8523. jQuery.event.triggered = undefined;
  8524.  
  8525. if (tmp) {
  8526. elem[ontype] = tmp;
  8527. }
  8528. }
  8529. }
  8530. }
  8531.  
  8532. return event.result;
  8533. },
  8534.  
  8535. dispatch: function (event) {
  8536.  
  8537. // Make a writable jQuery.Event from the native event object
  8538. event = jQuery.event.fix(event);
  8539.  
  8540. var i,
  8541. ret,
  8542. handleObj,
  8543. matched,
  8544. j,
  8545. handlerQueue = [],
  8546. args = slice.call(arguments),
  8547. handlers = (jQuery._data(this, "events") || {})[event.type] || [],
  8548. special = jQuery.event.special[event.type] || {};
  8549.  
  8550. // Use the fix-ed jQuery.Event rather than the (read-only) native event
  8551. args[0] = event;
  8552. event.delegateTarget = this;
  8553.  
  8554. // Call the preDispatch hook for the mapped type, and let it bail if desired
  8555. if (special.preDispatch && special.preDispatch.call(this, event) === false) {
  8556. return;
  8557. }
  8558.  
  8559. // Determine handlers
  8560. handlerQueue = jQuery.event.handlers.call(this, event, handlers);
  8561.  
  8562. // Run delegates first; they may want to stop propagation beneath us
  8563. i = 0;
  8564. while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) {
  8565. event.currentTarget = matched.elem;
  8566.  
  8567. j = 0;
  8568. while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) {
  8569.  
  8570. // Triggered event must either 1) have no namespace, or
  8571. // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
  8572. if (!event.namespace_re || event.namespace_re.test(handleObj.namespace)) {
  8573.  
  8574. event.handleObj = handleObj;
  8575. event.data = handleObj.data;
  8576.  
  8577. ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args);
  8578.  
  8579. if (ret !== undefined) {
  8580. if ((event.result = ret) === false) {
  8581. event.preventDefault();
  8582. event.stopPropagation();
  8583. }
  8584. }
  8585. }
  8586. }
  8587. }
  8588.  
  8589. // Call the postDispatch hook for the mapped type
  8590. if (special.postDispatch) {
  8591. special.postDispatch.call(this, event);
  8592. }
  8593.  
  8594. return event.result;
  8595. },
  8596.  
  8597. handlers: function (event, handlers) {
  8598. var sel,
  8599. handleObj,
  8600. matches,
  8601. i,
  8602. handlerQueue = [],
  8603. delegateCount = handlers.delegateCount,
  8604. cur = event.target;
  8605.  
  8606. // Find delegate handlers
  8607. // Black-hole SVG <use> instance trees (#13180)
  8608. // Avoid non-left-click bubbling in Firefox (#3861)
  8609. if (delegateCount && cur.nodeType && (!event.button || event.type !== "click")) {
  8610.  
  8611. /* jshint eqeqeq: false */
  8612. for (; cur != this; cur = cur.parentNode || this) {
  8613. /* jshint eqeqeq: true */
  8614.  
  8615. // Don't check non-elements (#13208)
  8616. // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
  8617. if (cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click")) {
  8618. matches = [];
  8619. for (i = 0; i < delegateCount; i++) {
  8620. handleObj = handlers[i];
  8621.  
  8622. // Don't conflict with Object.prototype properties (#13203)
  8623. sel = handleObj.selector + " ";
  8624.  
  8625. if (matches[sel] === undefined) {
  8626. matches[sel] = handleObj.needsContext ? jQuery(sel, this).index(cur) >= 0 : jQuery.find(sel, this, null, [cur]).length;
  8627. }
  8628. if (matches[sel]) {
  8629. matches.push(handleObj);
  8630. }
  8631. }
  8632. if (matches.length) {
  8633. handlerQueue.push({ elem: cur, handlers: matches });
  8634. }
  8635. }
  8636. }
  8637. }
  8638.  
  8639. // Add the remaining (directly-bound) handlers
  8640. if (delegateCount < handlers.length) {
  8641. handlerQueue.push({ elem: this, handlers: handlers.slice(delegateCount) });
  8642. }
  8643.  
  8644. return handlerQueue;
  8645. },
  8646.  
  8647. fix: function (event) {
  8648. if (event[jQuery.expando]) {
  8649. return event;
  8650. }
  8651.  
  8652. // Create a writable copy of the event object and normalize some properties
  8653. var i,
  8654. prop,
  8655. copy,
  8656. type = event.type,
  8657. originalEvent = event,
  8658. fixHook = this.fixHooks[type];
  8659.  
  8660. if (!fixHook) {
  8661. this.fixHooks[type] = fixHook = rmouseEvent.test(type) ? this.mouseHooks : rkeyEvent.test(type) ? this.keyHooks : {};
  8662. }
  8663. copy = fixHook.props ? this.props.concat(fixHook.props) : this.props;
  8664.  
  8665. event = new jQuery.Event(originalEvent);
  8666.  
  8667. i = copy.length;
  8668. while (i--) {
  8669. prop = copy[i];
  8670. event[prop] = originalEvent[prop];
  8671. }
  8672.  
  8673. // Support: IE<9
  8674. // Fix target property (#1925)
  8675. if (!event.target) {
  8676. event.target = originalEvent.srcElement || document;
  8677. }
  8678.  
  8679. // Support: Chrome 23+, Safari?
  8680. // Target should not be a text node (#504, #13143)
  8681. if (event.target.nodeType === 3) {
  8682. event.target = event.target.parentNode;
  8683. }
  8684.  
  8685. // Support: IE<9
  8686. // For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
  8687. event.metaKey = !!event.metaKey;
  8688.  
  8689. return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
  8690. },
  8691.  
  8692. // Includes some event props shared by KeyEvent and MouseEvent
  8693. props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
  8694.  
  8695. fixHooks: {},
  8696.  
  8697. keyHooks: {
  8698. props: "char charCode key keyCode".split(" "),
  8699. filter: function (event, original) {
  8700.  
  8701. // Add which for key events
  8702. if (event.which == null) {
  8703. event.which = original.charCode != null ? original.charCode : original.keyCode;
  8704. }
  8705.  
  8706. return event;
  8707. }
  8708. },
  8709.  
  8710. mouseHooks: {
  8711. props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
  8712. filter: function (event, original) {
  8713. var body,
  8714. eventDoc,
  8715. doc,
  8716. button = original.button,
  8717. fromElement = original.fromElement;
  8718.  
  8719. // Calculate pageX/Y if missing and clientX/Y available
  8720. if (event.pageX == null && original.clientX != null) {
  8721. eventDoc = event.target.ownerDocument || document;
  8722. doc = eventDoc.documentElement;
  8723. body = eventDoc.body;
  8724.  
  8725. event.pageX = original.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  8726. event.pageY = original.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  8727. }
  8728.  
  8729. // Add relatedTarget, if necessary
  8730. if (!event.relatedTarget && fromElement) {
  8731. event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
  8732. }
  8733.  
  8734. // Add which for click: 1 === left; 2 === middle; 3 === right
  8735. // Note: button is not normalized, so don't use it
  8736. if (!event.which && button !== undefined) {
  8737. event.which = button & 1 ? 1 : button & 2 ? 3 : button & 4 ? 2 : 0;
  8738. }
  8739.  
  8740. return event;
  8741. }
  8742. },
  8743.  
  8744. special: {
  8745. load: {
  8746. // Prevent triggered image.load events from bubbling to window.load
  8747. noBubble: true
  8748. },
  8749. focus: {
  8750. // Fire native event if possible so blur/focus sequence is correct
  8751. trigger: function () {
  8752. if (this !== safeActiveElement() && this.focus) {
  8753. try {
  8754. this.focus();
  8755. return false;
  8756. } catch (e) {
  8757. // Support: IE<9
  8758. // If we error on focus to hidden element (#1486, #12518),
  8759. // let .trigger() run the handlers
  8760. }
  8761. }
  8762. },
  8763. delegateType: "focusin"
  8764. },
  8765. blur: {
  8766. trigger: function () {
  8767. if (this === safeActiveElement() && this.blur) {
  8768. this.blur();
  8769. return false;
  8770. }
  8771. },
  8772. delegateType: "focusout"
  8773. },
  8774. click: {
  8775. // For checkbox, fire native event so checked state will be right
  8776. trigger: function () {
  8777. if (jQuery.nodeName(this, "input") && this.type === "checkbox" && this.click) {
  8778. this.click();
  8779. return false;
  8780. }
  8781. },
  8782.  
  8783. // For cross-browser consistency, don't fire native .click() on links
  8784. _default: function (event) {
  8785. return jQuery.nodeName(event.target, "a");
  8786. }
  8787. },
  8788.  
  8789. beforeunload: {
  8790. postDispatch: function (event) {
  8791.  
  8792. // Support: Firefox 20+
  8793. // Firefox doesn't alert if the returnValue field is not set.
  8794. if (event.result !== undefined && event.originalEvent) {
  8795. event.originalEvent.returnValue = event.result;
  8796. }
  8797. }
  8798. }
  8799. },
  8800.  
  8801. simulate: function (type, elem, event, bubble) {
  8802. // Piggyback on a donor event to simulate a different one.
  8803. // Fake originalEvent to avoid donor's stopPropagation, but if the
  8804. // simulated event prevents default then we do the same on the donor.
  8805. var e = jQuery.extend(new jQuery.Event(), event, {
  8806. type: type,
  8807. isSimulated: true,
  8808. originalEvent: {}
  8809. });
  8810. if (bubble) {
  8811. jQuery.event.trigger(e, null, elem);
  8812. } else {
  8813. jQuery.event.dispatch.call(elem, e);
  8814. }
  8815. if (e.isDefaultPrevented()) {
  8816. event.preventDefault();
  8817. }
  8818. }
  8819. };
  8820.  
  8821. jQuery.removeEvent = document.removeEventListener ? function (elem, type, handle) {
  8822. if (elem.removeEventListener) {
  8823. elem.removeEventListener(type, handle, false);
  8824. }
  8825. } : function (elem, type, handle) {
  8826. var name = "on" + type;
  8827.  
  8828. if (elem.detachEvent) {
  8829.  
  8830. // #8545, #7054, preventing memory leaks for custom events in IE6-8
  8831. // detachEvent needed property on element, by name of that event, to properly expose it to GC
  8832. if (typeof elem[name] === strundefined) {
  8833. elem[name] = null;
  8834. }
  8835.  
  8836. elem.detachEvent(name, handle);
  8837. }
  8838. };
  8839.  
  8840. jQuery.Event = function (src, props) {
  8841. // Allow instantiation without the 'new' keyword
  8842. if (!(this instanceof jQuery.Event)) {
  8843. return new jQuery.Event(src, props);
  8844. }
  8845.  
  8846. // Event object
  8847. if (src && src.type) {
  8848. this.originalEvent = src;
  8849. this.type = src.type;
  8850.  
  8851. // Events bubbling up the document may have been marked as prevented
  8852. // by a handler lower down the tree; reflect the correct value.
  8853. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined &&
  8854. // Support: IE < 9, Android < 4.0
  8855. src.returnValue === false ? returnTrue : returnFalse;
  8856.  
  8857. // Event type
  8858. } else {
  8859. this.type = src;
  8860. }
  8861.  
  8862. // Put explicitly provided properties onto the event object
  8863. if (props) {
  8864. jQuery.extend(this, props);
  8865. }
  8866.  
  8867. // Create a timestamp if incoming event doesn't have one
  8868. this.timeStamp = src && src.timeStamp || jQuery.now();
  8869.  
  8870. // Mark it as fixed
  8871. this[jQuery.expando] = true;
  8872. };
  8873.  
  8874. var rformElems = /^(?:input|select|textarea)$/i,
  8875. rkeyEvent = /^key/,
  8876. rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
  8877. rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
  8878. rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
  8879.  
  8880. function returnTrue() {
  8881. return true;
  8882. }
  8883.  
  8884. function returnFalse() {
  8885. return false;
  8886. }
  8887.  
  8888. // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
  8889. // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  8890. jQuery.Event.prototype = {
  8891. isDefaultPrevented: returnFalse,
  8892. isPropagationStopped: returnFalse,
  8893. isImmediatePropagationStopped: returnFalse,
  8894.  
  8895. preventDefault: function () {
  8896. var e = this.originalEvent;
  8897.  
  8898. this.isDefaultPrevented = returnTrue;
  8899. if (!e) {
  8900. return;
  8901. }
  8902.  
  8903. // If preventDefault exists, run it on the original event
  8904. if (e.preventDefault) {
  8905. e.preventDefault();
  8906.  
  8907. // Support: IE
  8908. // Otherwise set the returnValue property of the original event to false
  8909. } else {
  8910. e.returnValue = false;
  8911. }
  8912. },
  8913. stopPropagation: function () {
  8914. var e = this.originalEvent;
  8915.  
  8916. this.isPropagationStopped = returnTrue;
  8917. if (!e) {
  8918. return;
  8919. }
  8920. // If stopPropagation exists, run it on the original event
  8921. if (e.stopPropagation) {
  8922. e.stopPropagation();
  8923. }
  8924.  
  8925. // Support: IE
  8926. // Set the cancelBubble property of the original event to true
  8927. e.cancelBubble = true;
  8928. },
  8929. stopImmediatePropagation: function () {
  8930. var e = this.originalEvent;
  8931.  
  8932. this.isImmediatePropagationStopped = returnTrue;
  8933.  
  8934. if (e && e.stopImmediatePropagation) {
  8935. e.stopImmediatePropagation();
  8936. }
  8937.  
  8938. this.stopPropagation();
  8939. }
  8940. };
  8941.  
  8942. // IE submit delegation
  8943. if (!support.submitBubbles) {
  8944.  
  8945. jQuery.event.special.submit = {
  8946. setup: function () {
  8947. // Only need this for delegated form submit events
  8948. if (jQuery.nodeName(this, "form")) {
  8949. return false;
  8950. }
  8951.  
  8952. // Lazy-add a submit handler when a descendant form may potentially be submitted
  8953. jQuery.event.add(this, "click._submit keypress._submit", function (e) {
  8954. // Node name check avoids a VML-related crash in IE (#9807)
  8955. var elem = e.target,
  8956. form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined;
  8957. if (form && !jQuery._data(form, "submitBubbles")) {
  8958. jQuery.event.add(form, "submit._submit", function (event) {
  8959. event._submit_bubble = true;
  8960. });
  8961. jQuery._data(form, "submitBubbles", true);
  8962. }
  8963. });
  8964. // return undefined since we don't need an event listener
  8965. },
  8966.  
  8967. postDispatch: function (event) {
  8968. // If form was submitted by the user, bubble the event up the tree
  8969. if (event._submit_bubble) {
  8970. delete event._submit_bubble;
  8971. if (this.parentNode && !event.isTrigger) {
  8972. jQuery.event.simulate("submit", this.parentNode, event, true);
  8973. }
  8974. }
  8975. },
  8976.  
  8977. teardown: function () {
  8978. // Only need this for delegated form submit events
  8979. if (jQuery.nodeName(this, "form")) {
  8980. return false;
  8981. }
  8982.  
  8983. // Remove delegated handlers; cleanData eventually reaps submit handlers attached above
  8984. jQuery.event.remove(this, "._submit");
  8985. }
  8986. };
  8987. }
  8988.  
  8989. // IE change delegation and checkbox/radio fix
  8990. if (!support.changeBubbles) {
  8991.  
  8992. jQuery.event.special.change = {
  8993.  
  8994. setup: function () {
  8995.  
  8996. if (rformElems.test(this.nodeName)) {
  8997. // IE doesn't fire change on a check/radio until blur; trigger it on click
  8998. // after a propertychange. Eat the blur-change in special.change.handle.
  8999. // This still fires onchange a second time for check/radio after blur.
  9000. if (this.type === "checkbox" || this.type === "radio") {
  9001. jQuery.event.add(this, "propertychange._change", function (event) {
  9002. if (event.originalEvent.propertyName === "checked") {
  9003. this._just_changed = true;
  9004. }
  9005. });
  9006. jQuery.event.add(this, "click._change", function (event) {
  9007. if (this._just_changed && !event.isTrigger) {
  9008. this._just_changed = false;
  9009. }
  9010. // Allow triggered, simulated change events (#11500)
  9011. jQuery.event.simulate("change", this, event, true);
  9012. });
  9013. }
  9014. return false;
  9015. }
  9016. // Delegated event; lazy-add a change handler on descendant inputs
  9017. jQuery.event.add(this, "beforeactivate._change", function (e) {
  9018. var elem = e.target;
  9019.  
  9020. if (rformElems.test(elem.nodeName) && !jQuery._data(elem, "changeBubbles")) {
  9021. jQuery.event.add(elem, "change._change", function (event) {
  9022. if (this.parentNode && !event.isSimulated && !event.isTrigger) {
  9023. jQuery.event.simulate("change", this.parentNode, event, true);
  9024. }
  9025. });
  9026. jQuery._data(elem, "changeBubbles", true);
  9027. }
  9028. });
  9029. },
  9030.  
  9031. handle: function (event) {
  9032. var elem = event.target;
  9033.  
  9034. // Swallow native change events from checkbox/radio, we already triggered them above
  9035. if (this !== elem || event.isSimulated || event.isTrigger || elem.type !== "radio" && elem.type !== "checkbox") {
  9036. return event.handleObj.handler.apply(this, arguments);
  9037. }
  9038. },
  9039.  
  9040. teardown: function () {
  9041. jQuery.event.remove(this, "._change");
  9042.  
  9043. return !rformElems.test(this.nodeName);
  9044. }
  9045. };
  9046. }
  9047.  
  9048. // Create "bubbling" focus and blur events
  9049. if (!support.focusinBubbles) {
  9050. jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {
  9051.  
  9052. // Attach a single capturing handler on the document while someone wants focusin/focusout
  9053. var handler = function (event) {
  9054. jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true);
  9055. };
  9056.  
  9057. jQuery.event.special[fix] = {
  9058. setup: function () {
  9059. var doc = this.ownerDocument || this,
  9060. attaches = jQuery._data(doc, fix);
  9061.  
  9062. if (!attaches) {
  9063. doc.addEventListener(orig, handler, true);
  9064. }
  9065. jQuery._data(doc, fix, (attaches || 0) + 1);
  9066. },
  9067. teardown: function () {
  9068. var doc = this.ownerDocument || this,
  9069. attaches = jQuery._data(doc, fix) - 1;
  9070.  
  9071. if (!attaches) {
  9072. doc.removeEventListener(orig, handler, true);
  9073. jQuery._removeData(doc, fix);
  9074. } else {
  9075. jQuery._data(doc, fix, attaches);
  9076. }
  9077. }
  9078. };
  9079. });
  9080. }
  9081.  
  9082. jQuery.fn.extend({
  9083.  
  9084. on: function (types, selector, data, fn, /*INTERNAL*/one) {
  9085. var type, origFn;
  9086.  
  9087. // Types can be a map of types/handlers
  9088. if (typeof types === "object") {
  9089. // ( types-Object, selector, data )
  9090. if (typeof selector !== "string") {
  9091. // ( types-Object, data )
  9092. data = data || selector;
  9093. selector = undefined;
  9094. }
  9095. for (type in types) {
  9096. this.on(type, selector, data, types[type], one);
  9097. }
  9098. return this;
  9099. }
  9100.  
  9101. if (data == null && fn == null) {
  9102. // ( types, fn )
  9103. fn = selector;
  9104. data = selector = undefined;
  9105. } else if (fn == null) {
  9106. if (typeof selector === "string") {
  9107. // ( types, selector, fn )
  9108. fn = data;
  9109. data = undefined;
  9110. } else {
  9111. // ( types, data, fn )
  9112. fn = data;
  9113. data = selector;
  9114. selector = undefined;
  9115. }
  9116. }
  9117. if (fn === false) {
  9118. fn = returnFalse;
  9119. } else if (!fn) {
  9120. return this;
  9121. }
  9122.  
  9123. if (one === 1) {
  9124. origFn = fn;
  9125. fn = function (event) {
  9126. // Can use an empty set, since event contains the info
  9127. jQuery().off(event);
  9128. return origFn.apply(this, arguments);
  9129. };
  9130. // Use same guid so caller can remove using origFn
  9131. fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
  9132. }
  9133. return this.each(function () {
  9134. jQuery.event.add(this, types, fn, data, selector);
  9135. });
  9136. },
  9137. one: function (types, selector, data, fn) {
  9138. return this.on(types, selector, data, fn, 1);
  9139. },
  9140. off: function (types, selector, fn) {
  9141. var handleObj, type;
  9142. if (types && types.preventDefault && types.handleObj) {
  9143. // ( event ) dispatched jQuery.Event
  9144. handleObj = types.handleObj;
  9145. jQuery(types.delegateTarget).off(handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler);
  9146. return this;
  9147. }
  9148. if (typeof types === "object") {
  9149. // ( types-object [, selector] )
  9150. for (type in types) {
  9151. this.off(type, selector, types[type]);
  9152. }
  9153. return this;
  9154. }
  9155. if (selector === false || typeof selector === "function") {
  9156. // ( types [, fn] )
  9157. fn = selector;
  9158. selector = undefined;
  9159. }
  9160. if (fn === false) {
  9161. fn = returnFalse;
  9162. }
  9163. return this.each(function () {
  9164. jQuery.event.remove(this, types, fn, selector);
  9165. });
  9166. },
  9167.  
  9168. trigger: function (type, data) {
  9169. return this.each(function () {
  9170. jQuery.event.trigger(type, data, this);
  9171. });
  9172. },
  9173. triggerHandler: function (type, data) {
  9174. var elem = this[0];
  9175. if (elem) {
  9176. return jQuery.event.trigger(type, data, elem, true);
  9177. }
  9178. }
  9179. });
  9180.  
  9181. // Based off of the plugin by Clint Helfers, with permission.
  9182. // http://blindsignals.com/index.php/2009/07/jquery-delay/
  9183. jQuery.fn.delay = function (time, type) {
  9184. time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
  9185. type = type || "fx";
  9186.  
  9187. return this.queue(type, function (next, hooks) {
  9188. var timeout = setTimeout(next, time);
  9189. hooks.stop = function () {
  9190. clearTimeout(timeout);
  9191. };
  9192. });
  9193. };
  9194.  
  9195. var nonce = jQuery.now();
  9196.  
  9197. var rquery = /\?/;
  9198.  
  9199. var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
  9200.  
  9201. jQuery.parseJSON = function (data) {
  9202. // Attempt to parse using the native JSON parser first
  9203. if (window.JSON && window.JSON.parse) {
  9204. // Support: Android 2.3
  9205. // Workaround failure to string-cast null input
  9206. return window.JSON.parse(data + "");
  9207. }
  9208.  
  9209. var requireNonComma,
  9210. depth = null,
  9211. str = jQuery.trim(data + "");
  9212.  
  9213. // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
  9214. // after removing valid tokens
  9215. return str && !jQuery.trim(str.replace(rvalidtokens, function (token, comma, open, close) {
  9216.  
  9217. // Force termination if we see a misplaced comma
  9218. if (requireNonComma && comma) {
  9219. depth = 0;
  9220. }
  9221.  
  9222. // Perform no more replacements after returning to outermost depth
  9223. if (depth === 0) {
  9224. return token;
  9225. }
  9226.  
  9227. // Commas must not follow "[", "{", or ","
  9228. requireNonComma = open || comma;
  9229.  
  9230. // Determine new depth
  9231. // array/object open ("[" or "{"): depth += true - false (increment)
  9232. // array/object close ("]" or "}"): depth += false - true (decrement)
  9233. // other cases ("," or primitive): depth += true - true (numeric cast)
  9234. depth += !close - !open;
  9235.  
  9236. // Remove this token
  9237. return "";
  9238. })) ? Function("return " + str)() : jQuery.error("Invalid JSON: " + data);
  9239. };
  9240.  
  9241. // Cross-browser xml parsing
  9242. jQuery.parseXML = function (data) {
  9243. var xml, tmp;
  9244. if (!data || typeof data !== "string") {
  9245. return null;
  9246. }
  9247. try {
  9248. if (window.DOMParser) {
  9249. // Standard
  9250. tmp = new DOMParser();
  9251. xml = tmp.parseFromString(data, "text/xml");
  9252. } else {
  9253. // IE
  9254. xml = new ActiveXObject("Microsoft.XMLDOM");
  9255. xml.async = "false";
  9256. xml.loadXML(data);
  9257. }
  9258. } catch (e) {
  9259. xml = undefined;
  9260. }
  9261. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
  9262. jQuery.error("Invalid XML: " + data);
  9263. }
  9264. return xml;
  9265. };
  9266.  
  9267. var
  9268. // Document location
  9269. ajaxLocParts,
  9270. ajaxLocation,
  9271. rhash = /#.*$/,
  9272. rts = /([?&])_=[^&]*/,
  9273. rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
  9274. // IE leaves an \r character at EOL
  9275. // #7653, #8125, #8152: local protocol detection
  9276. rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
  9277. rnoContent = /^(?:GET|HEAD)$/,
  9278. rprotocol = /^\/\//,
  9279. rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
  9280.  
  9281.  
  9282. /* Prefilters
  9283. * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
  9284. * 2) These are called:
  9285. * - BEFORE asking for a transport
  9286. * - AFTER param serialization (s.data is a string if s.processData is true)
  9287. * 3) key is the dataType
  9288. * 4) the catchall symbol "*" can be used
  9289. * 5) execution will start with transport dataType and THEN continue down to "*" if needed
  9290. */
  9291. prefilters = {},
  9292.  
  9293.  
  9294. /* Transports bindings
  9295. * 1) key is the dataType
  9296. * 2) the catchall symbol "*" can be used
  9297. * 3) selection will start with transport dataType and THEN go to "*" if needed
  9298. */
  9299. transports = {},
  9300.  
  9301.  
  9302. // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
  9303. allTypes = "*/".concat("*");
  9304.  
  9305. // #8138, IE may throw an exception when accessing
  9306. // a field from window.location if document.domain has been set
  9307. try {
  9308. ajaxLocation = location.href;
  9309. } catch (e) {
  9310. // Use the href attribute of an A element
  9311. // since IE will modify it given document.location
  9312. ajaxLocation = document.createElement("a");
  9313. ajaxLocation.href = "";
  9314. ajaxLocation = ajaxLocation.href;
  9315. }
  9316.  
  9317. // Segment location into parts
  9318. ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [];
  9319.  
  9320. // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
  9321. function addToPrefiltersOrTransports(structure) {
  9322.  
  9323. // dataTypeExpression is optional and defaults to "*"
  9324. return function (dataTypeExpression, func) {
  9325.  
  9326. if (typeof dataTypeExpression !== "string") {
  9327. func = dataTypeExpression;
  9328. dataTypeExpression = "*";
  9329. }
  9330.  
  9331. var dataType,
  9332. i = 0,
  9333. dataTypes = dataTypeExpression.toLowerCase().match(rnotwhite) || [];
  9334.  
  9335. if (jQuery.isFunction(func)) {
  9336. // For each dataType in the dataTypeExpression
  9337. while (dataType = dataTypes[i++]) {
  9338. // Prepend if requested
  9339. if (dataType.charAt(0) === "+") {
  9340. dataType = dataType.slice(1) || "*";
  9341. (structure[dataType] = structure[dataType] || []).unshift(func);
  9342.  
  9343. // Otherwise append
  9344. } else {
  9345. (structure[dataType] = structure[dataType] || []).push(func);
  9346. }
  9347. }
  9348. }
  9349. };
  9350. }
  9351.  
  9352. // Base inspection function for prefilters and transports
  9353. function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
  9354.  
  9355. var inspected = {},
  9356. seekingTransport = structure === transports;
  9357.  
  9358. function inspect(dataType) {
  9359. var selected;
  9360. inspected[dataType] = true;
  9361. jQuery.each(structure[dataType] || [], function (_, prefilterOrFactory) {
  9362. var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
  9363. if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) {
  9364. options.dataTypes.unshift(dataTypeOrTransport);
  9365. inspect(dataTypeOrTransport);
  9366. return false;
  9367. } else if (seekingTransport) {
  9368. return !(selected = dataTypeOrTransport);
  9369. }
  9370. });
  9371. return selected;
  9372. }
  9373.  
  9374. return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
  9375. }
  9376.  
  9377. // A special extend for ajax options
  9378. // that takes "flat" options (not to be deep extended)
  9379. // Fixes #9887
  9380. function ajaxExtend(target, src) {
  9381. var deep,
  9382. key,
  9383. flatOptions = jQuery.ajaxSettings.flatOptions || {};
  9384.  
  9385. for (key in src) {
  9386. if (src[key] !== undefined) {
  9387. (flatOptions[key] ? target : deep || (deep = {}))[key] = src[key];
  9388. }
  9389. }
  9390. if (deep) {
  9391. jQuery.extend(true, target, deep);
  9392. }
  9393.  
  9394. return target;
  9395. }
  9396.  
  9397. /* Handles responses to an ajax request:
  9398. * - finds the right dataType (mediates between content-type and expected dataType)
  9399. * - returns the corresponding response
  9400. */
  9401. function ajaxHandleResponses(s, jqXHR, responses) {
  9402. var firstDataType,
  9403. ct,
  9404. finalDataType,
  9405. type,
  9406. contents = s.contents,
  9407. dataTypes = s.dataTypes;
  9408.  
  9409. // Remove auto dataType and get content-type in the process
  9410. while (dataTypes[0] === "*") {
  9411. dataTypes.shift();
  9412. if (ct === undefined) {
  9413. ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
  9414. }
  9415. }
  9416.  
  9417. // Check if we're dealing with a known content-type
  9418. if (ct) {
  9419. for (type in contents) {
  9420. if (contents[type] && contents[type].test(ct)) {
  9421. dataTypes.unshift(type);
  9422. break;
  9423. }
  9424. }
  9425. }
  9426.  
  9427. // Check to see if we have a response for the expected dataType
  9428. if (dataTypes[0] in responses) {
  9429. finalDataType = dataTypes[0];
  9430. } else {
  9431. // Try convertible dataTypes
  9432. for (type in responses) {
  9433. if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
  9434. finalDataType = type;
  9435. break;
  9436. }
  9437. if (!firstDataType) {
  9438. firstDataType = type;
  9439. }
  9440. }
  9441. // Or just use first one
  9442. finalDataType = finalDataType || firstDataType;
  9443. }
  9444.  
  9445. // If we found a dataType
  9446. // We add the dataType to the list if needed
  9447. // and return the corresponding response
  9448. if (finalDataType) {
  9449. if (finalDataType !== dataTypes[0]) {
  9450. dataTypes.unshift(finalDataType);
  9451. }
  9452. return responses[finalDataType];
  9453. }
  9454. }
  9455.  
  9456. /* Chain conversions given the request and the original response
  9457. * Also sets the responseXXX fields on the jqXHR instance
  9458. */
  9459. function ajaxConvert(s, response, jqXHR, isSuccess) {
  9460. var conv2,
  9461. current,
  9462. conv,
  9463. tmp,
  9464. prev,
  9465. converters = {},
  9466.  
  9467. // Work with a copy of dataTypes in case we need to modify it for conversion
  9468. dataTypes = s.dataTypes.slice();
  9469.  
  9470. // Create converters map with lowercased keys
  9471. if (dataTypes[1]) {
  9472. for (conv in s.converters) {
  9473. converters[conv.toLowerCase()] = s.converters[conv];
  9474. }
  9475. }
  9476.  
  9477. current = dataTypes.shift();
  9478.  
  9479. // Convert to each sequential dataType
  9480. while (current) {
  9481.  
  9482. if (s.responseFields[current]) {
  9483. jqXHR[s.responseFields[current]] = response;
  9484. }
  9485.  
  9486. // Apply the dataFilter if provided
  9487. if (!prev && isSuccess && s.dataFilter) {
  9488. response = s.dataFilter(response, s.dataType);
  9489. }
  9490.  
  9491. prev = current;
  9492. current = dataTypes.shift();
  9493.  
  9494. if (current) {
  9495.  
  9496. // There's only work to do if current dataType is non-auto
  9497. if (current === "*") {
  9498.  
  9499. current = prev;
  9500.  
  9501. // Convert response if prev dataType is non-auto and differs from current
  9502. } else if (prev !== "*" && prev !== current) {
  9503.  
  9504. // Seek a direct converter
  9505. conv = converters[prev + " " + current] || converters["* " + current];
  9506.  
  9507. // If none found, seek a pair
  9508. if (!conv) {
  9509. for (conv2 in converters) {
  9510.  
  9511. // If conv2 outputs current
  9512. tmp = conv2.split(" ");
  9513. if (tmp[1] === current) {
  9514.  
  9515. // If prev can be converted to accepted input
  9516. conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]];
  9517. if (conv) {
  9518. // Condense equivalence converters
  9519. if (conv === true) {
  9520. conv = converters[conv2];
  9521.  
  9522. // Otherwise, insert the intermediate dataType
  9523. } else if (converters[conv2] !== true) {
  9524. current = tmp[0];
  9525. dataTypes.unshift(tmp[1]);
  9526. }
  9527. break;
  9528. }
  9529. }
  9530. }
  9531. }
  9532.  
  9533. // Apply converter (if not an equivalence)
  9534. if (conv !== true) {
  9535.  
  9536. // Unless errors are allowed to bubble, catch and return them
  9537. if (conv && s["throws"]) {
  9538. response = conv(response);
  9539. } else {
  9540. try {
  9541. response = conv(response);
  9542. } catch (e) {
  9543. return {
  9544. state: "parsererror",
  9545. error: conv ? e : "No conversion from " + prev + " to " + current
  9546. };
  9547. }
  9548. }
  9549. }
  9550. }
  9551. }
  9552. }
  9553.  
  9554. return { state: "success", data: response };
  9555. }
  9556.  
  9557. jQuery.extend({
  9558.  
  9559. // Counter for holding the number of active queries
  9560. active: 0,
  9561.  
  9562. // Last-Modified header cache for next request
  9563. lastModified: {},
  9564. etag: {},
  9565.  
  9566. ajaxSettings: {
  9567. url: ajaxLocation,
  9568. type: "GET",
  9569. isLocal: rlocalProtocol.test(ajaxLocParts[1]),
  9570. global: true,
  9571. processData: true,
  9572. async: true,
  9573. contentType: "application/x-www-form-urlencoded; charset=UTF-8",
  9574. /*
  9575. timeout: 0,
  9576. data: null,
  9577. dataType: null,
  9578. username: null,
  9579. password: null,
  9580. cache: null,
  9581. throws: false,
  9582. traditional: false,
  9583. headers: {},
  9584. */
  9585.  
  9586. accepts: {
  9587. "*": allTypes,
  9588. text: "text/plain",
  9589. html: "text/html",
  9590. xml: "application/xml, text/xml",
  9591. json: "application/json, text/javascript"
  9592. },
  9593.  
  9594. contents: {
  9595. xml: /xml/,
  9596. html: /html/,
  9597. json: /json/
  9598. },
  9599.  
  9600. responseFields: {
  9601. xml: "responseXML",
  9602. text: "responseText",
  9603. json: "responseJSON"
  9604. },
  9605.  
  9606. // Data converters
  9607. // Keys separate source (or catchall "*") and destination types with a single space
  9608. converters: {
  9609.  
  9610. // Convert anything to text
  9611. "* text": String,
  9612.  
  9613. // Text to html (true = no transformation)
  9614. "text html": true,
  9615.  
  9616. // Evaluate text as a json expression
  9617. "text json": jQuery.parseJSON,
  9618.  
  9619. // Parse text as xml
  9620. "text xml": jQuery.parseXML
  9621. },
  9622.  
  9623. // For options that shouldn't be deep extended:
  9624. // you can add your own custom options here if
  9625. // and when you create one that shouldn't be
  9626. // deep extended (see ajaxExtend)
  9627. flatOptions: {
  9628. url: true,
  9629. context: true
  9630. }
  9631. },
  9632.  
  9633. // Creates a full fledged settings object into target
  9634. // with both ajaxSettings and settings fields.
  9635. // If target is omitted, writes into ajaxSettings.
  9636. ajaxSetup: function (target, settings) {
  9637. return settings ?
  9638.  
  9639. // Building a settings object
  9640. ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :
  9641.  
  9642. // Extending ajaxSettings
  9643. ajaxExtend(jQuery.ajaxSettings, target);
  9644. },
  9645.  
  9646. ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
  9647. ajaxTransport: addToPrefiltersOrTransports(transports),
  9648.  
  9649. // Main method
  9650. ajax: function (url, options) {
  9651.  
  9652. // If url is an object, simulate pre-1.5 signature
  9653. if (typeof url === "object") {
  9654. options = url;
  9655. url = undefined;
  9656. }
  9657.  
  9658. // Force options to be an object
  9659. options = options || {};
  9660.  
  9661. var // Cross-domain detection vars
  9662. parts,
  9663.  
  9664. // Loop variable
  9665. i,
  9666.  
  9667. // URL without anti-cache param
  9668. cacheURL,
  9669.  
  9670. // Response headers as string
  9671. responseHeadersString,
  9672.  
  9673. // timeout handle
  9674. timeoutTimer,
  9675.  
  9676.  
  9677. // To know if global events are to be dispatched
  9678. fireGlobals,
  9679. transport,
  9680.  
  9681. // Response headers
  9682. responseHeaders,
  9683.  
  9684. // Create the final options object
  9685. s = jQuery.ajaxSetup({}, options),
  9686.  
  9687. // Callbacks context
  9688. callbackContext = s.context || s,
  9689.  
  9690. // Context for global events is callbackContext if it is a DOM node or jQuery collection
  9691. globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery(callbackContext) : jQuery.event,
  9692.  
  9693. // Deferreds
  9694. deferred = jQuery.Deferred(),
  9695. completeDeferred = jQuery.Callbacks("once memory"),
  9696.  
  9697. // Status-dependent callbacks
  9698. statusCode = s.statusCode || {},
  9699.  
  9700. // Headers (they are sent all at once)
  9701. requestHeaders = {},
  9702. requestHeadersNames = {},
  9703.  
  9704. // The jqXHR state
  9705. state = 0,
  9706.  
  9707. // Default abort message
  9708. strAbort = "canceled",
  9709.  
  9710. // Fake xhr
  9711. jqXHR = {
  9712. readyState: 0,
  9713.  
  9714. // Builds headers hashtable if needed
  9715. getResponseHeader: function (key) {
  9716. var match;
  9717. if (state === 2) {
  9718. if (!responseHeaders) {
  9719. responseHeaders = {};
  9720. while (match = rheaders.exec(responseHeadersString)) {
  9721. responseHeaders[match[1].toLowerCase()] = match[2];
  9722. }
  9723. }
  9724. match = responseHeaders[key.toLowerCase()];
  9725. }
  9726. return match == null ? null : match;
  9727. },
  9728.  
  9729. // Raw string
  9730. getAllResponseHeaders: function () {
  9731. return state === 2 ? responseHeadersString : null;
  9732. },
  9733.  
  9734. // Caches the header
  9735. setRequestHeader: function (name, value) {
  9736. var lname = name.toLowerCase();
  9737. if (!state) {
  9738. name = requestHeadersNames[lname] = requestHeadersNames[lname] || name;
  9739. requestHeaders[name] = value;
  9740. }
  9741. return this;
  9742. },
  9743.  
  9744. // Overrides response content-type header
  9745. overrideMimeType: function (type) {
  9746. if (!state) {
  9747. s.mimeType = type;
  9748. }
  9749. return this;
  9750. },
  9751.  
  9752. // Status-dependent callbacks
  9753. statusCode: function (map) {
  9754. var code;
  9755. if (map) {
  9756. if (state < 2) {
  9757. for (code in map) {
  9758. // Lazy-add the new callback in a way that preserves old ones
  9759. statusCode[code] = [statusCode[code], map[code]];
  9760. }
  9761. } else {
  9762. // Execute the appropriate callbacks
  9763. jqXHR.always(map[jqXHR.status]);
  9764. }
  9765. }
  9766. return this;
  9767. },
  9768.  
  9769. // Cancel the request
  9770. abort: function (statusText) {
  9771. var finalText = statusText || strAbort;
  9772. if (transport) {
  9773. transport.abort(finalText);
  9774. }
  9775. done(0, finalText);
  9776. return this;
  9777. }
  9778. };
  9779.  
  9780. // Attach deferreds
  9781. deferred.promise(jqXHR).complete = completeDeferred.add;
  9782. jqXHR.success = jqXHR.done;
  9783. jqXHR.error = jqXHR.fail;
  9784.  
  9785. // Remove hash character (#7531: and string promotion)
  9786. // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
  9787. // Handle falsy url in the settings object (#10093: consistency with old signature)
  9788. // We also use the url parameter if available
  9789. s.url = ((url || s.url || ajaxLocation) + "").replace(rhash, "").replace(rprotocol, ajaxLocParts[1] + "//");
  9790.  
  9791. // Alias method option to type as per ticket #12004
  9792. s.type = options.method || options.type || s.method || s.type;
  9793.  
  9794. // Extract dataTypes list
  9795. s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(rnotwhite) || [""];
  9796.  
  9797. // A cross-domain request is in order when we have a protocol:host:port mismatch
  9798. if (s.crossDomain == null) {
  9799. parts = rurl.exec(s.url.toLowerCase());
  9800. s.crossDomain = !!(parts && (parts[1] !== ajaxLocParts[1] || parts[2] !== ajaxLocParts[2] || (parts[3] || (parts[1] === "http:" ? "80" : "443")) !== (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? "80" : "443"))));
  9801. }
  9802.  
  9803. // Convert data if not already a string
  9804. if (s.data && s.processData && typeof s.data !== "string") {
  9805. s.data = jQuery.param(s.data, s.traditional);
  9806. }
  9807.  
  9808. // Apply prefilters
  9809. inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
  9810.  
  9811. // If request was aborted inside a prefilter, stop there
  9812. if (state === 2) {
  9813. return jqXHR;
  9814. }
  9815.  
  9816. // We can fire global events as of now if asked to
  9817. fireGlobals = s.global;
  9818.  
  9819. // Watch for a new set of requests
  9820. if (fireGlobals && jQuery.active++ === 0) {
  9821. jQuery.event.trigger("ajaxStart");
  9822. }
  9823.  
  9824. // Uppercase the type
  9825. s.type = s.type.toUpperCase();
  9826.  
  9827. // Determine if request has content
  9828. s.hasContent = !rnoContent.test(s.type);
  9829.  
  9830. // Save the URL in case we're toying with the If-Modified-Since
  9831. // and/or If-None-Match header later on
  9832. cacheURL = s.url;
  9833.  
  9834. // More options handling for requests with no content
  9835. if (!s.hasContent) {
  9836.  
  9837. // If data is available, append data to url
  9838. if (s.data) {
  9839. cacheURL = s.url += (rquery.test(cacheURL) ? "&" : "?") + s.data;
  9840. // #9682: remove data so that it's not used in an eventual retry
  9841. delete s.data;
  9842. }
  9843.  
  9844. // Add anti-cache in url if needed
  9845. if (s.cache === false) {
  9846. s.url = rts.test(cacheURL) ?
  9847.  
  9848. // If there is already a '_' parameter, set its value
  9849. cacheURL.replace(rts, "$1_=" + nonce++) :
  9850.  
  9851. // Otherwise add one to the end
  9852. cacheURL + (rquery.test(cacheURL) ? "&" : "?") + "_=" + nonce++;
  9853. }
  9854. }
  9855.  
  9856. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
  9857. if (s.ifModified) {
  9858. if (jQuery.lastModified[cacheURL]) {
  9859. jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]);
  9860. }
  9861. if (jQuery.etag[cacheURL]) {
  9862. jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]);
  9863. }
  9864. }
  9865.  
  9866. // Set the correct header, if data is being sent
  9867. if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
  9868. jqXHR.setRequestHeader("Content-Type", s.contentType);
  9869. }
  9870.  
  9871. // Set the Accepts header for the server, depending on the dataType
  9872. // jqXHR.setRequestHeader(
  9873. // "Accept",
  9874. // s.dataTypes[0] && s.accepts[s.dataTypes[0]] ?
  9875. // s.accepts[s.dataTypes[0]] + ( s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
  9876. // s.accepts["*"]
  9877. // );
  9878.  
  9879. // Check for headers option
  9880. for (i in s.headers) {
  9881. jqXHR.setRequestHeader(i, s.headers[i]);
  9882. }
  9883.  
  9884. // Allow custom headers/mimetypes and early abort
  9885. if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2)) {
  9886. // Abort if not done already and return
  9887. return jqXHR.abort();
  9888. }
  9889.  
  9890. // aborting is no longer a cancellation
  9891. strAbort = "abort";
  9892.  
  9893. // Install callbacks on deferreds
  9894. for (i in { success: 1, error: 1, complete: 1 }) {
  9895. jqXHR[i](s[i]);
  9896. }
  9897.  
  9898. // Get transport
  9899. transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
  9900.  
  9901. // If no transport, we auto-abort
  9902. if (!transport) {
  9903. done(-1, "No Transport");
  9904. } else {
  9905. jqXHR.readyState = 1;
  9906.  
  9907. // Send global event
  9908. if (fireGlobals) {
  9909. globalEventContext.trigger("ajaxSend", [jqXHR, s]);
  9910. }
  9911. // Timeout
  9912. if (s.async && s.timeout > 0) {
  9913. timeoutTimer = setTimeout(function () {
  9914. jqXHR.abort("timeout");
  9915. }, s.timeout);
  9916. }
  9917.  
  9918. try {
  9919. state = 1;
  9920. transport.send(requestHeaders, done);
  9921. } catch (e) {
  9922. // Propagate exception as error if not done
  9923. if (state < 2) {
  9924. done(-1, e);
  9925. // Simply rethrow otherwise
  9926. } else {
  9927. throw e;
  9928. }
  9929. }
  9930. }
  9931.  
  9932. // Callback for when everything is done
  9933. function done(status, nativeStatusText, responses, headers) {
  9934. var isSuccess,
  9935. success,
  9936. error,
  9937. response,
  9938. modified,
  9939. statusText = nativeStatusText;
  9940.  
  9941. // Called once
  9942. if (state === 2) {
  9943. return;
  9944. }
  9945.  
  9946. // State is "done" now
  9947. state = 2;
  9948.  
  9949. // Clear timeout if it exists
  9950. if (timeoutTimer) {
  9951. clearTimeout(timeoutTimer);
  9952. }
  9953.  
  9954. // Dereference transport for early garbage collection
  9955. // (no matter how long the jqXHR object will be used)
  9956. transport = undefined;
  9957.  
  9958. // Cache response headers
  9959. responseHeadersString = headers || "";
  9960.  
  9961. // Set readyState
  9962. jqXHR.readyState = status > 0 ? 4 : 0;
  9963.  
  9964. // Determine if successful
  9965. isSuccess = status >= 200 && status < 300 || status === 304;
  9966.  
  9967. // Get response data
  9968. if (responses) {
  9969. response = ajaxHandleResponses(s, jqXHR, responses);
  9970. }
  9971.  
  9972. // Convert no matter what (that way responseXXX fields are always set)
  9973. response = ajaxConvert(s, response, jqXHR, isSuccess);
  9974.  
  9975. // If successful, handle type chaining
  9976. if (isSuccess) {
  9977.  
  9978. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
  9979. if (s.ifModified) {
  9980. modified = jqXHR.getResponseHeader("Last-Modified");
  9981. if (modified) {
  9982. jQuery.lastModified[cacheURL] = modified;
  9983. }
  9984. modified = jqXHR.getResponseHeader("etag");
  9985. if (modified) {
  9986. jQuery.etag[cacheURL] = modified;
  9987. }
  9988. }
  9989.  
  9990. // if no content
  9991. if (status === 204 || s.type === "HEAD") {
  9992. statusText = "nocontent";
  9993.  
  9994. // if not modified
  9995. } else if (status === 304) {
  9996. statusText = "notmodified";
  9997.  
  9998. // If we have data, let's convert it
  9999. } else {
  10000. statusText = response.state;
  10001. success = response.data;
  10002. error = response.error;
  10003. isSuccess = !error;
  10004. }
  10005. } else {
  10006. // We extract error from statusText
  10007. // then normalize statusText and status for non-aborts
  10008. error = statusText;
  10009. if (status || !statusText) {
  10010. statusText = "error";
  10011. if (status < 0) {
  10012. status = 0;
  10013. }
  10014. }
  10015. }
  10016.  
  10017. // Set data for the fake xhr object
  10018. jqXHR.status = status;
  10019. jqXHR.statusText = (nativeStatusText || statusText) + "";
  10020.  
  10021. // Success/Error
  10022. if (isSuccess) {
  10023. deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
  10024. } else {
  10025. deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
  10026. }
  10027.  
  10028. // Status-dependent callbacks
  10029. jqXHR.statusCode(statusCode);
  10030. statusCode = undefined;
  10031.  
  10032. if (fireGlobals) {
  10033. globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [jqXHR, s, isSuccess ? success : error]);
  10034. }
  10035.  
  10036. // Complete
  10037. completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
  10038.  
  10039. if (fireGlobals) {
  10040. globalEventContext.trigger("ajaxComplete", [jqXHR, s]);
  10041. // Handle the global AJAX counter
  10042. if (! --jQuery.active) {
  10043. jQuery.event.trigger("ajaxStop");
  10044. }
  10045. }
  10046. }
  10047.  
  10048. return jqXHR;
  10049. },
  10050.  
  10051. getJSON: function (url, data, callback) {
  10052. return jQuery.get(url, data, callback, "json");
  10053. },
  10054.  
  10055. getScript: function (url, callback) {
  10056. return jQuery.get(url, undefined, callback, "script");
  10057. }
  10058. });
  10059.  
  10060. jQuery.each(["get", "post"], function (i, method) {
  10061. jQuery[method] = function (url, data, callback, type) {
  10062. // shift arguments if data argument was omitted
  10063. if (jQuery.isFunction(data)) {
  10064. type = type || callback;
  10065. callback = data;
  10066. data = undefined;
  10067. }
  10068.  
  10069. return jQuery.ajax({
  10070. url: url,
  10071. type: method,
  10072. dataType: type,
  10073. data: data,
  10074. success: callback
  10075. });
  10076. };
  10077. });
  10078.  
  10079. // Attach a bunch of functions for handling common AJAX events
  10080. jQuery.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (i, type) {
  10081. jQuery.fn[type] = function (fn) {
  10082. return this.on(type, fn);
  10083. };
  10084. });
  10085.  
  10086. jQuery._evalUrl = function (url) {
  10087. return jQuery.ajax({
  10088. url: url,
  10089. type: "GET",
  10090. dataType: "script",
  10091. async: false,
  10092. global: false,
  10093. "throws": true
  10094. });
  10095. };
  10096.  
  10097. var r20 = /%20/g,
  10098. rbracket = /\[\]$/,
  10099. rCRLF = /\r?\n/g,
  10100. rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
  10101. rsubmittable = /^(?:input|select|textarea|keygen)/i;
  10102.  
  10103. function buildParams(prefix, obj, traditional, add) {
  10104. var name;
  10105.  
  10106. if (jQuery.isArray(obj)) {
  10107. // Serialize array item.
  10108. jQuery.each(obj, function (i, v) {
  10109. if (traditional || rbracket.test(prefix)) {
  10110. // Treat each array item as a scalar.
  10111. add(prefix, v);
  10112. } else {
  10113. // Item is non-scalar (array or object), encode its numeric index.
  10114. buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v, traditional, add);
  10115. }
  10116. });
  10117. } else if (!traditional && jQuery.type(obj) === "object") {
  10118. // Serialize object item.
  10119. for (name in obj) {
  10120. buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
  10121. }
  10122. } else {
  10123. // Serialize scalar item.
  10124. add(prefix, obj);
  10125. }
  10126. }
  10127.  
  10128. // Serialize an array of form elements or a set of
  10129. // key/values into a query string
  10130. jQuery.param = function (a, traditional) {
  10131. var prefix,
  10132. s = [],
  10133. add = function (key, value) {
  10134. // If value is a function, invoke it and return its value
  10135. value = jQuery.isFunction(value) ? value() : value == null ? "" : value;
  10136. s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
  10137. };
  10138.  
  10139. // Set traditional to true for jQuery <= 1.3.2 behavior.
  10140. if (traditional === undefined) {
  10141. traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
  10142. }
  10143.  
  10144. // If an array was passed in, assume that it is an array of form elements.
  10145. if (jQuery.isArray(a) || a.jquery && !jQuery.isPlainObject(a)) {
  10146. // Serialize the form elements
  10147. jQuery.each(a, function () {
  10148. add(this.name, this.value);
  10149. });
  10150. } else {
  10151. // If traditional, encode the "old" way (the way 1.3.2 or older
  10152. // did it), otherwise encode params recursively.
  10153. for (prefix in a) {
  10154. buildParams(prefix, a[prefix], traditional, add);
  10155. }
  10156. }
  10157.  
  10158. // Return the resulting serialization
  10159. return s.join("&").replace(r20, "+");
  10160. };
  10161.  
  10162. jQuery.fn.extend({
  10163. serialize: function () {
  10164. return jQuery.param(this.serializeArray());
  10165. },
  10166. serializeArray: function () {
  10167. return this.map(function () {
  10168. // Can add propHook for "elements" to filter or add form elements
  10169. var elements = jQuery.prop(this, "elements");
  10170. return elements ? jQuery.makeArray(elements) : this;
  10171. }).filter(function () {
  10172. var type = this.type;
  10173. // Use .is(":disabled") so that fieldset[disabled] works
  10174. return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type));
  10175. }).map(function (i, elem) {
  10176. var val = jQuery(this).val();
  10177.  
  10178. return val == null ? null : jQuery.isArray(val) ? jQuery.map(val, function (val) {
  10179. return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
  10180. }) : { name: elem.name, value: val.replace(rCRLF, "\r\n") };
  10181. }).get();
  10182. }
  10183. });
  10184.  
  10185. // Create the request object
  10186. // (This is still attached to ajaxSettings for backward compatibility)
  10187. jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
  10188. // Support: IE6+
  10189. function () {
  10190.  
  10191. // XHR cannot access local files, always use ActiveX for that case
  10192. return !this.isLocal &&
  10193.  
  10194. // Support: IE7-8
  10195. // oldIE XHR does not support non-RFC2616 methods (#13240)
  10196. // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
  10197. // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
  10198. // Although this check for six methods instead of eight
  10199. // since IE also does not support "trace" and "connect"
  10200. /^(get|post|head|put|delete|options)$/i.test(this.type) && createStandardXHR() || createActiveXHR();
  10201. } :
  10202. // For all other browsers, use the standard XMLHttpRequest object
  10203. createStandardXHR;
  10204.  
  10205. var xhrId = 0,
  10206. xhrCallbacks = {},
  10207. xhrSupported = jQuery.ajaxSettings.xhr();
  10208.  
  10209. // Support: IE<10
  10210. // Open requests must be manually aborted on unload (#5280)
  10211. if (window.ActiveXObject) {
  10212. jQuery(window).on("unload", function () {
  10213. for (var key in xhrCallbacks) {
  10214. xhrCallbacks[key](undefined, true);
  10215. }
  10216. });
  10217. }
  10218.  
  10219. // Determine support properties
  10220. support.cors = !!xhrSupported && "withCredentials" in xhrSupported;
  10221. xhrSupported = support.ajax = !!xhrSupported;
  10222.  
  10223. // Create transport if the browser can provide an xhr
  10224. if (xhrSupported) {
  10225.  
  10226. jQuery.ajaxTransport(function (options) {
  10227. // Cross domain only allowed if supported through XMLHttpRequest
  10228. if (!options.crossDomain || support.cors) {
  10229.  
  10230. var callback;
  10231.  
  10232. return {
  10233. send: function (headers, complete) {
  10234. var i,
  10235. xhr = options.xhr(),
  10236. id = ++xhrId;
  10237.  
  10238. // Open the socket
  10239. xhr.open(options.type, options.url, options.async, options.username, options.password);
  10240.  
  10241. // Apply custom fields if provided
  10242. if (options.xhrFields) {
  10243. for (i in options.xhrFields) {
  10244. xhr[i] = options.xhrFields[i];
  10245. }
  10246. }
  10247.  
  10248. // Override mime type if needed
  10249. if (options.mimeType && xhr.overrideMimeType) {
  10250. xhr.overrideMimeType(options.mimeType);
  10251. }
  10252.  
  10253. // X-Requested-With header
  10254. // For cross-domain requests, seeing as conditions for a preflight are
  10255. // akin to a jigsaw puzzle, we simply never set it to be sure.
  10256. // (it can always be set on a per-request basis or even using ajaxSetup)
  10257. // For same-domain requests, won't change header if already provided.
  10258. if (!options.crossDomain && !headers["X-Requested-With"]) {
  10259. headers["X-Requested-With"] = "XMLHttpRequest";
  10260. }
  10261.  
  10262. // Set headers
  10263. for (i in headers) {
  10264. // Support: IE<9
  10265. // IE's ActiveXObject throws a 'Type Mismatch' exception when setting
  10266. // request header to a null-value.
  10267. //
  10268. // To keep consistent with other XHR implementations, cast the value
  10269. // to string and ignore `undefined`.
  10270. if (headers[i] !== undefined) {
  10271. xhr.setRequestHeader(i, headers[i] + "");
  10272. }
  10273. }
  10274.  
  10275. if (xhr.upload && options.progress) {
  10276. xhr.upload.onprogress = options.progress;
  10277. }
  10278.  
  10279. // Do send the request
  10280. // This may raise an exception which is actually
  10281. // handled in jQuery.ajax (so no try/catch here)
  10282. xhr.send(options.hasContent && (options.body || options.data) || null);
  10283.  
  10284. // Listener
  10285. callback = function (_, isAbort) {
  10286. var status, statusText, responses;
  10287.  
  10288. // Was never called and is aborted or complete
  10289. if (callback && (isAbort || xhr.readyState === 4)) {
  10290. // Clean up
  10291. delete xhrCallbacks[id];
  10292. callback = undefined;
  10293. xhr.onreadystatechange = jQuery.noop;
  10294.  
  10295. // Abort manually if needed
  10296. if (isAbort) {
  10297. if (xhr.readyState !== 4) {
  10298. xhr.abort();
  10299. }
  10300. } else {
  10301. responses = {};
  10302. status = xhr.status;
  10303.  
  10304. // Support: IE<10
  10305. // Accessing binary-data responseText throws an exception
  10306. // (#11426)
  10307. if (typeof xhr.responseText === "string") {
  10308. responses.text = xhr.responseText;
  10309. }
  10310.  
  10311. // Firefox throws an exception when accessing
  10312. // statusText for faulty cross-domain requests
  10313. try {
  10314. statusText = xhr.statusText;
  10315. } catch (e) {
  10316. // We normalize with Webkit giving an empty statusText
  10317. statusText = "";
  10318. }
  10319.  
  10320. // Filter status for non standard behaviors
  10321.  
  10322. // If the request is local and we have data: assume a success
  10323. // (success with no data won't get notified, that's the best we
  10324. // can do given current implementations)
  10325. if (!status && options.isLocal && !options.crossDomain) {
  10326. status = responses.text ? 200 : 404;
  10327. // IE - #1450: sometimes returns 1223 when it should be 204
  10328. } else if (status === 1223) {
  10329. status = 204;
  10330. }
  10331. }
  10332. }
  10333.  
  10334. // Call complete if needed
  10335. if (responses) {
  10336. complete(status, statusText, responses, xhr.getAllResponseHeaders());
  10337. }
  10338. };
  10339.  
  10340. if (!options.async) {
  10341. // if we're in sync mode we fire the callback
  10342. callback();
  10343. } else if (xhr.readyState === 4) {
  10344. // (IE6 & IE7) if it's in cache and has been
  10345. // retrieved directly we need to fire the callback
  10346. setTimeout(callback);
  10347. } else {
  10348. // Add to the list of active xhr callbacks
  10349. xhr.onreadystatechange = xhrCallbacks[id] = callback;
  10350. }
  10351. },
  10352.  
  10353. abort: function () {
  10354. if (callback) {
  10355. callback(undefined, true);
  10356. }
  10357. }
  10358. };
  10359. }
  10360. });
  10361. }
  10362.  
  10363. // Functions to create xhrs
  10364. function createStandardXHR() {
  10365. try {
  10366. return new window.XMLHttpRequest();
  10367. } catch (e) {}
  10368. }
  10369.  
  10370. function createActiveXHR() {
  10371. try {
  10372. return new window.ActiveXObject("Microsoft.XMLHTTP");
  10373. } catch (e) {}
  10374. }
  10375.  
  10376. // Install script dataType
  10377. jQuery.ajaxSetup({
  10378. accepts: {
  10379. script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
  10380. },
  10381. contents: {
  10382. script: /(?:java|ecma)script/
  10383. },
  10384. converters: {
  10385. "text script": function (text) {
  10386. jQuery.globalEval(text);
  10387. return text;
  10388. }
  10389. }
  10390. });
  10391.  
  10392. // Handle cache's special case and global
  10393. jQuery.ajaxPrefilter("script", function (s) {
  10394. if (s.cache === undefined) {
  10395. s.cache = false;
  10396. }
  10397. if (s.crossDomain) {
  10398. s.type = "GET";
  10399. s.global = false;
  10400. }
  10401. });
  10402.  
  10403. // Bind script tag hack transport
  10404. jQuery.ajaxTransport("script", function (s) {
  10405.  
  10406. // This transport only deals with cross domain requests
  10407. if (s.crossDomain) {
  10408.  
  10409. var script,
  10410. head = document.head || jQuery("head")[0] || document.documentElement;
  10411.  
  10412. return {
  10413.  
  10414. send: function (_, callback) {
  10415.  
  10416. script = document.createElement("script");
  10417.  
  10418. script.async = true;
  10419.  
  10420. if (s.scriptCharset) {
  10421. script.charset = s.scriptCharset;
  10422. }
  10423.  
  10424. script.src = s.url;
  10425.  
  10426. // Attach handlers for all browsers
  10427. script.onload = script.onreadystatechange = function (_, isAbort) {
  10428.  
  10429. if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
  10430.  
  10431. // Handle memory leak in IE
  10432. script.onload = script.onreadystatechange = null;
  10433.  
  10434. // Remove the script
  10435. if (script.parentNode) {
  10436. script.parentNode.removeChild(script);
  10437. }
  10438.  
  10439. // Dereference the script
  10440. script = null;
  10441.  
  10442. // Callback if not abort
  10443. if (!isAbort) {
  10444. callback(200, "success");
  10445. }
  10446. }
  10447. };
  10448.  
  10449. // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
  10450. // Use native DOM manipulation to avoid our domManip AJAX trickery
  10451. head.insertBefore(script, head.firstChild);
  10452. },
  10453.  
  10454. abort: function () {
  10455. if (script) {
  10456. script.onload(undefined, true);
  10457. }
  10458. }
  10459. };
  10460. }
  10461. });
  10462.  
  10463. var oldCallbacks = [],
  10464. rjsonp = /(=)\?(?=&|$)|\?\?/;
  10465.  
  10466. // Default jsonp settings
  10467. jQuery.ajaxSetup({
  10468. jsonp: "callback",
  10469. jsonpCallback: function () {
  10470. var callback = oldCallbacks.pop() || jQuery.expando + "_" + nonce++;
  10471. this[callback] = true;
  10472. return callback;
  10473. }
  10474. });
  10475.  
  10476. // Detect, normalize options and install callbacks for jsonp requests
  10477. jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) {
  10478.  
  10479. var callbackName,
  10480. overwritten,
  10481. responseContainer,
  10482. jsonProp = s.jsonp !== false && (rjsonp.test(s.url) ? "url" : typeof s.data === "string" && !(s.contentType || "").indexOf("application/x-www-form-urlencoded") && rjsonp.test(s.data) && "data");
  10483.  
  10484. // Handle iff the expected data type is "jsonp" or we have a parameter to set
  10485. if (jsonProp || s.dataTypes[0] === "jsonp") {
  10486.  
  10487. // Get callback name, remembering preexisting value associated with it
  10488. callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback;
  10489.  
  10490. // Insert callback into url or form data
  10491. if (jsonProp) {
  10492. s[jsonProp] = s[jsonProp].replace(rjsonp, "$1" + callbackName);
  10493. } else if (s.jsonp !== false) {
  10494. s.url += (rquery.test(s.url) ? "&" : "?") + s.jsonp + "=" + callbackName;
  10495. }
  10496.  
  10497. // Use data converter to retrieve json after script execution
  10498. s.converters["script json"] = function () {
  10499. if (!responseContainer) {
  10500. jQuery.error(callbackName + " was not called");
  10501. }
  10502. return responseContainer[0];
  10503. };
  10504.  
  10505. // force json dataType
  10506. s.dataTypes[0] = "json";
  10507.  
  10508. // Install callback
  10509. overwritten = window[callbackName];
  10510. window[callbackName] = function () {
  10511. responseContainer = arguments;
  10512. };
  10513.  
  10514. // Clean-up function (fires after converters)
  10515. jqXHR.always(function () {
  10516. // Restore preexisting value
  10517. window[callbackName] = overwritten;
  10518.  
  10519. // Save back as free
  10520. if (s[callbackName]) {
  10521. // make sure that re-using the options doesn't screw things around
  10522. s.jsonpCallback = originalSettings.jsonpCallback;
  10523.  
  10524. // save the callback name for future use
  10525. oldCallbacks.push(callbackName);
  10526. }
  10527.  
  10528. // Call if it was a function and we have a response
  10529. if (responseContainer && jQuery.isFunction(overwritten)) {
  10530. overwritten(responseContainer[0]);
  10531. }
  10532.  
  10533. responseContainer = overwritten = undefined;
  10534. });
  10535.  
  10536. // Delegate to script
  10537. return "script";
  10538. }
  10539. });
  10540.  
  10541. // data: string of html
  10542. // context (optional): If specified, the fragment will be created in this context, defaults to document
  10543. // keepScripts (optional): If true, will include scripts passed in the html string
  10544. jQuery.parseHTML = function (data, context, keepScripts) {
  10545. if (!data || typeof data !== "string") {
  10546. return null;
  10547. }
  10548. if (typeof context === "boolean") {
  10549. keepScripts = context;
  10550. context = false;
  10551. }
  10552. context = context || document;
  10553.  
  10554. var parsed = rsingleTag.exec(data),
  10555. scripts = !keepScripts && [];
  10556.  
  10557. // Single tag
  10558. if (parsed) {
  10559. return [context.createElement(parsed[1])];
  10560. }
  10561.  
  10562. parsed = jQuery.buildFragment([data], context, scripts);
  10563.  
  10564. if (scripts && scripts.length) {
  10565. jQuery(scripts).remove();
  10566. }
  10567.  
  10568. return jQuery.merge([], parsed.childNodes);
  10569. };
  10570.  
  10571. return jQuery;
  10572. }();
  10573.  
  10574. var stringifyPrimitive = function (v) {
  10575. switch (typeof v) {
  10576. case 'string':
  10577. return v;
  10578. case 'boolean':
  10579. return v ? 'true' : 'false';
  10580. case 'number':
  10581. return isFinite(v) ? v : '';
  10582. default:
  10583. return '';
  10584. }
  10585. };
  10586.  
  10587. var queryStringify = function (obj, sep, eq, name) {
  10588. sep = sep || '&';
  10589. eq = eq || '=';
  10590. if (obj === null) {
  10591. obj = undefined;
  10592. }
  10593. if (typeof obj === 'object') {
  10594. return Object.keys(obj).map(function (k) {
  10595. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  10596. if (Array.isArray(obj[k])) {
  10597. return obj[k].map(function (v) {
  10598. return ks + encodeURIComponent(stringifyPrimitive(v));
  10599. }).join(sep);
  10600. } else {
  10601. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  10602. }
  10603. }).filter(Boolean).join(sep);
  10604. }
  10605. if (!name) return '';
  10606. return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj));
  10607. };
  10608.  
  10609. var request = function (options, callback) {
  10610.  
  10611. options = $.extend(true, { headers: {}, qs: {} }, options);
  10612.  
  10613. // method
  10614. options.type = options.method;
  10615. delete options.method;
  10616.  
  10617. // progress
  10618. if (options.onProgress) {
  10619. options.progress = options.onProgress;
  10620. delete options.onProgress;
  10621. }
  10622.  
  10623. // qs
  10624. if (options.qs) {
  10625. var qsStr = queryStringify(options.qs);
  10626. if (qsStr) {
  10627. options.url += (options.url.indexOf('?') === -1 ? '?' : '&') + qsStr;
  10628. }
  10629. delete options.qs;
  10630. }
  10631.  
  10632. // json
  10633. if (options.json) {
  10634. options.data = options.body;
  10635. delete options.json;
  10636. delete options.body;
  10637. !options.headers && (options.headers = {});
  10638. options.headers['Content-Type'] = 'application/json';
  10639. }
  10640.  
  10641. // body
  10642. if (options.body) {
  10643. if (!(options.body instanceof Blob || options.body.toString() === '[object File]' || options.body.toString() === '[object Blob]')) {
  10644. options.data = options.body;
  10645. delete options.body;
  10646. }
  10647. }
  10648.  
  10649. // headers
  10650. if (options.headers) {
  10651. var headers = options.headers;
  10652. delete options.headers;
  10653. options.beforeSend = function (xhr) {
  10654. for (var key in headers) {
  10655. if (headers.hasOwnProperty(key) && key.toLowerCase() !== 'content-length' && key.toLowerCase() !== 'user-agent' && key.toLowerCase() !== 'origin' && key.toLowerCase() !== 'host') {
  10656. xhr.setRequestHeader(key, headers[key]);
  10657. }
  10658. }
  10659. };
  10660. }
  10661.  
  10662. var getResponse = function (xhr) {
  10663. var headers = {};
  10664. xhr.getAllResponseHeaders().trim().split('\n').forEach(function (item) {
  10665. if (item) {
  10666. var index = item.indexOf(':');
  10667. var key = item.substr(0, index).trim().toLowerCase();
  10668. var val = item.substr(index + 1).trim();
  10669. headers[key] = val;
  10670. }
  10671. });
  10672. return {
  10673. statusCode: xhr.status,
  10674. statusMessage: xhr.statusText,
  10675. headers: headers
  10676. };
  10677. };
  10678.  
  10679. // callback
  10680. options.success = function (data, state, xhr) {
  10681. callback(null, getResponse(xhr), data);
  10682. };
  10683. options.error = function (xhr) {
  10684. if (xhr.responseText) {
  10685. callback(null, getResponse(xhr), xhr.responseText);
  10686. } else {
  10687. callback(xhr.statusText, getResponse(xhr), xhr.responseText);
  10688. }
  10689. };
  10690.  
  10691. options.dataType = 'text';
  10692.  
  10693. // send
  10694. return $.ajax(options);
  10695. };
  10696.  
  10697. module.exports = request;
  10698.  
  10699. /***/ }),
  10700. /* 14 */
  10701. /***/ (function(module, exports, __webpack_require__) {
  10702.  
  10703. var Async = __webpack_require__(15);
  10704. var EventProxy = __webpack_require__(2).EventProxy;
  10705. var util = __webpack_require__(0);
  10706.  
  10707. // 文件分块上传全过程,暴露的分块上传接口
  10708. function sliceUploadFile(params, callback) {
  10709. var self = this;
  10710. var ep = new EventProxy();
  10711. var TaskId = params.TaskId;
  10712. var Bucket = params.Bucket;
  10713. var Region = params.Region;
  10714. var Key = params.Key;
  10715. var Body = params.Body;
  10716. var ChunkSize = params.ChunkSize || params.SliceSize || self.options.ChunkSize;
  10717. var AsyncLimit = params.AsyncLimit;
  10718. var StorageClass = params.StorageClass || 'Standard';
  10719. var ServerSideEncryption = params.ServerSideEncryption;
  10720. var FileSize;
  10721.  
  10722. var onProgress;
  10723. var onHashProgress = params.onHashProgress;
  10724.  
  10725. // 上传过程中出现错误,返回错误
  10726. ep.on('error', function (err) {
  10727. if (!self._isRunningTask(TaskId)) return;
  10728. return callback(err);
  10729. });
  10730.  
  10731. // 上传分块完成,开始 uploadSliceComplete 操作
  10732. ep.on('upload_complete', function (UploadCompleteData) {
  10733. callback(null, UploadCompleteData);
  10734. });
  10735.  
  10736. // 上传分块完成,开始 uploadSliceComplete 操作
  10737. ep.on('upload_slice_complete', function (UploadData) {
  10738. uploadSliceComplete.call(self, {
  10739. Bucket: Bucket,
  10740. Region: Region,
  10741. Key: Key,
  10742. UploadId: UploadData.UploadId,
  10743. SliceList: UploadData.SliceList
  10744. }, function (err, data) {
  10745. if (!self._isRunningTask(TaskId)) return;
  10746. delete uploadIdUsing[UploadData.UploadId];
  10747. if (err) {
  10748. onProgress(null, true);
  10749. return ep.emit('error', err);
  10750. }
  10751. onProgress({ loaded: FileSize, total: FileSize }, true);
  10752. removeUploadId.call(self, UploadData.UploadId);
  10753. ep.emit('upload_complete', data);
  10754. });
  10755. });
  10756.  
  10757. // 获取 UploadId 完成,开始上传每个分片
  10758. ep.on('get_upload_data_finish', function (UploadData) {
  10759.  
  10760. // 处理 UploadId 缓存
  10761. var uuid = util.getFileUUID(Body, params.ChunkSize);
  10762. uuid && setUploadId.call(self, uuid, UploadData.UploadId); // 缓存 UploadId
  10763. uploadIdUsing[UploadData.UploadId] = true; // 标记 UploadId 为正在使用
  10764. TaskId && self.on('inner-kill-task', function (data) {
  10765. if (data.TaskId === TaskId && data.toState === 'canceled') {
  10766. delete uploadIdUsing[UploadData.UploadId]; // 去除 UploadId 正在使用的标记
  10767. }
  10768. });
  10769.  
  10770. // 获取 UploadId
  10771. onProgress(null, true); // 任务状态开始 uploading
  10772. uploadSliceList.call(self, {
  10773. TaskId: TaskId,
  10774. Bucket: Bucket,
  10775. Region: Region,
  10776. Key: Key,
  10777. Body: Body,
  10778. FileSize: FileSize,
  10779. SliceSize: ChunkSize,
  10780. AsyncLimit: AsyncLimit,
  10781. ServerSideEncryption: ServerSideEncryption,
  10782. UploadData: UploadData,
  10783. onProgress: onProgress
  10784. }, function (err, data) {
  10785. if (!self._isRunningTask(TaskId)) return;
  10786. if (err) {
  10787. onProgress(null, true);
  10788. return ep.emit('error', err);
  10789. }
  10790. ep.emit('upload_slice_complete', data);
  10791. });
  10792. });
  10793.  
  10794. // 开始获取文件 UploadId,里面会视情况计算 ETag,并比对,保证文件一致性,也优化上传
  10795. ep.on('get_file_size_finish', function () {
  10796.  
  10797. onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  10798.  
  10799. if (params.UploadData.UploadId) {
  10800. ep.emit('get_upload_data_finish', params.UploadData);
  10801. } else {
  10802. var _params = util.extend({
  10803. TaskId: TaskId,
  10804. Bucket: Bucket,
  10805. Region: Region,
  10806. Key: Key,
  10807. Headers: params.Headers,
  10808. StorageClass: StorageClass,
  10809. Body: Body,
  10810. FileSize: FileSize,
  10811. SliceSize: ChunkSize,
  10812. onHashProgress: onHashProgress
  10813. }, params);
  10814. getUploadIdAndPartList.call(self, _params, function (err, UploadData) {
  10815. if (!self._isRunningTask(TaskId)) return;
  10816. if (err) return ep.emit('error', err);
  10817. params.UploadData.UploadId = UploadData.UploadId;
  10818. params.UploadData.PartList = UploadData.PartList;
  10819. ep.emit('get_upload_data_finish', params.UploadData);
  10820. });
  10821. }
  10822. });
  10823.  
  10824. // 获取上传文件大小
  10825. FileSize = params.ContentLength;
  10826. delete params.ContentLength;
  10827. !params.Headers && (params.Headers = {});
  10828. util.each(params.Headers, function (item, key) {
  10829. if (key.toLowerCase() === 'content-length') {
  10830. delete params.Headers[key];
  10831. }
  10832. });
  10833.  
  10834. // 控制分片大小
  10835. (function () {
  10836. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  10837. var AutoChunkSize = 1024 * 1024;
  10838. for (var i = 0; i < SIZE.length; i++) {
  10839. AutoChunkSize = SIZE[i] * 1024 * 1024;
  10840. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  10841. }
  10842. params.ChunkSize = params.SliceSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  10843. })();
  10844.  
  10845. // 开始上传
  10846. if (FileSize === 0) {
  10847. params.Body = '';
  10848. params.ContentLength = 0;
  10849. params.SkipTask = true;
  10850. self.putObject(params, function (err, data) {
  10851. if (err) {
  10852. return callback(err);
  10853. }
  10854. callback(null, data);
  10855. });
  10856. } else {
  10857. ep.emit('get_file_size_finish');
  10858. }
  10859. }
  10860.  
  10861. // 按照文件特征值,缓存 UploadId
  10862. var uploadIdCache;
  10863. var uploadIdUsing = {};
  10864. var uploadIdCacheKey = 'cos_sdk_upload_cache';
  10865. function initUploadId() {
  10866. var cacheLimit = this.options.UploadIdCacheLimit;
  10867. if (!uploadIdCache) {
  10868. if (cacheLimit) {
  10869. try {
  10870. uploadIdCache = JSON.parse(localStorage.getItem(uploadIdCacheKey)) || [];
  10871. } catch (e) {}
  10872. }
  10873. if (!uploadIdCache) {
  10874. uploadIdCache = [];
  10875. }
  10876. }
  10877. }
  10878. function setUploadId(uuid, UploadId, isDisabled) {
  10879. initUploadId.call(this);
  10880. for (var i = uploadIdCache.length - 1; i >= 0; i--) {
  10881. if (uploadIdCache[i][0] === uuid && uploadIdCache[i][1] === UploadId) {
  10882. uploadIdCache.splice(i, 1);
  10883. }
  10884. }
  10885. uploadIdCache.unshift([uuid, UploadId]);
  10886. var cacheLimit = this.options.UploadIdCacheLimit;
  10887. if (uploadIdCache.length > cacheLimit) {
  10888. uploadIdCache.splice(cacheLimit);
  10889. }
  10890. cacheLimit && setTimeout(function () {
  10891. try {
  10892. localStorage.setItem(uploadIdCacheKey, JSON.stringify(uploadIdCache));
  10893. } catch (e) {}
  10894. });
  10895. }
  10896. function removeUploadId(UploadId) {
  10897. initUploadId.call(this);
  10898. delete uploadIdUsing[UploadId];
  10899. for (var i = uploadIdCache.length - 1; i >= 0; i--) {
  10900. if (uploadIdCache[i][1] === UploadId) {
  10901. uploadIdCache.splice(i, 1);
  10902. }
  10903. }
  10904. var cacheLimit = this.options.UploadIdCacheLimit;
  10905. if (uploadIdCache.length > cacheLimit) {
  10906. uploadIdCache.splice(cacheLimit);
  10907. }
  10908. cacheLimit && setTimeout(function () {
  10909. try {
  10910. if (uploadIdCache.length) {
  10911. localStorage.setItem(uploadIdCacheKey, JSON.stringify(uploadIdCache));
  10912. } else {
  10913. localStorage.removeItem(uploadIdCacheKey);
  10914. }
  10915. } catch (e) {}
  10916. });
  10917. }
  10918. function getUploadId(uuid) {
  10919. initUploadId.call(this);
  10920. var CacheUploadIdList = [];
  10921. for (var i = 0; i < uploadIdCache.length; i++) {
  10922. if (uploadIdCache[i][0] === uuid) {
  10923. CacheUploadIdList.push(uploadIdCache[i][1]);
  10924. }
  10925. }
  10926. return CacheUploadIdList.length ? CacheUploadIdList : null;
  10927. }
  10928.  
  10929. // 获取上传任务的 UploadId
  10930. function getUploadIdAndPartList(params, callback) {
  10931. var TaskId = params.TaskId;
  10932. var Bucket = params.Bucket;
  10933. var Region = params.Region;
  10934. var Key = params.Key;
  10935. var StorageClass = params.StorageClass;
  10936. var self = this;
  10937.  
  10938. // 计算 ETag
  10939. var ETagMap = {};
  10940. var FileSize = params.FileSize;
  10941. var SliceSize = params.SliceSize;
  10942. var SliceCount = Math.ceil(FileSize / SliceSize);
  10943. var FinishSliceCount = 0;
  10944. var FinishSize = 0;
  10945. var onHashProgress = util.throttleOnProgress.call(self, FileSize, params.onHashProgress);
  10946. var getChunkETag = function (PartNumber, callback) {
  10947. var start = SliceSize * (PartNumber - 1);
  10948. var end = Math.min(start + SliceSize, FileSize);
  10949. var ChunkSize = end - start;
  10950.  
  10951. if (ETagMap[PartNumber]) {
  10952. callback(null, {
  10953. PartNumber: PartNumber,
  10954. ETag: ETagMap[PartNumber],
  10955. Size: ChunkSize
  10956. });
  10957. } else {
  10958. util.fileSlice(params.Body, start, end, false, function (chunkItem) {
  10959. util.getFileMd5(chunkItem, function (err, md5) {
  10960. if (err) return callback(err);
  10961. var ETag = '"' + md5 + '"';
  10962. ETagMap[PartNumber] = ETag;
  10963. FinishSliceCount += 1;
  10964. FinishSize += ChunkSize;
  10965. callback(err, {
  10966. PartNumber: PartNumber,
  10967. ETag: ETag,
  10968. Size: ChunkSize
  10969. });
  10970. onHashProgress({ loaded: FinishSize, total: FileSize });
  10971. });
  10972. });
  10973. }
  10974. };
  10975.  
  10976. // 通过和文件的 md5 对比,判断 UploadId 是否可用
  10977. var isAvailableUploadList = function (PartList, callback) {
  10978. var PartCount = PartList.length;
  10979. // 如果没有分片,通过
  10980. if (PartCount === 0) {
  10981. return callback(null, true);
  10982. }
  10983. // 检查分片数量
  10984. if (PartCount > SliceCount) {
  10985. return callback(null, false);
  10986. }
  10987. // 检查分片大小
  10988. if (PartCount > 1) {
  10989. var PartSliceSize = Math.max(PartList[0].Size, PartList[1].Size);
  10990. if (PartSliceSize !== SliceSize) {
  10991. return callback(null, false);
  10992. }
  10993. }
  10994. // 逐个分片计算并检查 ETag 是否一致
  10995. var next = function (index) {
  10996. if (index < PartCount) {
  10997. var Part = PartList[index];
  10998. getChunkETag(Part.PartNumber, function (err, chunk) {
  10999. if (chunk && chunk.ETag === Part.ETag && chunk.Size === Part.Size) {
  11000. next(index + 1);
  11001. } else {
  11002. callback(null, false);
  11003. }
  11004. });
  11005. } else {
  11006. callback(null, true);
  11007. }
  11008. };
  11009. next(0);
  11010. };
  11011.  
  11012. var ep = new EventProxy();
  11013. ep.on('error', function (errData) {
  11014. if (!self._isRunningTask(TaskId)) return;
  11015. return callback(errData);
  11016. });
  11017.  
  11018. // 存在 UploadId
  11019. ep.on('upload_id_ready', function (UploadData) {
  11020. // 转换成 map
  11021. var map = {};
  11022. var list = [];
  11023. util.each(UploadData.PartList, function (item) {
  11024. map[item.PartNumber] = item;
  11025. });
  11026. for (var PartNumber = 1; PartNumber <= SliceCount; PartNumber++) {
  11027. var item = map[PartNumber];
  11028. if (item) {
  11029. item.PartNumber = PartNumber;
  11030. item.Uploaded = true;
  11031. } else {
  11032. item = {
  11033. PartNumber: PartNumber,
  11034. ETag: null,
  11035. Uploaded: false
  11036. };
  11037. }
  11038. list.push(item);
  11039. }
  11040. UploadData.PartList = list;
  11041. callback(null, UploadData);
  11042. });
  11043.  
  11044. // 不存在 UploadId, 初始化生成 UploadId
  11045. ep.on('no_available_upload_id', function () {
  11046. if (!self._isRunningTask(TaskId)) return;
  11047. var _params = util.extend({
  11048. Bucket: Bucket,
  11049. Region: Region,
  11050. Key: Key,
  11051. Headers: util.clone(params.Headers),
  11052. StorageClass: StorageClass,
  11053. Body: params.Body
  11054. }, params);
  11055. // 获取 File 或 Blob 的 type 属性,如果有,作为文件 Content-Type
  11056. var ContentType = params.Headers['Content-Type'] || params.Body && params.Body.type;
  11057. if (ContentType) {
  11058. _params.Headers['Content-Type'] = ContentType;
  11059. }
  11060. self.multipartInit(_params, function (err, data) {
  11061. if (!self._isRunningTask(TaskId)) return;
  11062. if (err) return ep.emit('error', err);
  11063. var UploadId = data.UploadId;
  11064. if (!UploadId) {
  11065. return callback({ Message: 'no upload id' });
  11066. }
  11067. ep.emit('upload_id_ready', { UploadId: UploadId, PartList: [] });
  11068. });
  11069. });
  11070.  
  11071. // 如果已存在 UploadId,找一个可以用的 UploadId
  11072. ep.on('has_upload_id', function (UploadIdList) {
  11073. // 串行地,找一个内容一致的 UploadId
  11074. UploadIdList = UploadIdList.reverse();
  11075. Async.eachLimit(UploadIdList, 1, function (UploadId, asyncCallback) {
  11076. if (!self._isRunningTask(TaskId)) return;
  11077. // 如果正在上传,跳过
  11078. if (uploadIdUsing[UploadId]) {
  11079. asyncCallback(); // 检查下一个 UploadId
  11080. return;
  11081. }
  11082. // 判断 UploadId 是否可用
  11083. wholeMultipartListPart.call(self, {
  11084. Bucket: Bucket,
  11085. Region: Region,
  11086. Key: Key,
  11087. UploadId: UploadId
  11088. }, function (err, PartListData) {
  11089. if (!self._isRunningTask(TaskId)) return;
  11090. if (err) {
  11091. removeUploadId.call(self, UploadId);
  11092. return ep.emit('error', err);
  11093. }
  11094. var PartList = PartListData.PartList;
  11095. PartList.forEach(function (item) {
  11096. item.PartNumber *= 1;
  11097. item.Size *= 1;
  11098. item.ETag = item.ETag || '';
  11099. });
  11100. isAvailableUploadList(PartList, function (err, isAvailable) {
  11101. if (!self._isRunningTask(TaskId)) return;
  11102. if (err) return ep.emit('error', err);
  11103. if (isAvailable) {
  11104. asyncCallback({
  11105. UploadId: UploadId,
  11106. PartList: PartList
  11107. }); // 马上结束
  11108. } else {
  11109. asyncCallback(); // 检查下一个 UploadId
  11110. }
  11111. });
  11112. });
  11113. }, function (AvailableUploadData) {
  11114. if (!self._isRunningTask(TaskId)) return;
  11115. onHashProgress(null, true);
  11116. if (AvailableUploadData && AvailableUploadData.UploadId) {
  11117. ep.emit('upload_id_ready', AvailableUploadData);
  11118. } else {
  11119. ep.emit('no_available_upload_id');
  11120. }
  11121. });
  11122. });
  11123.  
  11124. // 在本地缓存找可用的 UploadId
  11125. ep.on('seek_local_avail_upload_id', function (RemoteUploadIdList) {
  11126. // 在本地找可用的 UploadId
  11127. var uuid = util.getFileUUID(params.Body, params.ChunkSize),
  11128. LocalUploadIdList;
  11129. if (uuid && (LocalUploadIdList = getUploadId.call(self, uuid))) {
  11130. var next = function (index) {
  11131. // 如果本地找不到可用 UploadId,再一个个遍历校验远端
  11132. if (index >= LocalUploadIdList.length) {
  11133. ep.emit('has_upload_id', RemoteUploadIdList);
  11134. return;
  11135. }
  11136. var UploadId = LocalUploadIdList[index];
  11137. // 如果不在远端 UploadId 列表里,跳过并删除
  11138. if (!util.isInArray(RemoteUploadIdList, UploadId)) {
  11139. removeUploadId.call(self, UploadId);
  11140. next(index + 1);
  11141. return;
  11142. }
  11143. // 如果正在上传,跳过
  11144. if (uploadIdUsing[UploadId]) {
  11145. next(index + 1);
  11146. return;
  11147. }
  11148. // 判断 UploadId 是否存在线上
  11149. wholeMultipartListPart.call(self, {
  11150. Bucket: Bucket,
  11151. Region: Region,
  11152. Key: Key,
  11153. UploadId: UploadId
  11154. }, function (err, PartListData) {
  11155. if (!self._isRunningTask(TaskId)) return;
  11156. if (err) {
  11157. removeUploadId.call(self, UploadId);
  11158. next(index + 1);
  11159. } else {
  11160. // 找到可用 UploadId
  11161. ep.emit('upload_id_ready', {
  11162. UploadId: UploadId,
  11163. PartList: PartListData.PartList
  11164. });
  11165. }
  11166. });
  11167. };
  11168. next(0);
  11169. } else {
  11170. ep.emit('has_upload_id', RemoteUploadIdList);
  11171. }
  11172. });
  11173.  
  11174. // 获取线上 UploadId 列表
  11175. ep.on('get_remote_upload_id_list', function (RemoteUploadIdList) {
  11176. // 获取符合条件的 UploadId 列表,因为同一个文件可以有多个上传任务。
  11177. wholeMultipartList.call(self, {
  11178. Bucket: Bucket,
  11179. Region: Region,
  11180. Key: Key
  11181. }, function (err, data) {
  11182. if (!self._isRunningTask(TaskId)) return;
  11183. if (err) {
  11184. return ep.emit('error', err);
  11185. }
  11186. // 整理远端 UploadId 列表
  11187. var RemoteUploadIdList = util.filter(data.UploadList, function (item) {
  11188. return item.Key === Key && (!StorageClass || item.StorageClass.toUpperCase() === StorageClass.toUpperCase());
  11189. }).reverse().map(function (item) {
  11190. return item.UploadId || item.UploadID;
  11191. });
  11192. if (RemoteUploadIdList.length) {
  11193. ep.emit('seek_local_avail_upload_id', RemoteUploadIdList);
  11194. } else {
  11195. var uuid = util.getFileUUID(params.Body, params.ChunkSize),
  11196. LocalUploadIdList;
  11197. if (uuid && (LocalUploadIdList = getUploadId.call(self, uuid))) {
  11198. util.each(LocalUploadIdList, function (UploadId) {
  11199. removeUploadId.call(self, UploadId);
  11200. });
  11201. }
  11202. ep.emit('no_available_upload_id');
  11203. }
  11204. });
  11205. });
  11206.  
  11207. // 开始找可用 UploadId
  11208. ep.emit('get_remote_upload_id_list');
  11209. }
  11210.  
  11211. // 获取符合条件的全部上传任务 (条件包括 Bucket, Region, Prefix)
  11212. function wholeMultipartList(params, callback) {
  11213. var self = this;
  11214. var UploadList = [];
  11215. var sendParams = {
  11216. Bucket: params.Bucket,
  11217. Region: params.Region,
  11218. Prefix: params.Key
  11219. };
  11220. var next = function () {
  11221. self.multipartList(sendParams, function (err, data) {
  11222. if (err) return callback(err);
  11223. UploadList.push.apply(UploadList, data.Upload || []);
  11224. if (data.IsTruncated === 'true') {
  11225. // 列表不完整
  11226. sendParams.KeyMarker = data.NextKeyMarker;
  11227. sendParams.UploadIdMarker = data.NextUploadIdMarker;
  11228. next();
  11229. } else {
  11230. callback(null, { UploadList: UploadList });
  11231. }
  11232. });
  11233. };
  11234. next();
  11235. }
  11236.  
  11237. // 获取指定上传任务的分块列表
  11238. function wholeMultipartListPart(params, callback) {
  11239. var self = this;
  11240. var PartList = [];
  11241. var sendParams = {
  11242. Bucket: params.Bucket,
  11243. Region: params.Region,
  11244. Key: params.Key,
  11245. UploadId: params.UploadId
  11246. };
  11247. var next = function () {
  11248. self.multipartListPart(sendParams, function (err, data) {
  11249. if (err) return callback(err);
  11250. PartList.push.apply(PartList, data.Part || []);
  11251. if (data.IsTruncated === 'true') {
  11252. // 列表不完整
  11253. sendParams.PartNumberMarker = data.NextPartNumberMarker;
  11254. next();
  11255. } else {
  11256. callback(null, { PartList: PartList });
  11257. }
  11258. });
  11259. };
  11260. next();
  11261. }
  11262.  
  11263. // 上传文件分块,包括
  11264. /*
  11265. UploadId (上传任务编号)
  11266. AsyncLimit (并发量),
  11267. SliceList (上传的分块数组),
  11268. FilePath (本地文件的位置),
  11269. SliceSize (文件分块大小)
  11270. FileSize (文件大小)
  11271. onProgress (上传成功之后的回调函数)
  11272. */
  11273. function uploadSliceList(params, cb) {
  11274. var self = this;
  11275. var TaskId = params.TaskId;
  11276. var Bucket = params.Bucket;
  11277. var Region = params.Region;
  11278. var Key = params.Key;
  11279. var UploadData = params.UploadData;
  11280. var FileSize = params.FileSize;
  11281. var SliceSize = params.SliceSize;
  11282. var ChunkParallel = Math.min(params.AsyncLimit || self.options.ChunkParallelLimit || 1, 256);
  11283. var Body = params.Body;
  11284. var SliceCount = Math.ceil(FileSize / SliceSize);
  11285. var FinishSize = 0;
  11286. var ServerSideEncryption = params.ServerSideEncryption;
  11287. var needUploadSlices = util.filter(UploadData.PartList, function (SliceItem) {
  11288. if (SliceItem['Uploaded']) {
  11289. FinishSize += SliceItem['PartNumber'] >= SliceCount ? FileSize % SliceSize || SliceSize : SliceSize;
  11290. }
  11291. return !SliceItem['Uploaded'];
  11292. });
  11293. var onProgress = params.onProgress;
  11294.  
  11295. Async.eachLimit(needUploadSlices, ChunkParallel, function (SliceItem, asyncCallback) {
  11296. if (!self._isRunningTask(TaskId)) return;
  11297. var PartNumber = SliceItem['PartNumber'];
  11298. var currentSize = Math.min(FileSize, SliceItem['PartNumber'] * SliceSize) - (SliceItem['PartNumber'] - 1) * SliceSize;
  11299. var preAddSize = 0;
  11300. uploadSliceItem.call(self, {
  11301. TaskId: TaskId,
  11302. Bucket: Bucket,
  11303. Region: Region,
  11304. Key: Key,
  11305. SliceSize: SliceSize,
  11306. FileSize: FileSize,
  11307. PartNumber: PartNumber,
  11308. ServerSideEncryption: ServerSideEncryption,
  11309. Body: Body,
  11310. UploadData: UploadData,
  11311. onProgress: function (data) {
  11312. FinishSize += data.loaded - preAddSize;
  11313. preAddSize = data.loaded;
  11314. onProgress({ loaded: FinishSize, total: FileSize });
  11315. }
  11316. }, function (err, data) {
  11317. if (!self._isRunningTask(TaskId)) return;
  11318. if (util.isBrowser && !err && !data.ETag) {
  11319. err = 'get ETag error, please add "ETag" to CORS ExposeHeader setting.';
  11320. }
  11321. if (err) {
  11322. FinishSize -= preAddSize;
  11323. } else {
  11324. FinishSize += currentSize - preAddSize;
  11325. SliceItem.ETag = data.ETag;
  11326. }
  11327. asyncCallback(err || null, data);
  11328. });
  11329. }, function (err) {
  11330. if (!self._isRunningTask(TaskId)) return;
  11331. if (err) return cb(err);
  11332. cb(null, {
  11333. UploadId: UploadData.UploadId,
  11334. SliceList: UploadData.PartList
  11335. });
  11336. });
  11337. }
  11338.  
  11339. // 上传指定分片
  11340. function uploadSliceItem(params, callback) {
  11341. var self = this;
  11342. var TaskId = params.TaskId;
  11343. var Bucket = params.Bucket;
  11344. var Region = params.Region;
  11345. var Key = params.Key;
  11346. var FileSize = params.FileSize;
  11347. var FileBody = params.Body;
  11348. var PartNumber = params.PartNumber * 1;
  11349. var SliceSize = params.SliceSize;
  11350. var ServerSideEncryption = params.ServerSideEncryption;
  11351. var UploadData = params.UploadData;
  11352. var ChunkRetryTimes = self.options.ChunkRetryTimes + 1;
  11353.  
  11354. var start = SliceSize * (PartNumber - 1);
  11355.  
  11356. var ContentLength = SliceSize;
  11357.  
  11358. var end = start + SliceSize;
  11359.  
  11360. if (end > FileSize) {
  11361. end = FileSize;
  11362. ContentLength = end - start;
  11363. }
  11364.  
  11365. var PartItem = UploadData.PartList[PartNumber - 1];
  11366. Async.retry(ChunkRetryTimes, function (tryCallback) {
  11367. if (!self._isRunningTask(TaskId)) return;
  11368. util.fileSlice(FileBody, start, end, true, function (Body) {
  11369. self.multipartUpload({
  11370. TaskId: TaskId,
  11371. Bucket: Bucket,
  11372. Region: Region,
  11373. Key: Key,
  11374. ContentLength: ContentLength,
  11375. PartNumber: PartNumber,
  11376. UploadId: UploadData.UploadId,
  11377. ServerSideEncryption: ServerSideEncryption,
  11378. Body: Body,
  11379. onProgress: params.onProgress
  11380. }, function (err, data) {
  11381. if (!self._isRunningTask(TaskId)) return;
  11382. if (err) {
  11383. return tryCallback(err);
  11384. } else {
  11385. PartItem.Uploaded = true;
  11386. return tryCallback(null, data);
  11387. }
  11388. });
  11389. });
  11390. }, function (err, data) {
  11391. if (!self._isRunningTask(TaskId)) return;
  11392. return callback(err, data);
  11393. });
  11394. }
  11395.  
  11396. // 完成分块上传
  11397. function uploadSliceComplete(params, callback) {
  11398. var Bucket = params.Bucket;
  11399. var Region = params.Region;
  11400. var Key = params.Key;
  11401. var UploadId = params.UploadId;
  11402. var SliceList = params.SliceList;
  11403. var self = this;
  11404. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  11405. var Parts = SliceList.map(function (item) {
  11406. return {
  11407. PartNumber: item.PartNumber,
  11408. ETag: item.ETag
  11409. };
  11410. });
  11411. // 完成上传的请求也做重试
  11412. Async.retry(ChunkRetryTimes, function (tryCallback) {
  11413. self.multipartComplete({
  11414. Bucket: Bucket,
  11415. Region: Region,
  11416. Key: Key,
  11417. UploadId: UploadId,
  11418. Parts: Parts
  11419. }, tryCallback);
  11420. }, function (err, data) {
  11421. callback(err, data);
  11422. });
  11423. }
  11424.  
  11425. // 抛弃分块上传任务
  11426. /*
  11427. AsyncLimit (抛弃上传任务的并发量),
  11428. UploadId (上传任务的编号,当 Level 为 task 时候需要)
  11429. Level (抛弃分块上传任务的级别,task : 抛弃指定的上传任务,file : 抛弃指定的文件对应的上传任务,其他值 :抛弃指定Bucket 的全部上传任务)
  11430. */
  11431. function abortUploadTask(params, callback) {
  11432. var Bucket = params.Bucket;
  11433. var Region = params.Region;
  11434. var Key = params.Key;
  11435. var UploadId = params.UploadId;
  11436. var Level = params.Level || 'task';
  11437. var AsyncLimit = params.AsyncLimit;
  11438. var self = this;
  11439.  
  11440. var ep = new EventProxy();
  11441.  
  11442. ep.on('error', function (errData) {
  11443. return callback(errData);
  11444. });
  11445.  
  11446. // 已经获取到需要抛弃的任务列表
  11447. ep.on('get_abort_array', function (AbortArray) {
  11448. abortUploadTaskArray.call(self, {
  11449. Bucket: Bucket,
  11450. Region: Region,
  11451. Key: Key,
  11452. Headers: params.Headers,
  11453. AsyncLimit: AsyncLimit,
  11454. AbortArray: AbortArray
  11455. }, function (err, data) {
  11456. if (err) {
  11457. return callback(err);
  11458. }
  11459. callback(null, data);
  11460. });
  11461. });
  11462.  
  11463. if (Level === 'bucket') {
  11464. // Bucket 级别的任务抛弃,抛弃该 Bucket 下的全部上传任务
  11465. wholeMultipartList.call(self, {
  11466. Bucket: Bucket,
  11467. Region: Region
  11468. }, function (err, data) {
  11469. if (err) {
  11470. return callback(err);
  11471. }
  11472. ep.emit('get_abort_array', data.UploadList || []);
  11473. });
  11474. } else if (Level === 'file') {
  11475. // 文件级别的任务抛弃,抛弃该文件的全部上传任务
  11476. if (!Key) return callback({ error: 'abort_upload_task_no_key' });
  11477. wholeMultipartList.call(self, {
  11478. Bucket: Bucket,
  11479. Region: Region,
  11480. Key: Key
  11481. }, function (err, data) {
  11482. if (err) {
  11483. return callback(err);
  11484. }
  11485. ep.emit('get_abort_array', data.UploadList || []);
  11486. });
  11487. } else if (Level === 'task') {
  11488. // 单个任务级别的任务抛弃,抛弃指定 UploadId 的上传任务
  11489. if (!UploadId) return callback({ error: 'abort_upload_task_no_id' });
  11490. if (!Key) return callback({ error: 'abort_upload_task_no_key' });
  11491. ep.emit('get_abort_array', [{
  11492. Key: Key,
  11493. UploadId: UploadId
  11494. }]);
  11495. } else {
  11496. return callback({ error: 'abort_unknown_level' });
  11497. }
  11498. }
  11499.  
  11500. // 批量抛弃分块上传任务
  11501. function abortUploadTaskArray(params, callback) {
  11502.  
  11503. var Bucket = params.Bucket;
  11504. var Region = params.Region;
  11505. var Key = params.Key;
  11506. var AbortArray = params.AbortArray;
  11507. var AsyncLimit = params.AsyncLimit || 1;
  11508. var self = this;
  11509.  
  11510. var index = 0;
  11511. var resultList = new Array(AbortArray.length);
  11512. Async.eachLimit(AbortArray, AsyncLimit, function (AbortItem, callback) {
  11513. var eachIndex = index;
  11514. if (Key && Key !== AbortItem.Key) {
  11515. resultList[eachIndex] = { error: { KeyNotMatch: true } };
  11516. callback(null);
  11517. return;
  11518. }
  11519. var UploadId = AbortItem.UploadId || AbortItem.UploadID;
  11520.  
  11521. self.multipartAbort({
  11522. Bucket: Bucket,
  11523. Region: Region,
  11524. Key: AbortItem.Key,
  11525. Headers: params.Headers,
  11526. UploadId: UploadId
  11527. }, function (err, data) {
  11528. var task = {
  11529. Bucket: Bucket,
  11530. Region: Region,
  11531. Key: AbortItem.Key,
  11532. UploadId: UploadId
  11533. };
  11534. resultList[eachIndex] = { error: err, task: task };
  11535. callback(null);
  11536. });
  11537. index++;
  11538. }, function (err) {
  11539. if (err) {
  11540. return callback(err);
  11541. }
  11542.  
  11543. var successList = [];
  11544. var errorList = [];
  11545.  
  11546. for (var i = 0, len = resultList.length; i < len; i++) {
  11547. var item = resultList[i];
  11548. if (item['task']) {
  11549. if (item['error']) {
  11550. errorList.push(item['task']);
  11551. } else {
  11552. successList.push(item['task']);
  11553. }
  11554. }
  11555. }
  11556.  
  11557. return callback(null, {
  11558. successList: successList,
  11559. errorList: errorList
  11560. });
  11561. });
  11562. }
  11563.  
  11564. // 批量上传文件
  11565. function uploadFiles(params, callback) {
  11566. var self = this;
  11567.  
  11568. // 判断多大的文件使用分片上传
  11569. var SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;
  11570.  
  11571. // 汇总返回进度
  11572. var TotalSize = 0;
  11573. var TotalFinish = 0;
  11574. var onTotalProgress = util.throttleOnProgress.call(self, TotalFinish, params.onProgress);
  11575.  
  11576. // 汇总返回回调
  11577. var unFinishCount = params.files.length;
  11578. var _onTotalFileFinish = params.onFileFinish;
  11579. var resultList = Array(unFinishCount);
  11580. var onTotalFileFinish = function (err, data, options) {
  11581. onTotalProgress(null, true);
  11582. _onTotalFileFinish && _onTotalFileFinish(err, data, options);
  11583. resultList[options.Index] = {
  11584. options: options,
  11585. error: err,
  11586. data: data
  11587. };
  11588. if (--unFinishCount <= 0 && callback) {
  11589. callback(null, {
  11590. files: resultList
  11591. });
  11592. }
  11593. };
  11594.  
  11595. // 开始处理每个文件
  11596. var taskList = [];
  11597. util.each(params.files, function (fileParams, index) {
  11598. (function () {
  11599. // 对齐 nodejs 缩进
  11600.  
  11601. var Body = fileParams.Body;
  11602. var FileSize = Body.size || Body.length || 0;
  11603. var fileInfo = { Index: index, TaskId: '' };
  11604.  
  11605. // 更新文件总大小
  11606. TotalSize += FileSize;
  11607.  
  11608. // 整理 option,用于返回给回调
  11609. util.each(fileParams, function (v, k) {
  11610. if (typeof v !== 'object' && typeof v !== 'function') {
  11611. fileInfo[k] = v;
  11612. }
  11613. });
  11614.  
  11615. // 处理单个文件 TaskReady
  11616. var _onTaskReady = fileParams.onTaskReady;
  11617. var onTaskReady = function (tid) {
  11618. fileInfo.TaskId = tid;
  11619. _onTaskReady && _onTaskReady(tid);
  11620. };
  11621. fileParams.onTaskReady = onTaskReady;
  11622.  
  11623. // 处理单个文件进度
  11624. var PreAddSize = 0;
  11625. var _onProgress = fileParams.onProgress;
  11626. var onProgress = function (info) {
  11627. TotalFinish = TotalFinish - PreAddSize + info.loaded;
  11628. PreAddSize = info.loaded;
  11629. _onProgress && _onProgress(info);
  11630. onTotalProgress({ loaded: TotalFinish, total: TotalSize });
  11631. };
  11632. fileParams.onProgress = onProgress;
  11633.  
  11634. // 处理单个文件完成
  11635. var _onFileFinish = fileParams.onFileFinish;
  11636. var onFileFinish = function (err, data) {
  11637. _onFileFinish && _onFileFinish(err, data);
  11638. onTotalFileFinish && onTotalFileFinish(err, data, fileInfo);
  11639. };
  11640.  
  11641. // 添加上传任务
  11642. var api = FileSize >= SliceSize ? 'sliceUploadFile' : 'putObject';
  11643. taskList.push({
  11644. api: api,
  11645. params: fileParams,
  11646. callback: onFileFinish
  11647. });
  11648. })();
  11649. });
  11650. self._addTasks(taskList);
  11651. }
  11652.  
  11653. // 分片复制文件
  11654. function sliceCopyFile(params, callback) {
  11655. var ep = new EventProxy();
  11656.  
  11657. var self = this;
  11658. var Bucket = params.Bucket;
  11659. var Region = params.Region;
  11660. var Key = params.Key;
  11661. var CopySource = params.CopySource;
  11662. var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/);
  11663. if (!m) {
  11664. callback({ error: 'CopySource format error' });
  11665. return;
  11666. }
  11667.  
  11668. var SourceBucket = m[1];
  11669. var SourceRegion = m[3];
  11670. var SourceKey = decodeURIComponent(m[4]);
  11671. var CopySliceSize = params.CopySliceSize === undefined ? self.options.CopySliceSize : params.CopySliceSize;
  11672. CopySliceSize = Math.max(0, CopySliceSize);
  11673.  
  11674. var ChunkSize = params.CopyChunkSize || this.options.CopyChunkSize;
  11675. var ChunkParallel = this.options.CopyChunkParallelLimit;
  11676.  
  11677. var FinishSize = 0;
  11678. var FileSize;
  11679. var onProgress;
  11680.  
  11681. // 分片复制完成,开始 multipartComplete 操作
  11682. ep.on('copy_slice_complete', function (UploadData) {
  11683. self.multipartComplete({
  11684. Bucket: Bucket,
  11685. Region: Region,
  11686. Key: Key,
  11687. UploadId: UploadData.UploadId,
  11688. Parts: UploadData.PartList
  11689. }, function (err, data) {
  11690. if (err) {
  11691. onProgress(null, true);
  11692. return callback(err);
  11693. }
  11694. onProgress({ loaded: FileSize, total: FileSize }, true);
  11695. callback(null, data);
  11696. });
  11697. });
  11698.  
  11699. ep.on('get_copy_data_finish', function (UploadData) {
  11700. Async.eachLimit(UploadData.PartList, ChunkParallel, function (SliceItem, asyncCallback) {
  11701. var PartNumber = SliceItem.PartNumber;
  11702. var CopySourceRange = SliceItem.CopySourceRange;
  11703. var currentSize = SliceItem.end - SliceItem.start;
  11704. var preAddSize = 0;
  11705.  
  11706. copySliceItem.call(self, {
  11707. Bucket: Bucket,
  11708. Region: Region,
  11709. Key: Key,
  11710. CopySource: CopySource,
  11711. UploadId: UploadData.UploadId,
  11712. PartNumber: PartNumber,
  11713. CopySourceRange: CopySourceRange,
  11714. onProgress: function (data) {
  11715. FinishSize += data.loaded - preAddSize;
  11716. preAddSize = data.loaded;
  11717. onProgress({ loaded: FinishSize, total: FileSize });
  11718. }
  11719. }, function (err, data) {
  11720. if (err) {
  11721. return asyncCallback(err);
  11722. }
  11723. onProgress({ loaded: FinishSize, total: FileSize });
  11724.  
  11725. FinishSize += currentSize - preAddSize;
  11726. SliceItem.ETag = data.ETag;
  11727. asyncCallback(err || null, data);
  11728. });
  11729. }, function (err) {
  11730. if (err) {
  11731. onProgress(null, true);
  11732. return callback(err);
  11733. }
  11734.  
  11735. ep.emit('copy_slice_complete', UploadData);
  11736. });
  11737. });
  11738.  
  11739. ep.on('get_file_size_finish', function (SourceHeaders) {
  11740. // 控制分片大小
  11741. (function () {
  11742. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  11743. var AutoChunkSize = 1024 * 1024;
  11744. for (var i = 0; i < SIZE.length; i++) {
  11745. AutoChunkSize = SIZE[i] * 1024 * 1024;
  11746. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  11747. }
  11748. params.ChunkSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  11749.  
  11750. var ChunkCount = Math.ceil(FileSize / ChunkSize);
  11751.  
  11752. var list = [];
  11753. for (var partNumber = 1; partNumber <= ChunkCount; partNumber++) {
  11754. var start = (partNumber - 1) * ChunkSize;
  11755. var end = partNumber * ChunkSize < FileSize ? partNumber * ChunkSize - 1 : FileSize - 1;
  11756. var item = {
  11757. PartNumber: partNumber,
  11758. start: start,
  11759. end: end,
  11760. CopySourceRange: "bytes=" + start + "-" + end
  11761. };
  11762. list.push(item);
  11763. }
  11764. params.PartList = list;
  11765. })();
  11766.  
  11767. var TargetHeader;
  11768. if (params.Headers['x-cos-metadata-directive'] === 'Replaced') {
  11769. TargetHeader = params.Headers;
  11770. } else {
  11771. TargetHeader = SourceHeaders;
  11772. }
  11773. TargetHeader['x-cos-storage-class'] = params.Headers['x-cos-storage-class'] || SourceHeaders['x-cos-storage-class'];
  11774. TargetHeader = util.clearKey(TargetHeader);
  11775. /**
  11776. * 对于归档存储的对象,如果未恢复副本,则不允许 Copy
  11777. */
  11778. if (SourceHeaders['x-cos-storage-class'] === 'ARCHIVE') {
  11779. var restoreHeader = SourceHeaders['x-cos-restore'];
  11780. if (!restoreHeader || restoreHeader === 'ongoing-request="true"') {
  11781. callback({ error: 'Unrestored archive object is not allowed to be copied' });
  11782. return;
  11783. }
  11784. }
  11785. /**
  11786. * 去除一些无用的头部,规避 multipartInit 出错
  11787. * 这些头部通常是在 putObjectCopy 时才使用
  11788. */
  11789. delete TargetHeader['x-cos-copy-source'];
  11790. delete TargetHeader['x-cos-metadata-directive'];
  11791. delete TargetHeader['x-cos-copy-source-If-Modified-Since'];
  11792. delete TargetHeader['x-cos-copy-source-If-Unmodified-Since'];
  11793. delete TargetHeader['x-cos-copy-source-If-Match'];
  11794. delete TargetHeader['x-cos-copy-source-If-None-Match'];
  11795. self.multipartInit({
  11796. Bucket: Bucket,
  11797. Region: Region,
  11798. Key: Key,
  11799. Headers: TargetHeader
  11800. }, function (err, data) {
  11801. if (err) {
  11802. return callback(err);
  11803. }
  11804. params.UploadId = data.UploadId;
  11805. ep.emit('get_copy_data_finish', params);
  11806. });
  11807. });
  11808.  
  11809. // 获取远端复制源文件的大小
  11810. self.headObject({
  11811. Bucket: SourceBucket,
  11812. Region: SourceRegion,
  11813. Key: SourceKey
  11814. }, function (err, data) {
  11815. if (err) {
  11816. if (err.statusCode && err.statusCode === 404) {
  11817. callback({ ErrorStatus: SourceKey + ' Not Exist' });
  11818. } else {
  11819. callback(err);
  11820. }
  11821. return;
  11822. }
  11823.  
  11824. FileSize = params.FileSize = data.headers['content-length'];
  11825. if (FileSize === undefined || !FileSize) {
  11826. callback({ error: 'get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.' });
  11827. return;
  11828. }
  11829.  
  11830. onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  11831.  
  11832. // 开始上传
  11833. if (FileSize <= CopySliceSize) {
  11834. if (!params.Headers['x-cos-metadata-directive']) {
  11835. params.Headers['x-cos-metadata-directive'] = 'Copy';
  11836. }
  11837. self.putObjectCopy(params, function (err, data) {
  11838. if (err) {
  11839. onProgress(null, true);
  11840. return callback(err);
  11841. }
  11842. onProgress({ loaded: FileSize, total: FileSize }, true);
  11843. callback(err, data);
  11844. });
  11845. } else {
  11846. var resHeaders = data.headers;
  11847. var SourceHeaders = {
  11848. 'Cache-Control': resHeaders['cache-control'],
  11849. 'Content-Disposition': resHeaders['content-disposition'],
  11850. 'Content-Encoding': resHeaders['content-encoding'],
  11851. 'Content-Type': resHeaders['content-type'],
  11852. 'Expires': resHeaders['expires'],
  11853. 'x-cos-storage-class': resHeaders['x-cos-storage-class']
  11854. };
  11855. util.each(resHeaders, function (v, k) {
  11856. var metaPrefix = 'x-cos-meta-';
  11857. if (k.indexOf(metaPrefix) === 0 && k.length > metaPrefix.length) {
  11858. SourceHeaders[k] = v;
  11859. }
  11860. });
  11861. ep.emit('get_file_size_finish', SourceHeaders);
  11862. }
  11863. });
  11864. }
  11865.  
  11866. // 复制指定分片
  11867. function copySliceItem(params, callback) {
  11868. var TaskId = params.TaskId;
  11869. var Bucket = params.Bucket;
  11870. var Region = params.Region;
  11871. var Key = params.Key;
  11872. var CopySource = params.CopySource;
  11873. var UploadId = params.UploadId;
  11874. var PartNumber = params.PartNumber * 1;
  11875. var CopySourceRange = params.CopySourceRange;
  11876.  
  11877. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  11878. var self = this;
  11879.  
  11880. Async.retry(ChunkRetryTimes, function (tryCallback) {
  11881. self.uploadPartCopy({
  11882. TaskId: TaskId,
  11883. Bucket: Bucket,
  11884. Region: Region,
  11885. Key: Key,
  11886. CopySource: CopySource,
  11887. UploadId: UploadId,
  11888. PartNumber: PartNumber,
  11889. CopySourceRange: CopySourceRange,
  11890. onProgress: params.onProgress
  11891. }, function (err, data) {
  11892. tryCallback(err || null, data);
  11893. });
  11894. }, function (err, data) {
  11895. return callback(err, data);
  11896. });
  11897. }
  11898.  
  11899. var API_MAP = {
  11900. sliceUploadFile: sliceUploadFile,
  11901. abortUploadTask: abortUploadTask,
  11902. uploadFiles: uploadFiles,
  11903. sliceCopyFile: sliceCopyFile
  11904. };
  11905.  
  11906. module.exports.init = function (COS, task) {
  11907. task.transferToTaskMethod(API_MAP, 'sliceUploadFile');
  11908. util.each(API_MAP, function (fn, apiName) {
  11909. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  11910. });
  11911. };
  11912.  
  11913. /***/ }),
  11914. /* 15 */
  11915. /***/ (function(module, exports) {
  11916.  
  11917. var eachLimit = function (arr, limit, iterator, callback) {
  11918. callback = callback || function () {};
  11919. if (!arr.length || limit <= 0) {
  11920. return callback();
  11921. }
  11922.  
  11923. var completed = 0;
  11924. var started = 0;
  11925. var running = 0;
  11926.  
  11927. (function replenish() {
  11928. if (completed >= arr.length) {
  11929. return callback();
  11930. }
  11931.  
  11932. while (running < limit && started < arr.length) {
  11933. started += 1;
  11934. running += 1;
  11935. iterator(arr[started - 1], function (err) {
  11936.  
  11937. if (err) {
  11938. callback(err);
  11939. callback = function () {};
  11940. } else {
  11941. completed += 1;
  11942. running -= 1;
  11943. if (completed >= arr.length) {
  11944. callback();
  11945. } else {
  11946. replenish();
  11947. }
  11948. }
  11949. });
  11950. }
  11951. })();
  11952. };
  11953.  
  11954. var retry = function (times, iterator, callback) {
  11955. var next = function (index) {
  11956. iterator(function (err, data) {
  11957. if (err && index < times) {
  11958. next(index + 1);
  11959. } else {
  11960. callback(err, data);
  11961. }
  11962. });
  11963. };
  11964. if (times < 1) {
  11965. callback();
  11966. } else {
  11967. next(1);
  11968. }
  11969. };
  11970.  
  11971. var async = {
  11972. eachLimit: eachLimit,
  11973. retry: retry
  11974. };
  11975.  
  11976. module.exports = async;
  11977.  
  11978. /***/ })
  11979. /******/ ]);
  11980. });

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址