swagger-ui_rails 0.1.7 → 2.1.0.alpha.7.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +4 -2
  3. data/Rakefile +45 -0
  4. data/app/assets/images/explorer_icons.png +0 -0
  5. data/app/assets/javascripts/swagger-oauth.js +211 -0
  6. data/app/assets/javascripts/swagger-ui/index.js +13 -0
  7. data/app/assets/javascripts/{lib → swagger-ui/lib}/backbone-min.js +0 -0
  8. data/app/assets/javascripts/{lib → swagger-ui/lib}/handlebars-1.0.0.js +0 -0
  9. data/app/assets/javascripts/{lib → swagger-ui/lib}/highlight.7.3.pack.js +0 -0
  10. data/app/assets/javascripts/{lib → swagger-ui/lib}/jquery-1.8.0.min.js +0 -0
  11. data/app/assets/javascripts/{lib → swagger-ui/lib}/jquery.ba-bbq.min.js +0 -0
  12. data/app/assets/javascripts/{lib → swagger-ui/lib}/jquery.slideto.min.js +0 -0
  13. data/app/assets/javascripts/{lib → swagger-ui/lib}/jquery.wiggle.min.js +0 -0
  14. data/app/assets/javascripts/{lib → swagger-ui/lib}/shred.bundle.js +3 -3
  15. data/app/assets/javascripts/swagger-ui/lib/swagger-client.js +1606 -0
  16. data/app/assets/javascripts/swagger-ui/lib/swagger.js +1725 -0
  17. data/app/assets/javascripts/{lib → swagger-ui/lib}/underscore-min.js +0 -0
  18. data/app/assets/javascripts/swagger-ui/swagger-oauth.js +237 -0
  19. data/app/assets/javascripts/{swagger-ui.js.erb → swagger-ui/swagger-ui.js.erb} +1076 -520
  20. data/app/assets/stylesheets/swagger-ui/index.css +5 -0
  21. data/app/assets/stylesheets/swagger-ui/reset.css +125 -0
  22. data/app/assets/stylesheets/swagger-ui/screen.css +1224 -0
  23. data/app/views/swagger_ui/_swagger_ui.html.erb +1 -1
  24. data/lib/swagger-ui_rails/engine.rb +12 -2
  25. data/lib/swagger-ui_rails/version.rb +1 -1
  26. metadata +29 -28
  27. data/.gitignore +0 -17
  28. data/Gemfile +0 -4
  29. data/app/assets/javascripts/lib/shred/content.js +0 -193
  30. data/app/assets/javascripts/lib/swagger.js +0 -1480
  31. data/app/assets/stylesheets/hightlight.default.css +0 -135
  32. data/app/assets/stylesheets/screen.css +0 -1070
  33. data/app/assets/stylesheets/swagger-ui.css +0 -4
  34. data/swagger-ui_rails.gemspec +0 -23
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 6f16892da4c8e1d4512d2c812d9f97ff6b1a6f7e
4
- data.tar.gz: 8dc5172e35e1745954c7855580eb3063097b9011
3
+ metadata.gz: 939dd77729ecdf92e9ebb7e076b7aad79138bb2e
4
+ data.tar.gz: 7e1ab0f0d2778ebb57899a5dd947eb22ae42a8e0
5
5
  SHA512:
