You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1690 line
52 KiB

  1. // swagger.js
  2. // version 2.0.47
  3. (function () {
  4. var __bind = function (fn, me) {
  5. return function () {
  6. return fn.apply(me, arguments);
  7. };
  8. };
  9. var log = function () {
  10. log.history = log.history || [];
  11. log.history.push(arguments);
  12. if (this.console) {
  13. console.log(Array.prototype.slice.call(arguments)[0]);
  14. }
  15. };
  16. // if you want to apply conditional formatting of parameter values
  17. var parameterMacro = function (value) {
  18. return value;
  19. }
  20. // if you want to apply conditional formatting of model property values
  21. var modelPropertyMacro = function (value) {
  22. return value;
  23. }
  24. if (!Array.prototype.indexOf) {
  25. Array.prototype.indexOf = function (obj, start) {
  26. for (var i = (start || 0), j = this.length; i < j; i++) {
  27. if (this[i] === obj) { return i; }
  28. }
  29. return -1;
  30. }
  31. }
  32. if (!('filter' in Array.prototype)) {
  33. Array.prototype.filter = function (filter, that /*opt*/) {
  34. var other = [], v;
  35. for (var i = 0, n = this.length; i < n; i++)
  36. if (i in this && filter.call(that, v = this[i], i, this))
  37. other.push(v);
  38. return other;
  39. };
  40. }
  41. if (!('map' in Array.prototype)) {
  42. Array.prototype.map = function (mapper, that /*opt*/) {
  43. var other = new Array(this.length);
  44. for (var i = 0, n = this.length; i < n; i++)
  45. if (i in this)
  46. other[i] = mapper.call(that, this[i], i, this);
  47. return other;
  48. };
  49. }
  50. Object.keys = Object.keys || (function () {
  51. var hasOwnProperty = Object.prototype.hasOwnProperty,
  52. hasDontEnumBug = !{ toString: null }.propertyIsEnumerable("toString"),
  53. DontEnums = [
  54. 'toString',
  55. 'toLocaleString',
  56. 'valueOf',
  57. 'hasOwnProperty',
  58. 'isPrototypeOf',
  59. 'propertyIsEnumerable',
  60. 'constructor'
  61. ],
  62. DontEnumsLength = DontEnums.length;
  63. return function (o) {
  64. if (typeof o != "object" && typeof o != "function" || o === null)
  65. throw new TypeError("Object.keys called on a non-object");
  66. var result = [];
  67. for (var name in o) {
  68. if (hasOwnProperty.call(o, name))
  69. result.push(name);
  70. }
  71. if (hasDontEnumBug) {
  72. for (var i = 0; i < DontEnumsLength; i++) {
  73. if (hasOwnProperty.call(o, DontEnums[i]))
  74. result.push(DontEnums[i]);
  75. }
  76. }
  77. return result;
  78. };
  79. })();
  80. var SwaggerApi = function (url, options) {
  81. this.isBuilt = false;
  82. this.url = null;
  83. this.debug = false;
  84. this.basePath = null;
  85. this.authorizations = null;
  86. this.authorizationScheme = null;
  87. this.info = null;
  88. this.useJQuery = false;
  89. this.modelsArray = [];
  90. this.isValid;
  91. options = (options || {});
  92. if (url)
  93. if (url.url)
  94. options = url;
  95. else
  96. this.url = url;
  97. else
  98. options = url;
  99. if (options.url != null)
  100. this.url = options.url;
  101. if (options.success != null)
  102. this.success = options.success;
  103. if (typeof options.useJQuery === 'boolean')
  104. this.useJQuery = options.useJQuery;
  105. this.failure = options.failure != null ? options.failure : function () { };
  106. this.progress = options.progress != null ? options.progress : function () { };
  107. if (options.success != null) {
  108. this.build();
  109. this.isBuilt = true;
  110. }
  111. }
  112. SwaggerApi.prototype.build = function () {
  113. if (this.isBuilt)
  114. return this;
  115. var _this = this;
  116. this.progress('fetching resource list: ' + this.url);
  117. var obj = {
  118. useJQuery: this.useJQuery,
  119. url: this.url,
  120. method: "get",
  121. headers: {
  122. accept: "application/json,application/json;charset=\"utf-8\",*/*"
  123. },
  124. on: {
  125. error: function (response) {
  126. if (_this.url.substring(0, 4) !== 'http') {
  127. return _this.fail('Please specify the protocol for ' + _this.url);
  128. } else if (response.status === 0) {
  129. return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
  130. } else if (response.status === 404) {
  131. return _this.fail('Can\'t read swagger JSON from ' + _this.url);
  132. } else {
  133. return _this.fail(response.status + ' : ' + response.statusText + ' ' + _this.url);
  134. }
  135. },
  136. response: function (resp) {
  137. var responseObj = resp.obj || JSON.parse(resp.data);
  138. _this.swaggerVersion = responseObj.swaggerVersion;
  139. if (_this.swaggerVersion === "1.2") {
  140. return _this.buildFromSpec(responseObj);
  141. } else {
  142. return _this.buildFrom1_1Spec(responseObj);
  143. }
  144. }
  145. }
  146. };
  147. var e = (typeof window !== 'undefined' ? window : exports);
  148. e.authorizations.apply(obj);
  149. new SwaggerHttp().execute(obj);
  150. return this;
  151. };
  152. SwaggerApi.prototype.buildFromSpec = function (response) {
  153. if (response.apiVersion != null) {
  154. this.apiVersion = response.apiVersion;
  155. }
  156. this.apis = {};
  157. this.apisArray = [];
  158. this.consumes = response.consumes;
  159. this.produces = response.produces;
  160. this.authSchemes = response.authorizations;
  161. if (response.info != null) {
  162. this.info = response.info;
  163. }
  164. var isApi = false;
  165. var i;
  166. for (i = 0; i < response.apis.length; i++) {
  167. var api = response.apis[i];
  168. if (api.operations) {
  169. var j;
  170. for (j = 0; j < api.operations.length; j++) {
  171. operation = api.operations[j];
  172. isApi = true;
  173. }
  174. }
  175. }
  176. if (response.basePath)
  177. this.basePath = response.basePath;
  178. else if (this.url.indexOf('?') > 0)
  179. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  180. else
  181. this.basePath = this.url;
  182. if (isApi) {
  183. var newName = response.resourcePath.replace(/\//g, '');
  184. this.resourcePath = response.resourcePath;
  185. var res = new SwaggerResource(response, this);
  186. this.apis[newName] = res;
  187. this.apisArray.push(res);
  188. } else {
  189. var k;
  190. for (k = 0; k < response.apis.length; k++) {
  191. var resource = response.apis[k];
  192. var res = new SwaggerResource(resource, this);
  193. this.apis[res.name] = res;
  194. this.apisArray.push(res);
  195. }
  196. }
  197. this.isValid = true;
  198. if (this.success) {
  199. this.success();
  200. }
  201. return this;
  202. };
  203. SwaggerApi.prototype.buildFrom1_1Spec = function (response) {
  204. log("This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info");
  205. if (response.apiVersion != null)
  206. this.apiVersion = response.apiVersion;
  207. this.apis = {};
  208. this.apisArray = [];
  209. this.produces = response.produces;
  210. if (response.info != null) {
  211. this.info = response.info;
  212. }
  213. var isApi = false;
  214. for (var i = 0; i < response.apis.length; i++) {
  215. var api = response.apis[i];
  216. if (api.operations) {
  217. for (var j = 0; j < api.operations.length; j++) {
  218. operation = api.operations[j];
  219. isApi = true;
  220. }
  221. }
  222. }
  223. if (response.basePath) {
  224. this.basePath = response.basePath;
  225. } else if (this.url.indexOf('?') > 0) {
  226. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  227. } else {
  228. this.basePath = this.url;
  229. }
  230. if (isApi) {
  231. var newName = response.resourcePath.replace(/\//g, '');
  232. this.resourcePath = response.resourcePath;
  233. var res = new SwaggerResource(response, this);
  234. this.apis[newName] = res;
  235. this.apisArray.push(res);
  236. } else {
  237. for (k = 0; k < response.apis.length; k++) {
  238. resource = response.apis[k];
  239. var res = new SwaggerResource(resource, this);
  240. this.apis[res.name] = res;
  241. this.apisArray.push(res);
  242. }
  243. }
  244. this.isValid = true;
  245. if (this.success) {
  246. this.success();
  247. }
  248. return this;
  249. };
  250. SwaggerApi.prototype.selfReflect = function () {
  251. var resource, resource_name, _ref;
  252. if (this.apis == null) {
  253. return false;
  254. }
  255. _ref = this.apis;
  256. for (resource_name in _ref) {
  257. resource = _ref[resource_name];
  258. if (resource.ready == null) {
  259. return false;
  260. }
  261. }
  262. this.setConsolidatedModels();
  263. this.ready = true;
  264. if (this.success != null) {
  265. return this.success();
  266. }
  267. };
  268. SwaggerApi.prototype.fail = function (message) {
  269. this.failure(message);
  270. throw message;
  271. };
  272. SwaggerApi.prototype.setConsolidatedModels = function () {
  273. var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results;
  274. this.models = {};
  275. _ref = this.apis;
  276. for (resource_name in _ref) {
  277. resource = _ref[resource_name];
  278. for (modelName in resource.models) {
  279. if (this.models[modelName] == null) {
  280. this.models[modelName] = resource.models[modelName];
  281. this.modelsArray.push(resource.models[modelName]);
  282. }
  283. }
  284. }
  285. _ref1 = this.modelsArray;
  286. _results = [];
  287. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  288. model = _ref1[_i];
  289. _results.push(model.setReferencedModels(this.models));
  290. }
  291. return _results;
  292. };
  293. SwaggerApi.prototype.help = function () {
  294. var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2;
  295. _ref = this.apis;
  296. for (resource_name in _ref) {
  297. resource = _ref[resource_name];
  298. log(resource_name);
  299. _ref1 = resource.operations;
  300. for (operation_name in _ref1) {
  301. operation = _ref1[operation_name];
  302. log(" " + operation.nickname);
  303. _ref2 = operation.parameters;
  304. for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
  305. parameter = _ref2[_i];
  306. log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
  307. }
  308. }
  309. }
  310. return this;
  311. };
  312. var SwaggerResource = function (resourceObj, api) {
  313. var _this = this;
  314. this.api = api;
  315. this.api = this.api;
  316. var consumes = (this.consumes | []);
  317. var produces = (this.produces | []);
  318. this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path;
  319. this.description = resourceObj.description;
  320. var parts = this.path.split("/");
  321. this.name = parts[parts.length - 1].replace('.{format}', '');
  322. this.basePath = this.api.basePath;
  323. this.operations = {};
  324. this.operationsArray = [];
  325. this.modelsArray = [];
  326. this.models = {};
  327. this.rawModels = {};
  328. this.useJQuery = (typeof api.useJQuery !== 'undefined' ? api.useJQuery : null);
  329. if ((resourceObj.apis != null) && (this.api.resourcePath != null)) {
  330. this.addApiDeclaration(resourceObj);
  331. } else {
  332. if (this.path == null) {
  333. this.api.fail("SwaggerResources must have a path.");
  334. }
  335. if (this.path.substring(0, 4) === 'http') {
  336. this.url = this.path.replace('{format}', 'json');
  337. } else {
  338. this.url = this.api.basePath + this.path.replace('{format}', 'json');
  339. }
  340. this.api.progress('fetching resource ' + this.name + ': ' + this.url);
  341. var obj = {
  342. url: this.url,
  343. method: "get",
  344. useJQuery: this.useJQuery,
  345. headers: {
  346. accept: "application/json,application/json;charset=\"utf-8\",*/*"
  347. },
  348. on: {
  349. response: function (resp) {
  350. var responseObj = resp.obj || JSON.parse(resp.data);
  351. return _this.addApiDeclaration(responseObj);
  352. },
  353. error: function (response) {
  354. return _this.api.fail("Unable to read api '" +
  355. _this.name + "' from path " + _this.url + " (server returned " + response.statusText + ")");
  356. }
  357. }
  358. };
  359. var e = typeof window !== 'undefined' ? window : exports;
  360. e.authorizations.apply(obj);
  361. new SwaggerHttp().execute(obj);
  362. }
  363. }
  364. SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
  365. var pos, url;
  366. url = this.api.basePath;
  367. pos = url.lastIndexOf(relativeBasePath);
  368. var parts = url.split("/");
  369. var rootUrl = parts[0] + "//" + parts[2];
  370. if (relativeBasePath.indexOf("http") === 0)
  371. return relativeBasePath;
  372. if (relativeBasePath === "/")
  373. return rootUrl;
  374. if (relativeBasePath.substring(0, 1) == "/") {
  375. // use root + relative
  376. return rootUrl + relativeBasePath;
  377. }
  378. else {
  379. var pos = this.basePath.lastIndexOf("/");
  380. var base = this.basePath.substring(0, pos);
  381. if (base.substring(base.length - 1) == "/")
  382. return base + relativeBasePath;
  383. else
  384. return base + "/" + relativeBasePath;
  385. }
  386. };
  387. SwaggerResource.prototype.addApiDeclaration = function (response) {
  388. if (response.produces != null)
  389. this.produces = response.produces;
  390. if (response.consumes != null)
  391. this.consumes = response.consumes;
  392. if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0)
  393. this.basePath = response.basePath.indexOf("http") === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
  394. this.addModels(response.models);
  395. if (response.apis) {
  396. for (var i = 0 ; i < response.apis.length; i++) {
  397. var endpoint = response.apis[i];
  398. this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
  399. }
  400. }
  401. this.api[this.name] = this;
  402. this.ready = true;
  403. return this.api.selfReflect();
  404. };
  405. SwaggerResource.prototype.addModels = function (models) {
  406. if (models != null) {
  407. var modelName;
  408. for (modelName in models) {
  409. if (this.models[modelName] == null) {
  410. var swaggerModel = new SwaggerModel(modelName, models[modelName]);
  411. this.modelsArray.push(swaggerModel);
  412. this.models[modelName] = swaggerModel;
  413. this.rawModels[modelName] = models[modelName];
  414. }
  415. }
  416. var output = [];
  417. for (var i = 0; i < this.modelsArray.length; i++) {
  418. var model = this.modelsArray[i];
  419. output.push(model.setReferencedModels(this.models));
  420. }
  421. return output;
  422. }
  423. };
  424. SwaggerResource.prototype.addOperations = function (resource_path, ops, consumes, produces) {
  425. if (ops) {
  426. var output = [];
  427. for (var i = 0; i < ops.length; i++) {
  428. var o = ops[i];
  429. consumes = this.consumes;
  430. produces = this.produces;
  431. if (o.consumes != null)
  432. consumes = o.consumes;
  433. else
  434. consumes = this.consumes;
  435. if (o.produces != null)
  436. produces = o.produces;
  437. else
  438. produces = this.produces;
  439. var type = (o.type || o.responseClass);
  440. if (type === "array") {
  441. ref = null;
  442. if (o.items)
  443. ref = o.items["type"] || o.items["$ref"];
  444. type = "array[" + ref + "]";
  445. }
  446. var responseMessages = o.responseMessages;
  447. var method = o.method;
  448. if (o.httpMethod) {
  449. method = o.httpMethod;
  450. }
  451. if (o.supportedContentTypes) {
  452. consumes = o.supportedContentTypes;
  453. }
  454. if (o.errorResponses) {
  455. responseMessages = o.errorResponses;
  456. for (var j = 0; j < responseMessages.length; j++) {
  457. r = responseMessages[j];
  458. r.message = r.reason;
  459. r.reason = null;
  460. }
  461. }
  462. o.nickname = this.sanitize(o.nickname);
  463. var op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, type, responseMessages, this, consumes, produces, o.authorizations, o.deprecated);
  464. this.operations[op.nickname] = op;
  465. output.push(this.operationsArray.push(op));
  466. }
  467. return output;
  468. }
  469. };
  470. SwaggerResource.prototype.sanitize = function (nickname) {
  471. var op;
  472. op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
  473. op = op.replace(/((_){2,})/g, '_');
  474. op = op.replace(/^(_)*/g, '');
  475. op = op.replace(/([_])*$/g, '');
  476. return op;
  477. };
  478. SwaggerResource.prototype.help = function () {
  479. var op = this.operations;
  480. var output = [];
  481. var operation_name;
  482. for (operation_name in op) {
  483. operation = op[operation_name];
  484. var msg = " " + operation.nickname;
  485. for (var i = 0; i < operation.parameters; i++) {
  486. parameter = operation.parameters[i];
  487. msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description);
  488. }
  489. output.push(msg);
  490. }
  491. return output;
  492. };
  493. var SwaggerModel = function (modelName, obj) {
  494. this.name = obj.id != null ? obj.id : modelName;
  495. this.properties = [];
  496. var propertyName;
  497. for (propertyName in obj.properties) {
  498. if (obj.required != null) {
  499. var value;
  500. for (value in obj.required) {
  501. if (propertyName === obj.required[value]) {
  502. obj.properties[propertyName].required = true;
  503. }
  504. }
  505. }
  506. var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName]);
  507. this.properties.push(prop);
  508. }
  509. }
  510. SwaggerModel.prototype.setReferencedModels = function (allModels) {
  511. var results = [];
  512. for (var i = 0; i < this.properties.length; i++) {
  513. var property = this.properties[i];
  514. var type = property.type || property.dataType;
  515. if (allModels[type] != null)
  516. results.push(property.refModel = allModels[type]);
  517. else if ((property.refDataType != null) && (allModels[property.refDataType] != null))
  518. results.push(property.refModel = allModels[property.refDataType]);
  519. else
  520. results.push(void 0);
  521. }
  522. return results;
  523. };
  524. SwaggerModel.prototype.getMockSignature = function (modelsToIgnore) {
  525. var propertiesStr = [];
  526. for (var i = 0; i < this.properties.length; i++) {
  527. var prop = this.properties[i];
  528. propertiesStr.push(prop.toString());
  529. }
  530. var strong = '<span class="strong">';
  531. var stronger = '<span class="stronger">';
  532. var strongClose = '</span>';
  533. var classOpen = strong + this.name + ' {' + strongClose;
  534. var classClose = strong + '}' + strongClose;
  535. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  536. if (!modelsToIgnore)
  537. modelsToIgnore = [];
  538. modelsToIgnore.push(this.name);
  539. for (var i = 0; i < this.properties.length; i++) {
  540. var prop = this.properties[i];
  541. if ((prop.refModel != null) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
  542. returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
  543. }
  544. }
  545. return returnVal;
  546. };
  547. SwaggerModel.prototype.createJSONSample = function (modelsToIgnore) {
  548. if (sampleModels[this.name]) {
  549. return sampleModels[this.name];
  550. }
  551. else {
  552. var result = {};
  553. var modelsToIgnore = (modelsToIgnore || [])
  554. modelsToIgnore.push(this.name);
  555. for (var i = 0; i < this.properties.length; i++) {
  556. var prop = this.properties[i];
  557. result[prop.name] = prop.getSampleValue(modelsToIgnore);
  558. }
  559. modelsToIgnore.pop(this.name);
  560. return result;
  561. }
  562. };
  563. var SwaggerModelProperty = function (name, obj) {
  564. this.name = name;
  565. this.dataType = obj.type || obj.dataType || obj["$ref"];
  566. this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
  567. this.descr = obj.description;
  568. this.required = obj.required;
  569. this.defaultValue = modelPropertyMacro(obj.defaultValue);
  570. if (obj.items != null) {
  571. if (obj.items.type != null) {
  572. this.refDataType = obj.items.type;
  573. }
  574. if (obj.items.$ref != null) {
  575. this.refDataType = obj.items.$ref;
  576. }
  577. }
  578. this.dataTypeWithRef = this.refDataType != null ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
  579. if (obj.allowableValues != null) {
  580. this.valueType = obj.allowableValues.valueType;
  581. this.values = obj.allowableValues.values;
  582. if (this.values != null) {
  583. this.valuesString = "'" + this.values.join("' or '") + "'";
  584. }
  585. }
  586. if (obj["enum"] != null) {
  587. this.valueType = "string";
  588. this.values = obj["enum"];
  589. if (this.values != null) {
  590. this.valueString = "'" + this.values.join("' or '") + "'";
  591. }
  592. }
  593. }
  594. SwaggerModelProperty.prototype.getSampleValue = function (modelsToIgnore) {
  595. var result;
  596. if ((this.refModel != null) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) {
  597. result = this.refModel.createJSONSample(modelsToIgnore);
  598. } else {
  599. if (this.isCollection) {
  600. result = this.toSampleValue(this.refDataType);
  601. } else {
  602. result = this.toSampleValue(this.dataType);
  603. }
  604. }
  605. if (this.isCollection) {
  606. return [result];
  607. } else {
  608. return result;
  609. }
  610. };
  611. SwaggerModelProperty.prototype.toSampleValue = function (value) {
  612. var result;
  613. if ((typeof this.defaultValue !== 'undefined') && this.defaultValue !== null) {
  614. result = this.defaultValue;
  615. } else if (value === "integer") {
  616. result = 0;
  617. } else if (value === "boolean") {
  618. result = false;
  619. } else if (value === "double" || value === "number") {
  620. result = 0.0;
  621. } else if (value === "string") {
  622. result = "";
  623. } else {
  624. result = value;
  625. }
  626. return result;
  627. };
  628. SwaggerModelProperty.prototype.toString = function () {
  629. var req = this.required ? 'propReq' : 'propOpt';
  630. var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
  631. if (!this.required) {
  632. str += ', <span class="propOptKey">optional</span>';
  633. }
  634. str += ')';
  635. if (this.values != null) {
  636. str += " = <span class='propVals'>['" + this.values.join("' or '") + "']</span>";
  637. }
  638. if (this.descr != null) {
  639. str += ': <span class="propDesc">' + this.descr + '</span>';
  640. }
  641. return str;
  642. };
  643. var SwaggerOperation = function (nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations, deprecated) {
  644. var _this = this;
  645. var errors = [];
  646. this.nickname = (nickname || errors.push("SwaggerOperations must have a nickname."));
  647. this.path = (path || errors.push("SwaggerOperation " + nickname + " is missing path."));
  648. this.method = (method || errors.push("SwaggerOperation " + nickname + " is missing method."));
  649. this.parameters = parameters != null ? parameters : [];
  650. this.summary = summary;
  651. this.notes = notes;
  652. this.type = type;
  653. this.responseMessages = (responseMessages || []);
  654. this.resource = (resource || errors.push("Resource is required"));
  655. this.consumes = consumes;
  656. this.produces = produces;
  657. this.authorizations = authorizations;
  658. this.deprecated = deprecated;
  659. this["do"] = __bind(this["do"], this);
  660. if (errors.length > 0) {
  661. console.error('SwaggerOperation errors', errors, arguments);
  662. this.resource.api.fail(errors);
  663. }
  664. this.path = this.path.replace('{format}', 'json');
  665. this.method = this.method.toLowerCase();
  666. this.isGetMethod = this.method === "get";
  667. this.resourceName = this.resource.name;
  668. if (typeof this.type !== 'undefined' && this.type === 'void')
  669. this.type = null;
  670. else {
  671. this.responseClassSignature = this.getSignature(this.type, this.resource.models);
  672. this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
  673. }
  674. for (var i = 0; i < this.parameters.length; i++) {
  675. var param = this.parameters[i];
  676. // might take this away
  677. param.name = param.name || param.type || param.dataType;
  678. // for 1.1 compatibility
  679. var type = param.type || param.dataType;
  680. if (type === 'array') {
  681. type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
  682. }
  683. param.type = type;
  684. if (type && type.toLowerCase() === 'boolean') {
  685. param.allowableValues = {};
  686. param.allowableValues.values = ["true", "false"];
  687. }
  688. param.signature = this.getSignature(type, this.resource.models);
  689. param.sampleJSON = this.getSampleJSON(type, this.resource.models);
  690. var enumValue = param["enum"];
  691. if (enumValue != null) {
  692. param.isList = true;
  693. param.allowableValues = {};
  694. param.allowableValues.descriptiveValues = [];
  695. for (var j = 0; j < enumValue.length; j++) {
  696. var v = enumValue[j];
  697. if (param.defaultValue != null) {
  698. param.allowableValues.descriptiveValues.push({
  699. value: String(v),
  700. isDefault: (v === param.defaultValue)
  701. });
  702. }
  703. else {
  704. param.allowableValues.descriptiveValues.push({
  705. value: String(v),
  706. isDefault: false
  707. });
  708. }
  709. }
  710. }
  711. else if (param.allowableValues != null) {
  712. if (param.allowableValues.valueType === "RANGE")
  713. param.isRange = true;
  714. else
  715. param.isList = true;
  716. if (param.allowableValues != null) {
  717. param.allowableValues.descriptiveValues = [];
  718. if (param.allowableValues.values) {
  719. for (var j = 0; j < param.allowableValues.values.length; j++) {
  720. var v = param.allowableValues.values[j];
  721. if (param.defaultValue != null) {
  722. param.allowableValues.descriptiveValues.push({
  723. value: String(v),
  724. isDefault: (v === param.defaultValue)
  725. });
  726. }
  727. else {
  728. param.allowableValues.descriptiveValues.push({
  729. value: String(v),
  730. isDefault: false
  731. });
  732. }
  733. }
  734. }
  735. }
  736. }
  737. param.defaultValue = parameterMacro(param.defaultValue);
  738. }
  739. this.resource[this.nickname] = function (args, callback, error) {
  740. return _this["do"](args, callback, error);
  741. };
  742. this.resource[this.nickname].help = function () {
  743. return _this.help();
  744. };
  745. }
  746. SwaggerOperation.prototype.isListType = function (type) {
  747. if (type && type.indexOf('[') >= 0) {
  748. return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
  749. } else {
  750. return void 0;
  751. }
  752. };
  753. SwaggerOperation.prototype.getSignature = function (type, models) {
  754. var isPrimitive, listType;
  755. listType = this.isListType(type);
  756. isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
  757. if (isPrimitive) {
  758. return type;
  759. } else {
  760. if (listType != null) {
  761. return models[listType].getMockSignature();
  762. } else {
  763. return models[type].getMockSignature();
  764. }
  765. }
  766. };
  767. SwaggerOperation.prototype.getSampleJSON = function (type, models) {
  768. var isPrimitive, listType, val;
  769. listType = this.isListType(type);
  770. isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
  771. val = isPrimitive ? void 0 : (listType != null ? models[listType].createJSONSample() : models[type].createJSONSample());
  772. if (val) {
  773. val = listType ? [val] : val;
  774. if (typeof val == "string")
  775. return val;
  776. else if (typeof val === "object") {
  777. var t = val;
  778. if (val instanceof Array && val.length > 0) {
  779. t = val[0];
  780. }
  781. if (t.nodeName) {
  782. var xmlString = new XMLSerializer().serializeToString(t);
  783. return this.formatXml(xmlString);
  784. }
  785. else
  786. return JSON.stringify(val, null, 2);
  787. }
  788. else
  789. return val;
  790. }
  791. };
  792. SwaggerOperation.prototype["do"] = function (args, opts, callback, error) {
  793. var key, param, params, possibleParams, req, requestContentType, responseContentType, value, _i, _len, _ref;
  794. if (args == null) {
  795. args = {};
  796. }
  797. if (opts == null) {
  798. opts = {};
  799. }
  800. requestContentType = null;
  801. responseContentType = null;
  802. if ((typeof args) === "function") {
  803. error = opts;
  804. callback = args;
  805. args = {};
  806. }
  807. if ((typeof opts) === "function") {
  808. error = callback;
  809. callback = opts;
  810. }
  811. if (error == null) {
  812. error = function (xhr, textStatus, error) {
  813. return log(xhr, textStatus, error);
  814. };
  815. }
  816. if (callback == null) {
  817. callback = function (response) {
  818. var content;
  819. content = null;
  820. if (response != null) {
  821. content = response.data;
  822. } else {
  823. content = "no data";
  824. }
  825. return log("default callback: " + content);
  826. };
  827. }
  828. params = {};
  829. params.headers = [];
  830. if (args.headers != null) {
  831. params.headers = args.headers;
  832. delete args.headers;
  833. }
  834. var possibleParams = [];
  835. for (var i = 0; i < this.parameters.length; i++) {
  836. var param = this.parameters[i];
  837. if (param.paramType === 'header') {
  838. if (args[param.name])
  839. params.headers[param.name] = args[param.name];
  840. }
  841. else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
  842. possibleParams.push(param);
  843. else if (param.paramType === 'body' && param.name !== 'body') {
  844. if (args.body) {
  845. throw new Error("Saw two body params in an API listing; expecting a max of one.");
  846. }
  847. args.body = args[param.name];
  848. }
  849. }
  850. if (args.body != null) {
  851. params.body = args.body;
  852. delete args.body;
  853. }
  854. if (possibleParams) {
  855. var key;
  856. for (key in possibleParams) {
  857. var value = possibleParams[key];
  858. if (args[value.name]) {
  859. params[value.name] = args[value.name];
  860. }
  861. }
  862. }
  863. req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
  864. if (opts.mock != null) {
  865. return req;
  866. } else {
  867. return true;
  868. }
  869. };
  870. SwaggerOperation.prototype.pathJson = function () {
  871. return this.path.replace("{format}", "json");
  872. };
  873. SwaggerOperation.prototype.pathXml = function () {
  874. return this.path.replace("{format}", "xml");
  875. };
  876. SwaggerOperation.prototype.encodePathParam = function (pathParam) {
  877. var encParts, part, parts, _i, _len;
  878. pathParam = pathParam.toString();
  879. if (pathParam.indexOf("/") === -1) {
  880. return encodeURIComponent(pathParam);
  881. } else {
  882. parts = pathParam.split("/");
  883. encParts = [];
  884. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  885. part = parts[_i];
  886. encParts.push(encodeURIComponent(part));
  887. }
  888. return encParts.join("/");
  889. }
  890. };
  891. SwaggerOperation.prototype.urlify = function (args) {
  892. var url = this.resource.basePath + this.pathJson();
  893. var params = this.parameters;
  894. for (var i = 0; i < params.length; i++) {
  895. var param = params[i];
  896. if (param.paramType === 'path') {
  897. if (args[param.name]) {
  898. // apply path params and remove from args
  899. var reg = new RegExp('\\{\\s*?' + param.name + '.*?\\}(?=\\s*?(\\/?|$))', 'gi');
  900. url = url.replace(reg, this.encodePathParam(args[param.name]));
  901. delete args[param.name];
  902. }
  903. else
  904. throw "" + param.name + " is a required path param.";
  905. }
  906. }
  907. var queryParams = "";
  908. for (var i = 0; i < params.length; i++) {
  909. var param = params[i];
  910. if(param.paramType === 'query') {
  911. if (queryParams !== '')
  912. queryParams += '&';
  913. if (Array.isArray(param)) {
  914. var j;
  915. var output = '';
  916. for(j = 0; j < param.length; j++) {
  917. if(j > 0)
  918. output += ',';
  919. output += encodeURIComponent(param[j]);
  920. }
  921. queryParams += encodeURIComponent(param.name) + '=' + output;
  922. }
  923. else {
  924. if (args[param.name]) {
  925. queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
  926. } else {
  927. if (param.required)
  928. throw "" + param.name + " is a required query param.";
  929. }
  930. }
  931. }
  932. }
  933. if ((queryParams != null) && queryParams.length > 0)
  934. url += '?' + queryParams;
  935. return url;
  936. };
  937. SwaggerOperation.prototype.supportHeaderParams = function () {
  938. return this.resource.api.supportHeaderParams;
  939. };
  940. SwaggerOperation.prototype.supportedSubmitMethods = function () {
  941. return this.resource.api.supportedSubmitMethods;
  942. };
  943. SwaggerOperation.prototype.getQueryParams = function (args) {
  944. return this.getMatchingParams(['query'], args);
  945. };
  946. SwaggerOperation.prototype.getHeaderParams = function (args) {
  947. return this.getMatchingParams(['header'], args);
  948. };
  949. SwaggerOperation.prototype.getMatchingParams = function (paramTypes, args) {
  950. var matchingParams = {};
  951. var params = this.parameters;
  952. for (var i = 0; i < params.length; i++) {
  953. param = params[i];
  954. if (args && args[param.name])
  955. matchingParams[param.name] = args[param.name];
  956. }
  957. var headers = this.resource.api.headers;
  958. var name;
  959. for (name in headers) {
  960. var value = headers[name];
  961. matchingParams[name] = value;
  962. }
  963. return matchingParams;
  964. };
  965. SwaggerOperation.prototype.help = function () {
  966. var msg = "";
  967. var params = this.parameters;
  968. for (var i = 0; i < params.length; i++) {
  969. var param = params[i];
  970. if (msg !== "")
  971. msg += "\n";
  972. msg += "* " + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
  973. }
  974. return msg;
  975. };
  976. SwaggerOperation.prototype.formatXml = function (xml) {
  977. var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
  978. reg = /(>)(<)(\/*)/g;
  979. wsexp = /[ ]*(.*)[ ]+\n/g;
  980. contexp = /(<.+>)(.+\n)/g;
  981. xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
  982. pad = 0;
  983. formatted = '';
  984. lines = xml.split('\n');
  985. indent = 0;
  986. lastType = 'other';
  987. transitions = {
  988. 'single->single': 0,
  989. 'single->closing': -1,
  990. 'single->opening': 0,
  991. 'single->other': 0,
  992. 'closing->single': 0,
  993. 'closing->closing': -1,
  994. 'closing->opening': 0,
  995. 'closing->other': 0,
  996. 'opening->single': 1,
  997. 'opening->closing': 0,
  998. 'opening->opening': 1,
  999. 'opening->other': 1,
  1000. 'other->single': 0,
  1001. 'other->closing': -1,
  1002. 'other->opening': 0,
  1003. 'other->other': 0
  1004. };
  1005. _fn = function (ln) {
  1006. var fromTo, j, key, padding, type, types, value;
  1007. types = {
  1008. single: Boolean(ln.match(/<.+\/>/)),
  1009. closing: Boolean(ln.match(/<\/.+>/)),
  1010. opening: Boolean(ln.match(/<[^!?].*>/))
  1011. };
  1012. type = ((function () {
  1013. var _results;
  1014. _results = [];
  1015. for (key in types) {
  1016. value = types[key];
  1017. if (value) {
  1018. _results.push(key);
  1019. }
  1020. }
  1021. return _results;
  1022. })())[0];
  1023. type = type === void 0 ? 'other' : type;
  1024. fromTo = lastType + '->' + type;
  1025. lastType = type;
  1026. padding = '';
  1027. indent += transitions[fromTo];
  1028. padding = ((function () {
  1029. var _j, _ref5, _results;
  1030. _results = [];
  1031. for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
  1032. _results.push(' ');
  1033. }
  1034. return _results;
  1035. })()).join('');
  1036. if (fromTo === 'opening->closing') {
  1037. return formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
  1038. } else {
  1039. return formatted += padding + ln + '\n';
  1040. }
  1041. };
  1042. for (_i = 0, _len = lines.length; _i < _len; _i++) {
  1043. ln = lines[_i];
  1044. _fn(ln);
  1045. }
  1046. return formatted;
  1047. };
  1048. var SwaggerRequest = function (type, url, params, opts, successCallback, errorCallback, operation, execution) {
  1049. var _this = this;
  1050. var errors = [];
  1051. this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
  1052. this.type = (type || errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options)."));
  1053. this.url = (url || errors.push("SwaggerRequest url is required."));
  1054. this.params = params;
  1055. this.opts = opts;
  1056. this.successCallback = (successCallback || errors.push("SwaggerRequest successCallback is required."));
  1057. this.errorCallback = (errorCallback || errors.push("SwaggerRequest error callback is required."));
  1058. this.operation = (operation || errors.push("SwaggerRequest operation is required."));
  1059. this.execution = execution;
  1060. this.headers = (params.headers || {});
  1061. if (errors.length > 0) {
  1062. throw errors;
  1063. }
  1064. this.type = this.type.toUpperCase();
  1065. // set request, response content type headers
  1066. var headers = this.setHeaders(params, this.operation);
  1067. var body = params.body;
  1068. // encode the body for form submits
  1069. if (headers["Content-Type"]) {
  1070. var values = {};
  1071. var i;
  1072. var operationParams = this.operation.parameters;
  1073. for (i = 0; i < operationParams.length; i++) {
  1074. var param = operationParams[i];
  1075. if (param.paramType === "form")
  1076. values[param.name] = param;
  1077. }
  1078. if (headers["Content-Type"].indexOf("application/x-www-form-urlencoded") === 0) {
  1079. var encoded = "";
  1080. var key, value;
  1081. for (key in values) {
  1082. value = this.params[key];
  1083. if (typeof value !== 'undefined') {
  1084. if (encoded !== "")
  1085. encoded += "&";
  1086. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  1087. }
  1088. }
  1089. body = encoded;
  1090. }
  1091. else if (headers["Content-Type"].indexOf("multipart/form-data") === 0) {
  1092. // encode the body for form submits
  1093. var data = "";
  1094. var boundary = "----SwaggerFormBoundary" + Date.now();
  1095. var key, value;
  1096. for (key in values) {
  1097. value = this.params[key];
  1098. if (typeof value !== 'undefined') {
  1099. data += '--' + boundary + '\n';
  1100. data += 'Content-Disposition: form-data; name="' + key + '"';
  1101. data += '\n\n';
  1102. data += value + "\n";
  1103. }
  1104. }
  1105. data += "--" + boundary + "--\n";
  1106. headers["Content-Type"] = "multipart/form-data; boundary=" + boundary;
  1107. body = data;
  1108. }
  1109. }
  1110. var obj;
  1111. if (!((this.headers != null) && (this.headers.mock != null))) {
  1112. obj = {
  1113. url: this.url,
  1114. method: this.type,
  1115. headers: headers,
  1116. body: body,
  1117. useJQuery: this.useJQuery,
  1118. on: {
  1119. error: function (response) {
  1120. return _this.errorCallback(response, _this.opts.parent);
  1121. },
  1122. redirect: function (response) {
  1123. return _this.successCallback(response, _this.opts.parent);
  1124. },
  1125. 307: function (response) {
  1126. return _this.successCallback(response, _this.opts.parent);
  1127. },
  1128. response: function (response) {
  1129. return _this.successCallback(response, _this.opts.parent);
  1130. }
  1131. }
  1132. };
  1133. var e;
  1134. if (typeof window !== 'undefined') {
  1135. e = window;
  1136. } else {
  1137. e = exports;
  1138. }
  1139. var status = e.authorizations.apply(obj, this.operation.authorizations);
  1140. if (opts.mock == null) {
  1141. if (status !== false) {
  1142. new SwaggerHttp().execute(obj);
  1143. } else {
  1144. obj.canceled = true;
  1145. }
  1146. } else {
  1147. return obj;
  1148. }
  1149. }
  1150. return obj;
  1151. };
  1152. SwaggerRequest.prototype.setHeaders = function (params, operation) {
  1153. // default type
  1154. var accepts = "application/json";
  1155. var consumes = "application/json";
  1156. var allDefinedParams = this.operation.parameters;
  1157. var definedFormParams = [];
  1158. var definedFileParams = [];
  1159. var body = params.body;
  1160. var headers = {};
  1161. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  1162. var i;
  1163. for (i = 0; i < allDefinedParams.length; i++) {
  1164. var param = allDefinedParams[i];
  1165. if (param.paramType === "form")
  1166. definedFormParams.push(param);
  1167. else if (param.paramType === "file")
  1168. definedFileParams.push(param);
  1169. else if (param.paramType === "header" && this.params.headers) {
  1170. var key = param.name;
  1171. var headerValue = this.params.headers[param.name];
  1172. if (typeof this.params.headers[param.name] !== 'undefined')
  1173. headers[key] = headerValue;
  1174. }
  1175. }
  1176. // if there's a body, need to set the accepts header via requestContentType
  1177. if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH" || this.type === "DELETE")) {
  1178. if (this.opts.requestContentType)
  1179. consumes = this.opts.requestContentType;
  1180. } else {
  1181. // if any form params, content type must be set
  1182. if (definedFormParams.length > 0) {
  1183. if (definedFileParams.length > 0)
  1184. consumes = "multipart/form-data";
  1185. else
  1186. consumes = "application/x-www-form-urlencoded";
  1187. }
  1188. else if (this.type === "DELETE")
  1189. body = "{}";
  1190. else if (this.type != "DELETE")
  1191. consumes = null;
  1192. }
  1193. if (consumes && this.operation.consumes) {
  1194. if (this.operation.consumes.indexOf(consumes) === -1) {
  1195. log("server doesn't consume " + consumes + ", try " + JSON.stringify(this.operation.consumes));
  1196. consumes = this.operation.consumes[0];
  1197. }
  1198. }
  1199. if (this.opts.responseContentType) {
  1200. accepts = this.opts.responseContentType;
  1201. } else {
  1202. accepts = "application/json";
  1203. }
  1204. if (accepts && this.operation.produces) {
  1205. if (this.operation.produces.indexOf(accepts) === -1) {
  1206. log("server can't produce " + accepts);
  1207. accepts = this.operation.produces[0];
  1208. }
  1209. }
  1210. if ((consumes && body !== "") || (consumes === "application/x-www-form-urlencoded"))
  1211. headers["Content-Type"] = consumes;
  1212. if (accepts)
  1213. headers["Accept"] = accepts;
  1214. return headers;
  1215. }
  1216. SwaggerRequest.prototype.asCurl = function () {
  1217. var results = [];
  1218. if (this.headers) {
  1219. var key;
  1220. for (key in this.headers) {
  1221. results.push("--header \"" + key + ": " + this.headers[v] + "\"");
  1222. }
  1223. }
  1224. return "curl " + (results.join(" ")) + " " + this.url;
  1225. };
  1226. /**
  1227. * SwaggerHttp is a wrapper for executing requests
  1228. */
  1229. var SwaggerHttp = function () { };
  1230. SwaggerHttp.prototype.execute = function (obj) {
  1231. if (obj && (typeof obj.useJQuery === 'boolean'))
  1232. this.useJQuery = obj.useJQuery;
  1233. else
  1234. this.useJQuery = this.isIE8();
  1235. if (this.useJQuery)
  1236. return new JQueryHttpClient().execute(obj);
  1237. else
  1238. return new ShredHttpClient().execute(obj);
  1239. }
  1240. SwaggerHttp.prototype.isIE8 = function () {
  1241. var detectedIE = false;
  1242. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1243. nav = navigator.userAgent.toLowerCase();
  1244. if (nav.indexOf('msie') !== -1) {
  1245. var version = parseInt(nav.split('msie')[1]);
  1246. if (version <= 8) {
  1247. detectedIE = true;
  1248. }
  1249. }
  1250. }
  1251. return detectedIE;
  1252. };
  1253. /*
  1254. * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
  1255. * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
  1256. * Since we are using closures here we need to alias it for internal use.
  1257. */
  1258. var JQueryHttpClient = function (options) {
  1259. "use strict";
  1260. if (!jQuery) {
  1261. var jQuery = window.jQuery;
  1262. }
  1263. }
  1264. JQueryHttpClient.prototype.execute = function (obj) {
  1265. var cb = obj.on;
  1266. var request = obj;
  1267. obj.type = obj.method;
  1268. obj.cache = false;
  1269. obj.beforeSend = function (xhr) {
  1270. var key, results;
  1271. if (obj.headers) {
  1272. results = [];
  1273. var key;
  1274. for (key in obj.headers) {
  1275. if (key.toLowerCase() === "content-type") {
  1276. results.push(obj.contentType = obj.headers[key]);
  1277. } else if (key.toLowerCase() === "accept") {
  1278. results.push(obj.accepts = obj.headers[key]);
  1279. } else {
  1280. results.push(xhr.setRequestHeader(key, obj.headers[key]));
  1281. }
  1282. }
  1283. return results;
  1284. }
  1285. };
  1286. obj.data = obj.body;
  1287. obj.complete = function (response, textStatus, opts) {
  1288. var headers = {},
  1289. headerArray = response.getAllResponseHeaders().split("\n");
  1290. for (var i = 0; i < headerArray.length; i++) {
  1291. var toSplit = headerArray[i].trim();
  1292. if (toSplit.length === 0)
  1293. continue;
  1294. var separator = toSplit.indexOf(":");
  1295. if (separator === -1) {
  1296. // Name but no value in the header
  1297. headers[toSplit] = null;
  1298. continue;
  1299. }
  1300. var name = toSplit.substring(0, separator).trim(),
  1301. value = toSplit.substring(separator + 1).trim();
  1302. headers[name] = value;
  1303. }
  1304. var out = {
  1305. url: request.url,
  1306. method: request.method,
  1307. status: response.status,
  1308. data: response.responseText,
  1309. headers: headers
  1310. };
  1311. var contentType = (headers["content-type"] || headers["Content-Type"] || null)
  1312. if (contentType != null) {
  1313. if (contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1314. if (response.responseText && response.responseText !== "")
  1315. out.obj = JSON.parse(response.responseText);
  1316. else
  1317. out.obj = {}
  1318. }
  1319. }
  1320. if (response.status >= 200 && response.status < 300)
  1321. cb.response(out);
  1322. else if (response.status === 0 || (response.status >= 400 && response.status < 599))
  1323. cb.error(out);
  1324. else
  1325. return cb.response(out);
  1326. };
  1327. jQuery.support.cors = true;
  1328. return jQuery.ajax(obj);
  1329. }
  1330. /*
  1331. * ShredHttpClient is a light-weight, node or browser HTTP client
  1332. */
  1333. var ShredHttpClient = function (options) {
  1334. this.options = (options || {});
  1335. this.isInitialized = false;
  1336. var identity, toString;
  1337. if (typeof window !== 'undefined') {
  1338. this.Shred = require("./shred");
  1339. this.content = require("./shred/content");
  1340. }
  1341. else
  1342. this.Shred = require("shred");
  1343. this.shred = new this.Shred();
  1344. }
  1345. ShredHttpClient.prototype.initShred = function () {
  1346. this.isInitialized = true;
  1347. this.registerProcessors(this.shred);
  1348. }
  1349. ShredHttpClient.prototype.registerProcessors = function (shred) {
  1350. var identity = function (x) {
  1351. return x;
  1352. };
  1353. var toString = function (x) {
  1354. return x.toString();
  1355. };
  1356. if (typeof window !== 'undefined') {
  1357. this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1358. parser: identity,
  1359. stringify: toString
  1360. });
  1361. } else {
  1362. this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  1363. parser: identity,
  1364. stringify: toString
  1365. });
  1366. }
  1367. }
  1368. ShredHttpClient.prototype.execute = function (obj) {
  1369. if (!this.isInitialized)
  1370. this.initShred();
  1371. var cb = obj.on, res;
  1372. var transform = function (response) {
  1373. var out = {
  1374. headers: response._headers,
  1375. url: response.request.url,
  1376. method: response.request.method,
  1377. status: response.status,
  1378. data: response.content.data
  1379. };
  1380. var headers = response._headers.normalized || response._headers;
  1381. var contentType = (headers["content-type"] || headers["Content-Type"] || null)
  1382. if (contentType != null) {
  1383. if (contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
  1384. if (response.content.data && response.content.data !== "")
  1385. out.obj = JSON.parse(response.content.data);
  1386. else
  1387. out.obj = {}
  1388. }
  1389. }
  1390. return out;
  1391. };
  1392. // Transform an error into a usable response-like object
  1393. var transformError = function (error) {
  1394. var out = {
  1395. // Default to a status of 0 - The client will treat this as a generic permissions sort of error
  1396. status: 0,
  1397. data: error.message || error
  1398. };
  1399. if (error.code) {
  1400. out.obj = error;
  1401. if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
  1402. // We can tell the client that this should be treated as a missing resource and not as a permissions thing
  1403. out.status = 404;
  1404. }
  1405. }
  1406. return out;
  1407. };
  1408. var res = {
  1409. error: function (response) {
  1410. if (obj)
  1411. return cb.error(transform(response));
  1412. },
  1413. // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
  1414. request_error: function (err) {
  1415. if (obj)
  1416. return cb.error(transformError(err));
  1417. },
  1418. redirect: function (response) {
  1419. if (obj)
  1420. return cb.redirect(transform(response));
  1421. },
  1422. 307: function (response) {
  1423. if (obj)
  1424. return cb.redirect(transform(response));
  1425. },
  1426. response: function (response) {
  1427. if (obj)
  1428. return cb.response(transform(response));
  1429. }
  1430. };
  1431. if (obj) {
  1432. obj.on = res;
  1433. }
  1434. return this.shred.request(obj);
  1435. };
  1436. /**
  1437. * SwaggerAuthorizations applys the correct authorization to an operation being executed
  1438. */
  1439. var SwaggerAuthorizations = function () {
  1440. this.authz = {};
  1441. };
  1442. SwaggerAuthorizations.prototype.add = function (name, auth) {
  1443. this.authz[name] = auth;
  1444. return auth;
  1445. };
  1446. SwaggerAuthorizations.prototype.remove = function (name) {
  1447. return delete this.authz[name];
  1448. };
  1449. SwaggerAuthorizations.prototype.apply = function (obj, authorizations) {
  1450. var status = null;
  1451. var key, value, result;
  1452. // if the "authorizations" key is undefined, or has an empty array, add all keys
  1453. if (typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
  1454. for (key in this.authz) {
  1455. value = this.authz[key];
  1456. result = value.apply(obj, authorizations);
  1457. if (result === true)
  1458. status = true;
  1459. }
  1460. }
  1461. else {
  1462. for (name in authorizations) {
  1463. for (key in this.authz) {
  1464. if (key == name) {
  1465. value = this.authz[key];
  1466. result = value.apply(obj, authorizations);
  1467. if (result === true)
  1468. status = true;
  1469. }
  1470. }
  1471. }
  1472. }
  1473. return status;
  1474. };
  1475. /**
  1476. * ApiKeyAuthorization allows a query param or header to be injected
  1477. */
  1478. var ApiKeyAuthorization = function (name, value, type, delimiter) {
  1479. this.name = name;
  1480. this.value = value;
  1481. this.type = type;
  1482. this.delimiter = delimiter;
  1483. };
  1484. ApiKeyAuthorization.prototype.apply = function (obj, authorizations) {
  1485. if (this.type === "query") {
  1486. if (obj.url.indexOf('?') > 0)
  1487. obj.url = obj.url + "&" + this.name + "=" + this.value;
  1488. else
  1489. obj.url = obj.url + "?" + this.name + "=" + this.value;
  1490. return true;
  1491. } else if (this.type === "header") {
  1492. if (typeof obj.headers[this.name] !== 'undefined') {
  1493. if (typeof this.delimiter !== 'undefined')
  1494. obj.headers[this.name] = obj.headers[this.name] + this.delimiter + this.value;
  1495. }
  1496. else
  1497. obj.headers[this.name] = this.value;
  1498. return true;
  1499. }
  1500. };
  1501. var CookieAuthorization = function (cookie) {
  1502. this.cookie = cookie;
  1503. }
  1504. CookieAuthorization.prototype.apply = function (obj, authorizations) {
  1505. obj.cookieJar = obj.cookieJar || CookieJar();
  1506. obj.cookieJar.setCookie(this.cookie);
  1507. return true;
  1508. }
  1509. /**
  1510. * Password Authorization is a basic auth implementation
  1511. */
  1512. var PasswordAuthorization = function (name, username, password) {
  1513. this.name = name;
  1514. this.username = username;
  1515. this.password = password;
  1516. this._btoa = null;
  1517. if (typeof window !== 'undefined')
  1518. this._btoa = btoa;
  1519. else
  1520. this._btoa = require("btoa");
  1521. };
  1522. PasswordAuthorization.prototype.apply = function (obj, authorizations) {
  1523. var base64encoder = this._btoa;
  1524. obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
  1525. return true;
  1526. };
  1527. var e = (typeof window !== 'undefined' ? window : exports);
  1528. var sampleModels = {};
  1529. var cookies = {};
  1530. e.parameterMacro = parameterMacro;
  1531. e.modelPropertyMacro = modelPropertyMacro;
  1532. e.SampleModels = sampleModels;
  1533. e.SwaggerHttp = SwaggerHttp;
  1534. e.SwaggerRequest = SwaggerRequest;
  1535. e.authorizations = new SwaggerAuthorizations();
  1536. e.ApiKeyAuthorization = ApiKeyAuthorization;
  1537. e.PasswordAuthorization = PasswordAuthorization;
  1538. e.CookieAuthorization = CookieAuthorization;
  1539. e.JQueryHttpClient = JQueryHttpClient;
  1540. e.ShredHttpClient = ShredHttpClient;
  1541. e.SwaggerOperation = SwaggerOperation;
  1542. e.SwaggerModel = SwaggerModel;
  1543. e.SwaggerModelProperty = SwaggerModelProperty;
  1544. e.SwaggerResource = SwaggerResource;
  1545. e.SwaggerApi = SwaggerApi;
  1546. e.log = log;
  1547. })();