diff --git a/browser.js b/browser.js index 2f6572d..8431efe 100644 --- a/browser.js +++ b/browser.js @@ -27,6 +27,7 @@ var assert = require('assert'); var URI = require('urijs'); +var commonPrefix = require('common-prefix'); var SwaggerConverter = module.exports = {}; @@ -199,28 +200,29 @@ Converter.prototype.getResources = function(resourceListing, apiDeclarations) { * @returns {array} - list of Swagger 2.0 tags */ Converter.prototype.buildTags = function(resourceListing, resources) { - var resourcePaths = []; - this.forEach(resources, function(resource) { - var path = resource.resourcePath; - if (isValue(resource) && resourcePaths.indexOf(path) === -1) { - resourcePaths.push(path); - } + var resourcePaths = this.mapEach(resources, function(resource) { + return resource.resourcePath; }); //'resourcePath' is optional parameter and also frequently have invalid values // if so than we discard all values and use resource paths for listing instead. - if (getLength(resourcePaths) < getLength(resources)) { - resourcePaths = {}; + if (getLength(removeDuplicates(resourcePaths)) < getLength(resources)) { + resourcePaths = this.mapEach(resourceListing.apis, function(resource) { + return resource.path; + }); } + resourcePaths = stripCommonPath(resourcePaths); + var tags = []; this.forEach(resourceListing.apis, function(resource, index) { - if (!isEmpty(resource.operations)) { - return; - } + if (!isEmpty(resource.operations)) { return; } + + var tagName = URI(resourcePaths[index] || '').path(true) + .replace('{format}', 'json') + .replace(/\/$/, '') + .replace(/.json$/, ''); - var path = resourcePaths[index] || resource.path; - var tagName = this.extractTag(path); if (!isValue(tagName)) { return; } tags.push(extend({}, { @@ -232,21 +234,6 @@ Converter.prototype.buildTags = function(resourceListing, resources) { return tags; }; -/* - * Extract name of the tag from resourcePath - * @param resourcePath {string} - Swagger 1.x resource path - * @returns {string} - tag name -*/ -prototype.extractTag = function(resourcePath) { - var tag = URI(resourcePath || '').path(true) - .replace('{format}', 'json') - .replace(/\/$/, '') - .replace(/.json$/, '') - .split(['/']).pop(); - - return tag || undefined; -}; - /* * Builds "info" section of Swagger 2.0 document * @param resourceListing {object} - root of Swagger 1.x document @@ -979,11 +966,25 @@ function fixNonStringValue(value, skipError) { */ function removeDuplicates(collection) { return collection.filter(function(e, i, arr) { - return arr.lastIndexOf(e) === i; + return isValue(e) && arr.lastIndexOf(e) === i; }); } -},{"assert":2,"urijs":7}],2:[function(require,module,exports){ +/* + * Strip common prefix from paths + * @params paths {array} + * @returns {array} - path with remove common part + */ +function stripCommonPath(paths) { + var prefix = commonPrefix(paths); + var prefixLength = prefix.lastIndexOf('/') + 1; + + return paths.map(function(str) { + return str.slice(prefixLength); + }); +} + +},{"assert":2,"common-prefix":3,"urijs":8}],2:[function(require,module,exports){ // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! @@ -1344,7 +1345,30 @@ var objectKeys = Object.keys || function (obj) { return keys; }; -},{"util/":10}],3:[function(require,module,exports){ +},{"util/":11}],3:[function(require,module,exports){ +module.exports = common + +function common (strings) { + if (!Array.isArray(strings)) { + throw new Error('common-prefix expects an array of strings') + } + + var first = strings[0] || '' + var commonLength = first.length + + for (var i = 1; i < strings.length; ++i) { + for (var j = 0; j < commonLength; ++j) { + if (strings[i].charAt(j) !== first.charAt(j)) { + commonLength = j + break + } + } + } + + return first.slice(0, commonLength) +} + +},{}],4:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { @@ -1369,7 +1393,7 @@ if (typeof Object.create === 'function') { } } -},{}],4:[function(require,module,exports){ +},{}],5:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; @@ -1462,19 +1486,18 @@ process.chdir = function (dir) { }; process.umask = function() { return 0; }; -},{}],5:[function(require,module,exports){ +},{}],6:[function(require,module,exports){ /*! * URI.js - Mutating URLs * IPv6 Support * - * Version: 1.17.0 + * Version: 1.17.1 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license - * GPL v3 http://opensource.org/licenses/GPL-3.0 * */ @@ -1652,19 +1675,18 @@ process.umask = function() { return 0; }; }; })); -},{}],6:[function(require,module,exports){ +},{}],7:[function(require,module,exports){ /*! * URI.js - Mutating URLs * Second Level Domain (SLD) Support * - * Version: 1.17.0 + * Version: 1.17.1 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license - * GPL v3 http://opensource.org/licenses/GPL-3.0 * */ @@ -1895,18 +1917,17 @@ process.umask = function() { return 0; }; return SLD; })); -},{}],7:[function(require,module,exports){ +},{}],8:[function(require,module,exports){ /*! * URI.js - Mutating URLs * - * Version: 1.17.0 + * Version: 1.17.1 * * Author: Rodney Rehm * Web: http://medialize.github.io/URI.js/ * * Licensed under * MIT License http://www.opensource.org/licenses/mit-license - * GPL v3 http://opensource.org/licenses/GPL-3.0 * */ (function (root, factory) { @@ -1970,7 +1991,7 @@ process.umask = function() { return 0; }; return this; } - URI.version = '1.17.0'; + URI.version = '1.17.1'; var p = URI.prototype; var hasOwn = Object.prototype.hasOwnProperty; @@ -2693,18 +2714,35 @@ process.umask = function() { return 0; }; } }; URI.hasQuery = function(data, name, value, withinArray) { - if (typeof name === 'object') { - for (var key in name) { - if (hasOwn.call(name, key)) { - if (!URI.hasQuery(data, key, name[key])) { - return false; + switch (getType(name)) { + case 'String': + // Nothing to do here + break; + + case 'RegExp': + for (var key in data) { + if (hasOwn.call(data, key)) { + if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) { + return true; + } } } - } - return true; - } else if (typeof name !== 'string') { - throw new TypeError('URI.hasQuery() accepts an object, string as the name parameter'); + return false; + + case 'Object': + for (var _key in name) { + if (hasOwn.call(name, _key)) { + if (!URI.hasQuery(data, _key, name[_key])) { + return false; + } + } + } + + return true; + + default: + throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter'); } switch (getType(value)) { @@ -3122,8 +3160,6 @@ process.umask = function() { return 0; }; // compound accessors p.origin = function(v, build) { - var parts; - if (this._parts.urn) { return v === undefined ? '' : this; } @@ -3131,7 +3167,10 @@ process.umask = function() { return 0; }; if (v === undefined) { var protocol = this.protocol(); var authority = this.authority(); - if (!authority) return ''; + if (!authority) { + return ''; + } + return (protocol ? protocol + '://' : '') + this.authority(); } else { var origin = URI(v); @@ -3715,6 +3754,8 @@ process.umask = function() { return 0; }; return this; } + _path = URI.recodePath(_path); + var _was_relative; var _leadingParents = ''; var _parent, _pos; @@ -3745,7 +3786,7 @@ process.umask = function() { return 0; }; // resolve parents while (true) { - _parent = _path.indexOf('/..'); + _parent = _path.search(/\/\.\.(\/|$)/); if (_parent === -1) { // no more ../ to resolve break; @@ -3767,7 +3808,6 @@ process.umask = function() { return 0; }; _path = _leadingParents + _path.substring(1); } - _path = URI.recodePath(_path); this._parts.path = _path; this.build(!build); return this; @@ -4058,17 +4098,22 @@ process.umask = function() { return 0; }; return URI; })); -},{"./IPv6":5,"./SecondLevelDomains":6,"./punycode":8}],8:[function(require,module,exports){ +},{"./IPv6":6,"./SecondLevelDomains":7,"./punycode":9}],9:[function(require,module,exports){ (function (global){ -/*! http://mths.be/punycode v1.2.3 by @mathias */ +/*! https://mths.be/punycode v1.4.0 by @mathias */ ;(function(root) { /** Detect free variables */ - var freeExports = typeof exports == 'object' && exports; + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && - module.exports == freeExports && module; + !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { root = freeGlobal; } @@ -4094,8 +4139,8 @@ process.umask = function() { return 0; }; /** Regular expressions */ regexPunycode = /^xn--/, - regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { @@ -4121,7 +4166,7 @@ process.umask = function() { return 0; }; * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { - throw RangeError(errors[type]); + throw new RangeError(errors[type]); } /** @@ -4134,23 +4179,37 @@ process.umask = function() { return 0; }; */ function map(array, fn) { var length = array.length; + var result = []; while (length--) { - array[length] = fn(array[length]); + result[length] = fn(array[length]); } - return array; + return result; } /** - * A simple `Array#map`-like wrapper to work with domain name strings. + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. * @private - * @param {String} domain The domain name. + * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { - return map(string.split(regexSeparators), fn).join('.'); + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; } /** @@ -4160,7 +4219,7 @@ process.umask = function() { return 0; }; * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` - * @see + * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). @@ -4254,7 +4313,7 @@ process.umask = function() { return 0; }; /** * Bias adaptation function as per section 3.4 of RFC 3492. - * http://tools.ietf.org/html/rfc3492#section-3.4 + * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { @@ -4290,7 +4349,6 @@ process.umask = function() { return 0; }; k, digit, t, - length, /** Cached calculation results */ baseMinusT; @@ -4370,8 +4428,8 @@ process.umask = function() { return 0; }; } /** - * Converts a string of Unicode symbols to a Punycode string of ASCII-only - * symbols. + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. @@ -4484,17 +4542,18 @@ process.umask = function() { return 0; }; } /** - * Converts a Punycode string representing a domain name to Unicode. Only the - * Punycoded parts of the domain name will be converted, i.e. it doesn't - * matter if you call it on a string that has already been converted to - * Unicode. + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. * @memberOf punycode - * @param {String} domain The Punycode domain name to convert to Unicode. + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ - function toUnicode(domain) { - return mapDomain(domain, function(string) { + function toUnicode(input) { + return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; @@ -4502,15 +4561,18 @@ process.umask = function() { return 0; }; } /** - * Converts a Unicode string representing a domain name to Punycode. Only the - * non-ASCII parts of the domain name will be converted, i.e. it doesn't - * matter if you call it with a domain that's already in ASCII. + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. * @memberOf punycode - * @param {String} domain The domain name to convert, as a Unicode string. - * @returns {String} The Punycode representation of the given domain name. + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. */ - function toASCII(domain) { - return mapDomain(domain, function(string) { + function toASCII(input) { + return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; @@ -4526,11 +4588,11 @@ process.umask = function() { return 0; }; * @memberOf punycode * @type String */ - 'version': '1.2.3', + 'version': '1.3.2', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. - * @see + * @see * @memberOf punycode * @type Object */ @@ -4552,32 +4614,35 @@ process.umask = function() { return 0; }; typeof define.amd == 'object' && define.amd ) { - define(function() { + define('punycode', function() { return punycode; }); - } else if (freeExports && !freeExports.nodeType) { - if (freeModule) { // in Node.js or RingoJS v0.8.0+ + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; - } else { // in Narwhal or RingoJS v0.7.0- + } else { + // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } - } else { // in Rhino or a web browser + } else { + // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],9:[function(require,module,exports){ +},{}],10:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } -},{}],10:[function(require,module,exports){ +},{}],11:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // @@ -5167,5 +5232,5 @@ function hasOwnProperty(obj, prop) { } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":9,"_process":4,"inherits":3}]},{},[1])(1) +},{"./support/isBuffer":10,"_process":5,"inherits":4}]},{},[1])(1) }); \ No newline at end of file diff --git a/browser.min.js b/browser.min.js index be8b2e5..550277f 100644 --- a/browser.min.js +++ b/browser.min.js @@ -1,3 +1,3 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.SwaggerConverter=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o1){oName+="_"+grantParameters.flow}this.securityNamesMap[name].push(oName);securityDefinitions[oName]=extend({},securityDefinition,grantParameters)})});return securityDefinitions};prototype.buildModel=function(oldModel){var required=[];var properties={};var items;this.forEach(oldModel.properties,function(oldProperty,propertyName){if(fixNonStringValue(oldProperty.required)===true){required.push(propertyName)}properties[propertyName]=this.buildModel(oldProperty)});if(Array.isArray(oldModel.required)){required=oldModel.required}if(isValue(oldModel.items)){items=this.buildModel(oldModel.items)}return extend(this.buildDataType(oldModel,true),{description:oldModel.description,required:undefinedIfEmpty(required),properties:undefinedIfEmpty(properties),discriminator:oldModel.discriminator,example:oldModel.example,items:undefinedIfEmpty(items)})};prototype.buildDefinitions=function(oldModels){var models={};this.forEach(oldModels,function(oldModel,modelId){models[modelId]=this.buildModel(oldModel)});this.forEach(oldModels,function(parent,parentId){this.forEach(parent.subTypes,function(childId){var child=models[childId];if(!isValue(child)){throw new SwaggerConverterError('subTypes resolution: Missing "'+childId+'" type')}if(!isValue(child.allOf)){models[childId]=child={allOf:[child]}}child.allOf.push({$ref:"#/definitions/"+parentId})})});return models};prototype.mapEach=function(collection,iteratee){var result=[];this.forEach(collection,function(value,key){result.push(iteratee.bind(this)(value,key))});return result};prototype.forEach=function(collection,iteratee){if(!isValue(collection)){return}if(typeof collection!=="object"){throw new SwaggerConverterError("Expected array or object, instead got: "+JSON.stringify(collection,null,2))}iteratee=iteratee.bind(this);if(Array.isArray(collection)){collection.forEach(iteratee)}else{Object.keys(collection).sort().forEach(function(key){iteratee(collection[key],key)})}};function extend(destination){assert(typeof destination==="object");function assign(source){if(!source){return}Object.keys(source).forEach(function(key){var value=source[key];if(isValue(value)){destination[key]=value}})}for(var i=1;i=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":10}],3:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],4:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=setTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i1){_segments.splice(0,1)}else{break}}segments[i]=_segments.join("")}var best=-1;var _best=0;var _current=0;var current=-1;var inzeroes=false;for(i=0;i_best){best=current;_best=_current}}}else{if(segments[i]==="0"){inzeroes=true;current=i;_current=1}}}if(_current>_best){best=current;_best=_current}if(_best>1){segments.splice(best,_best,"")}length=segments.length;var result="";if(segments[0]===""){result=":"}for(i=0;i=domain.length-1){return false}var sldOffset=domain.lastIndexOf(".",tldOffset-1);if(sldOffset<=0||sldOffset>=tldOffset-1){return false}var sldList=SLD.list[domain.slice(tldOffset+1)];if(!sldList){return false}return sldList.indexOf(" "+domain.slice(sldOffset+1,tldOffset)+" ")>=0},is:function(domain){var tldOffset=domain.lastIndexOf(".");if(tldOffset<=0||tldOffset>=domain.length-1){return false}var sldOffset=domain.lastIndexOf(".",tldOffset-1);if(sldOffset>=0){return false}var sldList=SLD.list[domain.slice(tldOffset+1)];if(!sldList){return false}return sldList.indexOf(" "+domain.slice(0,tldOffset)+" ")>=0},get:function(domain){var tldOffset=domain.lastIndexOf(".");if(tldOffset<=0||tldOffset>=domain.length-1){return null}var sldOffset=domain.lastIndexOf(".",tldOffset-1);if(sldOffset<=0||sldOffset>=tldOffset-1){return null}var sldList=SLD.list[domain.slice(tldOffset+1)];if(!sldList){return null}if(sldList.indexOf(" "+domain.slice(sldOffset+1,tldOffset)+" ")<0){return null}return domain.slice(sldOffset+1)},noConflict:function(){if(root.SecondLevelDomains===this){root.SecondLevelDomains=_SecondLevelDomains}return this}};return SLD})},{}],7:[function(require,module,exports){(function(root,factory){"use strict";if(typeof exports==="object"){module.exports=factory(require("./punycode"),require("./IPv6"),require("./SecondLevelDomains"))}else if(typeof define==="function"&&define.amd){define(["./punycode","./IPv6","./SecondLevelDomains"],factory)}else{root.URI=factory(root.punycode,root.IPv6,root.SecondLevelDomains,root)}})(this,function(punycode,IPv6,SLD,root){"use strict";var _URI=root&&root.URI;function URI(url,base){var _urlSupplied=arguments.length>=1;var _baseSupplied=arguments.length>=2;if(!(this instanceof URI)){if(_urlSupplied){if(_baseSupplied){return new URI(url,base)}return new URI(url)}return new URI}if(url===undefined){if(_urlSupplied){throw new TypeError("undefined is not a valid argument for URI")}if(typeof location!=="undefined"){url=location.href+""}else{url=""}}this.href(url);if(base!==undefined){return this.absoluteTo(base)}return this}URI.version="1.17.0";var p=URI.prototype;var hasOwn=Object.prototype.hasOwnProperty;function escapeRegEx(string){return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function getType(value){if(value===undefined){return"Undefined"}return String(Object.prototype.toString.call(value)).slice(8,-1)}function isArray(obj){return getType(obj)==="Array"}function filterArrayValues(data,value){var lookup={};var i,length;if(getType(value)==="RegExp"){lookup=null}else if(isArray(value)){for(i=0,length=value.length;i]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;URI.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?«»“”„‘’]+$/};URI.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"};URI.invalid_hostname_characters=/[^a-zA-Z0-9\.-]/;URI.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"};URI.getDomAttribute=function(node){if(!node||!node.nodeName){return undefined}var nodeName=node.nodeName.toLowerCase();if(nodeName==="input"&&node.type!=="image"){return undefined}return URI.domAttributes[nodeName]};function escapeForDumbFirefox36(value){return escape(value)}function strictEncodeURIComponent(string){return encodeURIComponent(string).replace(/[!'()*]/g,escapeForDumbFirefox36).replace(/\*/g,"%2A")}URI.encode=strictEncodeURIComponent;URI.decode=decodeURIComponent;URI.iso8859=function(){URI.encode=escape;URI.decode=unescape};URI.unicode=function(){URI.encode=strictEncodeURIComponent;URI.decode=decodeURIComponent};URI.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/gi,map:{"%24":"$","%26":"&","%2B":"+","%2C":",","%3B":";","%3D":"=","%3A":":","%40":"@"}},decode:{expression:/[\/\?#]/g,map:{"/":"%2F","?":"%3F","#":"%23"}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/gi,map:{"%3A":":","%2F":"/","%3F":"?","%23":"#","%5B":"[","%5D":"]","%40":"@","%21":"!","%24":"$","%26":"&","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"="}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/gi,map:{"%21":"!","%24":"$","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"=","%40":"@"}},decode:{expression:/[\/\?#:]/g,map:{"/":"%2F","?":"%3F","#":"%23",":":"%3A"}}}};URI.encodeQuery=function(string,escapeQuerySpace){var escaped=URI.encode(string+"");if(escapeQuerySpace===undefined){escapeQuerySpace=URI.escapeQuerySpace}return escapeQuerySpace?escaped.replace(/%20/g,"+"):escaped};URI.decodeQuery=function(string,escapeQuerySpace){string+="";if(escapeQuerySpace===undefined){escapeQuerySpace=URI.escapeQuerySpace}try{return URI.decode(escapeQuerySpace?string.replace(/\+/g,"%20"):string)}catch(e){return string}};var _parts={encode:"encode",decode:"decode"};var _part;var generateAccessor=function(_group,_part){return function(string){try{return URI[_part](string+"").replace(URI.characters[_group][_part].expression,function(c){return URI.characters[_group][_part].map[c]})}catch(e){return string}}};for(_part in _parts){URI[_part+"PathSegment"]=generateAccessor("pathname",_parts[_part]);URI[_part+"UrnPathSegment"]=generateAccessor("urnpath",_parts[_part])}var generateSegmentedPathFunction=function(_sep,_codingFuncName,_innerCodingFuncName){return function(string){var actualCodingFunc;if(!_innerCodingFuncName){actualCodingFunc=URI[_codingFuncName]}else{actualCodingFunc=function(string){return URI[_codingFuncName](URI[_innerCodingFuncName](string))}}var segments=(string+"").split(_sep);for(var i=0,length=segments.length;i-1){parts.fragment=string.substring(pos+1)||null;string=string.substring(0,pos)}pos=string.indexOf("?");if(pos>-1){parts.query=string.substring(pos+1)||null;string=string.substring(0,pos)}if(string.substring(0,2)==="//"){parts.protocol=null;string=string.substring(2);string=URI.parseAuthority(string,parts)}else{pos=string.indexOf(":");if(pos>-1){parts.protocol=string.substring(0,pos)||null;if(parts.protocol&&!parts.protocol.match(URI.protocol_expression)){parts.protocol=undefined}else if(string.substring(pos+1,pos+3)==="//"){string=string.substring(pos+3);string=URI.parseAuthority(string,parts)}else{string=string.substring(pos+1);parts.urn=true}}}parts.path=string;return parts};URI.parseHost=function(string,parts){string=string.replace(/\\/g,"/");var pos=string.indexOf("/");var bracketPos;var t;if(pos===-1){pos=string.length}if(string.charAt(0)==="["){bracketPos=string.indexOf("]");parts.hostname=string.substring(1,bracketPos)||null;parts.port=string.substring(bracketPos+2,pos)||null;if(parts.port==="/"){parts.port=null}}else{var firstColon=string.indexOf(":");var firstSlash=string.indexOf("/");var nextColon=string.indexOf(":",firstColon+1);if(nextColon!==-1&&(firstSlash===-1||nextColon-1?firstSlash:string.length-1);var t;if(pos>-1&&(firstSlash===-1||pos= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw RangeError(errors[type])}function map(array,fn){var length=array.length;while(length--){array[length]=fn(array[length])}return array}function mapDomain(string,fn){return map(string.split(regexSeparators),fn).join(".")}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=55296&&value<=56319&&counter65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,length,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":9,_process:4,inherits:3}]},{},[1])(1)}); +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.SwaggerConverter=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o1){oName+="_"+grantParameters.flow}this.securityNamesMap[name].push(oName);securityDefinitions[oName]=extend({},securityDefinition,grantParameters)})});return securityDefinitions};prototype.buildModel=function(oldModel){var required=[];var properties={};var items;this.forEach(oldModel.properties,function(oldProperty,propertyName){if(fixNonStringValue(oldProperty.required)===true){required.push(propertyName)}properties[propertyName]=this.buildModel(oldProperty)});if(Array.isArray(oldModel.required)){required=oldModel.required}if(isValue(oldModel.items)){items=this.buildModel(oldModel.items)}return extend(this.buildDataType(oldModel,true),{description:oldModel.description,required:undefinedIfEmpty(required),properties:undefinedIfEmpty(properties),discriminator:oldModel.discriminator,example:oldModel.example,items:undefinedIfEmpty(items)})};prototype.buildDefinitions=function(oldModels){var models={};this.forEach(oldModels,function(oldModel,modelId){models[modelId]=this.buildModel(oldModel)});this.forEach(oldModels,function(parent,parentId){this.forEach(parent.subTypes,function(childId){var child=models[childId];if(!isValue(child)){throw new SwaggerConverterError('subTypes resolution: Missing "'+childId+'" type')}if(!isValue(child.allOf)){models[childId]=child={allOf:[child]}}child.allOf.push({$ref:"#/definitions/"+parentId})})});return models};prototype.mapEach=function(collection,iteratee){var result=[];this.forEach(collection,function(value,key){result.push(iteratee.bind(this)(value,key))});return result};prototype.forEach=function(collection,iteratee){if(!isValue(collection)){return}if(typeof collection!=="object"){throw new SwaggerConverterError("Expected array or object, instead got: "+JSON.stringify(collection,null,2))}iteratee=iteratee.bind(this);if(Array.isArray(collection)){collection.forEach(iteratee)}else{Object.keys(collection).sort().forEach(function(key){iteratee(collection[key],key)})}};function extend(destination){assert(typeof destination==="object");function assign(source){if(!source){return}Object.keys(source).forEach(function(key){var value=source[key];if(isValue(value)){destination[key]=value}})}for(var i=1;i=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":11}],3:[function(require,module,exports){module.exports=common;function common(strings){if(!Array.isArray(strings)){throw new Error("common-prefix expects an array of strings")}var first=strings[0]||"";var commonLength=first.length;for(var i=1;i1){for(var i=1;i1){_segments.splice(0,1)}else{break}}segments[i]=_segments.join("")}var best=-1;var _best=0;var _current=0;var current=-1;var inzeroes=false;for(i=0;i_best){best=current;_best=_current}}}else{if(segments[i]==="0"){inzeroes=true;current=i;_current=1}}}if(_current>_best){best=current;_best=_current}if(_best>1){segments.splice(best,_best,"")}length=segments.length;var result="";if(segments[0]===""){result=":"}for(i=0;i=domain.length-1){return false}var sldOffset=domain.lastIndexOf(".",tldOffset-1);if(sldOffset<=0||sldOffset>=tldOffset-1){return false}var sldList=SLD.list[domain.slice(tldOffset+1)];if(!sldList){return false}return sldList.indexOf(" "+domain.slice(sldOffset+1,tldOffset)+" ")>=0},is:function(domain){var tldOffset=domain.lastIndexOf(".");if(tldOffset<=0||tldOffset>=domain.length-1){return false}var sldOffset=domain.lastIndexOf(".",tldOffset-1);if(sldOffset>=0){return false}var sldList=SLD.list[domain.slice(tldOffset+1)];if(!sldList){return false}return sldList.indexOf(" "+domain.slice(0,tldOffset)+" ")>=0},get:function(domain){var tldOffset=domain.lastIndexOf(".");if(tldOffset<=0||tldOffset>=domain.length-1){return null}var sldOffset=domain.lastIndexOf(".",tldOffset-1);if(sldOffset<=0||sldOffset>=tldOffset-1){return null}var sldList=SLD.list[domain.slice(tldOffset+1)];if(!sldList){return null}if(sldList.indexOf(" "+domain.slice(sldOffset+1,tldOffset)+" ")<0){return null}return domain.slice(sldOffset+1)},noConflict:function(){if(root.SecondLevelDomains===this){root.SecondLevelDomains=_SecondLevelDomains}return this}};return SLD})},{}],8:[function(require,module,exports){(function(root,factory){"use strict";if(typeof exports==="object"){module.exports=factory(require("./punycode"),require("./IPv6"),require("./SecondLevelDomains"))}else if(typeof define==="function"&&define.amd){define(["./punycode","./IPv6","./SecondLevelDomains"],factory)}else{root.URI=factory(root.punycode,root.IPv6,root.SecondLevelDomains,root)}})(this,function(punycode,IPv6,SLD,root){"use strict";var _URI=root&&root.URI;function URI(url,base){var _urlSupplied=arguments.length>=1;var _baseSupplied=arguments.length>=2;if(!(this instanceof URI)){if(_urlSupplied){if(_baseSupplied){return new URI(url,base)}return new URI(url)}return new URI}if(url===undefined){if(_urlSupplied){throw new TypeError("undefined is not a valid argument for URI")}if(typeof location!=="undefined"){url=location.href+""}else{url=""}}this.href(url);if(base!==undefined){return this.absoluteTo(base)}return this}URI.version="1.17.1";var p=URI.prototype;var hasOwn=Object.prototype.hasOwnProperty;function escapeRegEx(string){return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function getType(value){if(value===undefined){return"Undefined"}return String(Object.prototype.toString.call(value)).slice(8,-1)}function isArray(obj){return getType(obj)==="Array"}function filterArrayValues(data,value){var lookup={};var i,length;if(getType(value)==="RegExp"){lookup=null}else if(isArray(value)){for(i=0,length=value.length;i]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;URI.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?«»“”„‘’]+$/};URI.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"};URI.invalid_hostname_characters=/[^a-zA-Z0-9\.-]/;URI.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"};URI.getDomAttribute=function(node){if(!node||!node.nodeName){return undefined}var nodeName=node.nodeName.toLowerCase();if(nodeName==="input"&&node.type!=="image"){return undefined}return URI.domAttributes[nodeName]};function escapeForDumbFirefox36(value){return escape(value)}function strictEncodeURIComponent(string){return encodeURIComponent(string).replace(/[!'()*]/g,escapeForDumbFirefox36).replace(/\*/g,"%2A")}URI.encode=strictEncodeURIComponent;URI.decode=decodeURIComponent;URI.iso8859=function(){URI.encode=escape;URI.decode=unescape};URI.unicode=function(){URI.encode=strictEncodeURIComponent;URI.decode=decodeURIComponent};URI.characters={pathname:{encode:{expression:/%(24|26|2B|2C|3B|3D|3A|40)/gi,map:{"%24":"$","%26":"&","%2B":"+","%2C":",","%3B":";","%3D":"=","%3A":":","%40":"@"}},decode:{expression:/[\/\?#]/g,map:{"/":"%2F","?":"%3F","#":"%23"}}},reserved:{encode:{expression:/%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/gi,map:{"%3A":":","%2F":"/","%3F":"?","%23":"#","%5B":"[","%5D":"]","%40":"@","%21":"!","%24":"$","%26":"&","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"="}}},urnpath:{encode:{expression:/%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/gi,map:{"%21":"!","%24":"$","%27":"'","%28":"(","%29":")","%2A":"*","%2B":"+","%2C":",","%3B":";","%3D":"=","%40":"@"}},decode:{expression:/[\/\?#:]/g,map:{"/":"%2F","?":"%3F","#":"%23",":":"%3A"}}}};URI.encodeQuery=function(string,escapeQuerySpace){var escaped=URI.encode(string+"");if(escapeQuerySpace===undefined){escapeQuerySpace=URI.escapeQuerySpace}return escapeQuerySpace?escaped.replace(/%20/g,"+"):escaped};URI.decodeQuery=function(string,escapeQuerySpace){string+="";if(escapeQuerySpace===undefined){escapeQuerySpace=URI.escapeQuerySpace}try{return URI.decode(escapeQuerySpace?string.replace(/\+/g,"%20"):string)}catch(e){return string}};var _parts={encode:"encode",decode:"decode"};var _part;var generateAccessor=function(_group,_part){return function(string){try{return URI[_part](string+"").replace(URI.characters[_group][_part].expression,function(c){return URI.characters[_group][_part].map[c]})}catch(e){return string}}};for(_part in _parts){URI[_part+"PathSegment"]=generateAccessor("pathname",_parts[_part]);URI[_part+"UrnPathSegment"]=generateAccessor("urnpath",_parts[_part])}var generateSegmentedPathFunction=function(_sep,_codingFuncName,_innerCodingFuncName){return function(string){var actualCodingFunc;if(!_innerCodingFuncName){actualCodingFunc=URI[_codingFuncName]}else{actualCodingFunc=function(string){return URI[_codingFuncName](URI[_innerCodingFuncName](string))}}var segments=(string+"").split(_sep);for(var i=0,length=segments.length;i-1){parts.fragment=string.substring(pos+1)||null;string=string.substring(0,pos)}pos=string.indexOf("?");if(pos>-1){parts.query=string.substring(pos+1)||null;string=string.substring(0,pos)}if(string.substring(0,2)==="//"){parts.protocol=null;string=string.substring(2);string=URI.parseAuthority(string,parts)}else{pos=string.indexOf(":");if(pos>-1){parts.protocol=string.substring(0,pos)||null;if(parts.protocol&&!parts.protocol.match(URI.protocol_expression)){parts.protocol=undefined}else if(string.substring(pos+1,pos+3)==="//"){string=string.substring(pos+3);string=URI.parseAuthority(string,parts)}else{string=string.substring(pos+1);parts.urn=true}}}parts.path=string;return parts};URI.parseHost=function(string,parts){string=string.replace(/\\/g,"/");var pos=string.indexOf("/");var bracketPos;var t;if(pos===-1){pos=string.length}if(string.charAt(0)==="["){bracketPos=string.indexOf("]");parts.hostname=string.substring(1,bracketPos)||null;parts.port=string.substring(bracketPos+2,pos)||null;if(parts.port==="/"){parts.port=null}}else{var firstColon=string.indexOf(":");var firstSlash=string.indexOf("/");var nextColon=string.indexOf(":",firstColon+1);if(nextColon!==-1&&(firstSlash===-1||nextColon-1?firstSlash:string.length-1);var t;if(pos>-1&&(firstSlash===-1||pos= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,key;function error(type){throw new RangeError(errors[type])}function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length])}return result}function mapDomain(string,fn){var parts=string.split("@");var result="";if(parts.length>1){result=parts[0]+"@";string=parts[1]}string=string.replace(regexSeparators,".");var labels=string.split(".");var encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=55296&&value<=56319&&counter65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value);return output}).join("")}function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22}if(codePoint-65<26){return codePoint-65}if(codePoint-97<26){return codePoint-97}return base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((flag!=0)<<5)}function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin)}return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,baseMinusT;basic=input.lastIndexOf(delimiter);if(basic<0){basic=0}for(j=0;j=128){error("not-basic")}output.push(input.charCodeAt(j))}for(index=basic>0?basic+1:0;index=inputLength){error("invalid-input")}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error("overflow")}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error("overflow")}w*=baseMinusT}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);if(floor(i/out)>maxInt-n){error("overflow")}n+=floor(i/out);i%=out;output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],inputLength,handledCPCountPlusOne,baseMinusT,qMinusT;input=ucs2decode(input);inputLength=input.length;n=initialN;delta=0;bias=initialBias;for(j=0;j=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne)){error("overflow")}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error("overflow")}if(currentValue==n){for(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":10,_process:5,inherits:4}]},{},[1])(1)}); diff --git a/index.js b/index.js index e96d425..da83aee 100644 --- a/index.js +++ b/index.js @@ -26,6 +26,7 @@ var assert = require('assert'); var URI = require('urijs'); +var commonPrefix = require('common-prefix'); var SwaggerConverter = module.exports = {}; @@ -198,28 +199,29 @@ Converter.prototype.getResources = function(resourceListing, apiDeclarations) { * @returns {array} - list of Swagger 2.0 tags */ Converter.prototype.buildTags = function(resourceListing, resources) { - var resourcePaths = []; - this.forEach(resources, function(resource) { - var path = resource.resourcePath; - if (isValue(resource) && resourcePaths.indexOf(path) === -1) { - resourcePaths.push(path); - } + var resourcePaths = this.mapEach(resources, function(resource) { + return resource.resourcePath; }); //'resourcePath' is optional parameter and also frequently have invalid values // if so than we discard all values and use resource paths for listing instead. - if (getLength(resourcePaths) < getLength(resources)) { - resourcePaths = {}; + if (getLength(removeDuplicates(resourcePaths)) < getLength(resources)) { + resourcePaths = this.mapEach(resourceListing.apis, function(resource) { + return resource.path; + }); } + resourcePaths = stripCommonPath(resourcePaths); + var tags = []; this.forEach(resourceListing.apis, function(resource, index) { - if (!isEmpty(resource.operations)) { - return; - } + if (!isEmpty(resource.operations)) { return; } + + var tagName = URI(resourcePaths[index] || '').path(true) + .replace('{format}', 'json') + .replace(/\/$/, '') + .replace(/.json$/, ''); - var path = resourcePaths[index] || resource.path; - var tagName = this.extractTag(path); if (!isValue(tagName)) { return; } tags.push(extend({}, { @@ -231,21 +233,6 @@ Converter.prototype.buildTags = function(resourceListing, resources) { return tags; }; -/* - * Extract name of the tag from resourcePath - * @param resourcePath {string} - Swagger 1.x resource path - * @returns {string} - tag name -*/ -prototype.extractTag = function(resourcePath) { - var tag = URI(resourcePath || '').path(true) - .replace('{format}', 'json') - .replace(/\/$/, '') - .replace(/.json$/, '') - .split(['/']).pop(); - - return tag || undefined; -}; - /* * Builds "info" section of Swagger 2.0 document * @param resourceListing {object} - root of Swagger 1.x document @@ -978,6 +965,20 @@ function fixNonStringValue(value, skipError) { */ function removeDuplicates(collection) { return collection.filter(function(e, i, arr) { - return arr.lastIndexOf(e) === i; + return isValue(e) && arr.lastIndexOf(e) === i; + }); +} + +/* + * Strip common prefix from paths + * @params paths {array} + * @returns {array} - path with remove common part + */ +function stripCommonPath(paths) { + var prefix = commonPrefix(paths); + var prefixLength = prefix.lastIndexOf('/') + 1; + + return paths.map(function(str) { + return str.slice(prefixLength); }); } diff --git a/package.json b/package.json index 70131d1..de00fd2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "swagger-converter", - "version": "1.2.0", + "version": "1.3.0", "description": "Converts Swagger documents from version 1.x to version 2.0", "main": "index.js", "scripts": { @@ -44,6 +44,7 @@ "uglify-js": "^2.6.0" }, "dependencies": { + "common-prefix": "^1.1.0", "urijs": "^1.16.1" } } diff --git a/test/input/fixable/index.json b/test/input/fixable/index.json index c517742..4789e08 100644 --- a/test/input/fixable/index.json +++ b/test/input/fixable/index.json @@ -4,11 +4,11 @@ "basePath": "/v1/", "apis": [ { - "path": "/pets", + "path": "/swagger_files/my/pets", "description": "A list of pets" }, { - "path": "/stores", + "path": "/swagger_files/our/stores", "description": "A list of stores" } ] diff --git a/test/output/fixable.json b/test/output/fixable.json index 1e31c6b..5250653 100644 --- a/test/output/fixable.json +++ b/test/output/fixable.json @@ -80,6 +80,7 @@ } }, "tags": [ + "my/pets", "pets" ] } @@ -92,7 +93,7 @@ } }, "tags": [ - "stores" + "our/stores" ] } } @@ -101,11 +102,11 @@ "tags": [ { "description": "A list of pets", - "name": "pets" + "name": "my/pets" }, { "description": "A list of stores", - "name": "stores" + "name": "our/stores" } ] } diff --git a/test/test.js b/test/test.js index 10d5155..c50a3c4 100644 --- a/test/test.js +++ b/test/test.js @@ -78,8 +78,8 @@ var inputs = [ { resourceListing: 'fixable/index.json', apiDeclarations: { - '/pets': 'fixable/pets.json', - '/stores': 'fixable/stores.json' + '/swagger_files/my/pets': 'fixable/pets.json', + '/swagger_files/our/stores': 'fixable/stores.json' }, output: 'fixable.json' },