Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

3050 linhas
88 KiB

  1. /**
  2. * swagger-client - swagger.js is a javascript client for use with swaggering APIs.
  3. * @version v2.1.6-M1
  4. * @link http://swagger.io
  5. * @license apache 2.0
  6. */
  7. (function(){
  8. var ArrayModel = function(definition) {
  9. this.name = "arrayModel";
  10. this.definition = definition || {};
  11. this.properties = [];
  12. var requiredFields = definition.enum || [];
  13. var innerType = definition.items;
  14. if(innerType) {
  15. if(innerType.type) {
  16. this.type = typeFromJsonSchema(innerType.type, innerType.format);
  17. }
  18. else {
  19. this.ref = innerType.$ref;
  20. }
  21. }
  22. return this;
  23. };
  24. ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
  25. var result;
  26. modelsToIgnore = (modelsToIgnore||{});
  27. if(this.type) {
  28. result = this.type;
  29. }
  30. else if (this.ref) {
  31. var name = simpleRef(this.ref);
  32. if(typeof modelsToIgnore[name] === 'undefined') {
  33. modelsToIgnore[name] = this;
  34. result = models[name].createJSONSample(modelsToIgnore);
  35. }
  36. else {
  37. return name;
  38. }
  39. }
  40. return [ result ];
  41. };
  42. ArrayModel.prototype.getSampleValue = function(modelsToIgnore) {
  43. var result;
  44. modelsToIgnore = (modelsToIgnore || {});
  45. if(this.type) {
  46. result = type;
  47. }
  48. else if (this.ref) {
  49. var name = simpleRef(this.ref);
  50. result = models[name].getSampleValue(modelsToIgnore);
  51. }
  52. return [ result ];
  53. };
  54. ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
  55. var propertiesStr = [];
  56. var i, prop;
  57. for (i = 0; i < this.properties.length; i++) {
  58. prop = this.properties[i];
  59. propertiesStr.push(prop.toString());
  60. }
  61. var strong = '<span class="strong">';
  62. var stronger = '<span class="stronger">';
  63. var strongClose = '</span>';
  64. var classOpen = strong + 'array' + ' {' + strongClose;
  65. var classClose = strong + '}' + strongClose;
  66. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  67. if (!modelsToIgnore)
  68. modelsToIgnore = {};
  69. modelsToIgnore[this.name] = this;
  70. for (i = 0; i < this.properties.length; i++) {
  71. prop = this.properties[i];
  72. var ref = prop.$ref;
  73. var model = models[ref];
  74. if (model && typeof modelsToIgnore[ref] === 'undefined') {
  75. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  76. }
  77. }
  78. return returnVal;
  79. };
  80. /**
  81. * SwaggerAuthorizations applys the correct authorization to an operation being executed
  82. */
  83. var SwaggerAuthorizations = function() {
  84. this.authz = {};
  85. };
  86. SwaggerAuthorizations.prototype.add = function(name, auth) {
  87. this.authz[name] = auth;
  88. return auth;
  89. };
  90. SwaggerAuthorizations.prototype.remove = function(name) {
  91. return delete this.authz[name];
  92. };
  93. SwaggerAuthorizations.prototype.apply = function (obj, authorizations) {
  94. var status = null;
  95. var key, name, value, result;
  96. // if the "authorizations" key is undefined, or has an empty array, add all keys
  97. if (typeof authorizations === 'undefined' || Object.keys(authorizations).length === 0) {
  98. for (key in this.authz) {
  99. value = this.authz[key];
  100. result = value.apply(obj, authorizations);
  101. if (result === true)
  102. status = true;
  103. }
  104. }
  105. else {
  106. // 2.0 support
  107. if (Array.isArray(authorizations)) {
  108. for (var i = 0; i < authorizations.length; i++) {
  109. var auth = authorizations[i];
  110. for (name in auth) {
  111. for (key in this.authz) {
  112. if (key == name) {
  113. value = this.authz[key];
  114. result = value.apply(obj, authorizations);
  115. if (result === true)
  116. status = true;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else {
  123. // 1.2 support
  124. for (name in authorizations) {
  125. for (key in this.authz) {
  126. if (key == name) {
  127. value = this.authz[key];
  128. result = value.apply(obj, authorizations);
  129. if (result === true)
  130. status = true;
  131. }
  132. }
  133. }
  134. }
  135. }
  136. return status;
  137. };
  138. /**
  139. * ApiKeyAuthorization allows a query param or header to be injected
  140. */
  141. var ApiKeyAuthorization = function(name, value, type) {
  142. this.name = name;
  143. this.value = value;
  144. this.type = type;
  145. };
  146. ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
  147. if (this.type === "query") {
  148. if (obj.url.indexOf('?') > 0)
  149. obj.url = obj.url + "&" + this.name + "=" + this.value;
  150. else
  151. obj.url = obj.url + "?" + this.name + "=" + this.value;
  152. return true;
  153. } else if (this.type === "header") {
  154. obj.headers[this.name] = this.value;
  155. return true;
  156. }
  157. };
  158. var CookieAuthorization = function(cookie) {
  159. this.cookie = cookie;
  160. };
  161. CookieAuthorization.prototype.apply = function(obj, authorizations) {
  162. obj.cookieJar = obj.cookieJar || CookieJar();
  163. obj.cookieJar.setCookie(this.cookie);
  164. return true;
  165. };
  166. /**
  167. * Password Authorization is a basic auth implementation
  168. */
  169. var PasswordAuthorization = function(name, username, password) {
  170. this.name = name;
  171. this.username = username;
  172. this.password = password;
  173. this._btoa = null;
  174. if (typeof window !== 'undefined')
  175. this._btoa = btoa;
  176. else
  177. this._btoa = require("btoa");
  178. };
  179. PasswordAuthorization.prototype.apply = function(obj, authorizations) {
  180. var base64encoder = this._btoa;
  181. obj.headers.Authorization = "Basic " + base64encoder(this.username + ":" + this.password);
  182. return true;
  183. };
  184. var __bind = function(fn, me){
  185. return function(){
  186. return fn.apply(me, arguments);
  187. };
  188. };
  189. fail = function(message) {
  190. log(message);
  191. };
  192. log = function(){
  193. log.history = log.history || [];
  194. log.history.push(arguments);
  195. if(this.console){
  196. console.log( Array.prototype.slice.call(arguments)[0] );
  197. }
  198. };
  199. if (!Array.prototype.indexOf) {
  200. Array.prototype.indexOf = function(obj, start) {
  201. for (var i = (start || 0), j = this.length; i < j; i++) {
  202. if (this[i] === obj) { return i; }
  203. }
  204. return -1;
  205. };
  206. }
  207. /**
  208. * allows override of the default value based on the parameter being
  209. * supplied
  210. **/
  211. var applyParameterMacro = function (operation, parameter) {
  212. var e = (typeof window !== 'undefined' ? window : exports);
  213. if(e.parameterMacro)
  214. return e.parameterMacro(operation, parameter);
  215. else
  216. return parameter.defaultValue;
  217. };
  218. /**
  219. * allows overriding the default value of an model property
  220. **/
  221. var applyModelPropertyMacro = function (model, property) {
  222. var e = (typeof window !== 'undefined' ? window : exports);
  223. if(e.modelPropertyMacro)
  224. return e.modelPropertyMacro(model, property);
  225. else
  226. return property.defaultValue;
  227. };
  228. /**
  229. * PrimitiveModel
  230. **/
  231. var PrimitiveModel = function(definition) {
  232. this.name = "name";
  233. this.definition = definition || {};
  234. this.properties = [];
  235. var requiredFields = definition.enum || [];
  236. this.type = typeFromJsonSchema(definition.type, definition.format);
  237. };
  238. PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
  239. var result = this.type;
  240. return result;
  241. };
  242. PrimitiveModel.prototype.getSampleValue = function() {
  243. var result = this.type;
  244. return null;
  245. };
  246. PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
  247. var propertiesStr = [];
  248. var i, prop;
  249. for (i = 0; i < this.properties.length; i++) {
  250. prop = this.properties[i];
  251. propertiesStr.push(prop.toString());
  252. }
  253. var strong = '<span class="strong">';
  254. var stronger = '<span class="stronger">';
  255. var strongClose = '</span>';
  256. var classOpen = strong + this.name + ' {' + strongClose;
  257. var classClose = strong + '}' + strongClose;
  258. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  259. if (!modelsToIgnore)
  260. modelsToIgnore = {};
  261. modelsToIgnore[this.name] = this;
  262. for (i = 0; i < this.properties.length; i++) {
  263. prop = this.properties[i];
  264. var ref = prop.$ref;
  265. var model = models[ref];
  266. if (model && typeof modelsToIgnore[ref] === 'undefined') {
  267. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  268. }
  269. }
  270. return returnVal;
  271. };
  272. var addModel = function(name, model) {
  273. models[name] = model;
  274. };
  275. var SwaggerClient = function(url, options) {
  276. this.isBuilt = false;
  277. this.url = null;
  278. this.debug = false;
  279. this.basePath = null;
  280. this.modelsArray = [];
  281. this.authorizations = null;
  282. this.authorizationScheme = null;
  283. this.isValid = false;
  284. this.info = null;
  285. this.useJQuery = false;
  286. this.resourceCount = 0;
  287. if(typeof url !== 'undefined')
  288. return this.initialize(url, options);
  289. };
  290. SwaggerClient.prototype.initialize = function (url, options) {
  291. this.models = models = {};
  292. options = (options||{});
  293. if(typeof url === 'string')
  294. this.url = url;
  295. else if(typeof url === 'object') {
  296. options = url;
  297. this.url = options.url;
  298. }
  299. this.swaggerRequstHeaders = options.swaggerRequstHeaders || 'application/json;charset=utf-8,*/*';
  300. this.defaultSuccessCallback = options.defaultSuccessCallback || null;
  301. this.defaultErrorCallback = options.defaultErrorCallback || null;
  302. if (typeof options.success === 'function')
  303. this.success = options.success;
  304. if (options.useJQuery)
  305. this.useJQuery = options.useJQuery;
  306. if (options.authorizations) {
  307. this.clientAuthorizations = options.authorizations;
  308. } else {
  309. var e = (typeof window !== 'undefined' ? window : exports);
  310. this.clientAuthorizations = e.authorizations;
  311. }
  312. this.supportedSubmitMethods = options.supportedSubmitMethods || [];
  313. this.failure = options.failure || function() {};
  314. this.progress = options.progress || function() {};
  315. this.spec = options.spec;
  316. this.options = options;
  317. if (typeof options.success === 'function') {
  318. this.ready = true;
  319. this.build();
  320. }
  321. };
  322. SwaggerClient.prototype.build = function(mock) {
  323. if (this.isBuilt) return this;
  324. var self = this;
  325. this.progress('fetching resource list: ' + this.url);
  326. var obj = {
  327. useJQuery: this.useJQuery,
  328. url: this.url,
  329. method: "get",
  330. headers: {
  331. accept: this.swaggerRequstHeaders
  332. },
  333. on: {
  334. error: function(response) {
  335. if (self.url.substring(0, 4) !== 'http')
  336. return self.fail('Please specify the protocol for ' + self.url);
  337. else if (response.status === 0)
  338. return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
  339. else if (response.status === 404)
  340. return self.fail('Can\'t read swagger JSON from ' + self.url);
  341. else
  342. return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
  343. },
  344. response: function(resp) {
  345. var responseObj = resp.obj || JSON.parse(resp.data);
  346. self.swaggerVersion = responseObj.swaggerVersion;
  347. if(responseObj.swagger && parseInt(responseObj.swagger) === 2) {
  348. self.swaggerVersion = responseObj.swagger;
  349. self.buildFromSpec(responseObj);
  350. self.isValid = true;
  351. }
  352. else {
  353. if (self.swaggerVersion === '1.2') {
  354. return self.buildFrom1_2Spec(responseObj);
  355. } else {
  356. return self.buildFrom1_1Spec(responseObj);
  357. }
  358. }
  359. }
  360. }
  361. };
  362. if(this.spec) {
  363. setTimeout(function() { self.buildFromSpec(self.spec); }, 10);
  364. }
  365. else {
  366. var e = (typeof window !== 'undefined' ? window : exports);
  367. var status = e.authorizations.apply(obj);
  368. if(mock)
  369. return obj;
  370. new SwaggerHttp().execute(obj);
  371. }
  372. return this;
  373. };
  374. SwaggerClient.prototype.buildFromSpec = function(response) {
  375. if(this.isBuilt) return this;
  376. this.info = response.info || {};
  377. this.title = response.title || '';
  378. this.host = response.host || '';
  379. this.schemes = response.schemes || [];
  380. this.basePath = response.basePath || '';
  381. this.apis = {};
  382. this.apisArray = [];
  383. this.consumes = response.consumes;
  384. this.produces = response.produces;
  385. this.securityDefinitions = response.securityDefinitions;
  386. // legacy support
  387. this.authSchemes = response.securityDefinitions;
  388. var definedTags = {};
  389. if(Array.isArray(response.tags)) {
  390. definedTags = {};
  391. for(k = 0; k < response.tags.length; k++) {
  392. var t = response.tags[k];
  393. definedTags[t.name] = t;
  394. }
  395. }
  396. var location;
  397. if(typeof this.url === 'string') {
  398. location = this.parseUri(this.url);
  399. }
  400. if(typeof this.schemes === 'undefined' || this.schemes.length === 0) {
  401. this.scheme = location.scheme || 'http';
  402. }
  403. else {
  404. this.scheme = this.schemes[0];
  405. }
  406. if(typeof this.host === 'undefined' || this.host === '') {
  407. this.host = location.host;
  408. if (location.port) {
  409. this.host = this.host + ':' + location.port;
  410. }
  411. }
  412. this.definitions = response.definitions;
  413. var key;
  414. for(key in this.definitions) {
  415. var model = new Model(key, this.definitions[key]);
  416. if(model) {
  417. models[key] = model;
  418. }
  419. }
  420. // get paths, create functions for each operationId
  421. var path;
  422. var operations = [];
  423. for(path in response.paths) {
  424. if(typeof response.paths[path] === 'object') {
  425. var httpMethod;
  426. for(httpMethod in response.paths[path]) {
  427. if(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].indexOf(httpMethod) === -1) {
  428. continue;
  429. }
  430. var operation = response.paths[path][httpMethod];
  431. var tags = operation.tags;
  432. if(typeof tags === 'undefined') {
  433. operation.tags = [ 'default' ];
  434. tags = operation.tags;
  435. }
  436. var operationId = this.idFromOp(path, httpMethod, operation);
  437. var operationObject = new Operation (
  438. this,
  439. operation.scheme,
  440. operationId,
  441. httpMethod,
  442. path,
  443. operation,
  444. this.definitions
  445. );
  446. // bind this operation's execute command to the api
  447. if(tags.length > 0) {
  448. var i;
  449. for(i = 0; i < tags.length; i++) {
  450. var tag = this.tagFromLabel(tags[i]);
  451. var operationGroup = this[tag];
  452. if(typeof this.apis[tag] === 'undefined')
  453. this.apis[tag] = {};
  454. if(typeof operationGroup === 'undefined') {
  455. this[tag] = [];
  456. operationGroup = this[tag];
  457. operationGroup.operations = {};
  458. operationGroup.label = tag;
  459. operationGroup.apis = [];
  460. var tagObject = definedTags[tag];
  461. if(typeof tagObject === 'object') {
  462. operationGroup.description = tagObject.description;
  463. operationGroup.externalDocs = tagObject.externalDocs;
  464. }
  465. this[tag].help = this.help.bind(operationGroup);
  466. this.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject));
  467. }
  468. if(typeof this.apis[tag].help !== 'function')
  469. this.apis[tag].help = this.help.bind(operationGroup);
  470. // bind to the apis object
  471. this.apis[tag][operationId] = operationObject.execute.bind(operationObject);
  472. this.apis[tag][operationId].help = operationObject.help.bind(operationObject);
  473. this.apis[tag][operationId].asCurl = operationObject.asCurl.bind(operationObject);
  474. operationGroup[operationId] = operationObject.execute.bind(operationObject);
  475. operationGroup[operationId].help = operationObject.help.bind(operationObject);
  476. operationGroup[operationId].asCurl = operationObject.asCurl.bind(operationObject);
  477. operationGroup.apis.push(operationObject);
  478. operationGroup.operations[operationId] = operationObject;
  479. // legacy UI feature
  480. var j;
  481. var api;
  482. for(j = 0; j < this.apisArray.length; j++) {
  483. if(this.apisArray[j].tag === tag) {
  484. api = this.apisArray[j];
  485. }
  486. }
  487. if(api) {
  488. api.operationsArray.push(operationObject);
  489. }
  490. }
  491. }
  492. else {
  493. log('no group to bind to');
  494. }
  495. }
  496. }
  497. }
  498. this.isBuilt = true;
  499. if (this.success) {
  500. this.isValid = true;
  501. this.isBuilt = true;
  502. this.success();
  503. }
  504. return this;
  505. };
  506. SwaggerClient.prototype.parseUri = function(uri) {
  507. var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
  508. var parts = urlParseRE.exec(uri);
  509. return {
  510. scheme: parts[4].replace(':',''),
  511. host: parts[11],
  512. port: parts[12],
  513. path: parts[15]
  514. };
  515. };
  516. SwaggerClient.prototype.help = function(dontPrint) {
  517. var i;
  518. var output = 'operations for the "' + this.label + '" tag';
  519. for(i = 0; i < this.apis.length; i++) {
  520. var api = this.apis[i];
  521. output += '\n * ' + api.nickname + ': ' + api.operation.summary;
  522. }
  523. if(dontPrint)
  524. return output;
  525. else {
  526. log(output);
  527. return output;
  528. }
  529. };
  530. SwaggerClient.prototype.tagFromLabel = function(label) {
  531. return label;
  532. };
  533. SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
  534. var opId = op.operationId || (path.substring(1) + '_' + httpMethod);
  535. return opId.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()\+\s]/g,'_');
  536. };
  537. SwaggerClient.prototype.fail = function(message) {
  538. this.failure(message);
  539. throw message;
  540. };
  541. var OperationGroup = function(tag, description, externalDocs, operation) {
  542. this.tag = tag;
  543. this.path = tag;
  544. this.description = description;
  545. this.externalDocs = externalDocs;
  546. this.name = tag;
  547. this.operation = operation;
  548. this.operationsArray = [];
  549. };
  550. var Operation = function(parent, scheme, operationId, httpMethod, path, args, definitions) {
  551. var errors = [];
  552. parent = parent||{};
  553. args = args||{};
  554. this.operations = {};
  555. this.operation = args;
  556. this.deprecated = args.deprecated;
  557. this.consumes = args.consumes;
  558. this.produces = args.produces;
  559. this.parent = parent;
  560. this.host = parent.host || 'localhost';
  561. this.schemes = parent.schemes;
  562. this.scheme = scheme || parent.scheme || 'http';
  563. this.basePath = parent.basePath || '/';
  564. this.nickname = (operationId||errors.push('Operations must have a nickname.'));
  565. this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
  566. this.path = (path||errors.push('Operation ' + this.nickname + ' is missing path.'));
  567. this.parameters = args !== null ? (args.parameters||[]) : {};
  568. this.summary = args.summary || '';
  569. this.responses = (args.responses||{});
  570. this.type = null;
  571. this.security = args.security;
  572. this.authorizations = args.security;
  573. this.description = args.description;
  574. this.useJQuery = parent.useJQuery;
  575. if(typeof this.deprecated === 'string') {
  576. switch(this.deprecated.toLowerCase()) {
  577. case 'true': case 'yes': case '1': {
  578. this.deprecated = true;
  579. break;
  580. }
  581. case 'false': case 'no': case '0': case null: {
  582. this.deprecated = false;
  583. break;
  584. }
  585. default: this.deprecated = Boolean(this.deprecated);
  586. }
  587. }
  588. var i, model;
  589. if(definitions) {
  590. // add to global models
  591. var key;
  592. for(key in this.definitions) {
  593. model = new Model(key, definitions[key]);
  594. if(model) {
  595. models[key] = model;
  596. }
  597. }
  598. }
  599. for(i = 0; i < this.parameters.length; i++) {
  600. var param = this.parameters[i];
  601. if(param.type === 'array') {
  602. param.isList = true;
  603. param.allowMultiple = true;
  604. }
  605. var innerType = this.getType(param);
  606. if(innerType && innerType.toString().toLowerCase() === 'boolean') {
  607. param.allowableValues = {};
  608. param.isList = true;
  609. param['enum'] = ["true", "false"];
  610. }
  611. if(typeof param['enum'] !== 'undefined') {
  612. var id;
  613. param.allowableValues = {};
  614. param.allowableValues.values = [];
  615. param.allowableValues.descriptiveValues = [];
  616. for(id = 0; id < param['enum'].length; id++) {
  617. var value = param['enum'][id];
  618. var isDefault = (value === param.default) ? true : false;
  619. param.allowableValues.values.push(value);
  620. param.allowableValues.descriptiveValues.push({value : value, isDefault: isDefault});
  621. }
  622. }
  623. if(param.type === 'array') {
  624. innerType = [innerType];
  625. if(typeof param.allowableValues === 'undefined') {
  626. // can't show as a list if no values to select from
  627. delete param.isList;
  628. delete param.allowMultiple;
  629. }
  630. }
  631. param.signature = this.getModelSignature(innerType, models).toString();
  632. param.sampleJSON = this.getModelSampleJSON(innerType, models);
  633. param.responseClassSignature = param.signature;
  634. }
  635. var defaultResponseCode, response, responses = this.responses;
  636. if(responses['200']) {
  637. response = responses['200'];
  638. defaultResponseCode = '200';
  639. }
  640. else if(responses['201']) {
  641. response = responses['201'];
  642. defaultResponseCode = '201';
  643. }
  644. else if(responses['202']) {
  645. response = responses['202'];
  646. defaultResponseCode = '202';
  647. }
  648. else if(responses['203']) {
  649. response = responses['203'];
  650. defaultResponseCode = '203';
  651. }
  652. else if(responses['204']) {
  653. response = responses['204'];
  654. defaultResponseCode = '204';
  655. }
  656. else if(responses['205']) {
  657. response = responses['205'];
  658. defaultResponseCode = '205';
  659. }
  660. else if(responses['206']) {
  661. response = responses['206'];
  662. defaultResponseCode = '206';
  663. }
  664. else if(responses['default']) {
  665. response = responses['default'];
  666. defaultResponseCode = 'default';
  667. }
  668. if(response && response.schema) {
  669. var resolvedModel = this.resolveModel(response.schema, definitions);
  670. delete responses[defaultResponseCode];
  671. if(resolvedModel) {
  672. this.successResponse = {};
  673. this.successResponse[defaultResponseCode] = resolvedModel;
  674. }
  675. else {
  676. this.successResponse = {};
  677. this.successResponse[defaultResponseCode] = response.schema.type;
  678. }
  679. this.type = response;
  680. }
  681. if (errors.length > 0) {
  682. if(this.resource && this.resource.api && this.resource.api.fail)
  683. this.resource.api.fail(errors);
  684. }
  685. return this;
  686. };
  687. OperationGroup.prototype.sort = function(sorter) {
  688. };
  689. Operation.prototype.getType = function (param) {
  690. var type = param.type;
  691. var format = param.format;
  692. var isArray = false;
  693. var str;
  694. if(type === 'integer' && format === 'int32')
  695. str = 'integer';
  696. else if(type === 'integer' && format === 'int64')
  697. str = 'long';
  698. else if(type === 'integer')
  699. str = 'integer';
  700. else if(type === 'string') {
  701. if(format === 'date-time')
  702. str = 'date-time';
  703. else if(format === 'date')
  704. str = 'date';
  705. else
  706. str = 'string';
  707. }
  708. else if(type === 'number' && format === 'float')
  709. str = 'float';
  710. else if(type === 'number' && format === 'double')
  711. str = 'double';
  712. else if(type === 'number')
  713. str = 'double';
  714. else if(type === 'boolean')
  715. str = 'boolean';
  716. else if(type === 'array') {
  717. isArray = true;
  718. if(param.items)
  719. str = this.getType(param.items);
  720. }
  721. if(param.$ref)
  722. str = param.$ref;
  723. var schema = param.schema;
  724. if(schema) {
  725. var ref = schema.$ref;
  726. if(ref) {
  727. ref = simpleRef(ref);
  728. if(isArray)
  729. return [ ref ];
  730. else
  731. return ref;
  732. }
  733. else
  734. return this.getType(schema);
  735. }
  736. if(isArray)
  737. return [ str ];
  738. else
  739. return str;
  740. };
  741. Operation.prototype.resolveModel = function (schema, definitions) {
  742. if(typeof schema.$ref !== 'undefined') {
  743. var ref = schema.$ref;
  744. if(ref.indexOf('#/definitions/') === 0)
  745. ref = ref.substring('#/definitions/'.length);
  746. if(definitions[ref]) {
  747. return new Model(ref, definitions[ref]);
  748. }
  749. }
  750. if(schema.type === 'array')
  751. return new ArrayModel(schema);
  752. else
  753. return null;
  754. };
  755. Operation.prototype.help = function(dontPrint) {
  756. var out = this.nickname + ': ' + this.summary + '\n';
  757. for(var i = 0; i < this.parameters.length; i++) {
  758. var param = this.parameters[i];
  759. var typeInfo = typeFromJsonSchema(param.type, param.format);
  760. out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description;
  761. }
  762. if(typeof dontPrint === 'undefined')
  763. log(out);
  764. return out;
  765. };
  766. Operation.prototype.getModelSignature = function(type, definitions) {
  767. var isPrimitive, listType;
  768. if(type instanceof Array) {
  769. listType = true;
  770. type = type[0];
  771. }
  772. else if(typeof type === 'undefined')
  773. type = 'undefined';
  774. if(type === 'string')
  775. isPrimitive = true;
  776. else
  777. isPrimitive = (listType && definitions[listType]) || (definitions[type]) ? false : true;
  778. if (isPrimitive) {
  779. if(listType)
  780. return 'Array[' + type + ']';
  781. else
  782. return type.toString();
  783. } else {
  784. if (listType)
  785. return 'Array[' + definitions[type].getMockSignature() + ']';
  786. else
  787. return definitions[type].getMockSignature();
  788. }
  789. };
  790. Operation.prototype.supportHeaderParams = function () {
  791. return true;
  792. };
  793. Operation.prototype.supportedSubmitMethods = function () {
  794. return this.parent.supportedSubmitMethods;
  795. };
  796. Operation.prototype.getHeaderParams = function (args) {
  797. var headers = this.setContentTypes(args, {});
  798. for(var i = 0; i < this.parameters.length; i++) {
  799. var param = this.parameters[i];
  800. if(typeof args[param.name] !== 'undefined') {
  801. if (param.in === 'header') {
  802. var value = args[param.name];
  803. if(Array.isArray(value))
  804. value = value.toString();
  805. headers[param.name] = value;
  806. }
  807. }
  808. }
  809. return headers;
  810. };
  811. Operation.prototype.urlify = function (args) {
  812. var formParams = {};
  813. var requestUrl = this.path;
  814. // grab params from the args, build the querystring along the way
  815. var querystring = '';
  816. for(var i = 0; i < this.parameters.length; i++) {
  817. var param = this.parameters[i];
  818. if(typeof args[param.name] !== 'undefined') {
  819. if(param.in === 'path') {
  820. var reg = new RegExp('\{' + param.name + '\}', 'gi');
  821. var value = args[param.name];
  822. if(Array.isArray(value))
  823. value = this.encodePathCollection(param.collectionFormat, param.name, value);
  824. else
  825. value = this.encodePathParam(value);
  826. requestUrl = requestUrl.replace(reg, value);
  827. }
  828. else if (param.in === 'query' && typeof args[param.name] !== 'undefined') {
  829. if(querystring === '')
  830. querystring += '?';
  831. else
  832. querystring += '&';
  833. if(typeof param.collectionFormat !== 'undefined') {
  834. var qp = args[param.name];
  835. if(Array.isArray(qp))
  836. querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp);
  837. else
  838. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  839. }
  840. else
  841. querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
  842. }
  843. else if (param.in === 'formData')
  844. formParams[param.name] = args[param.name];
  845. }
  846. }
  847. var url = this.scheme + '://' + this.host;
  848. if(this.basePath !== '/')
  849. url += this.basePath;
  850. return url + requestUrl + querystring;
  851. };
  852. Operation.prototype.getMissingParams = function(args) {
  853. var missingParams = [];
  854. // check required params, track the ones that are missing
  855. var i;
  856. for(i = 0; i < this.parameters.length; i++) {
  857. var param = this.parameters[i];
  858. if(param.required === true) {
  859. if(typeof args[param.name] === 'undefined')
  860. missingParams = param.name;
  861. }
  862. }
  863. return missingParams;
  864. };
  865. Operation.prototype.getBody = function(headers, args) {
  866. var formParams = {};
  867. var body;
  868. for(var i = 0; i < this.parameters.length; i++) {
  869. var param = this.parameters[i];
  870. if(typeof args[param.name] !== 'undefined') {
  871. if (param.in === 'body') {
  872. body = args[param.name];
  873. } else if(param.in === 'formData') {
  874. formParams[param.name] = args[param.name];
  875. }
  876. }
  877. }
  878. // handle form params
  879. if(headers['Content-Type'] === 'application/x-www-form-urlencoded') {
  880. var encoded = "";
  881. var key;
  882. for(key in formParams) {
  883. value = formParams[key];
  884. if(typeof value !== 'undefined'){
  885. if(encoded !== "")
  886. encoded += "&";
  887. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  888. }
  889. }
  890. body = encoded;
  891. }
  892. return body;
  893. };
  894. /**
  895. * gets sample response for a single operation
  896. **/
  897. Operation.prototype.getModelSampleJSON = function(type, models) {
  898. var isPrimitive, listType, sampleJson;
  899. listType = (type instanceof Array);
  900. isPrimitive = models[type] ? false : true;
  901. sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
  902. if (sampleJson) {
  903. sampleJson = listType ? [sampleJson] : sampleJson;
  904. if(typeof sampleJson == 'string')
  905. return sampleJson;
  906. else if(typeof sampleJson === 'object') {
  907. var t = sampleJson;
  908. if(sampleJson instanceof Array && sampleJson.length > 0) {
  909. t = sampleJson[0];
  910. }
  911. if(t.nodeName) {
  912. var xmlString = new XMLSerializer().serializeToString(t);
  913. return this.formatXml(xmlString);
  914. }
  915. else
  916. return JSON.stringify(sampleJson, null, 2);
  917. }
  918. else
  919. return sampleJson;
  920. }
  921. };
  922. /**
  923. * legacy binding
  924. **/
  925. Operation.prototype["do"] = function(args, opts, callback, error, parent) {
  926. return this.execute(args, opts, callback, error, parent);
  927. };
  928. /**
  929. * executes an operation
  930. **/
  931. Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
  932. var args = arg1 || {};
  933. var opts = {}, success, error;
  934. if(typeof arg2 === 'object') {
  935. opts = arg2;
  936. success = arg3;
  937. error = arg4;
  938. }
  939. if(typeof arg2 === 'function') {
  940. success = arg2;
  941. error = arg3;
  942. }
  943. success = (success||log);
  944. error = (error||log);
  945. if(typeof opts.useJQuery === 'boolean') {
  946. this.useJQuery = opts.useJQuery;
  947. }
  948. var missingParams = this.getMissingParams(args);
  949. if(missingParams.length > 0) {
  950. var message = 'missing required params: ' + missingParams;
  951. fail(message);
  952. return;
  953. }
  954. var allHeaders = this.getHeaderParams(args);
  955. var contentTypeHeaders = this.setContentTypes(args, opts);
  956. var headers = {}, attrname;
  957. for (attrname in allHeaders) { headers[attrname] = allHeaders[attrname]; }
  958. for (attrname in contentTypeHeaders) { headers[attrname] = contentTypeHeaders[attrname]; }
  959. var body = this.getBody(headers, args);
  960. var url = this.urlify(args);
  961. var obj = {
  962. url: url,
  963. method: this.method.toUpperCase(),
  964. body: body,
  965. useJQuery: this.useJQuery,
  966. headers: headers,
  967. on: {
  968. response: function(response) {
  969. return success(response, parent);
  970. },
  971. error: function(response) {
  972. return error(response, parent);
  973. }
  974. }
  975. };
  976. var status = e.authorizations.apply(obj, this.operation.security);
  977. if(opts.mock === true)
  978. return obj;
  979. else
  980. new SwaggerHttp().execute(obj, opts);
  981. };
  982. Operation.prototype.setContentTypes = function(args, opts) {
  983. // default type
  984. var accepts = 'application/json';
  985. var consumes = args.parameterContentType || 'application/json';
  986. var allDefinedParams = this.parameters;
  987. var definedFormParams = [];
  988. var definedFileParams = [];
  989. var body;
  990. var headers = {};
  991. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  992. var i;
  993. for(i = 0; i < allDefinedParams.length; i++) {
  994. var param = allDefinedParams[i];
  995. if(param.in === 'formData') {
  996. if(param.type === 'file')
  997. definedFileParams.push(param);
  998. else
  999. definedFormParams.push(param);
  1000. }
  1001. else if(param.in === 'header' && opts) {
  1002. var key = param.name;
  1003. var headerValue = opts[param.name];
  1004. if(typeof opts[param.name] !== 'undefined')
  1005. headers[key] = headerValue;
  1006. }
  1007. else if(param.in === 'body' && typeof args[param.name] !== 'undefined') {
  1008. body = args[param.name];
  1009. }
  1010. }
  1011. // if there's a body, need to set the consumes header via requestContentType
  1012. if (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) {
  1013. if (opts.requestContentType)
  1014. consumes = opts.requestContentType;
  1015. } else {
  1016. // if any form params, content type must be set
  1017. if(definedFormParams.length > 0) {
  1018. if(opts.requestContentType) // override if set
  1019. consumes = opts.requestContentType;
  1020. else if(definedFileParams.length > 0) // if a file, must be multipart/form-data
  1021. consumes = 'multipart/form-data';
  1022. else // default to x-www-from-urlencoded
  1023. consumes = 'application/x-www-form-urlencoded';
  1024. }
  1025. else if (this.type == 'DELETE')
  1026. body = '{}';
  1027. else if (this.type != 'DELETE')
  1028. consumes = null;
  1029. }
  1030. if (consumes && this.consumes) {
  1031. if (this.consumes.indexOf(consumes) === -1) {
  1032. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
  1033. }
  1034. }
  1035. if (opts.responseContentType) {
  1036. accepts = opts.responseContentType;
  1037. } else {
  1038. accepts = 'application/json';
  1039. }
  1040. if (accepts && this.produces) {
  1041. if (this.produces.indexOf(accepts) === -1) {
  1042. log('server can\'t produce ' + accepts);
  1043. }
  1044. }
  1045. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  1046. headers['Content-Type'] = consumes;
  1047. if (accepts)
  1048. headers.Accept = accepts;
  1049. return headers;
  1050. };
  1051. Operation.prototype.asCurl = function (args) {
  1052. var results = [];
  1053. var headers = this.getHeaderParams(args);
  1054. if (headers) {
  1055. var key;
  1056. for (key in headers)
  1057. results.push("--header \"" + key + ": " + headers[key] + "\"");
  1058. }
  1059. return "curl " + (results.join(" ")) + " " + this.urlify(args);
  1060. };
  1061. Operation.prototype.encodePathCollection = function(type, name, value) {
  1062. var encoded = '';
  1063. var i;
  1064. var separator = '';
  1065. if(type === 'ssv')
  1066. separator = '%20';
  1067. else if(type === 'tsv')
  1068. separator = '\\t';
  1069. else if(type === 'pipes')
  1070. separator = '|';
  1071. else
  1072. separator = ',';
  1073. for(i = 0; i < value.length; i++) {
  1074. if(i === 0)
  1075. encoded = this.encodeQueryParam(value[i]);
  1076. else
  1077. encoded += separator + this.encodeQueryParam(value[i]);
  1078. }
  1079. return encoded;
  1080. };
  1081. Operation.prototype.encodeQueryCollection = function(type, name, value) {
  1082. var encoded = '';
  1083. var i;
  1084. if(type === 'default' || type === 'multi') {
  1085. for(i = 0; i < value.length; i++) {
  1086. if(i > 0) encoded += '&';
  1087. encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  1088. }
  1089. }
  1090. else {
  1091. var separator = '';
  1092. if(type === 'csv')
  1093. separator = ',';
  1094. else if(type === 'ssv')
  1095. separator = '%20';
  1096. else if(type === 'tsv')
  1097. separator = '\\t';
  1098. else if(type === 'pipes')
  1099. separator = '|';
  1100. else if(type === 'brackets') {
  1101. for(i = 0; i < value.length; i++) {
  1102. if(i !== 0)
  1103. encoded += '&';
  1104. encoded += this.encodeQueryParam(name) + '[]=' + this.encodeQueryParam(value[i]);
  1105. }
  1106. }
  1107. if(separator !== '') {
  1108. for(i = 0; i < value.length; i++) {
  1109. if(i === 0)
  1110. encoded = this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
  1111. else
  1112. encoded += separator + this.encodeQueryParam(value[i]);
  1113. }
  1114. }
  1115. }
  1116. return encoded;
  1117. };
  1118. Operation.prototype.encodeQueryParam = function(arg) {
  1119. return encodeURIComponent(arg);
  1120. };
  1121. /**
  1122. * TODO revisit, might not want to leave '/'
  1123. **/
  1124. Operation.prototype.encodePathParam = function(pathParam) {
  1125. var encParts, part, parts, i, len;
  1126. pathParam = pathParam.toString();
  1127. if (pathParam.indexOf('/') === -1) {
  1128. return encodeURIComponent(pathParam);
  1129. } else {
  1130. parts = pathParam.split('/');
  1131. encParts = [];
  1132. for (i = 0, len = parts.length; i < len; i++) {
  1133. encParts.push(encodeURIComponent(parts[i]));
  1134. }
  1135. return encParts.join('/');
  1136. }
  1137. };
  1138. var Model = function(name, definition) {
  1139. this.name = name;
  1140. this.definition = definition || {};
  1141. this.properties = [];
  1142. var requiredFields = definition.required || [];
  1143. if(definition.type === 'array') {
  1144. var out = new ArrayModel(definition);
  1145. return out;
  1146. }
  1147. var key;
  1148. var props = definition.properties;
  1149. if(props) {
  1150. for(key in props) {
  1151. var required = false;
  1152. var property = props[key];
  1153. if(requiredFields.indexOf(key) >= 0)
  1154. required = true;
  1155. this.properties.push(new Property(key, property, required));
  1156. }
  1157. }
  1158. };
  1159. Model.prototype.createJSONSample = function(modelsToIgnore) {
  1160. var i, result = {};
  1161. modelsToIgnore = (modelsToIgnore||{});
  1162. modelsToIgnore[this.name] = this;
  1163. for (i = 0; i < this.properties.length; i++) {
  1164. prop = this.properties[i];
  1165. var sample = prop.getSampleValue(modelsToIgnore);
  1166. result[prop.name] = sample;
  1167. }
  1168. delete modelsToIgnore[this.name];
  1169. return result;
  1170. };
  1171. Model.prototype.getSampleValue = function(modelsToIgnore) {
  1172. var i, obj = {};
  1173. for(i = 0; i < this.properties.length; i++ ) {
  1174. var property = this.properties[i];
  1175. obj[property.name] = property.sampleValue(false, modelsToIgnore);
  1176. }
  1177. return obj;
  1178. };
  1179. Model.prototype.getMockSignature = function(modelsToIgnore) {
  1180. var i, prop, propertiesStr = [];
  1181. for (i = 0; i < this.properties.length; i++) {
  1182. prop = this.properties[i];
  1183. propertiesStr.push(prop.toString());
  1184. }
  1185. var strong = '<span class="strong">';
  1186. var stronger = '<span class="stronger">';
  1187. var strongClose = '</span>';
  1188. var classOpen = strong + this.name + ' {' + strongClose;
  1189. var classClose = strong + '}' + strongClose;
  1190. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  1191. if (!modelsToIgnore)
  1192. modelsToIgnore = {};
  1193. modelsToIgnore[this.name] = this;
  1194. for (i = 0; i < this.properties.length; i++) {
  1195. prop = this.properties[i];
  1196. var ref = prop.$ref;
  1197. var model = models[ref];
  1198. if (model && typeof modelsToIgnore[model.name] === 'undefined') {
  1199. returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
  1200. }
  1201. }
  1202. return returnVal;
  1203. };
  1204. var Property = function(name, obj, required) {
  1205. this.schema = obj;
  1206. this.required = required;
  1207. if(obj.$ref)
  1208. this.$ref = simpleRef(obj.$ref);
  1209. else if (obj.type === 'array' && obj.items) {
  1210. if(obj.items.$ref)
  1211. this.$ref = simpleRef(obj.items.$ref);
  1212. else
  1213. obj = obj.items;
  1214. }
  1215. this.name = name;
  1216. this.description = obj.description;
  1217. this.obj = obj;
  1218. this.optional = true;
  1219. this.optional = !required;
  1220. this.default = obj.default || null;
  1221. this.example = obj.example !== undefined ? obj.example : null;
  1222. this.collectionFormat = obj.collectionFormat || null;
  1223. this.maximum = obj.maximum || null;
  1224. this.exclusiveMaximum = obj.exclusiveMaximum || null;
  1225. this.minimum = obj.minimum || null;
  1226. this.exclusiveMinimum = obj.exclusiveMinimum || null;
  1227. this.maxLength = obj.maxLength || null;
  1228. this.minLength = obj.minLength || null;
  1229. this.pattern = obj.pattern || null;
  1230. this.maxItems = obj.maxItems || null;
  1231. this.minItems = obj.minItems || null;
  1232. this.uniqueItems = obj.uniqueItems || null;
  1233. this['enum'] = obj['enum'] || null;
  1234. this.multipleOf = obj.multipleOf || null;
  1235. };
  1236. Property.prototype.getSampleValue = function (modelsToIgnore) {
  1237. return this.sampleValue(false, modelsToIgnore);
  1238. };
  1239. Property.prototype.isArray = function () {
  1240. var schema = this.schema;
  1241. if(schema.type === 'array')
  1242. return true;
  1243. else
  1244. return false;
  1245. };
  1246. Property.prototype.sampleValue = function(isArray, ignoredModels) {
  1247. isArray = (isArray || this.isArray());
  1248. ignoredModels = (ignoredModels || {});
  1249. var type = getStringSignature(this.obj, true);
  1250. var output;
  1251. if(this.$ref) {
  1252. var refModelName = simpleRef(this.$ref);
  1253. var refModel = models[refModelName];
  1254. if(refModel && typeof ignoredModels[type] === 'undefined') {
  1255. ignoredModels[type] = this;
  1256. output = refModel.getSampleValue(ignoredModels);
  1257. }
  1258. else {
  1259. output = refModelName;
  1260. }
  1261. }
  1262. else if(this.example)
  1263. output = this.example;
  1264. else if(this.default)
  1265. output = this.default;
  1266. else if(type === 'date-time')
  1267. output = new Date().toISOString();
  1268. else if(type === 'date')
  1269. output = new Date().toISOString().split("T")[0];
  1270. else if(type === 'string')
  1271. output = 'string';
  1272. else if(type === 'integer')
  1273. output = 0;
  1274. else if(type === 'long')
  1275. output = 0;
  1276. else if(type === 'float')
  1277. output = 0.0;
  1278. else if(type === 'double')
  1279. output = 0.0;
  1280. else if(type === 'boolean')
  1281. output = true;
  1282. else
  1283. output = {};
  1284. ignoredModels[type] = output;
  1285. if(isArray)
  1286. return [output];
  1287. else
  1288. return output;
  1289. };
  1290. getStringSignature = function(obj, baseComponent) {
  1291. var str = '';
  1292. if(typeof obj.$ref !== 'undefined')
  1293. str += simpleRef(obj.$ref);
  1294. else if(typeof obj.type === 'undefined')
  1295. str += 'object';
  1296. else if(obj.type === 'array') {
  1297. if(baseComponent)
  1298. str += getStringSignature((obj.items || obj.$ref || {}));
  1299. else {
  1300. str += 'Array[';
  1301. str += getStringSignature((obj.items || obj.$ref || {}));
  1302. str += ']';
  1303. }
  1304. }
  1305. else if(obj.type === 'integer' && obj.format === 'int32')
  1306. str += 'integer';
  1307. else if(obj.type === 'integer' && obj.format === 'int64')
  1308. str += 'long';
  1309. else if(obj.type === 'integer' && typeof obj.format === 'undefined')
  1310. str += 'long';
  1311. else if(obj.type === 'string' && obj.format === 'date-time')
  1312. str += 'date-time';
  1313. else if(obj.type === 'string' && obj.format === 'date')
  1314. str += 'date';
  1315. else if(obj.type === 'string' && typeof obj.format === 'undefined')
  1316. str += 'string';
  1317. else if(obj.type === 'number' && obj.format === 'float')
  1318. str += 'float';
  1319. else if(obj.type === 'number' && obj.format === 'double')
  1320. str += 'double';
  1321. else if(obj.type === 'number' && typeof obj.format === 'undefined')
  1322. str += 'double';
  1323. else if(obj.type === 'boolean')
  1324. str += 'boolean';
  1325. else if(obj.$ref)
  1326. str += simpleRef(obj.$ref);
  1327. else
  1328. str += obj.type;
  1329. return str;
  1330. };
  1331. simpleRef = function(name) {
  1332. if(typeof name === 'undefined')
  1333. return null;
  1334. if(name.indexOf("#/definitions/") === 0)
  1335. return name.substring('#/definitions/'.length);
  1336. else
  1337. return name;
  1338. };
  1339. Property.prototype.toString = function() {
  1340. var str = getStringSignature(this.obj);
  1341. if(str !== '') {
  1342. str = '<span class="propName ' + this.required + '">' + this.name + '</span> (<span class="propType">' + str + '</span>';
  1343. if(!this.required)
  1344. str += ', <span class="propOptKey">optional</span>';
  1345. str += ')';
  1346. }
  1347. else
  1348. str = this.name + ' (' + JSON.stringify(this.obj) + ')';
  1349. if(typeof this.description !== 'undefined')
  1350. str += ': ' + this.description;
  1351. if (this['enum']) {
  1352. str += ' = <span class="propVals">[\'' + this['enum'].join('\' or \'') + '\']</span>';
  1353. }
  1354. if (this.descr) {
  1355. str += ': <span class="propDesc">' + this.descr + '</span>';
  1356. }
  1357. var options = '';
  1358. var isArray = this.schema.type === 'array';
  1359. var type;
  1360. if(isArray) {
  1361. if(this.schema.items)
  1362. type = this.schema.items.type;
  1363. else
  1364. type = '';
  1365. }
  1366. else {
  1367. type = this.schema.type;
  1368. }
  1369. if (this.default)
  1370. options += optionHtml('Default', this.default);
  1371. switch (type) {
  1372. case 'string':
  1373. if (this.minLength)
  1374. options += optionHtml('Min. Length', this.minLength);
  1375. if (this.maxLength)
  1376. options += optionHtml('Max. Length', this.maxLength);
  1377. if (this.pattern)
  1378. options += optionHtml('Reg. Exp.', this.pattern);
  1379. break;
  1380. case 'integer':
  1381. case 'number':
  1382. if (this.minimum)
  1383. options += optionHtml('Min. Value', this.minimum);
  1384. if (this.exclusiveMinimum)
  1385. options += optionHtml('Exclusive Min.', "true");
  1386. if (this.maximum)
  1387. options += optionHtml('Max. Value', this.maximum);
  1388. if (this.exclusiveMaximum)
  1389. options += optionHtml('Exclusive Max.', "true");
  1390. if (this.multipleOf)
  1391. options += optionHtml('Multiple Of', this.multipleOf);
  1392. break;
  1393. }
  1394. if (isArray) {
  1395. if (this.minItems)
  1396. options += optionHtml('Min. Items', this.minItems);
  1397. if (this.maxItems)
  1398. options += optionHtml('Max. Items', this.maxItems);
  1399. if (this.uniqueItems)
  1400. options += optionHtml('Unique Items', "true");
  1401. if (this.collectionFormat)
  1402. options += optionHtml('Coll. Format', this.collectionFormat);
  1403. }
  1404. if (this['enum']) {
  1405. var enumString;
  1406. if (type === 'number' || type === 'integer')
  1407. enumString = this['enum'].join(', ');
  1408. else {
  1409. enumString = '"' + this['enum'].join('", "') + '"';
  1410. }
  1411. options += optionHtml('Enum', enumString);
  1412. }
  1413. if (options.length > 0)
  1414. str = '<span class="propWrap">' + str + '<table class="optionsWrapper"><tr><th colspan="2">' + this.name + '</th></tr>' + options + '</table></span>';
  1415. return str;
  1416. };
  1417. optionHtml = function(label, value) {
  1418. return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
  1419. };
  1420. typeFromJsonSchema = function(type, format) {
  1421. var str;
  1422. if(type === 'integer' && format === 'int32')
  1423. str = 'integer';
  1424. else if(type === 'integer' && format === 'int64')
  1425. str = 'long';
  1426. else if(type === 'integer' && typeof format === 'undefined')
  1427. str = 'long';
  1428. else if(type === 'string' && format === 'date-time')
  1429. str = 'date-time';
  1430. else if(type === 'string' && format === 'date')
  1431. str = 'date';
  1432. else if(type === 'number' && format === 'float')
  1433. str = 'float';
  1434. else if(type === 'number' && format === 'double')
  1435. str = 'double';
  1436. else if(type === 'number' && typeof format === 'undefined')
  1437. str = 'double';
  1438. else if(type === 'boolean')
  1439. str = 'boolean';
  1440. else if(type === 'string')
  1441. str = 'string';
  1442. return str;
  1443. };
  1444. var sampleModels = {};
  1445. var cookies = {};
  1446. var models = {};
  1447. SwaggerClient.prototype.buildFrom1_2Spec = function (response) {
  1448. if (response.apiVersion !== null) {
  1449. this.apiVersion = response.apiVersion;
  1450. }
  1451. this.apis = {};
  1452. this.apisArray = [];
  1453. this.consumes = response.consumes;
  1454. this.produces = response.produces;
  1455. this.authSchemes = response.authorizations;
  1456. this.info = this.convertInfo(response.info);
  1457. var isApi = false, i, res;
  1458. for (i = 0; i < response.apis.length; i++) {
  1459. var api = response.apis[i];
  1460. if (api.operations) {
  1461. var j;
  1462. for (j = 0; j < api.operations.length; j++) {
  1463. operation = api.operations[j];
  1464. isApi = true;
  1465. }
  1466. }
  1467. }
  1468. if (response.basePath)
  1469. this.basePath = response.basePath;
  1470. else if (this.url.indexOf('?') > 0)
  1471. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  1472. else
  1473. this.basePath = this.url;
  1474. if (isApi) {
  1475. var newName = response.resourcePath.replace(/\//g, '');
  1476. this.resourcePath = response.resourcePath;
  1477. res = new SwaggerResource(response, this);
  1478. this.apis[newName] = res;
  1479. this.apisArray.push(res);
  1480. this.finish();
  1481. } else {
  1482. var k;
  1483. this.expectedResourceCount = response.apis.length;
  1484. for (k = 0; k < response.apis.length; k++) {
  1485. var resource = response.apis[k];
  1486. res = new SwaggerResource(resource, this);
  1487. this.apis[res.name] = res;
  1488. this.apisArray.push(res);
  1489. }
  1490. }
  1491. this.isValid = true;
  1492. return this;
  1493. };
  1494. SwaggerClient.prototype.finish = function() {
  1495. if (typeof this.success === 'function') {
  1496. this.isValid = true;
  1497. this.ready = true;
  1498. this.isBuilt = true;
  1499. this.selfReflect();
  1500. this.success();
  1501. }
  1502. };
  1503. SwaggerClient.prototype.buildFrom1_1Spec = function (response) {
  1504. log('This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info');
  1505. if (response.apiVersion !== null)
  1506. this.apiVersion = response.apiVersion;
  1507. this.apis = {};
  1508. this.apisArray = [];
  1509. this.produces = response.produces;
  1510. this.info = this.convertInfo(response.info);
  1511. var isApi = false, res;
  1512. for (var i = 0; i < response.apis.length; i++) {
  1513. var api = response.apis[i];
  1514. if (api.operations) {
  1515. for (var j = 0; j < api.operations.length; j++) {
  1516. operation = api.operations[j];
  1517. isApi = true;
  1518. }
  1519. }
  1520. }
  1521. if (response.basePath) {
  1522. this.basePath = response.basePath;
  1523. } else if (this.url.indexOf('?') > 0) {
  1524. this.basePath = this.url.substring(0, this.url.lastIndexOf('?'));
  1525. } else {
  1526. this.basePath = this.url;
  1527. }
  1528. if (isApi) {
  1529. var newName = response.resourcePath.replace(/\//g, '');
  1530. this.resourcePath = response.resourcePath;
  1531. res = new SwaggerResource(response, this);
  1532. this.apis[newName] = res;
  1533. this.apisArray.push(res);
  1534. this.finish();
  1535. } else {
  1536. this.expectedResourceCount = response.apis.length;
  1537. for (k = 0; k < response.apis.length; k++) {
  1538. resource = response.apis[k];
  1539. res = new SwaggerResource(resource, this);
  1540. this.apis[res.name] = res;
  1541. this.apisArray.push(res);
  1542. }
  1543. }
  1544. this.isValid = true;
  1545. return this;
  1546. };
  1547. SwaggerClient.prototype.convertInfo = function (resp) {
  1548. if(typeof resp == 'object') {
  1549. var info = {};
  1550. info.title = resp.title;
  1551. info.description = resp.description;
  1552. info.termsOfService = resp.termsOfServiceUrl;
  1553. info.contact = {};
  1554. info.contact.name = resp.contact;
  1555. info.license = {};
  1556. info.license.name = resp.license;
  1557. info.license.url = resp.licenseUrl;
  1558. return info;
  1559. }
  1560. };
  1561. SwaggerClient.prototype.selfReflect = function () {
  1562. var resource, tag, ref;
  1563. if (this.apis === null) {
  1564. return false;
  1565. }
  1566. ref = this.apis;
  1567. for (tag in ref) {
  1568. api = ref[tag];
  1569. if (api.ready === null) {
  1570. return false;
  1571. }
  1572. this[tag] = api;
  1573. this[tag].help = __bind(api.help, api);
  1574. }
  1575. this.setConsolidatedModels();
  1576. this.ready = true;
  1577. };
  1578. SwaggerClient.prototype.setConsolidatedModels = function () {
  1579. var model, modelName, resource, resource_name, i, apis, models, results;
  1580. this.models = {};
  1581. apis = this.apis;
  1582. for (resource_name in apis) {
  1583. resource = apis[resource_name];
  1584. for (modelName in resource.models) {
  1585. if (typeof this.models[modelName] === 'undefined') {
  1586. this.models[modelName] = resource.models[modelName];
  1587. this.modelsArray.push(resource.models[modelName]);
  1588. }
  1589. }
  1590. }
  1591. models = this.modelsArray;
  1592. results = [];
  1593. for (i = 0; i < models.length; i++) {
  1594. model = models[i];
  1595. results.push(model.setReferencedModels(this.models));
  1596. }
  1597. return results;
  1598. };
  1599. var SwaggerResource = function (resourceObj, api) {
  1600. var _this = this;
  1601. this.api = api;
  1602. this.swaggerRequstHeaders = api.swaggerRequstHeaders;
  1603. this.path = (typeof this.api.resourcePath === 'string') ? this.api.resourcePath : resourceObj.path;
  1604. this.description = resourceObj.description;
  1605. this.authorizations = (resourceObj.authorizations || {});
  1606. var parts = this.path.split('/');
  1607. this.name = parts[parts.length - 1].replace('.{format}', '');
  1608. this.basePath = this.api.basePath;
  1609. this.operations = {};
  1610. this.operationsArray = [];
  1611. this.modelsArray = [];
  1612. this.models = api.models || {};
  1613. this.rawModels = {};
  1614. this.useJQuery = (typeof api.useJQuery !== 'undefined') ? api.useJQuery : null;
  1615. if ((resourceObj.apis) && this.api.resourcePath) {
  1616. this.addApiDeclaration(resourceObj);
  1617. } else {
  1618. if (typeof this.path === 'undefined') {
  1619. this.api.fail('SwaggerResources must have a path.');
  1620. }
  1621. if (this.path.substring(0, 4) === 'http') {
  1622. this.url = this.path.replace('{format}', 'json');
  1623. } else {
  1624. this.url = this.api.basePath + this.path.replace('{format}', 'json');
  1625. }
  1626. this.api.progress('fetching resource ' + this.name + ': ' + this.url);
  1627. var obj = {
  1628. url: this.url,
  1629. method: 'GET',
  1630. useJQuery: this.useJQuery,
  1631. headers: {
  1632. accept: this.swaggerRequstHeaders
  1633. },
  1634. on: {
  1635. response: function (resp) {
  1636. var responseObj = resp.obj || JSON.parse(resp.data);
  1637. _this.api.resourceCount += 1;
  1638. return _this.addApiDeclaration(responseObj);
  1639. },
  1640. error: function (response) {
  1641. _this.api.resourceCount += 1;
  1642. return _this.api.fail('Unable to read api \'' +
  1643. _this.name + '\' from path ' + _this.url + ' (server returned ' + response.statusText + ')');
  1644. }
  1645. }
  1646. };
  1647. var e = typeof window !== 'undefined' ? window : exports;
  1648. e.authorizations.apply(obj);
  1649. new SwaggerHttp().execute(obj);
  1650. }
  1651. };
  1652. SwaggerResource.prototype.help = function (dontPrint) {
  1653. var i;
  1654. var output = 'operations for the "' + this.name + '" tag';
  1655. for(i = 0; i < this.operationsArray.length; i++) {
  1656. var api = this.operationsArray[i];
  1657. output += '\n * ' + api.nickname + ': ' + api.description;
  1658. }
  1659. if(dontPrint)
  1660. return output;
  1661. else {
  1662. log(output);
  1663. return output;
  1664. }
  1665. };
  1666. SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) {
  1667. var pos, url;
  1668. url = this.api.basePath;
  1669. pos = url.lastIndexOf(relativeBasePath);
  1670. var parts = url.split('/');
  1671. var rootUrl = parts[0] + '//' + parts[2];
  1672. if (relativeBasePath.indexOf('http') === 0)
  1673. return relativeBasePath;
  1674. if (relativeBasePath === '/')
  1675. return rootUrl;
  1676. if (relativeBasePath.substring(0, 1) == '/') {
  1677. // use root + relative
  1678. return rootUrl + relativeBasePath;
  1679. }
  1680. else {
  1681. pos = this.basePath.lastIndexOf('/');
  1682. var base = this.basePath.substring(0, pos);
  1683. if (base.substring(base.length - 1) == '/')
  1684. return base + relativeBasePath;
  1685. else
  1686. return base + '/' + relativeBasePath;
  1687. }
  1688. };
  1689. SwaggerResource.prototype.addApiDeclaration = function (response) {
  1690. if (typeof response.produces === 'string')
  1691. this.produces = response.produces;
  1692. if (typeof response.consumes === 'string')
  1693. this.consumes = response.consumes;
  1694. if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0)
  1695. this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath;
  1696. this.resourcePath = response.resourcePath;
  1697. this.addModels(response.models);
  1698. if (response.apis) {
  1699. for (var i = 0 ; i < response.apis.length; i++) {
  1700. var endpoint = response.apis[i];
  1701. this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces);
  1702. }
  1703. }
  1704. this.api[this.name] = this;
  1705. this.ready = true;
  1706. if(this.api.resourceCount === this.api.expectedResourceCount)
  1707. this.api.finish();
  1708. return this;
  1709. };
  1710. SwaggerResource.prototype.addModels = function (models) {
  1711. if (typeof models === 'object') {
  1712. var modelName;
  1713. for (modelName in models) {
  1714. if (typeof this.models[modelName] === 'undefined') {
  1715. var swaggerModel = new SwaggerModel(modelName, models[modelName]);
  1716. this.modelsArray.push(swaggerModel);
  1717. this.models[modelName] = swaggerModel;
  1718. this.rawModels[modelName] = models[modelName];
  1719. }
  1720. }
  1721. var output = [];
  1722. for (var i = 0; i < this.modelsArray.length; i++) {
  1723. var model = this.modelsArray[i];
  1724. output.push(model.setReferencedModels(this.models));
  1725. }
  1726. return output;
  1727. }
  1728. };
  1729. SwaggerResource.prototype.addOperations = function (resource_path, ops, consumes, produces) {
  1730. if (ops) {
  1731. var output = [];
  1732. for (var i = 0; i < ops.length; i++) {
  1733. var o = ops[i];
  1734. consumes = this.consumes;
  1735. produces = this.produces;
  1736. if (typeof o.consumes !== 'undefined')
  1737. consumes = o.consumes;
  1738. else
  1739. consumes = this.consumes;
  1740. if (typeof o.produces !== 'undefined')
  1741. produces = o.produces;
  1742. else
  1743. produces = this.produces;
  1744. var type = (o.type || o.responseClass);
  1745. if (type === 'array') {
  1746. ref = null;
  1747. if (o.items)
  1748. ref = o.items.type || o.items.$ref;
  1749. type = 'array[' + ref + ']';
  1750. }
  1751. var responseMessages = o.responseMessages;
  1752. var method = o.method;
  1753. if (o.httpMethod) {
  1754. method = o.httpMethod;
  1755. }
  1756. if (o.supportedContentTypes) {
  1757. consumes = o.supportedContentTypes;
  1758. }
  1759. if (o.errorResponses) {
  1760. responseMessages = o.errorResponses;
  1761. for (var j = 0; j < responseMessages.length; j++) {
  1762. r = responseMessages[j];
  1763. r.message = r.reason;
  1764. r.reason = null;
  1765. }
  1766. }
  1767. o.nickname = this.sanitize(o.nickname);
  1768. var op = new SwaggerOperation(o.nickname,
  1769. resource_path,
  1770. method,
  1771. o.parameters,
  1772. o.summary,
  1773. o.notes,
  1774. type,
  1775. responseMessages,
  1776. this,
  1777. consumes,
  1778. produces,
  1779. o.authorizations,
  1780. o.deprecated);
  1781. this.operations[op.nickname] = op;
  1782. output.push(this.operationsArray.push(op));
  1783. }
  1784. return output;
  1785. }
  1786. };
  1787. SwaggerResource.prototype.sanitize = function (nickname) {
  1788. var op;
  1789. op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_');
  1790. op = op.replace(/((_){2,})/g, '_');
  1791. op = op.replace(/^(_)*/g, '');
  1792. op = op.replace(/([_])*$/g, '');
  1793. return op;
  1794. };
  1795. var SwaggerModel = function (modelName, obj) {
  1796. this.name = typeof obj.id !== 'undefined' ? obj.id : modelName;
  1797. this.properties = [];
  1798. var propertyName;
  1799. for (propertyName in obj.properties) {
  1800. if (obj.required) {
  1801. var value;
  1802. for (value in obj.required) {
  1803. if (propertyName === obj.required[value]) {
  1804. obj.properties[propertyName].required = true;
  1805. }
  1806. }
  1807. }
  1808. var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName], this);
  1809. this.properties.push(prop);
  1810. }
  1811. };
  1812. SwaggerModel.prototype.setReferencedModels = function (allModels) {
  1813. var results = [];
  1814. for (var i = 0; i < this.properties.length; i++) {
  1815. var property = this.properties[i];
  1816. var type = property.type || property.dataType;
  1817. if (allModels[type])
  1818. results.push(property.refModel = allModels[type]);
  1819. else if ((property.refDataType) && (allModels[property.refDataType]))
  1820. results.push(property.refModel = allModels[property.refDataType]);
  1821. else
  1822. results.push(void 0);
  1823. }
  1824. return results;
  1825. };
  1826. SwaggerModel.prototype.getMockSignature = function (modelsToIgnore) {
  1827. var i, prop, propertiesStr = [];
  1828. for (i = 0; i < this.properties.length; i++) {
  1829. prop = this.properties[i];
  1830. propertiesStr.push(prop.toString());
  1831. }
  1832. var strong = '<span class="strong">';
  1833. var strongClose = '</span>';
  1834. var classOpen = strong + this.name + ' {' + strongClose;
  1835. var classClose = strong + '}' + strongClose;
  1836. var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
  1837. if (!modelsToIgnore)
  1838. modelsToIgnore = [];
  1839. modelsToIgnore.push(this.name);
  1840. for (i = 0; i < this.properties.length; i++) {
  1841. prop = this.properties[i];
  1842. if ((prop.refModel) && modelsToIgnore.indexOf(prop.refModel.name) === -1) {
  1843. returnVal = returnVal + ('<br>' + prop.refModel.getMockSignature(modelsToIgnore));
  1844. }
  1845. }
  1846. return returnVal;
  1847. };
  1848. SwaggerModel.prototype.createJSONSample = function (modelsToIgnore) {
  1849. if (sampleModels[this.name]) {
  1850. return sampleModels[this.name];
  1851. }
  1852. else {
  1853. var result = {};
  1854. modelsToIgnore = (modelsToIgnore || []);
  1855. modelsToIgnore.push(this.name);
  1856. for (var i = 0; i < this.properties.length; i++) {
  1857. var prop = this.properties[i];
  1858. result[prop.name] = prop.getSampleValue(modelsToIgnore);
  1859. }
  1860. modelsToIgnore.pop(this.name);
  1861. return result;
  1862. }
  1863. };
  1864. var SwaggerModelProperty = function (name, obj, model) {
  1865. this.name = name;
  1866. this.dataType = obj.type || obj.dataType || obj.$ref;
  1867. this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set');
  1868. this.descr = obj.description;
  1869. this.required = obj.required;
  1870. this.defaultValue = applyModelPropertyMacro(obj, model);
  1871. if (obj.items) {
  1872. if (obj.items.type) {
  1873. this.refDataType = obj.items.type;
  1874. }
  1875. if (obj.items.$ref) {
  1876. this.refDataType = obj.items.$ref;
  1877. }
  1878. }
  1879. this.dataTypeWithRef = this.refDataType ? (this.dataType + '[' + this.refDataType + ']') : this.dataType;
  1880. if (obj.allowableValues) {
  1881. this.valueType = obj.allowableValues.valueType;
  1882. this.values = obj.allowableValues.values;
  1883. if (this.values) {
  1884. this.valuesString = '\'' + this.values.join('\' or \'') + '\'';
  1885. }
  1886. }
  1887. if (obj['enum']) {
  1888. this.valueType = 'string';
  1889. this.values = obj['enum'];
  1890. if (this.values) {
  1891. this.valueString = '\'' + this.values.join('\' or \'') + '\'';
  1892. }
  1893. }
  1894. };
  1895. SwaggerModelProperty.prototype.getSampleValue = function (modelsToIgnore) {
  1896. var result;
  1897. if ((this.refModel) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) {
  1898. result = this.refModel.createJSONSample(modelsToIgnore);
  1899. } else {
  1900. if (this.isCollection) {
  1901. result = this.toSampleValue(this.refDataType);
  1902. } else {
  1903. result = this.toSampleValue(this.dataType);
  1904. }
  1905. }
  1906. if (this.isCollection) {
  1907. return [result];
  1908. } else {
  1909. return result;
  1910. }
  1911. };
  1912. SwaggerModelProperty.prototype.toSampleValue = function (value) {
  1913. var result;
  1914. if ((typeof this.defaultValue !== 'undefined') && this.defaultValue) {
  1915. result = this.defaultValue;
  1916. } else if (value === 'integer') {
  1917. result = 0;
  1918. } else if (value === 'boolean') {
  1919. result = false;
  1920. } else if (value === 'double' || value === 'number') {
  1921. result = 0.0;
  1922. } else if (value === 'string') {
  1923. result = '';
  1924. } else {
  1925. result = value;
  1926. }
  1927. return result;
  1928. };
  1929. SwaggerModelProperty.prototype.toString = function () {
  1930. var req = this.required ? 'propReq' : 'propOpt';
  1931. var str = '<span class="propName ' + req + '">' + this.name + '</span> (<span class="propType">' + this.dataTypeWithRef + '</span>';
  1932. if (!this.required) {
  1933. str += ', <span class="propOptKey">optional</span>';
  1934. }
  1935. str += ')';
  1936. if (this.values) {
  1937. str += ' = <span class="propVals">[\'' + this.values.join('\' or \'') + '\']</span>';
  1938. }
  1939. if (this.descr) {
  1940. str += ': <span class="propDesc">' + this.descr + '</span>';
  1941. }
  1942. return str;
  1943. };
  1944. var SwaggerOperation = function (nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations, deprecated) {
  1945. var _this = this;
  1946. var errors = [];
  1947. this.nickname = (nickname || errors.push('SwaggerOperations must have a nickname.'));
  1948. this.path = (path || errors.push('SwaggerOperation ' + nickname + ' is missing path.'));
  1949. this.method = (method || errors.push('SwaggerOperation ' + nickname + ' is missing method.'));
  1950. this.parameters = parameters ? parameters : [];
  1951. this.summary = summary;
  1952. this.notes = notes;
  1953. this.type = type;
  1954. this.responseMessages = (responseMessages || []);
  1955. this.resource = (resource || errors.push('Resource is required'));
  1956. this.consumes = consumes;
  1957. this.produces = produces;
  1958. this.authorizations = typeof authorizations !== 'undefined' ? authorizations : resource.authorizations;
  1959. this.deprecated = deprecated;
  1960. this['do'] = __bind(this['do'], this);
  1961. if(typeof this.deprecated === 'string') {
  1962. switch(this.deprecated.toLowerCase()) {
  1963. case 'true': case 'yes': case '1': {
  1964. this.deprecated = true;
  1965. break;
  1966. }
  1967. case 'false': case 'no': case '0': case null: {
  1968. this.deprecated = false;
  1969. break;
  1970. }
  1971. default: this.deprecated = Boolean(this.deprecated);
  1972. }
  1973. }
  1974. if (errors.length > 0) {
  1975. console.error('SwaggerOperation errors', errors, arguments);
  1976. this.resource.api.fail(errors);
  1977. }
  1978. this.path = this.path.replace('{format}', 'json');
  1979. this.method = this.method.toLowerCase();
  1980. this.isGetMethod = this.method === 'get';
  1981. var i, j, v;
  1982. this.resourceName = this.resource.name;
  1983. if (typeof this.type !== 'undefined' && this.type === 'void')
  1984. this.type = null;
  1985. else {
  1986. this.responseClassSignature = this.getSignature(this.type, this.resource.models);
  1987. this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models);
  1988. }
  1989. for (i = 0; i < this.parameters.length; i++) {
  1990. var param = this.parameters[i];
  1991. // might take this away
  1992. param.name = param.name || param.type || param.dataType;
  1993. // for 1.1 compatibility
  1994. type = param.type || param.dataType;
  1995. if (type === 'array') {
  1996. type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']';
  1997. }
  1998. param.type = type;
  1999. if (type && type.toLowerCase() === 'boolean') {
  2000. param.allowableValues = {};
  2001. param.allowableValues.values = ['true', 'false'];
  2002. }
  2003. param.signature = this.getSignature(type, this.resource.models);
  2004. param.sampleJSON = this.getSampleJSON(type, this.resource.models);
  2005. var enumValue = param['enum'];
  2006. if (typeof enumValue !== 'undefined') {
  2007. param.isList = true;
  2008. param.allowableValues = {};
  2009. param.allowableValues.descriptiveValues = [];
  2010. for (j = 0; j < enumValue.length; j++) {
  2011. v = enumValue[j];
  2012. if (param.defaultValue) {
  2013. param.allowableValues.descriptiveValues.push({
  2014. value: String(v),
  2015. isDefault: (v === param.defaultValue)
  2016. });
  2017. }
  2018. else {
  2019. param.allowableValues.descriptiveValues.push({
  2020. value: String(v),
  2021. isDefault: false
  2022. });
  2023. }
  2024. }
  2025. }
  2026. else if (param.allowableValues) {
  2027. if (param.allowableValues.valueType === 'RANGE')
  2028. param.isRange = true;
  2029. else
  2030. param.isList = true;
  2031. if (param.allowableValues) {
  2032. param.allowableValues.descriptiveValues = [];
  2033. if (param.allowableValues.values) {
  2034. for (j = 0; j < param.allowableValues.values.length; j++) {
  2035. v = param.allowableValues.values[j];
  2036. if (param.defaultValue !== null) {
  2037. param.allowableValues.descriptiveValues.push({
  2038. value: String(v),
  2039. isDefault: (v === param.defaultValue)
  2040. });
  2041. }
  2042. else {
  2043. param.allowableValues.descriptiveValues.push({
  2044. value: String(v),
  2045. isDefault: false
  2046. });
  2047. }
  2048. }
  2049. }
  2050. }
  2051. }
  2052. param.defaultValue = applyParameterMacro(this, param);
  2053. }
  2054. var defaultSuccessCallback = this.resource.api.defaultSuccessCallback || null;
  2055. var defaultErrorCallback = this.resource.api.defaultErrorCallback || null;
  2056. this.resource[this.nickname] = function (args, opts, callback, error) {
  2057. var arg1, arg2, arg3, arg4;
  2058. if(typeof args === 'function') { // right shift 3
  2059. arg1 = {}; arg2 = {}; arg3 = args; arg4 = opts;
  2060. }
  2061. else if(typeof args === 'object' && typeof opts === 'function') { // right shift 2
  2062. arg1 = args; arg2 = {}; arg3 = opts; arg4 = callback;
  2063. }
  2064. else {
  2065. arg1 = args; arg2 = opts; arg3 = callback; arg4 = error;
  2066. }
  2067. return _this['do'](arg1 || {}, arg2 || {}, arg3 || defaultSuccessCallback, arg4 || defaultErrorCallback);
  2068. };
  2069. this.resource[this.nickname].help = function (dontPrint) {
  2070. return _this.help(dontPrint);
  2071. };
  2072. this.resource[this.nickname].asCurl = function (args) {
  2073. return _this.asCurl(args);
  2074. };
  2075. };
  2076. SwaggerOperation.prototype.isListType = function (type) {
  2077. if (type && type.indexOf('[') >= 0) {
  2078. return type.substring(type.indexOf('[') + 1, type.indexOf(']'));
  2079. } else {
  2080. return void 0;
  2081. }
  2082. };
  2083. SwaggerOperation.prototype.getSignature = function (type, models) {
  2084. var isPrimitive, listType;
  2085. listType = this.isListType(type);
  2086. isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
  2087. if (isPrimitive) {
  2088. return type;
  2089. } else {
  2090. if (typeof listType !== 'undefined') {
  2091. return models[listType].getMockSignature();
  2092. } else {
  2093. return models[type].getMockSignature();
  2094. }
  2095. }
  2096. };
  2097. SwaggerOperation.prototype.getSampleJSON = function (type, models) {
  2098. var isPrimitive, listType, val;
  2099. listType = this.isListType(type);
  2100. isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true;
  2101. val = isPrimitive ? void 0 : (listType ? models[listType].createJSONSample() : models[type].createJSONSample());
  2102. if (val) {
  2103. val = listType ? [val] : val;
  2104. if (typeof val == 'string')
  2105. return val;
  2106. else if (typeof val === 'object') {
  2107. var t = val;
  2108. if (val instanceof Array && val.length > 0) {
  2109. t = val[0];
  2110. }
  2111. if (t.nodeName) {
  2112. var xmlString = new XMLSerializer().serializeToString(t);
  2113. return this.formatXml(xmlString);
  2114. }
  2115. else
  2116. return JSON.stringify(val, null, 2);
  2117. }
  2118. else
  2119. return val;
  2120. }
  2121. };
  2122. SwaggerOperation.prototype['do'] = function (args, opts, callback, error) {
  2123. var key, param, params, possibleParams = [], req, value;
  2124. if (typeof error !== 'function') {
  2125. error = function (xhr, textStatus, error) {
  2126. return log(xhr, textStatus, error);
  2127. };
  2128. }
  2129. if (typeof callback !== 'function') {
  2130. callback = function (response) {
  2131. var content;
  2132. content = null;
  2133. if (response !== null) {
  2134. content = response.data;
  2135. } else {
  2136. content = 'no data';
  2137. }
  2138. return log('default callback: ' + content);
  2139. };
  2140. }
  2141. params = {};
  2142. params.headers = [];
  2143. if (args.headers) {
  2144. params.headers = args.headers;
  2145. delete args.headers;
  2146. }
  2147. // allow override from the opts
  2148. if(opts && opts.responseContentType) {
  2149. params.headers['Content-Type'] = opts.responseContentType;
  2150. }
  2151. if(opts && opts.requestContentType) {
  2152. params.headers.Accept = opts.requestContentType;
  2153. }
  2154. for (var i = 0; i < this.parameters.length; i++) {
  2155. param = this.parameters[i];
  2156. if (param.paramType === 'header') {
  2157. if (typeof args[param.name] !== 'undefined')
  2158. params.headers[param.name] = args[param.name];
  2159. }
  2160. else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file')
  2161. possibleParams.push(param);
  2162. else if (param.paramType === 'body' && param.name !== 'body' && typeof args[param.name] !== 'undefined') {
  2163. if (args.body) {
  2164. throw new Error('Saw two body params in an API listing; expecting a max of one.');
  2165. }
  2166. args.body = args[param.name];
  2167. }
  2168. }
  2169. if (typeof args.body !== 'undefined') {
  2170. params.body = args.body;
  2171. delete args.body;
  2172. }
  2173. if (possibleParams) {
  2174. for (key in possibleParams) {
  2175. value = possibleParams[key];
  2176. if (args[value.name]) {
  2177. params[value.name] = args[value.name];
  2178. }
  2179. }
  2180. }
  2181. req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this);
  2182. if (opts.mock) {
  2183. return req;
  2184. } else {
  2185. return true;
  2186. }
  2187. };
  2188. SwaggerOperation.prototype.pathJson = function () {
  2189. return this.path.replace('{format}', 'json');
  2190. };
  2191. SwaggerOperation.prototype.pathXml = function () {
  2192. return this.path.replace('{format}', 'xml');
  2193. };
  2194. SwaggerOperation.prototype.encodePathParam = function (pathParam) {
  2195. var encParts, part, parts, _i, _len;
  2196. pathParam = pathParam.toString();
  2197. if (pathParam.indexOf('/') === -1) {
  2198. return encodeURIComponent(pathParam);
  2199. } else {
  2200. parts = pathParam.split('/');
  2201. encParts = [];
  2202. for (_i = 0, _len = parts.length; _i < _len; _i++) {
  2203. part = parts[_i];
  2204. encParts.push(encodeURIComponent(part));
  2205. }
  2206. return encParts.join('/');
  2207. }
  2208. };
  2209. SwaggerOperation.prototype.urlify = function (args) {
  2210. var i, j, param, url;
  2211. // ensure no double slashing...
  2212. if(this.resource.basePath.length > 1 && this.resource.basePath.slice(-1) === '/' && this.pathJson().charAt(0) === '/')
  2213. url = this.resource.basePath + this.pathJson().substring(1);
  2214. else
  2215. url = this.resource.basePath + this.pathJson();
  2216. var params = this.parameters;
  2217. for (i = 0; i < params.length; i++) {
  2218. param = params[i];
  2219. if (param.paramType === 'path') {
  2220. if (typeof args[param.name] !== 'undefined') {
  2221. // apply path params and remove from args
  2222. var reg = new RegExp('\\{\\s*?' + param.name + '[^\\{\\}\\/]*(?:\\{.*?\\}[^\\{\\}\\/]*)*\\}(?=(\\/?|$))', 'gi');
  2223. url = url.replace(reg, this.encodePathParam(args[param.name]));
  2224. delete args[param.name];
  2225. }
  2226. else
  2227. throw '' + param.name + ' is a required path param.';
  2228. }
  2229. }
  2230. var queryParams = '';
  2231. for (i = 0; i < params.length; i++) {
  2232. param = params[i];
  2233. if(param.paramType === 'query') {
  2234. if (queryParams !== '')
  2235. queryParams += '&';
  2236. if (Array.isArray(param)) {
  2237. var output = '';
  2238. for(j = 0; j < param.length; j++) {
  2239. if(j > 0)
  2240. output += ',';
  2241. output += encodeURIComponent(param[j]);
  2242. }
  2243. queryParams += encodeURIComponent(param.name) + '=' + output;
  2244. }
  2245. else {
  2246. if (typeof args[param.name] !== 'undefined') {
  2247. queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]);
  2248. } else {
  2249. if (param.required)
  2250. throw '' + param.name + ' is a required query param.';
  2251. }
  2252. }
  2253. }
  2254. }
  2255. if ((queryParams) && queryParams.length > 0)
  2256. url += '?' + queryParams;
  2257. return url;
  2258. };
  2259. SwaggerOperation.prototype.supportHeaderParams = function () {
  2260. return this.resource.api.supportHeaderParams;
  2261. };
  2262. SwaggerOperation.prototype.supportedSubmitMethods = function () {
  2263. return this.resource.api.supportedSubmitMethods;
  2264. };
  2265. SwaggerOperation.prototype.getQueryParams = function (args) {
  2266. return this.getMatchingParams(['query'], args);
  2267. };
  2268. SwaggerOperation.prototype.getHeaderParams = function (args) {
  2269. return this.getMatchingParams(['header'], args);
  2270. };
  2271. SwaggerOperation.prototype.getMatchingParams = function (paramTypes, args) {
  2272. var matchingParams = {};
  2273. var params = this.parameters;
  2274. for (var i = 0; i < params.length; i++) {
  2275. param = params[i];
  2276. if (args && args[param.name])
  2277. matchingParams[param.name] = args[param.name];
  2278. }
  2279. var headers = this.resource.api.headers;
  2280. var name;
  2281. for (name in headers) {
  2282. var value = headers[name];
  2283. matchingParams[name] = value;
  2284. }
  2285. return matchingParams;
  2286. };
  2287. SwaggerOperation.prototype.help = function (dontPrint) {
  2288. var msg = this.nickname + ': ' + this.summary;
  2289. var params = this.parameters;
  2290. for (var i = 0; i < params.length; i++) {
  2291. var param = params[i];
  2292. msg += '\n* ' + param.name + (param.required ? ' (required)' : '') + " - " + param.description;
  2293. }
  2294. if(dontPrint)
  2295. return msg;
  2296. else {
  2297. console.log(msg);
  2298. return msg;
  2299. }
  2300. };
  2301. SwaggerOperation.prototype.asCurl = function (args) {
  2302. var results = [];
  2303. var i;
  2304. var headers = SwaggerRequest.prototype.setHeaders(args, {}, this);
  2305. for(i = 0; i < this.parameters.length; i++) {
  2306. var param = this.parameters[i];
  2307. if(param.paramType && param.paramType === 'header' && args[param.name]) {
  2308. headers[param.name] = args[param.name];
  2309. }
  2310. }
  2311. var key;
  2312. for (key in headers) {
  2313. results.push('--header "' + key + ': ' + headers[key] + '"');
  2314. }
  2315. return 'curl ' + (results.join(' ')) + ' ' + this.urlify(args);
  2316. };
  2317. SwaggerOperation.prototype.formatXml = function (xml) {
  2318. var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len;
  2319. reg = /(>)(<)(\/*)/g;
  2320. wsexp = /[ ]*(.*)[ ]+\n/g;
  2321. contexp = /(<.+>)(.+\n)/g;
  2322. xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2');
  2323. pad = 0;
  2324. formatted = '';
  2325. lines = xml.split('\n');
  2326. indent = 0;
  2327. lastType = 'other';
  2328. transitions = {
  2329. 'single->single': 0,
  2330. 'single->closing': -1,
  2331. 'single->opening': 0,
  2332. 'single->other': 0,
  2333. 'closing->single': 0,
  2334. 'closing->closing': -1,
  2335. 'closing->opening': 0,
  2336. 'closing->other': 0,
  2337. 'opening->single': 1,
  2338. 'opening->closing': 0,
  2339. 'opening->opening': 1,
  2340. 'opening->other': 1,
  2341. 'other->single': 0,
  2342. 'other->closing': -1,
  2343. 'other->opening': 0,
  2344. 'other->other': 0
  2345. };
  2346. _fn = function (ln) {
  2347. var fromTo, j, key, padding, type, types, value;
  2348. types = {
  2349. single: Boolean(ln.match(/<.+\/>/)),
  2350. closing: Boolean(ln.match(/<\/.+>/)),
  2351. opening: Boolean(ln.match(/<[^!?].*>/))
  2352. };
  2353. type = ((function () {
  2354. var _results;
  2355. _results = [];
  2356. for (key in types) {
  2357. value = types[key];
  2358. if (value) {
  2359. _results.push(key);
  2360. }
  2361. }
  2362. return _results;
  2363. })())[0];
  2364. type = type === void 0 ? 'other' : type;
  2365. fromTo = lastType + '->' + type;
  2366. lastType = type;
  2367. padding = '';
  2368. indent += transitions[fromTo];
  2369. padding = ((function () {
  2370. var _j, _ref5, _results;
  2371. _results = [];
  2372. for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
  2373. _results.push(' ');
  2374. }
  2375. return _results;
  2376. })()).join('');
  2377. if (fromTo === 'opening->closing') {
  2378. formatted = formatted.substr(0, formatted.length - 1) + ln + '\n';
  2379. } else {
  2380. formatted += padding + ln + '\n';
  2381. }
  2382. };
  2383. for (_i = 0, _len = lines.length; _i < _len; _i++) {
  2384. ln = lines[_i];
  2385. _fn(ln);
  2386. }
  2387. return formatted;
  2388. };
  2389. var SwaggerRequest = function (type, url, params, opts, successCallback, errorCallback, operation, execution) {
  2390. var _this = this;
  2391. var errors = [];
  2392. this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null);
  2393. this.type = (type || errors.push('SwaggerRequest type is required (get/post/put/delete/patch/options).'));
  2394. this.url = (url || errors.push('SwaggerRequest url is required.'));
  2395. this.params = params;
  2396. this.opts = opts;
  2397. this.successCallback = (successCallback || errors.push('SwaggerRequest successCallback is required.'));
  2398. this.errorCallback = (errorCallback || errors.push('SwaggerRequest error callback is required.'));
  2399. this.operation = (operation || errors.push('SwaggerRequest operation is required.'));
  2400. this.execution = execution;
  2401. this.headers = (params.headers || {});
  2402. if (errors.length > 0) {
  2403. throw errors;
  2404. }
  2405. this.type = this.type.toUpperCase();
  2406. // set request, response content type headers
  2407. var headers = this.setHeaders(params, opts, this.operation);
  2408. var body = params.body;
  2409. // encode the body for form submits
  2410. if (headers['Content-Type']) {
  2411. var key, value, values = {}, i;
  2412. var operationParams = this.operation.parameters;
  2413. for (i = 0; i < operationParams.length; i++) {
  2414. var param = operationParams[i];
  2415. if (param.paramType === 'form')
  2416. values[param.name] = param;
  2417. }
  2418. if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') === 0) {
  2419. var encoded = '';
  2420. for (key in values) {
  2421. value = this.params[key];
  2422. if (typeof value !== 'undefined') {
  2423. if (encoded !== '')
  2424. encoded += '&';
  2425. encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
  2426. }
  2427. }
  2428. body = encoded;
  2429. }
  2430. else if (headers['Content-Type'].indexOf('multipart/form-data') === 0) {
  2431. // encode the body for form submits
  2432. var data = '';
  2433. var boundary = '----SwaggerFormBoundary' + Date.now();
  2434. for (key in values) {
  2435. value = this.params[key];
  2436. if (typeof value !== 'undefined') {
  2437. data += '--' + boundary + '\n';
  2438. data += 'Content-Disposition: form-data; name="' + key + '"';
  2439. data += '\n\n';
  2440. data += value + '\n';
  2441. }
  2442. }
  2443. data += '--' + boundary + '--\n';
  2444. headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary;
  2445. body = data;
  2446. }
  2447. }
  2448. var obj;
  2449. if (!((this.headers) && (this.headers.mock))) {
  2450. obj = {
  2451. url: this.url,
  2452. method: this.type,
  2453. headers: headers,
  2454. body: body,
  2455. useJQuery: this.useJQuery,
  2456. on: {
  2457. error: function (response) {
  2458. return _this.errorCallback(response, _this.opts.parent);
  2459. },
  2460. redirect: function (response) {
  2461. return _this.successCallback(response, _this.opts.parent);
  2462. },
  2463. 307: function (response) {
  2464. return _this.successCallback(response, _this.opts.parent);
  2465. },
  2466. response: function (response) {
  2467. return _this.successCallback(response, _this.opts.parent);
  2468. }
  2469. }
  2470. };
  2471. var status = false;
  2472. if (this.operation.resource && this.operation.resource.api && this.operation.resource.api.clientAuthorizations) {
  2473. // Get the client authorizations from the resource declaration
  2474. status = this.operation.resource.api.clientAuthorizations.apply(obj, this.operation.authorizations);
  2475. } else {
  2476. // Get the client authorization from the default authorization declaration
  2477. var e;
  2478. if (typeof window !== 'undefined') {
  2479. e = window;
  2480. } else {
  2481. e = exports;
  2482. }
  2483. status = e.authorizations.apply(obj, this.operation.authorizations);
  2484. }
  2485. if (!opts.mock) {
  2486. if (status !== false) {
  2487. new SwaggerHttp().execute(obj);
  2488. } else {
  2489. obj.canceled = true;
  2490. }
  2491. } else {
  2492. return obj;
  2493. }
  2494. }
  2495. return obj;
  2496. };
  2497. SwaggerRequest.prototype.setHeaders = function (params, opts, operation) {
  2498. // default type
  2499. var accepts = opts.responseContentType || 'application/json';
  2500. var consumes = opts.requestContentType || 'application/json';
  2501. var allDefinedParams = operation.parameters;
  2502. var definedFormParams = [];
  2503. var definedFileParams = [];
  2504. var body = params.body;
  2505. var headers = {};
  2506. // get params from the operation and set them in definedFileParams, definedFormParams, headers
  2507. var i;
  2508. for (i = 0; i < allDefinedParams.length; i++) {
  2509. var param = allDefinedParams[i];
  2510. if (param.paramType === 'form')
  2511. definedFormParams.push(param);
  2512. else if (param.paramType === 'file')
  2513. definedFileParams.push(param);
  2514. else if (param.paramType === 'header' && this.params.headers) {
  2515. var key = param.name;
  2516. var headerValue = this.params.headers[param.name];
  2517. if (typeof this.params.headers[param.name] !== 'undefined')
  2518. headers[key] = headerValue;
  2519. }
  2520. }
  2521. // if there's a body, need to set the accepts header via requestContentType
  2522. if (body && (this.type === 'POST' || this.type === 'PUT' || this.type === 'PATCH' || this.type === 'DELETE')) {
  2523. if (this.opts.requestContentType)
  2524. consumes = this.opts.requestContentType;
  2525. } else {
  2526. // if any form params, content type must be set
  2527. if (definedFormParams.length > 0) {
  2528. if (definedFileParams.length > 0)
  2529. consumes = 'multipart/form-data';
  2530. else
  2531. consumes = 'application/x-www-form-urlencoded';
  2532. }
  2533. else if (this.type === 'DELETE')
  2534. body = '{}';
  2535. else if (this.type != 'DELETE')
  2536. consumes = null;
  2537. }
  2538. if (consumes && this.operation.consumes) {
  2539. if (this.operation.consumes.indexOf(consumes) === -1) {
  2540. log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.operation.consumes));
  2541. }
  2542. }
  2543. if (this.opts && this.opts.responseContentType) {
  2544. accepts = this.opts.responseContentType;
  2545. } else {
  2546. accepts = 'application/json';
  2547. }
  2548. if (accepts && operation.produces) {
  2549. if (operation.produces.indexOf(accepts) === -1) {
  2550. log('server can\'t produce ' + accepts);
  2551. }
  2552. }
  2553. if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
  2554. headers['Content-Type'] = consumes;
  2555. if (accepts)
  2556. headers.Accept = accepts;
  2557. return headers;
  2558. };
  2559. /**
  2560. * SwaggerHttp is a wrapper for executing requests
  2561. */
  2562. var SwaggerHttp = function() {};
  2563. SwaggerHttp.prototype.execute = function(obj, opts) {
  2564. if(obj && (typeof obj.useJQuery === 'boolean'))
  2565. this.useJQuery = obj.useJQuery;
  2566. else
  2567. this.useJQuery = this.isIE8();
  2568. if(obj && typeof obj.body === 'object') {
  2569. obj.body = JSON.stringify(obj.body);
  2570. }
  2571. if(this.useJQuery)
  2572. return new JQueryHttpClient(opts).execute(obj);
  2573. else
  2574. return new ShredHttpClient(opts).execute(obj);
  2575. };
  2576. SwaggerHttp.prototype.isIE8 = function() {
  2577. var detectedIE = false;
  2578. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  2579. nav = navigator.userAgent.toLowerCase();
  2580. if (nav.indexOf('msie') !== -1) {
  2581. var version = parseInt(nav.split('msie')[1]);
  2582. if (version <= 8) {
  2583. detectedIE = true;
  2584. }
  2585. }
  2586. }
  2587. return detectedIE;
  2588. };
  2589. /*
  2590. * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
  2591. * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
  2592. * Since we are using closures here we need to alias it for internal use.
  2593. */
  2594. var JQueryHttpClient = function(options) {
  2595. "use strict";
  2596. if(!jQuery){
  2597. var jQuery = window.jQuery;
  2598. }
  2599. };
  2600. JQueryHttpClient.prototype.execute = function(obj) {
  2601. var cb = obj.on;
  2602. var request = obj;
  2603. obj.type = obj.method;
  2604. obj.cache = false;
  2605. obj.beforeSend = function(xhr) {
  2606. var key, results;
  2607. if (obj.headers) {
  2608. results = [];
  2609. for (key in obj.headers) {
  2610. if (key.toLowerCase() === "content-type") {
  2611. results.push(obj.contentType = obj.headers[key]);
  2612. } else if (key.toLowerCase() === "accept") {
  2613. results.push(obj.accepts = obj.headers[key]);
  2614. } else {
  2615. results.push(xhr.setRequestHeader(key, obj.headers[key]));
  2616. }
  2617. }
  2618. return results;
  2619. }
  2620. };
  2621. obj.data = obj.body;
  2622. obj.complete = function(response, textStatus, opts) {
  2623. var headers = {},
  2624. headerArray = response.getAllResponseHeaders().split("\n");
  2625. for(var i = 0; i < headerArray.length; i++) {
  2626. var toSplit = headerArray[i].trim();
  2627. if(toSplit.length === 0)
  2628. continue;
  2629. var separator = toSplit.indexOf(":");
  2630. if(separator === -1) {
  2631. // Name but no value in the header
  2632. headers[toSplit] = null;
  2633. continue;
  2634. }
  2635. var name = toSplit.substring(0, separator).trim(),
  2636. value = toSplit.substring(separator + 1).trim();
  2637. headers[name] = value;
  2638. }
  2639. var out = {
  2640. url: request.url,
  2641. method: request.method,
  2642. status: response.status,
  2643. statusText: response.statusText,
  2644. data: response.responseText,
  2645. headers: headers
  2646. };
  2647. var contentType = (headers["content-type"]||headers["Content-Type"]||null);
  2648. if(contentType) {
  2649. if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
  2650. try {
  2651. out.obj = response.responseJSON || JSON.parse(out.data) || {};
  2652. } catch (ex) {
  2653. // do not set out.obj
  2654. log("unable to parse JSON content");
  2655. }
  2656. }
  2657. }
  2658. if(response.status >= 200 && response.status < 300)
  2659. cb.response(out);
  2660. else if(response.status === 0 || (response.status >= 400 && response.status < 599))
  2661. cb.error(out);
  2662. else
  2663. return cb.response(out);
  2664. };
  2665. jQuery.support.cors = true;
  2666. return jQuery.ajax(obj);
  2667. };
  2668. /*
  2669. * ShredHttpClient is a light-weight, node or browser HTTP client
  2670. */
  2671. var ShredHttpClient = function(opts) {
  2672. this.opts = (opts||{});
  2673. this.isInitialized = false;
  2674. var identity, toString;
  2675. if (typeof window !== 'undefined') {
  2676. this.Shred = require("./shred");
  2677. this.content = require("./shred/content");
  2678. }
  2679. else
  2680. this.Shred = require("shred");
  2681. this.shred = new this.Shred(opts);
  2682. };
  2683. ShredHttpClient.prototype.initShred = function () {
  2684. this.isInitialized = true;
  2685. this.registerProcessors(this.shred);
  2686. };
  2687. ShredHttpClient.prototype.registerProcessors = function(shred) {
  2688. var identity = function(x) {
  2689. return x;
  2690. };
  2691. var toString = function(x) {
  2692. return x.toString();
  2693. };
  2694. if (typeof window !== 'undefined') {
  2695. this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  2696. parser: identity,
  2697. stringify: toString
  2698. });
  2699. } else {
  2700. this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
  2701. parser: identity,
  2702. stringify: toString
  2703. });
  2704. }
  2705. };
  2706. ShredHttpClient.prototype.execute = function(obj) {
  2707. if(!this.isInitialized)
  2708. this.initShred();
  2709. var cb = obj.on, res;
  2710. var transform = function(response) {
  2711. var out = {
  2712. headers: response._headers,
  2713. url: response.request.url,
  2714. method: response.request.method,
  2715. status: response.status,
  2716. data: response.content.data
  2717. };
  2718. var headers = response._headers.normalized || response._headers;
  2719. var contentType = (headers["content-type"]||headers["Content-Type"]||null);
  2720. if(contentType) {
  2721. if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) {
  2722. if(response.content.data && response.content.data !== "")
  2723. try{
  2724. out.obj = JSON.parse(response.content.data);
  2725. }
  2726. catch (e) {
  2727. // unable to parse
  2728. }
  2729. else
  2730. out.obj = {};
  2731. }
  2732. }
  2733. return out;
  2734. };
  2735. // Transform an error into a usable response-like object
  2736. var transformError = function (error) {
  2737. var out = {
  2738. // Default to a status of 0 - The client will treat this as a generic permissions sort of error
  2739. status: 0,
  2740. data: error.message || error
  2741. };
  2742. if (error.code) {
  2743. out.obj = error;
  2744. if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
  2745. // We can tell the client that this should be treated as a missing resource and not as a permissions thing
  2746. out.status = 404;
  2747. }
  2748. }
  2749. return out;
  2750. };
  2751. res = {
  2752. error: function (response) {
  2753. if (obj)
  2754. return cb.error(transform(response));
  2755. },
  2756. // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming)
  2757. request_error: function (err) {
  2758. if (obj)
  2759. return cb.error(transformError(err));
  2760. },
  2761. response: function (response) {
  2762. if (obj) {
  2763. return cb.response(transform(response));
  2764. }
  2765. }
  2766. };
  2767. if (obj) {
  2768. obj.on = res;
  2769. }
  2770. return this.shred.request(obj);
  2771. };
  2772. var e = (typeof window !== 'undefined' ? window : exports);
  2773. e.authorizations = new SwaggerAuthorizations();
  2774. e.ApiKeyAuthorization = ApiKeyAuthorization;
  2775. e.PasswordAuthorization = PasswordAuthorization;
  2776. e.CookieAuthorization = CookieAuthorization;
  2777. e.SwaggerClient = SwaggerClient;
  2778. e.SwaggerApi = SwaggerClient;
  2779. e.Operation = Operation;
  2780. e.Model = Model;
  2781. e.addModel = addModel;
  2782. })();