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