6
- metadata.gz: 424df93422b9eca4bc7d8e6ef69237f855bc9798b377bd25512bb10681df9c4d9bda4fda538d6be4d50c0e8a0a8ab3030d663f92738b66860b04008a600df31a
7
- data.tar.gz: 1d23987e2bdd41c740a76a65e9804e28da812fdb114d2c0b4a05aac96b0848cc2c3de7677cd0b01b37dd66de7b59b4e61c8ac4b4c6b2050820f32e715d84d560
6
+ metadata.gz: 9c66e1e296b78735be4ebb9e28b4cc0509492fdc0557786d8b83872cf053a1de5c92cfe37fbcb46729984f1a15a17322753897e7e47880afc4b91f7ad80499f2
7
+ data.tar.gz: 1f7057f798c3843b865fb1f3182bf489e4350a6525fd4a66753338cf9c0fefac176d5a7677cb3d53d27af64cb5cf87dfb8573ae84285254372fb0824d5a1252f
data/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  A gem that lets you add [swagger-ui](https://github.com/wordnik/swagger-ui) easily to your rails application
4
4
 
5
+ Current version: 2.1.0-alpha.7
6
+
5
7
  ## Installation
6
8
 
7
9
  Add this line to your application's Gemfile:
@@ -12,11 +14,11 @@ Add this line to your application's Gemfile:
12
14
 
13
15
  Add to your application.js
14
16
 
15
- //= swagger-ui
17
+ //= require swagger-ui
16
18
 
17
19
  Add to your application.css
18
20
 
19
- *= swagger-ui
21
+ *= require swagger-ui
20
22
 
21
23
  Then add to some api_docs/index.html
22
24
 
data/Rakefile CHANGED
@@ -1 +1,46 @@
1
+ require "fileutils"
1
2
  require "bundler/gem_tasks"
3
+
4
+ desc "Syncronize Swagger UI"
5
+ task :sync_swagger_ui do
6
+
7
+ source = File.join File.dirname(__FILE__), "swagger-ui-src", "dist"
8
+ destination = File.join File.dirname(__FILE__), "app", "assets"
9
+
10
+ js_destination = File.join destination, "javascripts", "swagger-ui"
11
+
12
+ idx = File.join js_destination, "index.js"
13
+
14
+ File.read(idx).each_line do | line |
15
+ if line =~ /require (.*)/
16
+ file = "#{source}/#{$1.strip}"
17
+ # hack to make throbber.gif available on asset pipeline
18
+ if $1.strip =~ /swagger-ui\.js/
19
+ contents = File.read file
20
+ File.open "#{file.gsub(source, js_destination)}.erb", "w" do | f |
21
+ f << contents.gsub("src='images/throbber.gif'", "src='<%= asset_path(\"throbber.gif\") %>'")
22
+ end
23
+ else
24
+ FileUtils.cp_r file, file.gsub(source, js_destination), verbose: true
25
+ end
26
+ end
27
+ end
28
+
29
+ oauth_source = File.join source, "lib", "swagger-oauth.js"
30
+ oauth_dest = js_destination.gsub "swagger-ui-src", "swagger-oauth.js"
31
+
32
+ FileUtils.cp_r oauth_source, oauth_dest, verbose: true
33
+
34
+ css_destination = File.join destination, "stylesheets", "swagger-ui"
35
+ css_source = File.join source, "css"
36
+
37
+ idx = File.join css_destination, "index.css"
38
+
39
+ File.read(idx).each_line do | line |
40
+ if line =~ /require (.*)\.css/
41
+ file = "#{css_source}/#{$1.strip}.css"
42
+ FileUtils.cp_r file, file.gsub(css_source, css_destination), verbose: true
43
+ end
44
+ end
45
+
46
+ end
@@ -0,0 +1,211 @@
1
+ var appName;
2
+ var popupMask;
3
+ var popupDialog;
4
+ var clientId;
5
+ var realm;
6
+
7
+ function handleLogin() {
8
+ var scopes = [];
9
+
10
+ if(window.swaggerUi.api.authSchemes
11
+ && window.swaggerUi.api.authSchemes.oauth2
12
+ && window.swaggerUi.api.authSchemes.oauth2.scopes) {
13
+ scopes = window.swaggerUi.api.authSchemes.oauth2.scopes;
14
+ }
15
+
16
+ if(window.swaggerUi.api
17
+ && window.swaggerUi.api.info) {
18
+ appName = window.swaggerUi.api.info.title;
19
+ }
20
+
21
+ if(popupDialog.length > 0)
22
+ popupDialog = popupDialog.last();
23
+ else {
24
+ popupDialog = $(
25
+ [
26
+ '<div class="api-popup-dialog">',
27
+ '<div class="api-popup-title">Select OAuth2.0 Scopes</div>',
28
+ '<div class="api-popup-content">',
29
+ '<p>Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.',
30
+ '<a href="#">Learn how to use</a>',
31
+ '</p>',
32
+ '<p><strong>' + appName + '</strong> API requires the following scopes. Select which ones you want to grant to Swagger UI.</p>',
33
+ '<ul class="api-popup-scopes">',
34
+ '</ul>',
35
+ '<p class="error-msg"></p>',
36
+ '<div class="api-popup-actions"><button class="api-popup-authbtn api-button green" type="button">Authorize</button><button class="api-popup-cancel api-button gray" type="button">Cancel</button></div>',
37
+ '</div>',
38
+ '</div>'].join(''));
39
+ $(document.body).append(popupDialog);
40
+
41
+ popup = popupDialog.find('ul.api-popup-scopes').empty();
42
+ for (i = 0; i < scopes.length; i ++) {
43
+ scope = scopes[i];
44
+ str = '<li><input type="checkbox" id="scope_' + i + '" scope="' + scope.scope + '"/>' + '<label for="scope_' + i + '">' + scope.scope;
45
+ if (scope.description) {
46
+ str += '<br/><span class="api-scope-desc">' + scope.description + '</span>';
47
+ }
48
+ str += '</label></li>';
49
+ popup.append(str);
50
+ }
51
+ }
52
+
53
+ var $win = $(window),
54
+ dw = $win.width(),
55
+ dh = $win.height(),
56
+ st = $win.scrollTop(),
57
+ dlgWd = popupDialog.outerWidth(),
58
+ dlgHt = popupDialog.outerHeight(),
59
+ top = (dh -dlgHt)/2 + st,
60
+ left = (dw - dlgWd)/2;
61
+
62
+ popupDialog.css({
63
+ top: (top < 0? 0 : top) + 'px',
64
+ left: (left < 0? 0 : left) + 'px'
65
+ });
66
+
67
+ popupDialog.find('button.api-popup-cancel').click(function() {
68
+ popupMask.hide();
69
+ popupDialog.hide();
70
+ });
71
+ popupDialog.find('button.api-popup-authbtn').click(function() {
72
+ popupMask.hide();
73
+ popupDialog.hide();
74
+
75
+ var authSchemes = window.swaggerUi.api.authSchemes;
76
+ var host = window.location;
77
+ var redirectUrl = host.protocol + '//' + host.host + "/o2c.html";
78
+ var url = null;
79
+
80
+ var p = window.swaggerUi.api.authSchemes;
81
+ for (var key in p) {
82
+ if (p.hasOwnProperty(key)) {
83
+ var o = p[key].grantTypes;
84
+ for(var t in o) {
85
+ if(o.hasOwnProperty(t) && t === 'implicit') {
86
+ var dets = o[t];
87
+ url = dets.loginEndpoint.url + "?response_type=token";
88
+ window.swaggerUi.tokenName = dets.tokenName;
89
+ }
90
+ }
91
+ }
92
+ }
93
+ var scopes = []
94
+ var o = $('.api-popup-scopes').find('input:checked');
95
+
96
+ for(k =0; k < o.length; k++) {
97
+ scopes.push($(o[k]).attr("scope"));
98
+ }
99
+
100
+ window.enabledScopes=scopes;
101
+
102
+ url += '&redirect_uri=' + encodeURIComponent(redirectUrl);
103
+ url += '&realm=' + encodeURIComponent(realm);
104
+ url += '&client_id=' + encodeURIComponent(clientId);
105
+ url += '&scope=' + encodeURIComponent(scopes);
106
+
107
+ window.open(url);
108
+ });
109
+
110
+ popupMask.show();
111
+ popupDialog.show();
112
+ return;
113
+ }
114
+
115
+
116
+ function handleLogout() {
117
+ for(key in window.authorizations.authz){
118
+ window.authorizations.remove(key)
119
+ }
120
+ window.enabledScopes = null;
121
+ $('.api-ic.ic-on').addClass('ic-off');
122
+ $('.api-ic.ic-on').removeClass('ic-on');
123
+
124
+ // set the info box
125
+ $('.api-ic.ic-warning').addClass('ic-error');
126
+ $('.api-ic.ic-warning').removeClass('ic-warning');
127
+ }
128
+
129
+ function initOAuth(opts) {
130
+ var o = (opts||{});
131
+ var errors = [];
132
+
133
+ appName = (o.appName||errors.push("missing appName"));
134
+ popupMask = (o.popupMask||$('#api-common-mask'));
135
+ popupDialog = (o.popupDialog||$('.api-popup-dialog'));
136
+ clientId = (o.clientId||errors.push("missing client id"));
137
+ realm = (o.realm||errors.push("missing realm"));
138
+
139
+ if(errors.length > 0){
140
+ log("auth unable initialize oauth: " + errors);
141
+ return;
142
+ }
143
+
144
+ $('pre code').each(function(i, e) {hljs.highlightBlock(e)});
145
+ $('.api-ic').click(function(s) {
146
+ if($(s.target).hasClass('ic-off'))
147
+ handleLogin();
148
+ else {
149
+ handleLogout();
150
+ }
151
+ false;
152
+ });
153
+ }
154
+
155
+ function onOAuthComplete(token) {
156
+ if(token) {
157
+ if(token.error) {
158
+ var checkbox = $('input[type=checkbox],.secured')
159
+ checkbox.each(function(pos){
160
+ checkbox[pos].checked = false;
161
+ });
162
+ alert(token.error);
163
+ }
164
+ else {
165
+ var b = token[window.swaggerUi.tokenName];
166
+ if(b){
167
+ // if all roles are satisfied
168
+ var o = null;
169
+ $.each($('.auth #api_information_panel'), function(k, v) {
170
+ var children = v;
171
+ if(children && children.childNodes) {
172
+ var requiredScopes = [];
173
+ $.each((children.childNodes), function (k1, v1){
174
+ var inner = v1.innerHTML;
175
+ if(inner)
176
+ requiredScopes.push(inner);
177
+ });
178
+ var diff = [];
179
+ for(var i=0; i < requiredScopes.length; i++) {
180
+ var s = requiredScopes[i];
181
+ if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) {
182
+ diff.push(s);
183
+ }
184
+ }
185
+ if(diff.length > 0){
186
+ o = v.parentNode;
187
+ $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off');
188
+ $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on');
189
+
190
+ // sorry, not all scopes are satisfied
191
+ $(o).find('.api-ic').addClass('ic-warning');
192
+ $(o).find('.api-ic').removeClass('ic-error');
193
+ }
194
+ else {
195
+ o = v.parentNode;
196
+ $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on');
197
+ $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off');
198
+
199
+ // all scopes are satisfied
200
+ $(o).find('.api-ic').addClass('ic-info');
201
+ $(o).find('.api-ic').removeClass('ic-warning');
202
+ $(o).find('.api-ic').removeClass('ic-error');
203
+ }
204
+ }
205
+ });
206
+
207
+ window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "Bearer " + b, "header"));
208
+ }
209
+ }
210
+ }
211
+ }
@@ -0,0 +1,13 @@
1
+ //= require ./lib/shred.bundle.js
2
+ //= require ./lib/jquery-1.8.0.min.js
3
+ //= require ./lib/jquery.slideto.min.js
4
+ //= require ./lib/jquery.wiggle.min.js
5
+ //= require ./lib/jquery.ba-bbq.min.js
6
+ //= require ./lib/handlebars-1.0.0.js
7
+ //= require ./lib/underscore-min.js
8
+ //= require ./lib/backbone-min.js
9
+ //= require ./lib/swagger.js
10
+ //= require ./lib/swagger-client.js
11
+ //= require ./swagger-ui.js
12
+ //= require ./lib/highlight.7.3.pack.js
13
+
@@ -2131,10 +2131,10 @@ require.define("/shred/mixins/headers.js", function (require, module, exports, _
2131
2131
  // to `Content-Type`.
2132
2132
 
2133
2133
  var corsetCase = function(string) {
2134
- return string.toLowerCase()
2134
+ return string;//.toLowerCase()
2135
2135
  //.replace("_","-")
2136
- .replace(/(^|-)(\w)/g,
2137
- function(s) { return s.toUpperCase(); });
2136
+ // .replace(/(^|-)(\w)/g,
2137
+ // function(s) { return s.toUpperCase(); });
2138
2138
  };
2139
2139
 
2140
2140
  // We suspect that `initializeHeaders` was once more complicated ...
@@ -0,0 +1,1606 @@
1
+ // swagger-client.js
2
+ // version 2.1.0-alpha.5
3
+ /**
4
+ * Array Model
5
+ **/
6
+ var ArrayModel = function(definition) {
7
+ this.name = "name";
8
+ this.definition = definition || {};
9
+ this.properties = [];
10
+ this.type;
11
+ this.ref;
12
+
13
+ var requiredFields = definition.enum || [];
14
+ var items = definition.items;
15
+ if(items) {
16
+ var type = items.type;
17
+ if(items.type) {
18
+ this.type = typeFromJsonSchema(type.type, type.format);
19
+ }
20
+ else {
21
+ this.ref = items['$ref'];
22
+ }
23
+ }
24
+ }
25
+
26
+ ArrayModel.prototype.createJSONSample = function(modelsToIgnore) {
27
+ var result;
28
+ modelsToIgnore = (modelsToIgnore||{})
29
+ if(this.type) {
30
+ result = type;
31
+ }
32
+ else if (this.ref) {
33
+ var name = simpleRef(this.ref);
34
+ result = models[name].createJSONSample();
35
+ }
36
+ return [ result ];
37
+ };
38
+
39
+ ArrayModel.prototype.getSampleValue = function(modelsToIgnore) {
40
+ var result;
41
+ modelsToIgnore = (modelsToIgnore || {})
42
+ if(this.type) {
43
+ result = type;
44
+ }
45
+ else if (this.ref) {
46
+ var name = simpleRef(this.ref);
47
+ result = models[name].getSampleValue(modelsToIgnore);
48
+ }
49
+ return [ result ];
50
+ }
51
+
52
+ ArrayModel.prototype.getMockSignature = function(modelsToIgnore) {
53
+ var propertiesStr = [];
54
+
55
+ if(this.ref) {
56
+ return models[simpleRef(this.ref)].getMockSignature();
57
+ }
58
+ };
59
+
60
+ /**
61
+ * SwaggerAuthorizations applys the correct authorization to an operation being executed
62
+ */
63
+ var SwaggerAuthorizations = function() {
64
+ this.authz = {};
65
+ };
66
+
67
+ SwaggerAuthorizations.prototype.add = function(name, auth) {
68
+ this.authz[name] = auth;
69
+ return auth;
70
+ };
71
+
72
+ SwaggerAuthorizations.prototype.remove = function(name) {
73
+ return delete this.authz[name];
74
+ };
75
+
76
+ SwaggerAuthorizations.prototype.apply = function(obj, authorizations) {
77
+ var status = null;
78
+ var key;
79
+
80
+ // if the "authorizations" key is undefined, or has an empty array, add all keys
81
+ if(typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) {
82
+ for (key in this.authz) {
83
+ value = this.authz[key];
84
+ result = value.apply(obj, authorizations);
85
+ if (result === true)
86
+ status = true;
87
+ }
88
+ }
89
+ else {
90
+ if(Array.isArray(authorizations)) {
91
+ var i;
92
+ for(i = 0; i < authorizations.length; i++) {
93
+ var auth = authorizations[i];
94
+ log(auth);
95
+ for (key in this.authz) {
96
+ var value = this.authz[key];
97
+ if(typeof value !== 'undefined') {
98
+ result = value.apply(obj, authorizations);
99
+ if (result === true)
100
+ status = true;
101
+ }
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ return status;
108
+ };
109
+
110
+ /**
111
+ * ApiKeyAuthorization allows a query param or header to be injected
112
+ */
113
+ var ApiKeyAuthorization = function(name, value, type) {
114
+ this.name = name;
115
+ this.value = value;
116
+ this.type = type;
117
+ };
118
+
119
+ ApiKeyAuthorization.prototype.apply = function(obj, authorizations) {
120
+ if (this.type === "query") {
121
+ if (obj.url.indexOf('?') > 0)
122
+ obj.url = obj.url + "&" + this.name + "=" + this.value;
123
+ else
124
+ obj.url = obj.url + "?" + this.name + "=" + this.value;
125
+ return true;
126
+ } else if (this.type === "header") {
127
+ obj.headers[this.name] = this.value;
128
+ return true;
129
+ }
130
+ };
131
+
132
+ var CookieAuthorization = function(cookie) {
133
+ this.cookie = cookie;
134
+ }
135
+
136
+ CookieAuthorization.prototype.apply = function(obj, authorizations) {
137
+ obj.cookieJar = obj.cookieJar || CookieJar();
138
+ obj.cookieJar.setCookie(this.cookie);
139
+ return true;
140
+ }
141
+
142
+ /**
143
+ * Password Authorization is a basic auth implementation
144
+ */
145
+ var PasswordAuthorization = function(name, username, password) {
146
+ this.name = name;
147
+ this.username = username;
148
+ this.password = password;
149
+ this._btoa = null;
150
+ if (typeof window !== 'undefined')
151
+ this._btoa = btoa;
152
+ else
153
+ this._btoa = require("btoa");
154
+ };
155
+
156
+ PasswordAuthorization.prototype.apply = function(obj, authorizations) {
157
+ var base64encoder = this._btoa;
158
+ obj.headers["Authorization"] = "Basic " + base64encoder(this.username + ":" + this.password);
159
+ return true;
160
+ };var __bind = function(fn, me){
161
+ return function(){
162
+ return fn.apply(me, arguments);
163
+ };
164
+ };
165
+
166
+ fail = function(message) {
167
+ log(message);
168
+ }
169
+
170
+ log = function(){
171
+ log.history = log.history || [];
172
+ log.history.push(arguments);
173
+ if(this.console){
174
+ console.log( Array.prototype.slice.call(arguments)[0] );
175
+ }
176
+ };
177
+
178
+ if (!Array.prototype.indexOf) {
179
+ Array.prototype.indexOf = function(obj, start) {
180
+ for (var i = (start || 0), j = this.length; i < j; i++) {
181
+ if (this[i] === obj) { return i; }
182
+ }
183
+ return -1;
184
+ }
185
+ }
186
+
187
+ if (!('filter' in Array.prototype)) {
188
+ Array.prototype.filter= function(filter, that /*opt*/) {
189
+ var other= [], v;
190
+ for (var i=0, n= this.length; i<n; i++)
191
+ if (i in this && filter.call(that, v= this[i], i, this))
192
+ other.push(v);
193
+ return other;
194
+ };
195
+ }
196
+
197
+ if (!('map' in Array.prototype)) {
198
+ Array.prototype.map= function(mapper, that /*opt*/) {
199
+ var other= new Array(this.length);
200
+ for (var i= 0, n= this.length; i<n; i++)
201
+ if (i in this)
202
+ other[i]= mapper.call(that, this[i], i, this);
203
+ return other;
204
+ };
205
+ }
206
+
207
+ Object.keys = Object.keys || (function () {
208
+ var hasOwnProperty = Object.prototype.hasOwnProperty,
209
+ hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
210
+ DontEnums = [
211
+ 'toString',
212
+ 'toLocaleString',
213
+ 'valueOf',
214
+ 'hasOwnProperty',
215
+ 'isPrototypeOf',
216
+ 'propertyIsEnumerable',
217
+ 'constructor'
218
+ ],
219
+ DontEnumsLength = DontEnums.length;
220
+
221
+ return function (o) {
222
+ if (typeof o != "object" && typeof o != "function" || o === null)
223
+ throw new TypeError("Object.keys called on a non-object");
224
+
225
+ var result = [];
226
+ for (var name in o) {
227
+ if (hasOwnProperty.call(o, name))
228
+ result.push(name);
229
+ }
230
+
231
+ if (hasDontEnumBug) {
232
+ for (var i = 0; i < DontEnumsLength; i++) {
233
+ if (hasOwnProperty.call(o, DontEnums[i]))
234
+ result.push(DontEnums[i]);
235
+ }
236
+ }
237
+
238
+ return result;
239
+ };
240
+ })();
241
+ /**
242
+ * PrimitiveModel
243
+ **/
244
+ var PrimitiveModel = function(definition) {
245
+ this.name = "name";
246
+ this.definition = definition || {};
247
+ this.properties = [];
248
+ this.type;
249
+
250
+ var requiredFields = definition.enum || [];
251
+ this.type = typeFromJsonSchema(definition.type, definition.format);
252
+ }
253
+
254
+ PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) {
255
+ var result = this.type;
256
+ return result;
257
+ };
258
+
259
+ PrimitiveModel.prototype.getSampleValue = function() {
260
+ var result = this.type;
261
+ return null;
262
+ }
263
+
264
+ PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) {
265
+ var propertiesStr = [];
266
+ var i;
267
+ for (i = 0; i < this.properties.length; i++) {
268
+ var prop = this.properties[i];
269
+ propertiesStr.push(prop.toString());
270
+ }
271
+
272
+ var strong = '<span class="strong">';
273
+ var stronger = '<span class="stronger">';
274
+ var strongClose = '</span>';
275
+ var classOpen = strong + this.name + ' {' + strongClose;
276
+ var classClose = strong + '}' + strongClose;
277
+ var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
278
+
279
+ if (!modelsToIgnore)
280
+ modelsToIgnore = {};
281
+ modelsToIgnore[this.name] = this;
282
+ var i;
283
+ for (i = 0; i < this.properties.length; i++) {
284
+ var prop = this.properties[i];
285
+ var ref = prop['$ref'];
286
+ var model = models[ref];
287
+ if (model && typeof modelsToIgnore[ref] === 'undefined') {
288
+ returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
289
+ }
290
+ }
291
+ return returnVal;
292
+ };var SwaggerClient = function(url, options) {
293
+ this.isBuilt = false;
294
+ this.url = null;
295
+ this.debug = false;
296
+ this.basePath = null;
297
+ this.authorizations = null;
298
+ this.authorizationScheme = null;
299
+ this.isValid = false;
300
+ this.info = null;
301
+ this.useJQuery = false;
302
+ this.models = models;
303
+
304
+ options = (options||{});
305
+ if (url)
306
+ if (url.url) options = url;
307
+ else this.url = url;
308
+ else options = url;
309
+
310
+ if (options.url != null)
311
+ this.url = options.url;
312
+
313
+ if (options.success != null)
314
+ this.success = options.success;
315
+
316
+ if (typeof options.useJQuery === 'boolean')
317
+ this.useJQuery = options.useJQuery;
318
+
319
+ this.failure = options.failure != null ? options.failure : function() {};
320
+ this.progress = options.progress != null ? options.progress : function() {};
321
+ this.spec = options.spec;
322
+
323
+ if (options.success != null)
324
+ this.build();
325
+ }
326
+
327
+ SwaggerClient.prototype.build = function() {
328
+ var self = this;
329
+ this.progress('fetching resource list: ' + this.url);
330
+ var obj = {
331
+ useJQuery: this.useJQuery,
332
+ url: this.url,
333
+ method: "get",
334
+ headers: {
335
+ accept: "application/json, */*"
336
+ },
337
+ on: {
338
+ error: function(response) {
339
+ if (self.url.substring(0, 4) !== 'http')
340
+ return self.fail('Please specify the protocol for ' + self.url);
341
+ else if (response.status === 0)
342
+ return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
343
+ else if (response.status === 404)
344
+ return self.fail('Can\'t read swagger JSON from ' + self.url);
345
+ else
346
+ return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
347
+ },
348
+ response: function(resp) {
349
+ var responseObj = resp.obj || JSON.parse(resp.data);
350
+ self.swaggerVersion = responseObj.swaggerVersion;
351
+
352
+ if(responseObj.swagger && parseInt(responseObj.swagger) === 2) {
353
+ self.swaggerVersion = responseObj.swagger;
354
+ self.buildFromSpec(responseObj);
355
+ self.isValid = true;
356
+ }
357
+ else {
358
+ self.isValid = false;
359
+ self.failure();
360
+ }
361
+ }
362
+ }
363
+ };
364
+ if(this.spec) {
365
+ var self = this;
366
+ setTimeout(function() { self.buildFromSpec(self.spec); }, 10);
367
+ }
368
+ else {
369
+ var e = (typeof window !== 'undefined' ? window : exports);
370
+ var status = e.authorizations.apply(obj);
371
+ new SwaggerHttp().execute(obj);
372
+ }
373
+
374
+ return this;
375
+ };
376
+
377
+ SwaggerClient.prototype.buildFromSpec = function(response) {
378
+ if(this.isBuilt) return this;
379
+
380
+ this.info = response.info || {};
381
+ this.title = response.title || '';
382
+ this.host = response.host || '';
383
+ this.schemes = response.schemes || [];
384
+ this.scheme;
385
+ this.basePath = response.basePath || '';
386
+ this.apis = {};
387
+ this.apisArray = [];
388
+ this.consumes = response.consumes;
389
+ this.produces = response.produces;
390
+ this.securityDefinitions = response.securityDefinitions;
391
+
392
+ // legacy support
393
+ this.authSchemes = response.securityDefinitions;
394
+
395
+ var location = this.parseUri(this.url);
396
+ if(typeof this.schemes === 'undefined' || this.schemes.length === 0) {
397
+ this.scheme = location.scheme;
398
+ }
399
+ else {
400
+ this.scheme = this.schemes[0];
401
+ }
402
+
403
+ if(typeof this.host === 'undefined' || this.host === '') {
404
+ this.host = location.host;
405
+ if (location.port) {
406
+ this.host = this.host + ':' + location.port;
407
+ }
408
+ }
409
+
410
+ this.definitions = response.definitions;
411
+ var key;
412
+ for(key in this.definitions) {
413
+ var model = new Model(key, this.definitions[key]);
414
+ if(model) {
415
+ models[key] = model;
416
+ }
417
+ }
418
+
419
+ // get paths, create functions for each operationId
420
+ var path;
421
+ var operations = [];
422
+ for(path in response.paths) {
423
+ if(typeof response.paths[path] === 'object') {
424
+ var httpMethod;
425
+ for(httpMethod in response.paths[path]) {
426
+ if(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].indexOf(httpMethod) === -1) {
427
+ continue;
428
+ }
429
+ var operation = response.paths[path][httpMethod];
430
+ var tags = operation.tags;
431
+ if(typeof tags === 'undefined') {
432
+ operation.tags = [ 'default' ];
433
+ tags = operation.tags;
434
+ }
435
+ var operationId = this.idFromOp(path, httpMethod, operation);
436
+ var operationObject = new Operation (
437
+ this,
438
+ operationId,
439
+ httpMethod,
440
+ path,
441
+ operation,
442
+ this.definitions
443
+ );
444
+ // bind this operation's execute command to the api
445
+ if(tags.length > 0) {
446
+ var i;
447
+ for(i = 0; i < tags.length; i++) {
448
+ var tag = this.tagFromLabel(tags[i]);
449
+ var operationGroup = this[tag];
450
+ if(typeof operationGroup === 'undefined') {
451
+ this[tag] = [];
452
+ operationGroup = this[tag];
453
+ operationGroup.label = tag;
454
+ operationGroup.apis = [];
455
+ this[tag].help = this.help.bind(operationGroup);
456
+ this.apisArray.push(new OperationGroup(tag, operationObject));
457
+ }
458
+ operationGroup[operationId] = operationObject.execute.bind(operationObject);
459
+ operationGroup[operationId].help = operationObject.help.bind(operationObject);
460
+ operationGroup.apis.push(operationObject);
461
+
462
+ // legacy UI feature
463
+ var j;
464
+ var api;
465
+ for(j = 0; j < this.apisArray.length; j++) {
466
+ if(this.apisArray[j].tag === tag) {
467
+ api = this.apisArray[j];
468
+ }
469
+ }
470
+ if(api) {
471
+ api.operationsArray.push(operationObject);
472
+ }
473
+ }
474
+ }
475
+ else {
476
+ log('no group to bind to');
477
+ }
478
+ }
479
+ }
480
+ }
481
+ this.isBuilt = true;
482
+ if (this.success)
483
+ this.success();
484
+ return this;
485
+ }
486
+
487
+ SwaggerClient.prototype.parseUri = function(uri) {
488
+ var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
489
+ var parts = urlParseRE.exec(uri);
490
+ return {
491
+ scheme: parts[4].replace(':',''),
492
+ host: parts[11],
493
+ port: parts[12],
494
+ path: parts[15]
495
+ };
496
+ }
497
+
498
+ SwaggerClient.prototype.help = function() {
499
+ var i;
500
+ log('operations for the "' + this.label + '" tag');
501
+ for(i = 0; i < this.apis.length; i++) {
502
+ var api = this.apis[i];
503
+ log(' * ' + api.nickname + ': ' + api.operation.summary);
504
+ }
505
+ }
506
+
507
+ SwaggerClient.prototype.tagFromLabel = function(label) {
508
+ return label;
509
+ }
510
+
511
+ SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) {
512
+ if(typeof op.operationId !== 'undefined') {
513
+ return (op.operationId);
514
+ }
515
+ else {
516
+ return path.substring(1)
517
+ .replace(/\//g, "_")
518
+ .replace(/\{/g, "")
519
+ .replace(/\}/g, "")
520
+ .replace(/\./g, "_") + "_" + httpMethod;
521
+ }
522
+ }
523
+
524
+ SwaggerClient.prototype.fail = function(message) {
525
+ this.failure(message);
526
+ throw message;
527
+ };
528
+
529
+ var OperationGroup = function(tag, operation) {
530
+ this.tag = tag;
531
+ this.path = tag;
532
+ this.name = tag;
533
+ this.operation = operation;
534
+ this.operationsArray = [];
535
+
536
+ this.description = operation.description || "";
537
+ }
538
+
539
+ var Operation = function(parent, operationId, httpMethod, path, args, definitions) {
540
+ var errors = [];
541
+ parent = parent||{};
542
+ args = args||{};
543
+
544
+ this.operation = args;
545
+ this.deprecated = args.deprecated;
546
+ this.consumes = args.consumes;
547
+ this.produces = args.produces;
548
+ this.parent = parent;
549
+ this.host = parent.host || 'localhost';
550
+ this.schemes = parent.schemes;
551
+ this.scheme = parent.scheme || 'http';
552
+ this.basePath = parent.basePath || '/';
553
+ this.nickname = (operationId||errors.push('Operations must have a nickname.'));
554
+ this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.'));
555
+ this.path = (path||errors.push('Operation ' + this.nickname + ' is missing path.'));
556
+ this.parameters = args != null ? (args.parameters||[]) : {};
557
+ this.summary = args.summary || '';
558
+ this.responses = (args.responses||{});
559
+ this.type = null;
560
+ this.security = args.security;
561
+ this.authorizations = args.security;
562
+ this.description = args.description;
563
+
564
+ var i;
565
+ for(i = 0; i < this.parameters.length; i++) {
566
+ var param = this.parameters[i];
567
+ if(param.type === 'array') {
568
+ param.isList = true;
569
+ param.allowMultiple = true;
570
+ }
571
+ var innerType = this.getType(param);
572
+ if(innerType && innerType.toString().toLowerCase() === 'boolean') {
573
+ param.allowableValues = {};
574
+ param.isList = true;
575
+ param.enum = ["true", "false"];
576
+ }
577
+ if(typeof param.enum !== 'undefined') {
578
+ var id;
579
+ param.allowableValues = {};
580
+ param.allowableValues.values = [];
581
+ param.allowableValues.descriptiveValues = [];
582
+ for(id = 0; id < param.enum.length; id++) {
583
+ var value = param.enum[id];
584
+ var isDefault = (value === param.default) ? true : false;
585
+ param.allowableValues.values.push(value);
586
+ param.allowableValues.descriptiveValues.push({value : value, isDefault: isDefault});
587
+ }
588
+ }
589
+ if(param.type === 'array' && typeof param.allowableValues === 'undefined') {
590
+ // can't show as a list if no values to select from
591
+ delete param.isList;
592
+ delete param.allowMultiple;
593
+ }
594
+ param.signature = this.getSignature(innerType, models);
595
+ param.sampleJSON = this.getSampleJSON(innerType, models);
596
+ param.responseClassSignature = param.signature;
597
+ }
598
+
599
+ var response;
600
+ var model;
601
+ var responses = this.responses;
602
+
603
+ if(responses['200']) {
604
+ response = responses['200'];
605
+ defaultResponseCode = '200';
606
+ }
607
+ else if(responses['201']) {
608
+ response = responses['201'];
609
+ defaultResponseCode = '201';
610
+ }
611
+ else if(responses['202']) {
612
+ response = responses['202'];
613
+ defaultResponseCode = '202';
614
+ }
615
+ else if(responses['203']) {
616
+ response = responses['203'];
617
+ defaultResponseCode = '203';
618
+ }
619
+ else if(responses['204']) {
620
+ response = responses['204'];
621
+ defaultResponseCode = '204';
622
+ }
623
+ else if(responses['205']) {
624
+ response = responses['205'];
625
+ defaultResponseCode = '205';
626
+ }
627
+ else if(responses['206']) {
628
+ response = responses['206'];
629
+ defaultResponseCode = '206';
630
+ }
631
+ else if(responses['default']) {
632
+ response = responses['default'];
633
+ defaultResponseCode = 'default';
634
+ }
635
+
636
+ if(response && response.schema) {
637
+ var resolvedModel = this.resolveModel(response.schema, definitions);
638
+ if(resolvedModel) {
639
+ this.type = resolvedModel.name;
640
+ this.responseSampleJSON = JSON.stringify(resolvedModel.getSampleValue(), null, 2);
641
+ this.responseClassSignature = resolvedModel.getMockSignature();
642
+ delete responses[defaultResponseCode];
643
+ }
644
+ else {
645
+ this.type = response.schema.type;
646
+ }
647
+ }
648
+
649
+ if (errors.length > 0) {
650
+ if(this.resource && this.resource.api && this.resource.api.fail)
651
+ this.resource.api.fail(errors);
652
+ }
653
+
654
+ return this;
655
+ }
656
+
657
+ OperationGroup.prototype.sort = function(sorter) {
658
+
659
+ }
660
+
661
+ Operation.prototype.getType = function (param) {
662
+ var type = param.type;
663
+ var format = param.format;
664
+ var isArray = false;
665
+ var str;
666
+ if(type === 'integer' && format === 'int32')
667
+ str = 'integer';
668
+ else if(type === 'integer' && format === 'int64')
669
+ str = 'long';
670
+ else if(type === 'integer')
671
+ str = 'integer'
672
+ else if(type === 'string' && format === 'date-time')
673
+ str = 'date-time';
674
+ else if(type === 'string' && format === 'date')
675
+ str = 'date';
676
+ else if(type === 'number' && format === 'float')
677
+ str = 'float';
678
+ else if(type === 'number' && format === 'double')
679
+ str = 'double';
680
+ else if(type === 'number')
681
+ str = 'double';
682
+ else if(type === 'boolean')
683
+ str = 'boolean';
684
+ else if(type === 'string')
685
+ str = 'string';
686
+ else if(type === 'array') {
687
+ isArray = true;
688
+ if(param.items)
689
+ str = this.getType(param.items);
690
+ }
691
+ if(param['$ref'])
692
+ str = param['$ref'];
693
+
694
+ var schema = param.schema;
695
+ if(schema) {
696
+ var ref = schema['$ref'];
697
+ if(ref) {
698
+ ref = simpleRef(ref);
699
+ if(isArray)
700
+ return [ ref ];
701
+ else
702
+ return ref;
703
+ }
704
+ else
705
+ return this.getType(schema);
706
+ }
707
+ if(isArray)
708
+ return [ str ];
709
+ else
710
+ return str;
711
+ }
712
+
713
+ Operation.prototype.resolveModel = function (schema, definitions) {
714
+ if(typeof schema['$ref'] !== 'undefined') {
715
+ var ref = schema['$ref'];
716
+ if(ref.indexOf('#/definitions/') == 0)
717
+ ref = ref.substring('#/definitions/'.length);
718
+ if(definitions[ref])
719
+ return new Model(ref, definitions[ref]);
720
+ }
721
+ if(schema.type === 'array')
722
+ return new ArrayModel(schema);
723
+ else
724
+ return null;
725
+ }
726
+
727
+ Operation.prototype.help = function(dontPrint) {
728
+ var out = this.nickname + ': ' + this.summary + '\n';
729
+ for(var i = 0; i < this.parameters.length; i++) {
730
+ var param = this.parameters[i];
731
+ var typeInfo = typeFromJsonSchema(param.type, param.format);
732
+ out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description;
733
+ }
734
+ if(typeof dontPrint === 'undefined')
735
+ log(out);
736
+ return out;
737
+ }
738
+
739
+ Operation.prototype.getSignature = function(type, models) {
740
+ var isPrimitive, listType;
741
+
742
+ if(type instanceof Array) {
743
+ listType = true;
744
+ type = type[0];
745
+ }
746
+
747
+ if(type === 'string')
748
+ isPrimitive = true
749
+ else
750
+ isPrimitive = ((listType != null) && models[listType]) || (models[type] != null) ? false : true;
751
+ if (isPrimitive) {
752
+ return type;
753
+ } else {
754
+ if (listType != null)
755
+ return models[type].getMockSignature();
756
+ else
757
+ return models[type].getMockSignature();
758
+ }
759
+ };
760
+
761
+ Operation.prototype.supportHeaderParams = function () {
762
+ return true;
763
+ };
764
+
765
+ Operation.prototype.supportedSubmitMethods = function () {
766
+ return this.resource.api.supportedSubmitMethods;
767
+ };
768
+
769
+ Operation.prototype.getHeaderParams = function (args) {
770
+ var headers = this.setContentTypes(args, {});
771
+ for(var i = 0; i < this.parameters.length; i++) {
772
+ var param = this.parameters[i];
773
+ if(typeof args[param.name] !== 'undefined') {
774
+ if (param.in === 'header') {
775
+ var value = args[param.name];
776
+ if(Array.isArray(value))
777
+ value = this.encodePathCollection(param.collectionFormat, param.name, value);
778
+ else
779
+ value = this.encodePathParam(value);
780
+ headers[param.name] = value;
781
+ }
782
+ }
783
+ }
784
+ return headers;
785
+ }
786
+
787
+ Operation.prototype.urlify = function (args) {
788
+ var formParams = {};
789
+ var requestUrl = this.path;
790
+
791
+ // grab params from the args, build the querystring along the way
792
+ var querystring = '';
793
+ for(var i = 0; i < this.parameters.length; i++) {
794
+ var param = this.parameters[i];
795
+ if(typeof args[param.name] !== 'undefined') {
796
+ if(param.in === 'path') {
797
+ var reg = new RegExp('\{' + param.name + '[^\}]*\}', 'gi');
798
+ var value = args[param.name];
799
+ if(Array.isArray(value))
800
+ value = this.encodePathCollection(param.collectionFormat, param.name, value);
801
+ else
802
+ value = this.encodePathParam(value);
803
+ requestUrl = requestUrl.replace(reg, value);
804
+ }
805
+ else if (param.in === 'query' && typeof args[param.name] !== 'undefined') {
806
+ if(querystring === '')
807
+ querystring += '?';
808
+ else
809
+ querystring += '&';
810
+ if(typeof param.collectionFormat !== 'undefined') {
811
+ var qp = args[param.name];
812
+ if(Array.isArray(qp))
813
+ querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp);
814
+ else
815
+ querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
816
+ }
817
+ else
818
+ querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
819
+ }
820
+ else if (param.in === 'formData')
821
+ formParams[param.name] = args[param.name];
822
+ }
823
+ }
824
+ var url = this.scheme + '://' + this.host;
825
+
826
+ if(this.basePath !== '/')
827
+ url += this.basePath;
828
+
829
+ return url + requestUrl + querystring;
830
+ }
831
+
832
+ Operation.prototype.getMissingParams = function(args) {
833
+ var missingParams = [];
834
+ // check required params, track the ones that are missing
835
+ var i;
836
+ for(i = 0; i < this.parameters.length; i++) {
837
+ var param = this.parameters[i];
838
+ if(param.required === true) {
839
+ if(typeof args[param.name] === 'undefined')
840
+ missingParams = param.name;
841
+ }
842
+ }
843
+ return missingParams;
844
+ }
845
+
846
+ Operation.prototype.getBody = function(headers, args) {
847
+ var formParams = {};
848
+ var body;
849
+
850
+ for(var i = 0; i < this.parameters.length; i++) {
851
+ var param = this.parameters[i];
852
+ if(typeof args[param.name] !== 'undefined') {
853
+ if (param.in === 'body')
854
+ body = args[param.name];
855
+ }
856
+ }
857
+
858
+ // handle form params
859
+ if(headers['Content-Type'] === 'application/x-www-form-urlencoded') {
860
+ var encoded = "";
861
+ var key;
862
+ for(key in formParams) {
863
+ value = formParams[key];
864
+ if(typeof value !== 'undefined'){
865
+ if(encoded !== "")
866
+ encoded += "&";
867
+ encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
868
+ }
869
+ }
870
+ body = encoded;
871
+ }
872
+
873
+ return body;
874
+ }
875
+
876
+ /**
877
+ * gets sample response for a single operation
878
+ **/
879
+ Operation.prototype.getSampleJSON = function(type, models) {
880
+ var isPrimitive, listType, sampleJson;
881
+
882
+ listType = (type instanceof Array);
883
+ isPrimitive = (models[type] != null) ? false : true;
884
+ sampleJson = isPrimitive ? void 0 : models[type].createJSONSample();
885
+
886
+ if (sampleJson) {
887
+ sampleJson = listType ? [sampleJson] : sampleJson;
888
+ if(typeof sampleJson == 'string')
889
+ return sampleJson;
890
+ else if(typeof sampleJson === 'object') {
891
+ var t = sampleJson;
892
+ if(sampleJson instanceof Array && sampleJson.length > 0) {
893
+ t = sampleJson[0];
894
+ }
895
+ if(t.nodeName) {
896
+ var xmlString = new XMLSerializer().serializeToString(t);
897
+ return this.formatXml(xmlString);
898
+ }
899
+ else
900
+ return JSON.stringify(sampleJson, null, 2);
901
+ }
902
+ else
903
+ return sampleJson;
904
+ }
905
+ }
906
+
907
+ /**
908
+ * legacy binding
909
+ **/
910
+ Operation.prototype["do"] = function(args, opts, callback, error, parent) {
911
+ return this.execute(args, opts, callback, error, parent);
912
+ }
913
+
914
+
915
+ /**
916
+ * executes an operation
917
+ **/
918
+ Operation.prototype.execute = function(arg1, arg2, arg3, arg4, parent) {
919
+ var args = arg1 || {};
920
+ var opts = {}, success, error;
921
+ if(typeof arg2 === 'object') {
922
+ opts = arg2;
923
+ success = arg3;
924
+ error = arg4;
925
+ }
926
+
927
+ if(typeof arg2 === 'function') {
928
+ success = arg2;
929
+ error = arg3;
930
+ }
931
+
932
+ success = (success||log)
933
+ error = (error||log)
934
+
935
+ var missingParams = this.getMissingParams(args);
936
+ if(missingParams.length > 0) {
937
+ var message = 'missing required params: ' + missingParams;
938
+ fail(message);
939
+ return;
940
+ }
941
+
942
+ var headers = this.getHeaderParams(args);
943
+ var body = this.getBody(headers, args);
944
+ var url = this.urlify(args)
945
+
946
+ var obj = {
947
+ url: url,
948
+ method: this.method,
949
+ body: body,
950
+ useJQuery: this.useJQuery,
951
+ headers: headers,
952
+ on: {
953
+ response: function(response) {
954
+ return success(response, parent);
955
+ },
956
+ error: function(response) {
957
+ return error(response, parent);
958
+ }
959
+ }
960
+ };
961
+ var status = e.authorizations.apply(obj, this.operation.security);
962
+ new SwaggerHttp().execute(obj);
963
+ }
964
+
965
+ Operation.prototype.setContentTypes = function(args, opts) {
966
+ // default type
967
+ var accepts = 'application/json';
968
+ var consumes = args.parameterContentType || 'application/json';
969
+
970
+ var allDefinedParams = this.parameters;
971
+ var definedFormParams = [];
972
+ var definedFileParams = [];
973
+ var body;
974
+ var headers = {};
975
+
976
+ // get params from the operation and set them in definedFileParams, definedFormParams, headers
977
+ var i;
978
+ for(i = 0; i < allDefinedParams.length; i++) {
979
+ var param = allDefinedParams[i];
980
+ if(param.in === 'formData') {
981
+ if(param.type === 'file')
982
+ definedFileParams.push(param);
983
+ else
984
+ definedFormParams.push(param);
985
+ }
986
+ else if(param.in === 'header' && this.headers) {
987
+ var key = param.name;
988
+ var headerValue = this.headers[param.name];
989
+ if(typeof this.headers[param.name] !== 'undefined')
990
+ headers[key] = headerValue;
991
+ }
992
+ else if(param.in === 'body' && typeof args[param.name] !== 'undefined') {
993
+ body = args[param.name];
994
+ }
995
+ }
996
+
997
+ // if there's a body, need to set the consumes header via requestContentType
998
+ if (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) {
999
+ if (opts.requestContentType)
1000
+ consumes = opts.requestContentType;
1001
+ } else {
1002
+ // if any form params, content type must be set
1003
+ if(definedFormParams.length > 0) {
1004
+ if(opts.requestContentType) // override if set
1005
+ consumes = opts.requestContentType;
1006
+ else if(definedFileParams.length > 0) // if a file, must be multipart/form-data
1007
+ consumes = 'multipart/form-data';
1008
+ else // default to x-www-from-urlencoded
1009
+ consumes = 'application/x-www-form-urlencoded';
1010
+ }
1011
+ else if (this.type == 'DELETE')
1012
+ body = '{}';
1013
+ else if (this.type != 'DELETE')
1014
+ consumes = null;
1015
+ }
1016
+
1017
+ if (consumes && this.consumes) {
1018
+ if (this.consumes.indexOf(consumes) === -1) {
1019
+ log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
1020
+ consumes = this.operation.consumes[0];
1021
+ }
1022
+ }
1023
+
1024
+ if (opts.responseContentType) {
1025
+ accepts = opts.responseContentType;
1026
+ } else {
1027
+ accepts = 'application/json';
1028
+ }
1029
+ if (accepts && this.produces) {
1030
+ if (this.produces.indexOf(accepts) === -1) {
1031
+ log('server can\'t produce ' + accepts);
1032
+ accepts = this.produces[0];
1033
+ }
1034
+ }
1035
+
1036
+ if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded'))
1037
+ headers['Content-Type'] = consumes;
1038
+ if (accepts)
1039
+ headers['Accept'] = accepts;
1040
+ return headers;
1041
+ }
1042
+
1043
+ Operation.prototype.asCurl = function (args) {
1044
+ var results = [];
1045
+ var headers = this.getHeaderParams(args);
1046
+ if (headers) {
1047
+ var key;
1048
+ for (key in headers)
1049
+ results.push("--header \"" + key + ": " + headers[key] + "\"");
1050
+ }
1051
+ return "curl " + (results.join(" ")) + " " + this.urlify(args);
1052
+ }
1053
+
1054
+ Operation.prototype.encodePathCollection = function(type, name, value) {
1055
+ var encoded = '';
1056
+ var i;
1057
+ var separator = '';
1058
+ if(type === 'ssv')
1059
+ separator = '%20';
1060
+ else if(type === 'tsv')
1061
+ separator = '\\t';
1062
+ else if(type === 'pipes')
1063
+ separator = '|';
1064
+ else
1065
+ separator = ',';
1066
+
1067
+ for(i = 0; i < value.length; i++) {
1068
+ if(i == 0)
1069
+ encoded = this.encodeQueryParam(value[i]);
1070
+ else
1071
+ encoded += separator + this.encodeQueryParam(value[i]);
1072
+ }
1073
+ return encoded;
1074
+ }
1075
+
1076
+ Operation.prototype.encodeQueryCollection = function(type, name, value) {
1077
+ var encoded = '';
1078
+ var i;
1079
+ if(type === 'default' || type === 'multi') {
1080
+ for(i = 0; i < value.length; i++) {
1081
+ if(i > 0) encoded += '&'
1082
+ encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
1083
+ }
1084
+ }
1085
+ else {
1086
+ var separator = '';
1087
+ if(type === 'csv')
1088
+ separator = ',';
1089
+ else if(type === 'ssv')
1090
+ separator = '%20';
1091
+ else if(type === 'tsv')
1092
+ separator = '\\t';
1093
+ else if(type === 'pipes')
1094
+ separator = '|';
1095
+ else if(type === 'brackets') {
1096
+ for(i = 0; i < value.length; i++) {
1097
+ if(i !== 0)
1098
+ encoded += '&';
1099
+ encoded += this.encodeQueryParam(name) + '[]=' + this.encodeQueryParam(value[i]);
1100
+ }
1101
+ }
1102
+ if(separator !== '') {
1103
+ for(i = 0; i < value.length; i++) {
1104
+ if(i == 0)
1105
+ encoded = this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
1106
+ else
1107
+ encoded += separator + this.encodeQueryParam(value[i]);
1108
+ }
1109
+ }
1110
+ }
1111
+ return encoded;
1112
+ }
1113
+
1114
+ /**
1115
+ * TODO this encoding needs to be changed
1116
+ **/
1117
+ Operation.prototype.encodeQueryParam = function(arg) {
1118
+ return escape(arg);
1119
+ }
1120
+
1121
+ /**
1122
+ * TODO revisit, might not want to leave '/'
1123
+ **/
1124
+ Operation.prototype.encodePathParam = function(pathParam) {
1125
+ var encParts, part, parts, i, len;
1126
+ pathParam = pathParam.toString();
1127
+ if (pathParam.indexOf('/') === -1) {
1128
+ return encodeURIComponent(pathParam);
1129
+ } else {
1130
+ parts = pathParam.split('/');
1131
+ encParts = [];
1132
+ for (i = 0, len = parts.length; i < len; i++) {
1133
+ encParts.push(encodeURIComponent(parts[i]));
1134
+ }
1135
+ return encParts.join('/');
1136
+ }
1137
+ };
1138
+
1139
+ var Model = function(name, definition) {
1140
+ this.name = name;
1141
+ this.definition = definition || {};
1142
+ this.properties = [];
1143
+ var requiredFields = definition.required || [];
1144
+
1145
+ var key;
1146
+ var props = definition.properties;
1147
+ if(props) {
1148
+ for(key in props) {
1149
+ var required = false;
1150
+ var property = props[key];
1151
+ if(requiredFields.indexOf(key) >= 0)
1152
+ required = true;
1153
+ this.properties.push(new Property(key, property, required));
1154
+ }
1155
+ }
1156
+ }
1157
+
1158
+ Model.prototype.createJSONSample = function(modelsToIgnore) {
1159
+ var result = {};
1160
+ modelsToIgnore = (modelsToIgnore||{})
1161
+ modelsToIgnore[this.name] = this;
1162
+ var i;
1163
+ for (i = 0; i < this.properties.length; i++) {
1164
+ prop = this.properties[i];
1165
+ result[prop.name] = prop.getSampleValue(modelsToIgnore);
1166
+ }
1167
+ delete modelsToIgnore[this.name];
1168
+ return result;
1169
+ };
1170
+
1171
+ Model.prototype.getSampleValue = function(modelsToIgnore) {
1172
+ var i;
1173
+ var obj = {};
1174
+ for(i = 0; i < this.properties.length; i++ ) {
1175
+ var property = this.properties[i];
1176
+ obj[property.name] = property.sampleValue(false, modelsToIgnore);
1177
+ }
1178
+ return obj;
1179
+ }
1180
+
1181
+ Model.prototype.getMockSignature = function(modelsToIgnore) {
1182
+ var propertiesStr = [];
1183
+ var i;
1184
+ for (i = 0; i < this.properties.length; i++) {
1185
+ var prop = this.properties[i];
1186
+ propertiesStr.push(prop.toString());
1187
+ }
1188
+
1189
+ var strong = '<span class="strong">';
1190
+ var stronger = '<span class="stronger">';
1191
+ var strongClose = '</span>';
1192
+ var classOpen = strong + this.name + ' {' + strongClose;
1193
+ var classClose = strong + '}' + strongClose;
1194
+ var returnVal = classOpen + '<div>' + propertiesStr.join(',</div><div>') + '</div>' + classClose;
1195
+ if (!modelsToIgnore)
1196
+ modelsToIgnore = {};
1197
+
1198
+ modelsToIgnore[this.name] = this;
1199
+ var i;
1200
+ for (i = 0; i < this.properties.length; i++) {
1201
+ var prop = this.properties[i];
1202
+ var ref = prop['$ref'];
1203
+ var model = models[ref];
1204
+ if (model && typeof modelsToIgnore[model.name] === 'undefined') {
1205
+ returnVal = returnVal + ('<br>' + model.getMockSignature(modelsToIgnore));
1206
+ }
1207
+ }
1208
+ return returnVal;
1209
+ };
1210
+
1211
+ var Property = function(name, obj, required) {
1212
+ this.schema = obj;
1213
+ this.required = required;
1214
+ if(obj['$ref'])
1215
+ this['$ref'] = simpleRef(obj['$ref']);
1216
+ else if (obj.type === 'array') {
1217
+ if(obj.items['$ref'])
1218
+ this['$ref'] = simpleRef(obj.items['$ref']);
1219
+ else
1220
+ obj = obj.items;
1221
+ }
1222
+ this.name = name;
1223
+ this.description = obj.description;
1224
+ this.obj = obj;
1225
+ this.optional = true;
1226
+ this.default = obj.default || null;
1227
+ this.example = obj.example || null;
1228
+ }
1229
+
1230
+ Property.prototype.getSampleValue = function (modelsToIgnore) {
1231
+ return this.sampleValue(false, modelsToIgnore);
1232
+ }
1233
+
1234
+ Property.prototype.isArray = function () {
1235
+ var schema = this.schema;
1236
+ if(schema.type === 'array')
1237
+ return true;
1238
+ else
1239
+ return false;
1240
+ }
1241
+
1242
+ Property.prototype.sampleValue = function(isArray, ignoredModels) {
1243
+ isArray = (isArray || this.isArray());
1244
+ ignoredModels = (ignoredModels || {});
1245
+ var type = getStringSignature(this.obj);
1246
+ var output;
1247
+
1248
+ if(this['$ref']) {
1249
+ var refModelName = simpleRef(this['$ref']);
1250
+ var refModel = models[refModelName];
1251
+ if(refModel && typeof ignoredModels[type] === 'undefined') {
1252
+ ignoredModels[type] = this;
1253
+ output = refModel.getSampleValue(ignoredModels);
1254
+ }
1255
+ else
1256
+ type = refModel;
1257
+ }
1258
+ else if(this.example)
1259
+ output = this.example;
1260
+ else if(this.default)
1261
+ output = this.default;
1262
+ else if(type === 'date-time')
1263
+ output = new Date().toISOString();
1264
+ else if(type === 'string')
1265
+ output = 'string';
1266
+ else if(type === 'integer')
1267
+ output = 0;
1268
+ else if(type === 'long')
1269
+ output = 0;
1270
+ else if(type === 'float')
1271
+ output = 0.0;
1272
+ else if(type === 'double')
1273
+ output = 0.0;
1274
+ else if(type === 'boolean')
1275
+ output = true;
1276
+ else
1277
+ output = {};
1278
+ ignoredModels[type] = output;
1279
+ if(isArray)
1280
+ return [output];
1281
+ else
1282
+ return output;
1283
+ }
1284
+
1285
+ getStringSignature = function(obj) {
1286
+ var str = '';
1287
+ if(obj.type === 'array') {
1288
+ obj = (obj.items || obj['$ref'] || {});
1289
+ str += 'Array[';
1290
+ }
1291
+ if(obj.type === 'integer' && obj.format === 'int32')
1292
+ str += 'integer';
1293
+ else if(obj.type === 'integer' && obj.format === 'int64')
1294
+ str += 'long';
1295
+ else if(obj.type === 'integer' && typeof obj.format === 'undefined')
1296
+ str += 'long';
1297
+ else if(obj.type === 'string' && obj.format === 'date-time')
1298
+ str += 'date-time';
1299
+ else if(obj.type === 'string' && obj.format === 'date')
1300
+ str += 'date';
1301
+ else if(obj.type === 'number' && obj.format === 'float')
1302
+ str += 'float';
1303
+ else if(obj.type === 'number' && obj.format === 'double')
1304
+ str += 'double';
1305
+ else if(obj.type === 'number' && typeof obj.format === 'undefined')
1306
+ str += 'double';
1307
+ else if(obj.type === 'boolean')
1308
+ str += 'boolean';
1309
+ else if(obj['$ref'])
1310
+ str += simpleRef(obj['$ref']);
1311
+ else
1312
+ str += obj.type;
1313
+ if(obj.type === 'array')
1314
+ str += ']';
1315
+ return str;
1316
+ }
1317
+
1318
+ simpleRef = function(name) {
1319
+ if(typeof name === 'undefined')
1320
+ return null;
1321
+ if(name.indexOf("#/definitions/") === 0)
1322
+ return name.substring('#/definitions/'.length)
1323
+ else
1324
+ return name;
1325
+ }
1326
+
1327
+ Property.prototype.toString = function() {
1328
+ var str = getStringSignature(this.obj);
1329
+ if(str !== '') {
1330
+ str = '<span class="propName ' + this.required + '">' + this.name + '</span> (<span class="propType">' + str + '</span>';
1331
+ if(!this.required)
1332
+ str += ', <span class="propOptKey">optional</span>';
1333
+ str += ')';
1334
+ }
1335
+ else
1336
+ str = this.name + ' (' + JSON.stringify(this.obj) + ')';
1337
+
1338
+ if(typeof this.description !== 'undefined')
1339
+ str += ': ' + this.description;
1340
+ return str;
1341
+ }
1342
+
1343
+ typeFromJsonSchema = function(type, format) {
1344
+ var str;
1345
+ if(type === 'integer' && format === 'int32')
1346
+ str = 'integer';
1347
+ else if(type === 'integer' && format === 'int64')
1348
+ str = 'long';
1349
+ else if(type === 'integer' && typeof format === 'undefined')
1350
+ str = 'long';
1351
+ else if(type === 'string' && format === 'date-time')
1352
+ str = 'date-time';
1353
+ else if(type === 'string' && format === 'date')
1354
+ str = 'date';
1355
+ else if(type === 'number' && format === 'float')
1356
+ str = 'float';
1357
+ else if(type === 'number' && format === 'double')
1358
+ str = 'double';
1359
+ else if(type === 'number' && typeof format === 'undefined')
1360
+ str = 'double';
1361
+ else if(type === 'boolean')
1362
+ str = 'boolean';
1363
+ else if(type === 'string')
1364
+ str = 'string';
1365
+
1366
+ return str;
1367
+ }
1368
+
1369
+ var e = (typeof window !== 'undefined' ? window : exports);
1370
+
1371
+ var sampleModels = {};
1372
+ var cookies = {};
1373
+ var models = {};
1374
+
1375
+ e.authorizations = new SwaggerAuthorizations();
1376
+ e.ApiKeyAuthorization = ApiKeyAuthorization;
1377
+ e.PasswordAuthorization = PasswordAuthorization;
1378
+ e.CookieAuthorization = CookieAuthorization;
1379
+ e.SwaggerClient = SwaggerClient;
1380
+ e.Operation = Operation;
1381
+ /**
1382
+ * SwaggerHttp is a wrapper for executing requests
1383
+ */
1384
+ var SwaggerHttp = function() {};
1385
+
1386
+ SwaggerHttp.prototype.execute = function(obj) {
1387
+ if(obj && (typeof obj.useJQuery === 'boolean'))
1388
+ this.useJQuery = obj.useJQuery;
1389
+ else
1390
+ this.useJQuery = this.isIE8();
1391
+
1392
+ if(this.useJQuery)
1393
+ return new JQueryHttpClient().execute(obj);
1394
+ else
1395
+ return new ShredHttpClient().execute(obj);
1396
+ }
1397
+
1398
+ SwaggerHttp.prototype.isIE8 = function() {
1399
+ var detectedIE = false;
1400
+ if (typeof navigator !== 'undefined' && navigator.userAgent) {
1401
+ nav = navigator.userAgent.toLowerCase();
1402
+ if (nav.indexOf('msie') !== -1) {
1403
+ var version = parseInt(nav.split('msie')[1]);
1404
+ if (version <= 8) {
1405
+ detectedIE = true;
1406
+ }
1407
+ }
1408
+ }
1409
+ return detectedIE;
1410
+ };
1411
+
1412
+ /*
1413
+ * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic.
1414
+ * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space.
1415
+ * Since we are using closures here we need to alias it for internal use.
1416
+ */
1417
+ var JQueryHttpClient = function(options) {
1418
+ "use strict";
1419
+ if(!jQuery){
1420
+ var jQuery = window.jQuery;
1421
+ }
1422
+ }
1423
+
1424
+ JQueryHttpClient.prototype.execute = function(obj) {
1425
+ var cb = obj.on;
1426
+ var request = obj;
1427
+
1428
+ obj.type = obj.method;
1429
+ obj.cache = false;
1430
+
1431
+ obj.beforeSend = function(xhr) {
1432
+ var key, results;
1433
+ if (obj.headers) {
1434
+ results = [];
1435
+ var key;
1436
+ for (key in obj.headers) {
1437
+ if (key.toLowerCase() === "content-type") {
1438
+ results.push(obj.contentType = obj.headers[key]);
1439
+ } else if (key.toLowerCase() === "accept") {
1440
+ results.push(obj.accepts = obj.headers[key]);
1441
+ } else {
1442
+ results.push(xhr.setRequestHeader(key, obj.headers[key]));
1443
+ }
1444
+ }
1445
+ return results;
1446
+ }
1447
+ };
1448
+
1449
+ obj.data = obj.body;
1450
+ obj.complete = function(response, textStatus, opts) {
1451
+ var headers = {},
1452
+ headerArray = response.getAllResponseHeaders().split("\n");
1453
+
1454
+ for(var i = 0; i < headerArray.length; i++) {
1455
+ var toSplit = headerArray[i].trim();
1456
+ if(toSplit.length === 0)
1457
+ continue;
1458
+ var separator = toSplit.indexOf(":");
1459
+ if(separator === -1) {
1460
+ // Name but no value in the header
1461
+ headers[toSplit] = null;
1462
+ continue;
1463
+ }
1464
+ var name = toSplit.substring(0, separator).trim(),
1465
+ value = toSplit.substring(separator + 1).trim();
1466
+ headers[name] = value;
1467
+ }
1468
+
1469
+ var out = {
1470
+ url: request.url,
1471
+ method: request.method,
1472
+ status: response.status,
1473
+ data: response.responseText,
1474
+ headers: headers
1475
+ };
1476
+
1477
+ var contentType = (headers["content-type"]||headers["Content-Type"]||null)
1478
+
1479
+ if(contentType != null) {
1480
+ if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1481
+ if(response.responseText && response.responseText !== "") {
1482
+ try {
1483
+ out.obj = JSON.parse(response.content.data);
1484
+ }
1485
+ catch (ex) {
1486
+ // do not set out.obj
1487
+ log ("unable to parse JSON content");
1488
+ }
1489
+ }
1490
+ else
1491
+ out.obj = {}
1492
+ }
1493
+ }
1494
+
1495
+ if(response.status >= 200 && response.status < 300)
1496
+ cb.response(out);
1497
+ else if(response.status === 0 || (response.status >= 400 && response.status < 599))
1498
+ cb.error(out);
1499
+ else
1500
+ return cb.response(out);
1501
+ };
1502
+
1503
+ jQuery.support.cors = true;
1504
+ return jQuery.ajax(obj);
1505
+ }
1506
+
1507
+ /*
1508
+ * ShredHttpClient is a light-weight, node or browser HTTP client
1509
+ */
1510
+ var ShredHttpClient = function(options) {
1511
+ this.options = (options||{});
1512
+ this.isInitialized = false;
1513
+
1514
+ var identity, toString;
1515
+
1516
+ if (typeof window !== 'undefined') {
1517
+ this.Shred = require("./shred");
1518
+ this.content = require("./shred/content");
1519
+ }
1520
+ else
1521
+ this.Shred = require("shred");
1522
+ this.shred = new this.Shred(options);
1523
+ }
1524
+
1525
+ ShredHttpClient.prototype.initShred = function () {
1526
+ this.isInitialized = true;
1527
+ this.registerProcessors(this.shred);
1528
+ }
1529
+
1530
+ ShredHttpClient.prototype.registerProcessors = function(shred) {
1531
+ var identity = function(x) {
1532
+ return x;
1533
+ };
1534
+ var toString = function(x) {
1535
+ return x.toString();
1536
+ };
1537
+
1538
+ if (typeof window !== 'undefined') {
1539
+ this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1540
+ parser: identity,
1541
+ stringify: toString
1542
+ });
1543
+ } else {
1544
+ this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], {
1545
+ parser: identity,
1546
+ stringify: toString
1547
+ });
1548
+ }
1549
+ }
1550
+
1551
+ ShredHttpClient.prototype.execute = function(obj) {
1552
+ if(!this.isInitialized)
1553
+ this.initShred();
1554
+
1555
+ var cb = obj.on, res;
1556
+
1557
+ var transform = function(response) {
1558
+ var out = {
1559
+ headers: response._headers,
1560
+ url: response.request.url,
1561
+ method: response.request.method,
1562
+ status: response.status,
1563
+ data: response.content.data
1564
+ };
1565
+
1566
+ var contentType = (response._headers["content-type"]||response._headers["Content-Type"]||null)
1567
+
1568
+ if(contentType != null) {
1569
+ if(contentType.indexOf("application/json") == 0 || contentType.indexOf("+json") > 0) {
1570
+ if(response.content.data && response.content.data !== "")
1571
+ try{
1572
+ out.obj = JSON.parse(response.content.data);
1573
+ }
1574
+ catch (e) {
1575
+ // unable to parse
1576
+ }
1577
+ else
1578
+ out.obj = {}
1579
+ }
1580
+ }
1581
+ return out;
1582
+ };
1583
+
1584
+ res = {
1585
+ error: function(response) {
1586
+ if (obj)
1587
+ return cb.error(transform(response));
1588
+ },
1589
+ redirect: function(response) {
1590
+ if (obj)
1591
+ return cb.redirect(transform(response));
1592
+ },
1593
+ 307: function(response) {
1594
+ if (obj)
1595
+ return cb.redirect(transform(response));
1596
+ },
1597
+ response: function(response) {
1598
+ if (obj)
1599
+ return cb.response(transform(response));
1600
+ }
1601
+ };
1602
+ if (obj) {
1603
+ obj.on = res;
1604
+ }
1605
+ return this.shred.request(obj);
1606
+ };