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