diff --git a/.jshintignore b/.jshintignore index 90d45b85..38614d1f 100644 --- a/.jshintignore +++ b/.jshintignore @@ -1,2 +1,3 @@ +src/main/javascript/doc.js dist lib \ No newline at end of file diff --git a/dist/swagger-ui.js b/dist/swagger-ui.js index 9e510605..d74fd4ca 100644 --- a/dist/swagger-ui.js +++ b/dist/swagger-ui.js @@ -4,6 +4,202 @@ * @link http://swagger.io * @license Apache 2.0 */ +'use strict'; + +var SwaggerUi = Backbone.Router.extend({ + + dom_id: 'swagger_ui', + + // Attributes + options: null, + api: null, + headerView: null, + mainView: null, + + // SwaggerUi accepts all the same options as SwaggerApi + initialize: function(options) { + options = options || {}; + + // Allow dom_id to be overridden + if (options.dom_id) { + this.dom_id = options.dom_id; + delete options.dom_id; + } + + if (!options.supportedSubmitMethods){ + options.supportedSubmitMethods = [ + 'get', + 'put', + 'post', + 'delete', + 'head', + 'options', + 'patch' + ]; + } + + // Create an empty div which contains the dom_id + if (! $('#' + this.dom_id)){ + $('body').append('
') ; + } + + this.options = options; + + // set marked options + marked.setOptions({gfm: true}); + + // Set the callbacks + this.options.success = function() { return this.render(); }; + this.options.progress = function(d) { return this.showMessage(d); }; + this.options.failure = function(d) { return this.onLoadFailure(d); }; + + // Create view to handle the header inputs + this.headerView = new HeaderView({el: $('#header')}); + + // Event handler for when the baseUrl/apiKey is entered by user + this.headerView.on('update-swagger-ui', function(data) { + return this.updateSwaggerUi(data); + }); + }, + + // Set an option after initializing + setOption: function(option, value) { + this.options[option] = value; + }, + + // Get the value of a previously set option + getOption: function(option) { + return this.options[option]; + }, + + // Event handler for when url/key is received from user + updateSwaggerUi: function(data){ + this.options.url = data.url; + this.load(); + }, + + // Create an api and render + load: function(){ + // Initialize the API object + if (this.mainView) { + this.mainView.clear(); + } + var url = this.options.url; + if (url && url.indexOf('http') !== 0) { + url = this.buildUrl(window.location.href.toString(), url); + } + + this.options.url = url; + this.headerView.update(url); + + this.api = new SwaggerClient(this.options); + }, + + // collapse all sections + collapseAll: function(){ + Docs.collapseEndpointListForResource(''); + }, + + // list operations for all sections + listAll: function(){ + Docs.collapseOperationsForResource(''); + }, + + // expand operations for all sections + expandAll: function(){ + Docs.expandOperationsForResource(''); + }, + + // This is bound to success handler for SwaggerApi + // so it gets called when SwaggerApi completes loading + render: function(){ + this.showMessage('Finished Loading Resource Information. Rendering Swagger UI...'); + this.mainView = new MainView({ + model: this.api, + el: $('#' + this.dom_id), + swaggerOptions: this.options + }).render(); + this.showMessage(); + switch (this.options.docExpansion) { + case 'full': + this.expandAll(); break; + case 'list': + this.listAll(); break; + default: + break; + } + this.renderGFM(); + + if (this.options.onComplete){ + this.options.onComplete(this.api, this); + } + + setTimeout(Docs.shebang.bind(this), 100); + }, + + buildUrl: function(base, url){ + if (url.indexOf('/') === 0) { + var parts = base.split('/'); + base = parts[0] + '//' + parts[2]; + return base + url; + } else { + var endOfPath = base.length; + + if (base.indexOf('?') > -1){ + endOfPath = Math.min(endOfPath, base.indexOf('?')); + } + + if (base.indexOf('#') > -1){ + endOfPath = Math.min(endOfPath, base.indexOf('#')); + } + + base = base.substring(0, endOfPath); + + if (base.indexOf('/', base.length - 1 ) !== -1){ + return base + url; + } + + return base + '/' + url; + } + }, + + // Shows message on topbar of the ui + showMessage: function(data){ + if (data === undefined) { + data = ''; + } + $('#message-bar').removeClass('message-fail'); + $('#message-bar').addClass('message-success'); + $('#message-bar').html(data); + }, + + // shows message in red + onLoadFailure: function(data){ + if (data === undefined) { + data = ''; + } + $('#message-bar').removeClass('message-success'); + $('#message-bar').addClass('message-fail'); + + var val = $('#message-bar').html(data); + + if (this.options.onFailure) { + this.options.onFailure(data); + } + + return val; + }, + + // Renders GFM for elements with 'markdown' class + renderGFM: function(){ + $('.markdown').each(function(){ + $(this).html(marked($(this).html())); + }); + } + +}); + +window.SwaggerUi = SwaggerUi; this["Handlebars"] = this["Handlebars"] || {}; this["Handlebars"]["templates"] = this["Handlebars"]["templates"] || {}; this["Handlebars"]["templates"]["apikey_button_view"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { @@ -231,11 +427,13 @@ var Docs = { } }; -Handlebars.registerHelper('sanitize', function(html) { - html = html.replace(/)<[^<]*)*<\/script>/gi, ''); - return new Handlebars.SafeString(html); +'use strict'; + +Handlebars.registerHelper('sanitize', function(html) { + // Strip the script tags from the html, and return it as a Handlebars.SafeString + html = html.replace(/)<[^<]*)*<\/script>/gi, ''); + return new Handlebars.SafeString(html); }); - this["Handlebars"]["templates"]["main"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression, buffer = "
" + escapeExpression(lambda(((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.title : stack1), depth0)) @@ -434,6 +632,69 @@ this["Handlebars"]["templates"]["operation"] = Handlebars.template({"1":function if (stack1 != null) { buffer += stack1; } return buffer + " \n \n
\n \n \n"; },"useData":true}); +this["Handlebars"]["templates"]["param"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isFile : depth0), {"name":"if","hash":{},"fn":this.program(2, data),"inverse":this.program(4, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"2":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n
\n"; +},"4":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0['default'] : depth0), {"name":"if","hash":{},"fn":this.program(5, data),"inverse":this.program(7, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"5":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n
\n
\n"; +},"7":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n
\n
\n"; +},"9":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isFile : depth0), {"name":"if","hash":{},"fn":this.program(2, data),"inverse":this.program(10, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"10":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0['default'] : depth0), {"name":"if","hash":{},"fn":this.program(11, data),"inverse":this.program(13, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"11":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n"; +},"13":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n"; +},"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, buffer = "" + + escapeExpression(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"name","hash":{},"data":data}) : helper))) + + "\n\n\n"; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isBody : depth0), {"name":"if","hash":{},"fn":this.program(1, data),"inverse":this.program(9, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + buffer += "\n\n"; + stack1 = ((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"description","hash":{},"data":data}) : helper)); + if (stack1 != null) { buffer += stack1; } + buffer += "\n"; + stack1 = ((helper = (helper = helpers.paramType || (depth0 != null ? depth0.paramType : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"paramType","hash":{},"data":data}) : helper)); + if (stack1 != null) { buffer += stack1; } + return buffer + "\n\n \n\n"; +},"useData":true}); this["Handlebars"]["templates"]["param_list"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; return "" @@ -498,9 +759,9 @@ this["Handlebars"]["templates"]["param_list"] = Handlebars.template({"1":functio if (stack1 != null) { buffer += stack1; } return buffer + "\n"; },"useData":true}); -this["Handlebars"]["templates"]["param_readonly_required"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { +this["Handlebars"]["templates"]["param_readonly"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; - return " \n
\n
\n"; -},"7":function(depth0,helpers,partials,data) { - var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; - return " \n
\n
\n"; -},"9":function(depth0,helpers,partials,data) { - var stack1, buffer = ""; - stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isFile : depth0), {"name":"if","hash":{},"fn":this.program(2, data),"inverse":this.program(10, data),"data":data}); - if (stack1 != null) { buffer += stack1; } - return buffer; -},"10":function(depth0,helpers,partials,data) { - var stack1, buffer = ""; - stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0['default'] : depth0), {"name":"if","hash":{},"fn":this.program(11, data),"inverse":this.program(13, data),"data":data}); - if (stack1 != null) { buffer += stack1; } - return buffer; -},"11":function(depth0,helpers,partials,data) { - var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; - return " \n"; -},"13":function(depth0,helpers,partials,data) { - var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; - return " \n"; -},"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { - var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, buffer = "" - + escapeExpression(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"name","hash":{},"data":data}) : helper))) - + "\n\n\n"; - stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isBody : depth0), {"name":"if","hash":{},"fn":this.program(1, data),"inverse":this.program(9, data),"data":data}); - if (stack1 != null) { buffer += stack1; } - buffer += "\n\n"; - stack1 = ((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"description","hash":{},"data":data}) : helper)); - if (stack1 != null) { buffer += stack1; } - buffer += "\n"; - stack1 = ((helper = (helper = helpers.paramType || (depth0 != null ? depth0.paramType : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"paramType","hash":{},"data":data}) : helper)); - if (stack1 != null) { buffer += stack1; } - return buffer + "\n\n \n\n"; -},"useData":true}); this["Handlebars"]["templates"]["parameter_content_type"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var stack1, buffer = ""; stack1 = helpers.each.call(depth0, (depth0 != null ? depth0.consumes : depth0), {"name":"each","hash":{},"fn":this.program(2, data),"inverse":this.noop,"data":data}); @@ -802,1495 +1000,1183 @@ this["Handlebars"]["templates"]["status_code"] = Handlebars.template({"1":functi if (stack1 != null) { buffer += stack1; } return buffer + " \n \n"; },"useData":true}); -var SwaggerUi, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -SwaggerUi = (function(superClass) { - extend(SwaggerUi, superClass); - - function SwaggerUi() { - return SwaggerUi.__super__.constructor.apply(this, arguments); - } - - SwaggerUi.prototype.domEl = $('#swagger_ui'); - - SwaggerUi.prototype.options = null; - - SwaggerUi.prototype.api = null; - - SwaggerUi.prototype.headerView = null; - - SwaggerUi.prototype.mainView = null; - - SwaggerUi.prototype.initialize = function(options) { - if (options == null) { - options = {}; - } - if (options.dom_id != null) { - this.domEl = $('#' + options.dom_id); - delete options.dom_id; - } else if (options.domEl != null) { - this.domEl = options.domEl; - } - if (options.supportedSubmitMethods == null) { - options.supportedSubmitMethods = ['get', 'put', 'post', 'delete', 'head', 'options', 'patch']; - } - this.domEl = $(this.domEl); - if (!$.contains(document.documentElement, this.domEl.get(0))) { - $('body').append(this.domEl); - } - this.options = options; - marked.setOptions({ - gfm: true - }); - this.options.success = (function(_this) { - return function() { - return _this.render(); - }; - })(this); - this.options.progress = (function(_this) { - return function(d) { - return _this.showMessage(d); - }; - })(this); - this.options.failure = (function(_this) { - return function(d) { - return _this.onLoadFailure(d); - }; - })(this); - if ($('#header').length) { - this.headerView = new HeaderView({ - el: $('#header') - }); - return this.headerView.on('update-swagger-ui', (function(_this) { - return function(data) { - return _this.updateSwaggerUi(data); - }; - })(this)); - } - }; - - SwaggerUi.prototype.setOption = function(option, value) { - return this.options[option] = value; - }; - - SwaggerUi.prototype.getOption = function(option) { - return this.options[option]; - }; - - SwaggerUi.prototype.updateSwaggerUi = function(data) { - this.options.url = data.url; - return this.load(); - }; - - SwaggerUi.prototype.load = function() { - var ref, url; - if ((ref = this.mainView) != null) { - ref.clear(); - } - url = this.options.url; - if (url && url.indexOf("http") !== 0) { - url = this.buildUrl(window.location.href.toString(), url); - } - this.options.url = url; - if (this.headerView) { - this.headerView.update(url); - } - return this.api = new SwaggerClient(this.options); - }; - - SwaggerUi.prototype.collapseAll = function() { - return Docs.collapseEndpointListForResource(''); - }; - - SwaggerUi.prototype.listAll = function() { - return Docs.collapseOperationsForResource(''); - }; - - SwaggerUi.prototype.expandAll = function() { - return Docs.expandOperationsForResource(''); - }; - - SwaggerUi.prototype.render = function() { - this.showMessage('Finished Loading Resource Information. Rendering Swagger UI...'); - this.mainView = new MainView({ - model: this.api, - el: this.domEl, - swaggerOptions: this.options, - router: this - }).render(); - this.showMessage(); - switch (this.options.docExpansion) { - case "full": - this.expandAll(); - break; - case "list": - this.listAll(); - } - this.renderGFM(); - if (this.options.onComplete) { - this.options.onComplete(this.api, this); - } - return setTimeout((function(_this) { - return function() { - return Docs.shebang(); - }; - })(this), 100); - }; - - SwaggerUi.prototype.buildUrl = function(base, url) { - var endOfPath, parts; - if (url.indexOf("/") === 0) { - parts = base.split("/"); - base = parts[0] + "//" + parts[2]; - return base + url; - } else { - endOfPath = base.length; - if (base.indexOf("?") > -1) { - endOfPath = Math.min(endOfPath, base.indexOf("?")); - } - if (base.indexOf("#") > -1) { - endOfPath = Math.min(endOfPath, base.indexOf("#")); - } - base = base.substring(0, endOfPath); - if (base.indexOf("/", base.length - 1) !== -1) { - return base + url; - } - return base + "/" + url; - } - }; - - SwaggerUi.prototype.showMessage = function(data) { - if (data == null) { - data = ''; - } - $('#message-bar').removeClass('message-fail'); - $('#message-bar').addClass('message-success'); - return $('#message-bar').html(data); - }; - - SwaggerUi.prototype.onLoadFailure = function(data) { - var val; - if (data == null) { - data = ''; - } - $('#message-bar').removeClass('message-success'); - $('#message-bar').addClass('message-fail'); - val = $('#message-bar').html(data); - if (this.options.onFailure != null) { - this.options.onFailure(data); - } - return val; - }; - - SwaggerUi.prototype.renderGFM = function(data) { - if (data == null) { - data = ''; - } - return $('.markdown').each(function(index) { - return $(this).html(marked($(this).html())); - }); - }; - - return SwaggerUi; - -})(Backbone.Router); - -window.SwaggerUi = SwaggerUi; - -var ApiKeyButton, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -ApiKeyButton = (function(superClass) { - extend(ApiKeyButton, superClass); - - function ApiKeyButton() { - return ApiKeyButton.__super__.constructor.apply(this, arguments); - } - - ApiKeyButton.prototype.initialize = function() {}; - - ApiKeyButton.prototype.render = function() { - var template; - template = this.template(); - $(this.el).html(template(this.model)); - return this; - }; - - ApiKeyButton.prototype.events = { - "click #apikey_button": "toggleApiKeyContainer", - "click #apply_api_key": "applyApiKey" - }; - - ApiKeyButton.prototype.applyApiKey = function() { - var elem; - window.authorizations.add(this.model.name, new ApiKeyAuthorization(this.model.name, $("#input_apiKey_entry").val(), this.model["in"])); - window.swaggerUi.load(); - return elem = $('#apikey_container').show(); - }; - - ApiKeyButton.prototype.toggleApiKeyContainer = function() { - var elem; - if ($('#apikey_container').length > 0) { - elem = $('#apikey_container').first(); - if (elem.is(':visible')) { - return elem.hide(); - } else { - $('.auth_container').hide(); - return elem.show(); - } - } - }; - - ApiKeyButton.prototype.template = function() { - return Handlebars.templates.apikey_button_view; - }; - - return ApiKeyButton; - -})(Backbone.View); - -var BasicAuthButton, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -BasicAuthButton = (function(superClass) { - extend(BasicAuthButton, superClass); - - function BasicAuthButton() { - return BasicAuthButton.__super__.constructor.apply(this, arguments); - } - - BasicAuthButton.prototype.initialize = function() {}; - - BasicAuthButton.prototype.render = function() { - var template; - template = this.template(); - $(this.el).html(template(this.model)); - return this; - }; - - BasicAuthButton.prototype.events = { - "click #basic_auth_button": "togglePasswordContainer", - "click #apply_basic_auth": "applyPassword" - }; - - BasicAuthButton.prototype.applyPassword = function() { - var elem, password, username; - username = $(".input_username").val(); - password = $(".input_password").val(); - window.authorizations.add(this.model.type, new PasswordAuthorization("basic", username, password)); - window.swaggerUi.load(); - return elem = $('#basic_auth_container').hide(); - }; - - BasicAuthButton.prototype.togglePasswordContainer = function() { - var elem; - if ($('#basic_auth_container').length > 0) { - elem = $('#basic_auth_container').show(); - if (elem.is(':visible')) { - return elem.slideUp(); - } else { - $('.auth_container').hide(); - return elem.show(); - } - } - }; - - BasicAuthButton.prototype.template = function() { - return Handlebars.templates.basic_auth_button_view; - }; - - return BasicAuthButton; - -})(Backbone.View); - -var ContentTypeView, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -ContentTypeView = (function(superClass) { - extend(ContentTypeView, superClass); - - function ContentTypeView() { - return ContentTypeView.__super__.constructor.apply(this, arguments); - } - - ContentTypeView.prototype.initialize = function() {}; - - ContentTypeView.prototype.render = function() { - var template; - template = this.template(); - $(this.el).html(template(this.model)); - $('label[for=contentType]', $(this.el)).text('Response Content Type'); - return this; - }; - - ContentTypeView.prototype.template = function() { - return Handlebars.templates.content_type; - }; - - return ContentTypeView; - -})(Backbone.View); - -var HeaderView, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -HeaderView = (function(superClass) { - extend(HeaderView, superClass); - - function HeaderView() { - return HeaderView.__super__.constructor.apply(this, arguments); - } - - HeaderView.prototype.events = { - 'click #show-pet-store-icon': 'showPetStore', - 'click #show-wordnik-dev-icon': 'showWordnikDev', - 'click #explore': 'showCustom', - 'keyup #input_baseUrl': 'showCustomOnKeyup', - 'keyup #input_apiKey': 'showCustomOnKeyup' - }; - - HeaderView.prototype.initialize = function() {}; - - HeaderView.prototype.showPetStore = function(e) { - return this.trigger('update-swagger-ui', { - url: "http://petstore.swagger.wordnik.com/api/api-docs" - }); - }; - - HeaderView.prototype.showWordnikDev = function(e) { - return this.trigger('update-swagger-ui', { - url: "http://api.wordnik.com/v4/resources.json" - }); - }; - - HeaderView.prototype.showCustomOnKeyup = function(e) { - if (e.keyCode === 13) { - return this.showCustom(); - } - }; - - HeaderView.prototype.showCustom = function(e) { - if (e != null) { - e.preventDefault(); - } - return this.trigger('update-swagger-ui', { - url: $('#input_baseUrl').val(), - apiKey: $('#input_apiKey').val() - }); - }; - - HeaderView.prototype.update = function(url, apiKey, trigger) { - if (trigger == null) { - trigger = false; - } - $('#input_baseUrl').val(url); - if (trigger) { - return this.trigger('update-swagger-ui', { - url: url - }); - } - }; - - return HeaderView; - -})(Backbone.View); - -var MainView, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -MainView = (function(superClass) { - var sorters; - - extend(MainView, superClass); - - function MainView() { - return MainView.__super__.constructor.apply(this, arguments); - } - - sorters = { - 'alpha': function(a, b) { - return a.path.localeCompare(b.path); - }, - 'method': function(a, b) { - return a.method.localeCompare(b.method); - } - }; - - MainView.prototype.initialize = function(opts) { - var auth, key, ref, value; - if (opts == null) { - opts = {}; - } - this.model.auths = []; - ref = this.model.securityDefinitions; - for (key in ref) { - value = ref[key]; - auth = { - name: key, - type: value.type, - value: value - }; - this.model.auths.push(auth); - } - if (this.model.swaggerVersion === "2.0") { - if ("validatorUrl" in opts.swaggerOptions) { - return this.model.validatorUrl = opts.swaggerOptions.validatorUrl; - } else if (this.model.url.indexOf("localhost") > 0) { - return this.model.validatorUrl = null; - } else { - return this.model.validatorUrl = "http://online.swagger.io/validator"; - } - } - }; - - MainView.prototype.render = function() { - var auth, button, counter, i, id, len, name, ref, resource, resources; - if (this.model.securityDefinitions) { - for (name in this.model.securityDefinitions) { - auth = this.model.securityDefinitions[name]; - if (auth.type === "apiKey" && $("#apikey_button").length === 0) { - button = new ApiKeyButton({ - model: auth - }).render().el; - $('.auth_main_container').append(button); - } - if (auth.type === "basicAuth" && $("#basic_auth_button").length === 0) { - button = new BasicAuthButton({ - model: auth - }).render().el; - $('.auth_main_container').append(button); - } - } - } - $(this.el).html(Handlebars.templates.main(this.model)); - resources = {}; - counter = 0; - ref = this.model.apisArray; - for (i = 0, len = ref.length; i < len; i++) { - resource = ref[i]; - id = resource.name; - while (typeof resources[id] !== 'undefined') { - id = id + "_" + counter; - counter += 1; - } - resource.id = id; - resources[id] = resource; - this.addResource(resource, this.model.auths); - } - $('.propWrap').hover(function() { - return $('.optionsWrapper', $(this)).show(); - }, function() { - return $('.optionsWrapper', $(this)).hide(); - }); - return this; - }; - - MainView.prototype.addResource = function(resource, auths) { - var resourceView; - resource.id = resource.id.replace(/\s/g, '_'); - resourceView = new ResourceView({ - model: resource, - tagName: 'li', - id: 'resource_' + resource.id, - className: 'resource', - auths: auths, - swaggerOptions: this.options.swaggerOptions, - parent: this - }); - return $('#resources', this.el).append(resourceView.render().el); - }; - - MainView.prototype.clear = function() { - return $(this.el).html(''); - }; - - return MainView; - -})(Backbone.View); - -var OperationView, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - -OperationView = (function(superClass) { - extend(OperationView, superClass); - - function OperationView() { - return OperationView.__super__.constructor.apply(this, arguments); - } - - OperationView.prototype.invocationUrl = null; - - OperationView.prototype.events = { - 'submit .sandbox': 'submitOperation', - 'click .submit': 'submitOperation', - 'click .response_hider': 'hideResponse', - 'click .toggleOperation': 'toggleOperationContent', - 'mouseenter .api-ic': 'mouseEnter', - 'mouseout .api-ic': 'mouseExit' - }; - - OperationView.prototype.initialize = function(opts) { - if (opts == null) { - opts = {}; - } - this.auths = opts.auths; - this.parentId = this.model.parentId; - this.nickname = this.model.nickname; - return this; - }; - - OperationView.prototype.mouseEnter = function(e) { - var elem, hgh, pos, scMaxX, scMaxY, scX, scY, wd, x, y; - elem = $(this.el).find('.content'); - x = e.pageX; - y = e.pageY; - scX = $(window).scrollLeft(); - scY = $(window).scrollTop(); - scMaxX = scX + $(window).width(); - scMaxY = scY + $(window).height(); - wd = elem.width(); - hgh = elem.height(); - if (x + wd > scMaxX) { - x = scMaxX - wd; - } - if (x < scX) { - x = scX; - } - if (y + hgh > scMaxY) { - y = scMaxY - hgh; - } - if (y < scY) { - y = scY; - } - pos = {}; - pos.top = y; - pos.left = x; - elem.css(pos); - return $(e.currentTarget.parentNode).find('#api_information_panel').show(); - }; - - OperationView.prototype.mouseExit = function(e) { - return $(e.currentTarget.parentNode).find('#api_information_panel').hide(); - }; - - OperationView.prototype.render = function() { - var a, auth, auths, code, contentTypeModel, isMethodSubmissionSupported, k, key, l, len, len1, len2, len3, len4, m, modelAuths, n, o, p, param, q, ref, ref1, ref2, ref3, ref4, ref5, responseContentTypeView, responseSignatureView, schema, schemaObj, scopeIndex, signatureModel, statusCode, successResponse, type, v, value; - isMethodSubmissionSupported = jQuery.inArray(this.model.method, this.model.supportedSubmitMethods()) >= 0; - if (!isMethodSubmissionSupported) { - this.model.isReadOnly = true; - } - this.model.description = this.model.description || this.model.notes; - if (this.model.description) { - this.model.description = this.model.description.replace(/(?:\r\n|\r|\n)/g, '
'); - } - this.model.oauth = null; - modelAuths = this.model.authorizations || this.model.security; - if (modelAuths) { - if (Array.isArray(modelAuths)) { - for (l = 0, len = modelAuths.length; l < len; l++) { - auths = modelAuths[l]; - for (key in auths) { - auth = auths[key]; - for (a in this.auths) { - auth = this.auths[a]; - if (auth.type === 'oauth2') { - this.model.oauth = {}; - this.model.oauth.scopes = []; - ref1 = auth.value.scopes; - for (k in ref1) { - v = ref1[k]; - scopeIndex = auths[key].indexOf(k); - if (scopeIndex >= 0) { - o = { - scope: k, - description: v - }; - this.model.oauth.scopes.push(o); - } - } - } - } - } - } - } else { - for (k in modelAuths) { - v = modelAuths[k]; - if (k === "oauth2") { - if (this.model.oauth === null) { - this.model.oauth = {}; - } - if (this.model.oauth.scopes === void 0) { - this.model.oauth.scopes = []; - } - for (m = 0, len1 = v.length; m < len1; m++) { - o = v[m]; - this.model.oauth.scopes.push(o); - } - } - } - } - } - if (typeof this.model.responses !== 'undefined') { - this.model.responseMessages = []; - ref2 = this.model.responses; - for (code in ref2) { - value = ref2[code]; - schema = null; - schemaObj = this.model.responses[code].schema; - if (schemaObj && schemaObj['$ref']) { - schema = schemaObj['$ref']; - if (schema.indexOf('#/definitions/') === 0) { - schema = schema.substring('#/definitions/'.length); - } - } - this.model.responseMessages.push({ - code: code, - message: value.description, - responseModel: schema - }); - } - } - if (typeof this.model.responseMessages === 'undefined') { - this.model.responseMessages = []; - } - signatureModel = null; - if (this.model.successResponse) { - successResponse = this.model.successResponse; - for (key in successResponse) { - value = successResponse[key]; - this.model.successCode = key; - if (typeof value === 'object' && typeof value.createJSONSample === 'function') { - signatureModel = { - sampleJSON: JSON.stringify(value.createJSONSample(), void 0, 2), - isParam: false, - signature: value.getMockSignature() - }; - } - } - } else if (this.model.responseClassSignature && this.model.responseClassSignature !== 'string') { - signatureModel = { - sampleJSON: this.model.responseSampleJSON, - isParam: false, - signature: this.model.responseClassSignature - }; - } - $(this.el).html(Handlebars.templates.operation(this.model)); - if (signatureModel) { - responseSignatureView = new SignatureView({ - model: signatureModel, - tagName: 'div', - parent: this - }); - $('.model-signature', $(this.el)).append(responseSignatureView.render().el); - } else { - this.model.responseClassSignature = 'string'; - $('.model-signature', $(this.el)).html(this.model.type); - } - contentTypeModel = { - isParam: false - }; - contentTypeModel.consumes = this.model.consumes; - contentTypeModel.produces = this.model.produces; - ref3 = this.model.parameters; - for (n = 0, len2 = ref3.length; n < len2; n++) { - param = ref3[n]; - type = param.type || param.dataType || ''; - if (typeof type === 'undefined') { - schema = param.schema; - if (schema && schema['$ref']) { - ref = schema['$ref']; - if (ref.indexOf('#/definitions/') === 0) { - type = ref.substring('#/definitions/'.length); - } else { - type = ref; - } - } - } - if (type && type.toLowerCase() === 'file') { - if (!contentTypeModel.consumes) { - contentTypeModel.consumes = 'multipart/form-data'; - } - } - param.type = type; - } - responseContentTypeView = new ResponseContentTypeView({ - model: contentTypeModel, - parent: this - }); - $('.response-content-type', $(this.el)).append(responseContentTypeView.render().el); - ref4 = this.model.parameters; - for (p = 0, len3 = ref4.length; p < len3; p++) { - param = ref4[p]; - this.addParameter(param, contentTypeModel.consumes); - } - ref5 = this.model.responseMessages; - for (q = 0, len4 = ref5.length; q < len4; q++) { - statusCode = ref5[q]; - this.addStatusCode(statusCode); - } - return this; - }; - - OperationView.prototype.addParameter = function(param, consumes) { - var paramView; - param.consumes = consumes; - paramView = new ParameterView({ - model: param, - tagName: 'tr', - readOnly: this.model.isReadOnly, - parent: this - }); - return $('.operation-params', $(this.el)).append(paramView.render().el); - }; - - OperationView.prototype.addStatusCode = function(statusCode) { - var statusCodeView; - statusCodeView = new StatusCodeView({ - model: statusCode, - tagName: 'tr', - parent: this - }); - return $('.operation-status', $(this.el)).append(statusCodeView.render().el); - }; - - OperationView.prototype.submitOperation = function(e) { - var error_free, form, isFileUpload, l, len, len1, len2, m, map, n, o, opts, ref1, ref2, ref3, val; - if (e != null) { - e.preventDefault(); - } - form = $('.sandbox', $(this.el)); - error_free = true; - form.find("input.required").each(function() { - $(this).removeClass("error"); - if (jQuery.trim($(this).val()) === "") { - $(this).addClass("error"); - $(this).wiggle({ - callback: (function(_this) { - return function() { - return $(_this).focus(); - }; - })(this) - }); - return error_free = false; - } - }); - form.find("textarea.required").each(function() { - $(this).removeClass("error"); - if (jQuery.trim($(this).val()) === "") { - $(this).addClass("error"); - $(this).wiggle({ - callback: (function(_this) { - return function() { - return $(_this).focus(); - }; - })(this) - }); - return error_free = false; - } - }); - if (error_free) { - map = {}; - opts = { - parent: this - }; - isFileUpload = false; - ref1 = form.find("input"); - for (l = 0, len = ref1.length; l < len; l++) { - o = ref1[l]; - if ((o.value != null) && jQuery.trim(o.value).length > 0) { - map[o.name] = o.value; - } - if (o.type === "file") { - map[o.name] = o.files[0]; - isFileUpload = true; - } - } - ref2 = form.find("textarea"); - for (m = 0, len1 = ref2.length; m < len1; m++) { - o = ref2[m]; - if ((o.value != null) && jQuery.trim(o.value).length > 0) { - map[o.name] = o.value; - } - } - ref3 = form.find("select"); - for (n = 0, len2 = ref3.length; n < len2; n++) { - o = ref3[n]; - val = this.getSelectedValue(o); - if ((val != null) && jQuery.trim(val).length > 0) { - map[o.name] = val; - } - } - opts.responseContentType = $("div select[name=responseContentType]", $(this.el)).val(); - opts.requestContentType = $("div select[name=parameterContentType]", $(this.el)).val(); - $(".response_throbber", $(this.el)).show(); - if (isFileUpload) { - return this.handleFileUpload(map, form); - } else { - return this.model["do"](map, opts, this.showCompleteStatus, this.showErrorStatus, this); - } - } - }; - - OperationView.prototype.success = function(response, parent) { - return parent.showCompleteStatus(response); - }; - - OperationView.prototype.handleFileUpload = function(map, form) { - var bodyParam, el, headerParams, l, len, len1, len2, len3, m, n, o, obj, p, param, params, ref1, ref2, ref3, ref4; - ref1 = form.serializeArray(); - for (l = 0, len = ref1.length; l < len; l++) { - o = ref1[l]; - if ((o.value != null) && jQuery.trim(o.value).length > 0) { - map[o.name] = o.value; - } - } - bodyParam = new FormData(); - params = 0; - ref2 = this.model.parameters; - for (m = 0, len1 = ref2.length; m < len1; m++) { - param = ref2[m]; - if (param.paramType === 'form' || param["in"] === 'formData') { - if (param.type.toLowerCase() !== 'file' && map[param.name] !== void 0) { - bodyParam.append(param.name, map[param.name]); - } - } - } - headerParams = {}; - ref3 = this.model.parameters; - for (n = 0, len2 = ref3.length; n < len2; n++) { - param = ref3[n]; - if (param.paramType === 'header') { - headerParams[param.name] = map[param.name]; - } - } - ref4 = form.find('input[type~="file"]'); - for (p = 0, len3 = ref4.length; p < len3; p++) { - el = ref4[p]; - if (typeof el.files[0] !== 'undefined') { - bodyParam.append($(el).attr('name'), el.files[0]); - params += 1; - } - } - this.invocationUrl = this.model.supportHeaderParams() ? (headerParams = this.model.getHeaderParams(map), delete headerParams['Content-Type'], this.model.urlify(map, false)) : this.model.urlify(map, true); - $(".request_url", $(this.el)).html("
");
-    $(".request_url pre", $(this.el)).text(this.invocationUrl);
-    obj = {
-      type: this.model.method,
-      url: this.invocationUrl,
-      headers: headerParams,
-      data: bodyParam,
-      dataType: 'json',
-      contentType: false,
-      processData: false,
-      error: (function(_this) {
-        return function(data, textStatus, error) {
-          return _this.showErrorStatus(_this.wrap(data), _this);
-        };
-      })(this),
-      success: (function(_this) {
-        return function(data) {
-          return _this.showResponse(data, _this);
-        };
-      })(this),
-      complete: (function(_this) {
-        return function(data) {
-          return _this.showCompleteStatus(_this.wrap(data), _this);
-        };
-      })(this)
-    };
-    if (window.authorizations) {
-      window.authorizations.apply(obj);
-    }
-    if (params === 0) {
-      obj.data.append("fake", "true");
-    }
-    jQuery.ajax(obj);
-    return false;
-  };
-
-  OperationView.prototype.wrap = function(data) {
-    var h, headerArray, headers, i, l, len, o;
-    headers = {};
-    headerArray = data.getAllResponseHeaders().split("\r");
-    for (l = 0, len = headerArray.length; l < len; l++) {
-      i = headerArray[l];
-      h = i.match(/^([^:]*?):(.*)$/);
-      if (!h) {
-        h = [];
-      }
-      h.shift();
-      if (h[0] !== void 0 && h[1] !== void 0) {
-        headers[h[0].trim()] = h[1].trim();
-      }
-    }
-    o = {};
-    o.content = {};
-    o.content.data = data.responseText;
-    o.headers = headers;
-    o.request = {};
-    o.request.url = this.invocationUrl;
-    o.status = data.status;
-    return o;
-  };
-
-  OperationView.prototype.getSelectedValue = function(select) {
-    var l, len, opt, options, ref1;
-    if (!select.multiple) {
-      return select.value;
-    } else {
-      options = [];
-      ref1 = select.options;
-      for (l = 0, len = ref1.length; l < len; l++) {
-        opt = ref1[l];
-        if (opt.selected) {
-          options.push(opt.value);
-        }
-      }
-      if (options.length > 0) {
-        return options;
-      } else {
-        return null;
-      }
-    }
-  };
-
-  OperationView.prototype.hideResponse = function(e) {
-    if (e != null) {
-      e.preventDefault();
-    }
-    $(".response", $(this.el)).slideUp();
-    return $(".response_hider", $(this.el)).fadeOut();
-  };
-
-  OperationView.prototype.showResponse = function(response) {
-    var prettyJson;
-    prettyJson = JSON.stringify(response, null, "\t").replace(/\n/g, "
"); - return $(".response_body", $(this.el)).html(escape(prettyJson)); - }; - - OperationView.prototype.showErrorStatus = function(data, parent) { - return parent.showStatus(data); - }; - - OperationView.prototype.showCompleteStatus = function(data, parent) { - return parent.showStatus(data); - }; - - OperationView.prototype.formatXml = function(xml) { - var contexp, fn, formatted, indent, l, lastType, len, lines, ln, pad, reg, transitions, wsexp; - reg = /(>)(<)(\/*)/g; - wsexp = /[ ]*(.*)[ ]+\n/g; - contexp = /(<.+>)(.+\n)/g; - xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2'); - pad = 0; - formatted = ''; - lines = xml.split('\n'); - indent = 0; - lastType = 'other'; - transitions = { - 'single->single': 0, - 'single->closing': -1, - 'single->opening': 0, - 'single->other': 0, - 'closing->single': 0, - 'closing->closing': -1, - 'closing->opening': 0, - 'closing->other': 0, - 'opening->single': 1, - 'opening->closing': 0, - 'opening->opening': 1, - 'opening->other': 1, - 'other->single': 0, - 'other->closing': -1, - 'other->opening': 0, - 'other->other': 0 - }; - fn = function(ln) { - var fromTo, j, key, padding, type, types, value; - types = { - single: Boolean(ln.match(/<.+\/>/)), - closing: Boolean(ln.match(/<\/.+>/)), - opening: Boolean(ln.match(/<[^!?].*>/)) - }; - type = ((function() { - var results; - results = []; - for (key in types) { - value = types[key]; - if (value) { - results.push(key); - } - } - return results; - })())[0]; - type = type === void 0 ? 'other' : type; - fromTo = lastType + '->' + type; - lastType = type; - padding = ''; - indent += transitions[fromTo]; - padding = ((function() { - var m, ref1, results; - results = []; - for (j = m = 0, ref1 = indent; 0 <= ref1 ? m < ref1 : m > ref1; j = 0 <= ref1 ? ++m : --m) { - results.push(' '); - } - return results; - })()).join(''); - if (fromTo === 'opening->closing') { - return formatted = formatted.substr(0, formatted.length - 1) + ln + '\n'; - } else { - return formatted += padding + ln + '\n'; - } - }; - for (l = 0, len = lines.length; l < len; l++) { - ln = lines[l]; - fn(ln); - } - return formatted; - }; - - OperationView.prototype.showStatus = function(response) { - var code, content, contentType, e, headers, json, opts, pre, response_body, response_body_el, supportsAudioPlayback, url; - if (response.content === void 0) { - content = response.data; - url = response.url; - } else { - content = response.content.data; - url = response.request.url; - } - headers = response.headers; - contentType = null; - if (headers) { - contentType = headers["Content-Type"] || headers["content-type"]; - if (contentType) { - contentType = contentType.split(";")[0].trim(); - } - } - $(".response_body", $(this.el)).removeClass('json'); - $(".response_body", $(this.el)).removeClass('xml'); - supportsAudioPlayback = function(contentType) { - var audioElement; - audioElement = document.createElement('audio'); - return !!(audioElement.canPlayType && audioElement.canPlayType(contentType).replace(/no/, '')); - }; - if (!content) { - code = $('').text("no content"); - pre = $('
').append(code);
-    } else if (contentType === "application/json" || /\+json$/.test(contentType)) {
-      json = null;
-      try {
-        json = JSON.stringify(JSON.parse(content), null, "  ");
-      } catch (_error) {
-        e = _error;
-        json = "can't parse JSON.  Raw result:\n\n" + content;
-      }
-      code = $('').text(json);
-      pre = $('
').append(code);
-    } else if (contentType === "application/xml" || /\+xml$/.test(contentType)) {
-      code = $('').text(this.formatXml(content));
-      pre = $('
').append(code);
-    } else if (contentType === "text/html") {
-      code = $('').html(_.escape(content));
-      pre = $('
').append(code);
-    } else if (/^image\//.test(contentType)) {
-      pre = $('').attr('src', url);
-    } else if (/^audio\//.test(contentType) && supportsAudioPlayback(contentType)) {
-      pre = $('