Showing preview only (1,610K chars total). Download the full file or copy to clipboard to get everything.
Repository: RhinoSecurityLabs/Swagger-EZ
Branch: master
Commit: de5cfa6b722f
Files: 6
Total size: 1.5 MB
Directory structure:
gitextract_06y61mnm/
├── LICENSE
├── README.md
├── css/
│ └── layout.css
├── index.html
└── js/
├── swagger-client.js
└── ui.js
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
BSD 3-Clause License
Copyright (c) 2018, Rhino Security Labs
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README.md
================================================
# Swagger-EZ
A tool geared towards pentesting APIs using OpenAPI definitions.
We have a version hosted here: https://rhinosecuritylabs.github.io/Swagger-EZ/
Blog post: https://rhinosecuritylabs.com/application-security/simplifying-api-pentesting-swagger-files/
## Setup
`git clone https://github.com/RhinoSecurityLabs/Swagger-EZ.git`
Open `index.html` in your browser.
## Usage
Once the UI is loaded into the browser, we suggest pressing F12 to have the browser console open to watch for potential errors.
Configure your browser to use the proxy tool you would like i.e. Burp Suite.
Now you can insert the URL containing the Swagger 2.0 JSON or simply copy and paste an entire JSON Swagger 2.0 blob into the input field.
Pressing load will parse the JSON and load the input fields for the parameters that need to be filled out.
Fill out each parameters with some data and when ready press send.
You should see the site tree of your proxy filling up.

================================================
FILE: css/layout.css
================================================
* {box-sizing: border-box;}
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.topnav {
overflow: hidden;
background-color: #b30000;
height: 48px;
}
.topnav a {
float: left;
display: block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #2196F3;
color: white;
}
.topnav .search-container {
float: right;
color: white;
}
.topnav input[type=text] {
padding: 6px;
margin-top: 8px;
font-size: 17px;
border: none;
}
.topnav .search-container button {
float: right;
padding: 6px;
margin-top: 8px;
margin-right: 16px;
background: #ddd;
font-size: 17px;
border: none;
cursor: pointer;
}
.topnav .search-container button:hover {
background: #ccc;
}
@media screen and (max-width: 600px) {
.topnav .search-container {
float: none;
}
.topnav a, .topnav input[type=text], .topnav .search-container button {
float: none;
display: block;
text-align: left;
width: 100%;
margin: 0;
padding: 14px;
}
.topnav input[type=text] {
border: 1px solid #ccc;
}
}
label {
width:210px;
clear:left;
text-align:right;
padding-right:10px;
}
.inputbody, label, select {
float:left;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
font-size: 16px;
}
.inputbody {
border: 2px solid #dadada;
height: 30px;
}
.inputbody:focus{
outline: none;
border-color: #b30000;
box-shadow: 0 0 10px #b30000;
}
================================================
FILE: index.html
================================================
<html>
<head>
<title>
Swagger-EZ
</title>
<link rel = "stylesheet" type = "text/css" href = "css/layout.css" />
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<script src='js/swagger-client.js' type='text/javascript'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type='text/javascript'></script>
<script src='js/ui.js' type='text/javascript'></script>
<body>
<div id="navbar" class="topnav">
<div class="search-container">
Url or raw JSON: <input type="text" size=70 id="url" value="https://petstore.swagger.io/v2/swagger.json">
<button type="submit" onclick=executeAll(apis);>Send All</button>
<button type="submit" onclick=autoFill();>Auto Fill</button>
<button type="submit" onclick=init(document.getElementById("url").value);>Load</button>
</div>
</div>
<br>
Authorization key: <input type="text" size=70 id="api-key" value="">
<br>
<div id="info" class="w3-container"></div>
<br>
<div id="head" class="w3-container">
</div>
<div id="input-form-container" class="w3-container">
</div>
<br>
<div class="w3-panel w3-card"><code>
<h4><p align="right">Regex for CORS response headers Burp Suite</p></h4>
<p align="right">
<b>Match: </b>Access-Control-Allow-Origin:(.*?)$<br>
<b>Replace: </b>Access-Control-Allow-Origin: *<br>
<br>
<b>Match: </b>Access-Control-Allow-Methods:(.*?)$<br>
<b>Replace: </b>Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT<br>
<br>
<b>Match: </b>Access-Control-Allow-Headers:(.*?)$
</p>
</code></div>
<div id="output">
<h4>Requests Made:</h4>
</div>
</body>
================================================
FILE: js/swagger-client.js
================================================
/**
* swagger-client - swagger-client is a javascript client for use with swaggering APIs.
* @version v2.1.13
* @link http://swagger.io
* @license Apache-2.0
*/
(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.SwaggerClient = 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;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var auth = require('./lib/auth');
var helpers = require('./lib/helpers');
var SwaggerClient = require('./lib/client');
var deprecationWrapper = function (url, options) {
helpers.log('This is deprecated, use "new SwaggerClient" instead.');
return new SwaggerClient(url, options);
};
/* Here for IE8 Support */
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
};
}
/* Here for IE8 Support */
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
/* Here for node 10.x support */
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
module.exports = SwaggerClient;
SwaggerClient.ApiKeyAuthorization = auth.ApiKeyAuthorization;
SwaggerClient.PasswordAuthorization = auth.PasswordAuthorization;
SwaggerClient.CookieAuthorization = auth.CookieAuthorization;
SwaggerClient.SwaggerApi = deprecationWrapper;
SwaggerClient.SwaggerClient = deprecationWrapper;
SwaggerClient.SchemaMarkup = require('./lib/schema-markup');
},{"./lib/auth":2,"./lib/client":3,"./lib/helpers":4,"./lib/schema-markup":7}],2:[function(require,module,exports){
'use strict';
var helpers = require('./helpers');
var btoa = require('btoa'); // jshint ignore:line
var CookieJar = require('cookiejar').CookieJar;
var _ = {
each: require('lodash-compat/collection/each'),
includes: require('lodash-compat/collection/includes'),
isObject: require('lodash-compat/lang/isObject'),
isArray: require('lodash-compat/lang/isArray')
};
/**
* SwaggerAuthorizations applys the correct authorization to an operation being executed
*/
var SwaggerAuthorizations = module.exports.SwaggerAuthorizations = function (authz) {
this.authz = authz || {};
};
/**
* Add auths to the hash
* Will overwrite any existing
*
*/
SwaggerAuthorizations.prototype.add = function (name, auth) {
if(_.isObject(name)) {
for (var key in name) {
this.authz[key] = name[key];
}
} else if(typeof name === 'string' ){
this.authz[name] = auth;
}
return auth;
};
SwaggerAuthorizations.prototype.remove = function (name) {
return delete this.authz[name];
};
SwaggerAuthorizations.prototype.apply = function (obj, securities) {
var status = true;
var applyAll = !securities;
var flattenedSecurities = [];
// Securities could be [ {} ]
_.each(securities, function (obj, key) {
// Make sure we account for securities being [ str ]
if(typeof key === 'string') {
flattenedSecurities.push(key);
}
// Flatten keys in to our array
_.each(obj, function (val, key) {
flattenedSecurities.push(key);
});
});
_.each(this.authz, function (auth, authName) {
if(applyAll || _.includes(flattenedSecurities, authName)) {
var newStatus = auth.apply(obj);
status = status && !!newStatus; // logical ORs regarding status
}
});
return status;
};
/**
* ApiKeyAuthorization allows a query param or header to be injected
*/
var ApiKeyAuthorization = module.exports.ApiKeyAuthorization = function (name, value, type) {
this.name = name;
this.value = value;
this.type = type;
};
ApiKeyAuthorization.prototype.apply = function (obj) {
if (this.type === 'query') {
// see if already applied. If so, don't do it again
var qp;
if (obj.url.indexOf('?') > 0) {
qp = obj.url.substring(obj.url.indexOf('?') + 1);
var parts = qp.split('&');
if(parts && parts.length > 0) {
for(var i = 0; i < parts.length; i++) {
var kv = parts[i].split('=');
if(kv && kv.length > 0) {
if (kv[0] === this.name) {
// skip it
return false;
}
}
}
}
}
if (obj.url.indexOf('?') > 0) {
obj.url = obj.url + '&' + this.name + '=' + this.value;
} else {
obj.url = obj.url + '?' + this.name + '=' + this.value;
}
return true;
} else if (this.type === 'header') {
if(typeof obj.headers[this.name] === 'undefined') {
obj.headers[this.name] = this.value;
}
return true;
}
};
var CookieAuthorization = module.exports.CookieAuthorization = function (cookie) {
this.cookie = cookie;
};
CookieAuthorization.prototype.apply = function (obj) {
obj.cookieJar = obj.cookieJar || new CookieJar();
obj.cookieJar.setCookie(this.cookie);
return true;
};
/**
* Password Authorization is a basic auth implementation
*/
var PasswordAuthorization = module.exports.PasswordAuthorization = function (username, password) {
if (arguments.length === 3) {
helpers.log('PasswordAuthorization: the \'name\' argument has been removed, pass only username and password');
username = arguments[1];
password = arguments[2];
}
this.username = username;
this.password = password;
};
PasswordAuthorization.prototype.apply = function (obj) {
if(typeof obj.headers.Authorization === 'undefined') {
obj.headers.Authorization = 'Basic ' + btoa(this.username + ':' + this.password);
}
return true;
};
},{"./helpers":4,"btoa":14,"cookiejar":19,"lodash-compat/collection/each":53,"lodash-compat/collection/includes":56,"lodash-compat/lang/isArray":141,"lodash-compat/lang/isObject":145}],3:[function(require,module,exports){
'use strict';
var _ = {
bind: require('lodash-compat/function/bind'),
cloneDeep: require('lodash-compat/lang/cloneDeep'),
find: require('lodash-compat/collection/find'),
forEach: require('lodash-compat/collection/forEach'),
indexOf: require('lodash-compat/array/indexOf'),
isArray: require('lodash-compat/lang/isArray'),
isObject: require('lodash-compat/lang/isObject'),
isFunction: require('lodash-compat/lang/isFunction'),
isPlainObject: require('lodash-compat/lang/isPlainObject'),
isUndefined: require('lodash-compat/lang/isUndefined')
};
var auth = require('./auth');
var helpers = require('./helpers');
var Model = require('./types/model');
var Operation = require('./types/operation');
var OperationGroup = require('./types/operationGroup');
var Resolver = require('./resolver');
var SwaggerHttp = require('./http');
var SwaggerSpecConverter = require('./spec-converter');
var Q = require('q');
// We have to keep track of the function/property names to avoid collisions for tag names which are used to allow the
// following usage: 'client.{tagName}'
var reservedClientTags = [
'apis',
'authorizationScheme',
'authorizations',
'basePath',
'build',
'buildFrom1_1Spec',
'buildFrom1_2Spec',
'buildFromSpec',
'clientAuthorizations',
'convertInfo',
'debug',
'defaultErrorCallback',
'defaultSuccessCallback',
'enableCookies',
'fail',
'failure',
'finish',
'help',
'idFromOp',
'info',
'initialize',
'isBuilt',
'isValid',
'modelPropertyMacro',
'models',
'modelsArray',
'options',
'parameterMacro',
'parseUri',
'progress',
'resourceCount',
'sampleModels',
'selfReflect',
'setConsolidatedModels',
'spec',
'supportedSubmitMethods',
'swaggerRequestHeaders',
'tagFromLabel',
'title',
'url',
'useJQuery'
];
// We have to keep track of the function/property names to avoid collisions for tag names which are used to allow the
// following usage: 'client.apis.{tagName}'
var reservedApiTags = [
'apis',
'asCurl',
'description',
'externalDocs',
'help',
'label',
'name',
'operation',
'operations',
'operationsArray',
'path',
'tag'
];
var supportedOperationMethods = ['delete', 'get', 'head', 'options', 'patch', 'post', 'put'];
var SwaggerClient = module.exports = function (url, options) {
this.authorizations = null;
this.authorizationScheme = null;
this.basePath = null;
this.debug = false;
this.enableCookies = false;
this.info = null;
this.isBuilt = false;
this.isValid = false;
this.modelsArray = [];
this.resourceCount = 0;
this.url = null;
this.useJQuery = false;
this.swaggerObject = {};
this.deferredClient = Q.defer();
this.clientAuthorizations = new auth.SwaggerAuthorizations();
if (typeof url !== 'undefined') {
return this.initialize(url, options);
} else {
return this;
}
};
SwaggerClient.prototype.initialize = function (url, options) {
this.models = {};
this.sampleModels = {};
if (typeof url === 'string') {
this.url = url;
} else if (_.isObject(url)) {
options = url;
this.url = options.url;
}
options = options || {};
this.clientAuthorizations.add(options.authorizations);
this.swaggerRequestHeaders = options.swaggerRequestHeaders || 'application/json;charset=utf-8,*/*';
this.defaultSuccessCallback = options.defaultSuccessCallback || null;
this.defaultErrorCallback = options.defaultErrorCallback || null;
this.modelPropertyMacro = options.modelPropertyMacro || null;
this.parameterMacro = options.parameterMacro || null;
this.usePromise = options.usePromise || null;
if (typeof options.success === 'function') {
this.success = options.success;
}
if (options.useJQuery) {
this.useJQuery = options.useJQuery;
}
if (options.enableCookies) {
this.enableCookies = options.enableCookies;
}
this.options = options || {};
this.supportedSubmitMethods = options.supportedSubmitMethods || [];
this.failure = options.failure || function (err) { throw err; };
this.progress = options.progress || function () {};
this.spec = _.cloneDeep(options.spec); // Clone so we do not alter the provided document
if (options.scheme) {
this.scheme = options.scheme;
}
if (this.usePromise || typeof options.success === 'function') {
this.ready = true;
return this.build();
}
};
SwaggerClient.prototype.build = function (mock) {
if (this.isBuilt) {
return this;
}
var self = this;
this.progress('fetching resource list: ' + this.url + '; Please wait.');
var obj = {
useJQuery: this.useJQuery,
url: this.url,
method: 'get',
headers: {
accept: this.swaggerRequestHeaders
},
on: {
error: function (response) {
if (self.url.substring(0, 4) !== 'http') {
return self.fail('Please specify the protocol for ' + self.url);
} else if (response.status === 0) {
return self.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.');
} else if (response.status === 404) {
return self.fail('Can\'t read swagger JSON from ' + self.url);
} else {
return self.fail(response.status + ' : ' + response.statusText + ' ' + self.url);
}
},
response: function (resp) {
var responseObj = resp.obj;
if(!responseObj) {
return self.fail('failed to parse JSON/YAML response');
}
self.swaggerVersion = responseObj.swaggerVersion;
self.swaggerObject = responseObj;
if (responseObj.swagger && parseInt(responseObj.swagger) === 2) {
self.swaggerVersion = responseObj.swagger;
new Resolver().resolve(responseObj, self.url, self.buildFromSpec, self);
self.isValid = true;
} else {
var converter = new SwaggerSpecConverter();
self.oldSwaggerObject = self.swaggerObject;
converter.setDocumentationLocation(self.url);
converter.convert(responseObj, self.clientAuthorizations, self.options, function(spec) {
self.swaggerObject = spec;
new Resolver().resolve(spec, self.url, self.buildFromSpec, self);
self.isValid = true;
});
}
}
}
};
if (this.spec) {
self.swaggerObject = this.spec;
setTimeout(function () {
new Resolver().resolve(self.spec, self.url, self.buildFromSpec, self);
}, 10);
} else {
this.clientAuthorizations.apply(obj);
if (mock) {
return obj;
}
new SwaggerHttp().execute(obj, this.options);
}
return (this.usePromise) ? this.deferredClient.promise : this;
};
SwaggerClient.prototype.buildFromSpec = function (response) {
if (this.isBuilt) {
return this;
}
this.apis = {};
this.apisArray = [];
this.basePath = response.basePath || '';
this.consumes = response.consumes;
this.host = response.host || '';
this.info = response.info || {};
this.produces = response.produces;
this.schemes = response.schemes || [];
this.securityDefinitions = response.securityDefinitions;
this.title = response.title || '';
if (response.externalDocs) {
this.externalDocs = response.externalDocs;
}
// legacy support
this.authSchemes = response.securityDefinitions;
var definedTags = {};
var k;
if (Array.isArray(response.tags)) {
definedTags = {};
for (k = 0; k < response.tags.length; k++) {
var t = response.tags[k];
definedTags[t.name] = t;
}
}
var location;
if (typeof this.url === 'string') {
location = this.parseUri(this.url);
if (typeof this.scheme === 'undefined' && typeof this.schemes === 'undefined' || this.schemes.length === 0) {
this.scheme = location.scheme || 'http';
} else if (typeof this.scheme === 'undefined') {
this.scheme = this.schemes[0] || location.scheme;
}
if (typeof this.host === 'undefined' || this.host === '') {
this.host = location.host;
if (location.port) {
this.host = this.host + ':' + location.port;
}
}
}
else {
if (typeof this.schemes === 'undefined' || this.schemes.length === 0) {
this.scheme = 'http';
}
else if (typeof this.scheme === 'undefined') {
this.scheme = this.schemes[0];
}
}
this.definitions = response.definitions;
var key;
for (key in this.definitions) {
var model = new Model(key, this.definitions[key], this.models, this.modelPropertyMacro);
if (model) {
this.models[key] = model;
}
}
// get paths, create functions for each operationId
var self = this;
// Bind help to 'client.apis'
self.apis.help = _.bind(self.help, self);
_.forEach(response.paths, function (pathObj, path) {
// Only process a path if it's an object
if (!_.isPlainObject(pathObj)) {
return;
}
_.forEach(supportedOperationMethods, function (method) {
var operation = pathObj[method];
if (_.isUndefined(operation)) {
// Operation does not exist
return;
} else if (!_.isPlainObject(operation)) {
// Operation exists but it is not an Operation Object. Since this is invalid, log it.
helpers.log('The \'' + method + '\' operation for \'' + path + '\' path is not an Operation Object');
return;
}
var tags = operation.tags;
if (_.isUndefined(tags) || !_.isArray(tags) || tags.length === 0) {
tags = operation.tags = [ 'default' ];
}
var operationId = self.idFromOp(path, method, operation);
var operationObject = new Operation(self,
operation.scheme,
operationId,
method,
path,
operation,
self.definitions,
self.models,
self.clientAuthorizations);
// bind self operation's execute command to the api
_.forEach(tags, function (tag) {
var clientProperty = _.indexOf(reservedClientTags, tag) > -1 ? '_' + tag : tag;
var apiProperty = _.indexOf(reservedApiTags, tag) > -1 ? '_' + tag : tag;
var operationGroup = self[clientProperty];
if (clientProperty !== tag) {
helpers.log('The \'' + tag + '\' tag conflicts with a SwaggerClient function/property name. Use \'client.' +
clientProperty + '\' or \'client.apis.' + tag + '\' instead of \'client.' + tag + '\'.');
}
if (apiProperty !== tag) {
helpers.log('The \'' + tag + '\' tag conflicts with a SwaggerClient operation function/property name. Use ' +
'\'client.apis.' + apiProperty + '\' instead of \'client.apis.' + tag + '\'.');
}
if (_.indexOf(reservedApiTags, operationId) > -1) {
helpers.log('The \'' + operationId + '\' operationId conflicts with a SwaggerClient operation ' +
'function/property name. Use \'client.apis.' + apiProperty + '._' + operationId +
'\' instead of \'client.apis.' + apiProperty + '.' + operationId + '\'.');
operationId = '_' + operationId;
operationObject.nickname = operationId; // So 'client.apis.[tag].operationId.help() works properly
}
if (_.isUndefined(operationGroup)) {
operationGroup = self[clientProperty] = self.apis[apiProperty] = {};
operationGroup.operations = {};
operationGroup.label = apiProperty;
operationGroup.apis = {};
var tagDef = definedTags[tag];
if (!_.isUndefined(tagDef)) {
operationGroup.description = tagDef.description;
operationGroup.externalDocs = tagDef.externalDocs;
}
self[clientProperty].help = _.bind(self.help, operationGroup);
self.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject));
}
operationId = self.makeUniqueOperationId(operationId, self.apis[apiProperty]);
// Bind tag help
if (!_.isFunction(operationGroup.help)) {
operationGroup.help = _.bind(self.help, operationGroup);
}
// bind to the apis object
self.apis[apiProperty][operationId] = operationGroup[operationId] = _.bind(operationObject.execute,
operationObject);
self.apis[apiProperty][operationId].help = operationGroup[operationId].help = _.bind(operationObject.help,
operationObject);
self.apis[apiProperty][operationId].asCurl = operationGroup[operationId].asCurl = _.bind(operationObject.asCurl,
operationObject);
operationGroup.apis[operationId] = operationGroup.operations[operationId] = operationObject;
// legacy UI feature
var api = _.find(self.apisArray, function (api) {
return api.tag === tag;
});
if (api) {
api.operationsArray.push(operationObject);
}
});
});
});
_.forEach(response.definitions, function (definitionObj, definition) {
definitionObj['id'] = definition.toLowerCase();
definitionObj['name'] = definition;
self.modelsArray.push(definitionObj);
});
this.isBuilt = true;
if (this.usePromise) {
this.isValid = true;
this.isBuilt = true;
this.deferredClient.resolve(this);
return this.deferredClient.promise;
}
if (this.success) {
this.success();
}
return this;
};
SwaggerClient.prototype.makeUniqueOperationId = function(operationId, api) {
var count = 0;
var name = operationId;
// make unique across this operation group
while(true) {
var matched = false;
_.forEach(api.operations, function (operation) {
if(operation.nickname === name) {
matched = true;
}
});
if(!matched) {
return name;
}
name = operationId + '_' + count;
count ++;
}
return operationId;
};
SwaggerClient.prototype.parseUri = function (uri) {
var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
var parts = urlParseRE.exec(uri);
return {
scheme: parts[4] ? parts[4].replace(':','') : undefined,
host: parts[11],
port: parts[12],
path: parts[15]
};
};
SwaggerClient.prototype.help = function (dontPrint) {
var output = '';
if (this instanceof SwaggerClient) {
_.forEach(this.apis, function (api, name) {
if (_.isPlainObject(api)) {
output += 'operations for the \'' + name + '\' tag\n';
_.forEach(api.operations, function (operation, name) {
output += ' * ' + name + ': ' + operation.summary + '\n';
});
}
});
} else if (this instanceof OperationGroup || _.isPlainObject(this)) {
output += 'operations for the \'' + this.label + '\' tag\n';
_.forEach(this.apis, function (operation, name) {
output += ' * ' + name + ': ' + operation.summary + '\n';
});
}
if (dontPrint) {
return output;
} else {
helpers.log(output);
return output;
}
};
SwaggerClient.prototype.tagFromLabel = function (label) {
return label;
};
SwaggerClient.prototype.idFromOp = function (path, httpMethod, op) {
if(!op || !op.operationId) {
op = op || {};
op.operationId = httpMethod + '_' + path;
}
var opId = op.operationId.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_') || (path.substring(1) + '_' + httpMethod);
opId = opId.replace(/((_){2,})/g, '_');
opId = opId.replace(/^(_)*/g, '');
opId = opId.replace(/([_])*$/g, '');
return opId;
};
SwaggerClient.prototype.setHost = function (host) {
this.host = host;
if(this.apis) {
_.forEach(this.apis, function(api) {
if(api.operations) {
_.forEach(api.operations, function(operation) {
operation.host = host;
});
}
});
}
};
SwaggerClient.prototype.setBasePath = function (basePath) {
this.basePath = basePath;
if(this.apis) {
_.forEach(this.apis, function(api) {
if(api.operations) {
_.forEach(api.operations, function(operation) {
operation.basePath = basePath;
});
}
});
}
};
SwaggerClient.prototype.fail = function (message) {
if (this.usePromise) {
this.deferredClient.reject(message);
return this.deferredClient.promise;
} else {
if (this.failure) {
this.failure(message);
}
else {
this.failure(message);
}
}
};
},{"./auth":2,"./helpers":4,"./http":5,"./resolver":6,"./spec-converter":8,"./types/model":9,"./types/operation":10,"./types/operationGroup":11,"lodash-compat/array/indexOf":50,"lodash-compat/collection/find":54,"lodash-compat/collection/forEach":55,"lodash-compat/function/bind":59,"lodash-compat/lang/cloneDeep":139,"lodash-compat/lang/isArray":141,"lodash-compat/lang/isFunction":143,"lodash-compat/lang/isObject":145,"lodash-compat/lang/isPlainObject":146,"lodash-compat/lang/isUndefined":149,"q":158}],4:[function(require,module,exports){
(function (process){
'use strict';
var _ = {
isPlainObject: require('lodash-compat/lang/isPlainObject'),
indexOf: require('lodash-compat/array/indexOf')
};
module.exports.__bind = function (fn, me) {
return function(){
return fn.apply(me, arguments);
};
};
var log = module.exports.log = function() {
// Only log if available and we're not testing
if (console && process.env.NODE_ENV !== 'test') {
console.log(Array.prototype.slice.call(arguments)[0]);
}
};
module.exports.fail = function (message) {
log(message);
};
var optionHtml = module.exports.optionHtml = function (label, value) {
return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
};
var resolveSchema = module.exports.resolveSchema = function (schema) {
if (_.isPlainObject(schema.schema)) {
schema = resolveSchema(schema.schema);
}
return schema;
};
var simpleRef = module.exports.simpleRef = function (name) {
if (typeof name === 'undefined') {
return null;
}
if (name.indexOf('#/definitions/') === 0) {
return name.substring('#/definitions/'.length);
} else {
return name;
}
};
}).call(this,require('_process'))
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImxpYi9oZWxwZXJzLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiJ3VzZSBzdHJpY3QnO1xuXG52YXIgXyA9IHtcbiAgaXNQbGFpbk9iamVjdDogcmVxdWlyZSgnbG9kYXNoLWNvbXBhdC9sYW5nL2lzUGxhaW5PYmplY3QnKSxcbiAgaW5kZXhPZjogcmVxdWlyZSgnbG9kYXNoLWNvbXBhdC9hcnJheS9pbmRleE9mJylcbn07XG5cbm1vZHVsZS5leHBvcnRzLl9fYmluZCA9IGZ1bmN0aW9uIChmbiwgbWUpIHtcbiAgcmV0dXJuIGZ1bmN0aW9uKCl7XG4gICAgcmV0dXJuIGZuLmFwcGx5KG1lLCBhcmd1bWVudHMpO1xuICB9O1xufTtcblxudmFyIGxvZyA9IG1vZHVsZS5leHBvcnRzLmxvZyA9IGZ1bmN0aW9uKCkge1xuICAvLyBPbmx5IGxvZyBpZiBhdmFpbGFibGUgYW5kIHdlJ3JlIG5vdCB0ZXN0aW5nXG4gIGlmIChjb25zb2xlICYmIHByb2Nlc3MuZW52Lk5PREVfRU5WICE9PSAndGVzdCcpIHtcbiAgICBjb25zb2xlLmxvZyhBcnJheS5wcm90b3R5cGUuc2xpY2UuY2FsbChhcmd1bWVudHMpWzBdKTtcbiAgfVxufTtcblxubW9kdWxlLmV4cG9ydHMuZmFpbCA9IGZ1bmN0aW9uIChtZXNzYWdlKSB7XG4gIGxvZyhtZXNzYWdlKTtcbn07XG5cbnZhciBvcHRpb25IdG1sID0gbW9kdWxlLmV4cG9ydHMub3B0aW9uSHRtbCA9IGZ1bmN0aW9uIChsYWJlbCwgdmFsdWUpIHtcbiAgcmV0dXJuICc8dHI+PHRkIGNsYXNzPVwib3B0aW9uTmFtZVwiPicgKyBsYWJlbCArICc6PC90ZD48dGQ+JyArIHZhbHVlICsgJzwvdGQ+PC90cj4nO1xufTtcblxudmFyIHJlc29sdmVTY2hlbWEgPSBtb2R1bGUuZXhwb3J0cy5yZXNvbHZlU2NoZW1hID0gZnVuY3Rpb24gKHNjaGVtYSkge1xuICBpZiAoXy5pc1BsYWluT2JqZWN0KHNjaGVtYS5zY2hlbWEpKSB7XG4gICAgc2NoZW1hID0gcmVzb2x2ZVNjaGVtYShzY2hlbWEuc2NoZW1hKTtcbiAgfVxuXG4gIHJldHVybiBzY2hlbWE7XG59O1xuXG52YXIgc2ltcGxlUmVmID0gbW9kdWxlLmV4cG9ydHMuc2ltcGxlUmVmID0gZnVuY3Rpb24gKG5hbWUpIHtcbiAgaWYgKHR5cGVvZiBuYW1lID09PSAndW5kZWZpbmVkJykge1xuICAgIHJldHVybiBudWxsO1xuICB9XG5cbiAgaWYgKG5hbWUuaW5kZXhPZignIy9kZWZpbml0aW9ucy8nKSA9PT0gMCkge1xuICAgIHJldHVybiBuYW1lLnN1YnN0cmluZygnIy9kZWZpbml0aW9ucy8nLmxlbmd0aCk7XG4gIH0gZWxzZSB7XG4gICAgcmV0dXJuIG5hbWU7XG4gIH1cbn07XG5cbiJdfQ==
},{"_process":13,"lodash-compat/array/indexOf":50,"lodash-compat/lang/isPlainObject":146}],5:[function(require,module,exports){
'use strict';
var helpers = require('./helpers');
var request = require('superagent');
var jsyaml = require('js-yaml');
var _ = {
isObject: require('lodash-compat/lang/isObject')
};
/*
* JQueryHttpClient is a light-weight, node or browser HTTP client
*/
var JQueryHttpClient = function () {
this.type = 'JQueryHttpClient';
};
/*
* SuperagentHttpClient is a light-weight, node or browser HTTP client
*/
var SuperagentHttpClient = function () {
this.type = 'SuperagentHttpClient';
};
/**
* SwaggerHttp is a wrapper for executing requests
*/
var SwaggerHttp = module.exports = function () {};
SwaggerHttp.prototype.execute = function (obj, opts) {
var client;
if(opts && opts.client) {
client = opts.client;
}
else {
client = new SuperagentHttpClient(opts);
}
client.opts = opts || {};
// legacy support
var hasJQuery = false;
if(typeof window !== 'undefined') {
if(typeof window.jQuery !== 'undefined') {
hasJQuery = true;
}
}
// OPTIONS support
if(obj.method.toLowerCase() === 'options' && client.type === 'SuperagentHttpClient') {
log('forcing jQuery as OPTIONS are not supported by SuperAgent');
obj.useJQuery = true;
}
if(this.isInternetExplorer() && (obj.useJQuery === false || !hasJQuery )) {
throw new Error('Unsupported configuration! JQuery is required but not available');
}
if ((obj && obj.useJQuery === true) || this.isInternetExplorer() && hasJQuery) {
client = new JQueryHttpClient(opts);
}
var success = obj.on.response;
var requestInterceptor = function(data) {
if(opts && opts.requestInterceptor) {
data = opts.requestInterceptor.apply(data);
}
return data;
};
var responseInterceptor = function(data) {
if(opts && opts.responseInterceptor) {
data = opts.responseInterceptor.apply(data);
}
return success(data);
};
obj.on.response = function(data) {
responseInterceptor(data);
};
if (_.isObject(obj) && _.isObject(obj.body)) {
// special processing for file uploads via jquery
if (obj.body.type && obj.body.type === 'formData'){
obj.contentType = false;
obj.processData = false;
delete obj.headers['Content-Type'];
} else {
obj.body = JSON.stringify(obj.body);
}
}
obj = requestInterceptor(obj) || obj;
if (obj.beforeSend) {
obj.beforeSend(function(_obj) {
client.execute(_obj || obj);
});
} else {
client.execute(obj);
}
return (obj.deferred) ? obj.deferred.promise : obj;
};
SwaggerHttp.prototype.isInternetExplorer = function () {
var detectedIE = false;
if (typeof navigator !== 'undefined' && navigator.userAgent) {
var nav = navigator.userAgent.toLowerCase();
if (nav.indexOf('msie') !== -1) {
var version = parseInt(nav.split('msie')[1]);
if (version <= 8) {
detectedIE = true;
}
}
}
return detectedIE;
};
JQueryHttpClient.prototype.execute = function (obj) {
var jq = this.jQuery || (typeof window !== 'undefined' && window.jQuery);
var cb = obj.on;
var request = obj;
if(typeof jq === 'undefined' || jq === false) {
throw new Error('Unsupported configuration! JQuery is required but not available');
}
obj.type = obj.method;
obj.cache = false;
delete obj.useJQuery;
/*
obj.beforeSend = function (xhr) {
var key, results;
if (obj.headers) {
results = [];
for (key in obj.headers) {
if (key.toLowerCase() === 'content-type') {
results.push(obj.contentType = obj.headers[key]);
} else if (key.toLowerCase() === 'accept') {
results.push(obj.accepts = obj.headers[key]);
} else {
results.push(xhr.setRequestHeader(key, obj.headers[key]));
}
}
return results;
}
};*/
obj.data = obj.body;
delete obj.body;
obj.complete = function (response) {
var headers = {};
var headerArray = response.getAllResponseHeaders().split('\n');
for (var i = 0; i < headerArray.length; i++) {
var toSplit = headerArray[i].trim();
if (toSplit.length === 0) {
continue;
}
var separator = toSplit.indexOf(':');
if (separator === -1) {
// Name but no value in the header
headers[toSplit] = null;
continue;
}
var name = toSplit.substring(0, separator).trim();
var value = toSplit.substring(separator + 1).trim();
headers[name] = value;
}
var out = {
url: request.url,
method: request.method,
status: response.status,
statusText: response.statusText,
data: response.responseText,
headers: headers
};
try {
var possibleObj = response.responseJSON || jsyaml.safeLoad(response.responseText);
out.obj = (typeof possibleObj === 'string') ? {} : possibleObj;
} catch (ex) {
// do not set out.obj
helpers.log('unable to parse JSON/YAML content');
}
// I can throw, or parse null?
out.obj = out.obj || null;
if (response.status >= 200 && response.status < 300) {
cb.response(out);
} else if (response.status === 0 || (response.status >= 400 && response.status < 599)) {
cb.error(out);
} else {
return cb.response(out);
}
};
jq.support.cors = true;
return jq.ajax(obj);
};
SuperagentHttpClient.prototype.execute = function (obj) {
var method = obj.method.toLowerCase();
if (method === 'delete') {
method = 'del';
}
var headers = obj.headers || {};
var r = request[method](obj.url);
var name;
for (name in headers) {
r.set(name, headers[name]);
}
if (obj.enableCookies) {
r.withCredentials();
}
if (obj.body) {
r.send(obj.body);
}
if(typeof r.buffer === 'function') {
r.buffer(); // force superagent to populate res.text with the raw response data
}
r.end(function (err, res) {
res = res || {
status: 0,
headers: {error: 'no response from server'}
};
var response = {
url: obj.url,
method: obj.method,
headers: res.headers
};
var cb;
if (!err && res.error) {
err = res.error;
}
if (err && obj.on && obj.on.error) {
response.errObj = err;
response.status = res ? res.status : 500;
response.statusText = res ? res.text : err.message;
if(res.headers && res.headers['content-type']) {
if(res.headers['content-type'].indexOf('application/json') >= 0) {
try {
response.obj = JSON.parse(response.statusText);
}
catch (e) {
response.obj = null;
}
}
}
cb = obj.on.error;
} else if (res && obj.on && obj.on.response) {
var possibleObj;
// Already parsed by by superagent?
if(res.body && Object.keys(res.body).length > 0) {
possibleObj = res.body;
} else {
try {
possibleObj = jsyaml.safeLoad(res.text);
// can parse into a string... which we don't need running around in the system
possibleObj = (typeof possibleObj === 'string') ? null : possibleObj;
} catch(e) {
helpers.log('cannot parse JSON/YAML content');
}
}
// null means we can't parse into object
response.obj = (typeof possibleObj === 'object') ? possibleObj : null;
response.status = res.status;
response.statusText = res.text;
cb = obj.on.response;
}
response.data = response.statusText;
if (cb) {
cb(response);
}
});
};
},{"./helpers":4,"js-yaml":20,"lodash-compat/lang/isObject":145,"superagent":159}],6:[function(require,module,exports){
'use strict';
var SwaggerHttp = require('./http');
var _ = {
isObject: require('lodash-compat/lang/isObject'),
cloneDeep: require('lodash-compat/lang/cloneDeep'),
isArray: require('lodash-compat/lang/isArray')
};
/**
* Resolves a spec's remote references
*/
var Resolver = module.exports = function () {
this.failedUrls = [];
};
Resolver.prototype.processAllOf = function(root, name, definition, resolutionTable, unresolvedRefs, spec) {
var i, location, property;
definition['x-resolved-from'] = [ '#/definitions/' + name ];
var allOf = definition.allOf;
// the refs go first
allOf.sort(function(a, b) {
if(a.$ref && b.$ref) { return 0; }
else if(a.$ref) { return -1; }
else { return 1; }
});
for (i = 0; i < allOf.length; i++) {
property = allOf[i];
location = '/definitions/' + name + '/allOf';
this.resolveInline(root, spec, property, resolutionTable, unresolvedRefs, location);
}
};
Resolver.prototype.resolve = function (spec, arg1, arg2, arg3) {
this.spec = spec;
var root = arg1, callback = arg2, scope = arg3, opts = {}, location, i;
if(typeof arg1 === 'function') {
root = null;
callback = arg1;
scope = arg2;
}
var _root = root;
this.scope = (scope || this);
this.iteration = this.iteration || 0;
if(this.scope.options && this.scope.options.requestInterceptor){
opts.requestInterceptor = this.scope.options.requestInterceptor;
}
if(this.scope.options && this.scope.options.responseInterceptor){
opts.responseInterceptor = this.scope.options.responseInterceptor;
}
var name, path, property, propertyName;
var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {};
var resolutionTable = []; // store objects for dereferencing
spec.definitions = spec.definitions || {};
// definitions
for (name in spec.definitions) {
var definition = spec.definitions[name];
for (propertyName in definition.properties) {
property = definition.properties[propertyName];
if(_.isArray(property.allOf)) {
this.processAllOf(root, name, property, resolutionTable, unresolvedRefs, spec);
}
else {
this.resolveTo(root, property, resolutionTable, '/definitions');
}
}
if(definition.allOf) {
this.processAllOf(root, name, definition, resolutionTable, unresolvedRefs, spec);
}
}
// operations
for (name in spec.paths) {
var method, operation, responseCode;
path = spec.paths[name];
for (method in path) {
// operation reference
if(method === '$ref') {
// location = path[method];
location = '/paths' + name;
this.resolveInline(root, spec, path, resolutionTable, unresolvedRefs, location);
}
else {
operation = path[method];
var sharedParameters = path.parameters || [];
var parameters = operation.parameters || [];
for (i in sharedParameters) {
var parameter = sharedParameters[i];
parameters.unshift(parameter);
}
if(method !== 'parameters' && _.isObject(operation)) {
operation.parameters = operation.parameters || parameters;
}
for (i in parameters) {
var parameter = parameters[i];
location = '/paths' + name + '/' + method + '/parameters';
if (parameter.in === 'body' && parameter.schema) {
if(_.isArray(parameter.schema.allOf)) {
// move to a definition
var modelName = 'inline_model';
var name = modelName;
var done = false; var counter = 0;
while(!done) {
if(typeof spec.definitions[name] === 'undefined') {
done = true;
break;
}
name = modelName + '_' + counter;
counter ++;
}
spec.definitions[name] = { allOf: parameter.schema.allOf };
delete parameter.schema.allOf;
parameter.schema.$ref = '#/definitions/' + name;
this.processAllOf(root, name, spec.definitions[name], resolutionTable, unresolvedRefs, spec);
}
else {
this.resolveTo(root, parameter.schema, resolutionTable, location);
}
}
if (parameter.$ref) {
// parameter reference
this.resolveInline(root, spec, parameter, resolutionTable, unresolvedRefs, parameter.$ref);
}
}
for (responseCode in operation.responses) {
var response = operation.responses[responseCode];
location = '/paths' + name + '/' + method + '/responses/' + responseCode;
if(_.isObject(response)) {
if(response.$ref) {
// response reference
this.resolveInline(root, spec, response, resolutionTable, unresolvedRefs, location);
}
if (response.schema) {
var responseObj = response;
if(_.isArray(responseObj.schema.allOf)) {
// move to a definition
var modelName = 'inline_model';
var name = modelName;
var done = false; var counter = 0;
while(!done) {
if(typeof spec.definitions[name] === 'undefined') {
done = true;
break;
}
name = modelName + '_' + counter;
counter ++;
}
spec.definitions[name] = { allOf: responseObj.schema.allOf };
delete responseObj.schema.allOf;
delete responseObj.schema.type;
responseObj.schema.$ref = '#/definitions/' + name;
this.processAllOf(root, name, spec.definitions[name], resolutionTable, unresolvedRefs, spec);
}
else {
this.resolveTo(root, response.schema, resolutionTable, location);
}
}
}
}
}
}
// clear them out to avoid multiple resolutions
path.parameters = [];
}
var expectedCalls = 0, toResolve = [];
// if the root is same as obj[i].root we can resolve locally
var all = resolutionTable;
var parts;
for(i = 0; i < all.length; i++) {
var a = all[i];
if(root === a.root) {
if(a.resolveAs === 'ref') {
// resolve any path walking
var joined = ((a.root || '') + '/' + a.key).split('/');
var normalized = [];
var url = '';
var k;
if(a.key.indexOf('../') >= 0) {
for(var j = 0; j < joined.length; j++) {
if(joined[j] === '..') {
normalized = normalized.slice(0, normalized.length-1);
}
else {
normalized.push(joined[j]);
}
}
for(k = 0; k < normalized.length; k ++) {
if(k > 0) {
url += '/';
}
url += normalized[k];
}
// we now have to remote resolve this because the path has changed
a.root = url;
toResolve.push(a);
}
else {
parts = a.key.split('#');
if(parts.length === 2) {
if(parts[0].indexOf('http://') === 0 || parts[0].indexOf('https://') === 0) {
a.root = parts[0];
}
location = parts[1].split('/');
var r;
var s = spec;
for(k = 0; k < location.length; k++) {
var part = location[k];
if(part !== '') {
s = s[part];
if(typeof s !== 'undefined') {
r = s;
}
else {
r = null;
break;
}
}
}
if(r === null) {
// must resolve this too
toResolve.push(a);
}
}
}
}
else {
if (a.resolveAs === 'inline') {
if(a.key && a.key.indexOf('#') === -1 && a.key.charAt(0) !== '/') {
// handle relative schema
parts = a.root.split('/');
location = '';
for(i = 0; i < parts.length - 1; i++) {
location += parts[i] + '/';
}
location += a.key;
a.root = location;
a.location = '';
}
toResolve.push(a);
}
}
}
else {
toResolve.push(a);
}
}
expectedCalls = toResolve.length;
// resolve anything that is local
for(var ii = 0; ii < toResolve.length; ii++) {
(function(item, spec, self) {
// NOTE: this used to be item.root === null, but I (@ponelat) have added a guard against .split, which means item.root can be ''
if(!item.root || item.root === root) {
// local resolve
self.resolveItem(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, item);
processedCalls += 1;
if(processedCalls === expectedCalls) {
self.finish(spec, root, resolutionTable, resolvedRefs, unresolvedRefs, callback, true);
}
}
else if(self.failedUrls.indexOf(item.root) === -1) {
var obj = {
useJQuery: false, // TODO
url: item.root,
method: 'get',
headers: {
accept: self.scope.swaggerRequestHeaders || 'application/json'
},
on: {
error: function (error) {
processedCalls += 1;
console.log('failed url: ' + obj.url);
self.failedUrls.push(obj.url);
unresolvedRefs[item.key] = {
root: item.root,
location: item.location
};
if (processedCalls === expectedCalls) {
self.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback);
}
}, // jshint ignore:line
response: function (response) {
var swagger = response.obj;
self.resolveItem(swagger, item.root, resolutionTable, resolvedRefs, unresolvedRefs, item);
processedCalls += 1;
if (processedCalls === expectedCalls) {
self.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback);
}
}
} // jshint ignore:line
};
if (scope && scope.clientAuthorizations) {
scope.clientAuthorizations.apply(obj);
}
new SwaggerHttp().execute(obj, opts);
}
else {
processedCalls += 1;
unresolvedRefs[item.key] = {
root: item.root,
location: item.location
};
if (processedCalls === expectedCalls) {
self.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback);
}
}
}(toResolve[ii], spec, this));
}
if (Object.keys(toResolve).length === 0) {
this.finish(spec, _root, resolutionTable, resolvedRefs, unresolvedRefs, callback);
}
};
Resolver.prototype.resolveItem = function(spec, root, resolutionTable, resolvedRefs, unresolvedRefs, item) {
var path = item.location;
var location = spec, parts = path.split('/');
if(path !== '') {
for (var j = 0; j < parts.length; j++) {
var segment = parts[j];
if (segment.indexOf('~1') !== -1) {
segment = parts[j].replace(/~0/g, '~').replace(/~1/g, '/');
if (segment.charAt(0) !== '/') {
segment = '/' + segment;
}
}
if (typeof location === 'undefined' || location === null) {
break;
}
if (segment === '' && j === (parts.length - 1) && parts.length > 1) {
location = null;
break;
}
if (segment.length > 0) {
location = location[segment];
}
}
}
var resolved = item.key;
parts = item.key.split('/');
var resolvedName = parts[parts.length-1];
if(resolvedName.indexOf('#') >= 0) {
resolvedName = resolvedName.split('#')[1];
}
if (location !== null && typeof location !== 'undefined') {
resolvedRefs[resolved] = {
name: resolvedName,
obj: location,
key: item.key,
root: item.root
};
} else {
unresolvedRefs[resolved] = {
root: item.root,
location: item.location
};
}
};
Resolver.prototype.finish = function (spec, root, resolutionTable, resolvedRefs, unresolvedRefs, callback, localResolve) {
// walk resolution table and replace with resolved refs
var ref;
for (ref in resolutionTable) {
var item = resolutionTable[ref];
var key = item.key;
var resolvedTo = resolvedRefs[key];
if (resolvedTo) {
spec.definitions = spec.definitions || {};
if (item.resolveAs === 'ref') {
if (localResolve !== true) {
// don't retain root for local definitions
for (key in resolvedTo.obj) {
var abs = this.retainRoot(resolvedTo.obj[key], item.root);
}
}
spec.definitions[resolvedTo.name] = resolvedTo.obj;
item.obj.$ref = '#/definitions/' + resolvedTo.name;
} else if (item.resolveAs === 'inline') {
var targetObj = item.obj;
targetObj['x-resolved-from'] = [ item.key ];
delete targetObj.$ref;
for (key in resolvedTo.obj) {
var abs = resolvedTo.obj[key];
if (localResolve !== true) {
// don't retain root for local definitions
abs = this.retainRoot(resolvedTo.obj[key], item.root);
}
targetObj[key] = abs;
}
}
}
}
var existingUnresolved = this.countUnresolvedRefs(spec);
if(existingUnresolved === 0 || this.iteration > 5) {
this.resolveAllOf(spec.definitions);
callback.call(this.scope, spec, unresolvedRefs);
}
else {
this.iteration += 1;
this.resolve(spec, root, callback, this.scope);
}
};
Resolver.prototype.countUnresolvedRefs = function(spec) {
var i;
var refs = this.getRefs(spec);
var keys = [];
var unresolvedKeys = [];
for(i in refs) {
if(i.indexOf('#') === 0) {
keys.push(i.substring(1));
}
else {
unresolvedKeys.push(i);
}
}
// verify possible keys
for (i = 0; i < keys.length; i++) {
var part = keys[i];
var parts = part.split('/');
var obj = spec;
for (var k = 0; k < parts.length; k++) {
var key = parts[k];
if(key !== '') {
obj = obj[key];
if(typeof obj === 'undefined') {
unresolvedKeys.push(part);
break;
}
}
}
}
return unresolvedKeys.length;
};
Resolver.prototype.getRefs = function(spec, obj) {
obj = obj || spec;
var output = {};
for(var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
var item = obj[key];
if(key === '$ref' && typeof item === 'string') {
output[item] = null;
}
else if(_.isObject(item)) {
var o = this.getRefs(item);
for(var k in o) {
output[k] = null;
}
}
}
return output;
};
Resolver.prototype.retainRoot = function(obj, root) {
// walk object and look for relative $refs
for(var key in obj) {
var item = obj[key];
if(key === '$ref' && typeof item === 'string') {
// stop and inspect
if(item.indexOf('http://') !== 0 && item.indexOf('https://') !== 0) {
// TODO: check if root ends in '/'. If not, AND item has no protocol, make relative
var appendHash = true;
var oldRoot = root;
if(root) {
var lastChar = root.slice(-1);
if(lastChar !== '/' && (item.indexOf('#') !== 0 && item.indexOf('http://') !== 0 && item.indexOf('https://'))) {
console.log('working with ' + item);
appendHash = false;
var parts = root.split('\/');
parts = parts.splice(0, parts.length - 1);
root = '';
for(var i = 0; i < parts.length; i++) {
root += parts[i] + '/';
}
}
}
if(item.indexOf('#') !== 0 && appendHash) {
item = '#' + item;
}
item = (root || '') + item;
obj[key] = item;
}
}
else if(_.isObject(item)) {
this.retainRoot(item, root);
}
}
return obj;
};
/**
* immediately in-lines local refs, queues remote refs
* for inline resolution
*/
Resolver.prototype.resolveInline = function (root, spec, property, resolutionTable, unresolvedRefs, location) {
var key = property.$ref, ref = property.$ref, i, p, p2, rs;
var rootTrimmed = false;
root = root || '' // Guard against .split. @fehguy, you'll need to check if this logic fits
// More imporantly is how do we gracefully handle relative urls, when provided just a 'spec', not a 'url' ?
if (ref) {
if(ref.indexOf('../') === 0) {
// reset root
p = ref.split('../');
p2 = root.split('/');
ref = '';
for(i = 0; i < p.length; i++) {
if(p[i] === '') {
p2 = p2.slice(0, p2.length-1);
}
else {
ref += p[i];
}
}
root = '';
for(i = 0; i < p2.length - 1; i++) {
if(i > 0) { root += '/'; }
root += p2[i];
}
rootTrimmed = true;
}
if(ref.indexOf('#') >= 0) {
if(ref.indexOf('/') === 0) {
rs = ref.split('#');
p = root.split('//');
p2 = p[1].split('/');
root = p[0] + '//' + p2[0] + rs[0];
location = rs[1];
}
else {
rs = ref.split('#');
if(rs[0] !== '') {
p2 = root.split('/');
p2 = p2.slice(0, p2.length - 1);
if(!rootTrimmed) {
root = '';
for (var k = 0; k < p2.length; k++) {
if(k > 0) { root += '/'; }
root += p2[k];
}
}
root += '/' + ref.split('#')[0];
}
location = rs[1];
}
}
if (ref.indexOf('http') === 0) {
if(ref.indexOf('#') >= 0) {
root = ref.split('#')[0];
location = ref.split('#')[1];
}
else {
root = ref;
location = '';
}
resolutionTable.push({obj: property, resolveAs: 'inline', root: root, key: key, location: location});
} else if (ref.indexOf('#') === 0) {
location = ref.split('#')[1];
resolutionTable.push({obj: property, resolveAs: 'inline', root: root, key: key, location: location});
}
else {
resolutionTable.push({obj: property, resolveAs: 'inline', root: root, key: key, location: location});
}
}
else if (property.type === 'array') {
this.resolveTo(root, property.items, resolutionTable, location);
}
};
Resolver.prototype.resolveTo = function (root, property, resolutionTable, location) {
var sp, i;
var ref = property.$ref;
var lroot = root;
if ((typeof ref !== 'undefined') && (ref !== null)) {
if(ref.indexOf('#') >= 0) {
var parts = ref.split('#');
// #/definitions/foo
// foo.json#/bar
if(parts[0] && ref.indexOf('/') === 0) {
}
else if(parts[0] && parts[0].indexOf('http') === 0) {
lroot = parts[0];
ref = parts[1];
}
else if(parts[0] && parts[0].length > 0) {
// relative file
sp = root.split('/');
lroot = '';
for(i = 0; i < sp.length - 1; i++) {
lroot += sp[i] + '/';
}
lroot += parts[0];
}
else {
}
location = parts[1];
}
else if (ref.indexOf('http://') === 0 || ref.indexOf('https://') === 0) {
lroot = ref;
location = '';
}
else {
// relative file
sp = root.split('/');
lroot = '';
for(i = 0; i < sp.length - 1; i++) {
lroot += sp[i] + '/';
}
lroot += ref;
location = '';
}
resolutionTable.push({
obj: property, resolveAs: 'ref', root: lroot, key: ref, location: location
});
} else if (property.type === 'array') {
var items = property.items;
this.resolveTo(root, items, resolutionTable, location);
} else {
if(property && property.properties) {
var name = this.uniqueName('inline_model');
if (property.title) {
name = this.uniqueName(property.title);
}
delete property.title;
this.spec.definitions[name] = _.cloneDeep(property);
property['$ref'] = '#/definitions/' + name;
delete property.type;
delete property.properties;
}
}
};
Resolver.prototype.uniqueName = function(base) {
var name = base;
var count = 0;
while(true) {
if(!_.isObject(this.spec.definitions[name])) {
return name;
}
name = base + '_' + count;
count++;
}
};
Resolver.prototype.resolveAllOf = function(spec, obj, depth) {
depth = depth || 0;
obj = obj || spec;
var name;
for(var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
var item = obj[key];
if(item === null) {
throw new TypeError('Swagger 2.0 does not support null types (' + obj + '). See https://github.com/swagger-api/swagger-spec/issues/229.');
}
if(typeof item === 'object') {
this.resolveAllOf(spec, item, depth + 1);
}
if(item && typeof item.allOf !== 'undefined') {
var allOf = item.allOf;
if(_.isArray(allOf)) {
var output = _.cloneDeep(item);
delete output.allOf;
output['x-composed'] = true;
if (typeof item['x-resolved-from'] !== 'undefined') {
output['x-resolved-from'] = item['x-resolved-from'];
}
for(var i = 0; i < allOf.length; i++) {
var component = allOf[i];
var source = 'self';
if(typeof component['x-resolved-from'] !== 'undefined') {
source = component['x-resolved-from'][0];
}
for(var part in component) {
if(!output.hasOwnProperty(part)) {
output[part] = _.cloneDeep(component[part]);
if(part === 'properties') {
for(name in output[part]) {
output[part][name]['x-resolved-from'] = source;
}
}
}
else {
if(part === 'properties') {
var properties = component[part];
for(name in properties) {
output.properties[name] = _.cloneDeep(properties[name]);
var resolvedFrom = properties[name]['x-resolved-from'];
if (typeof resolvedFrom === 'undefined' || resolvedFrom === 'self') {
resolvedFrom = source;
}
output.properties[name]['x-resolved-from'] = resolvedFrom;
}
}
else if(part === 'required') {
// merge & dedup the required array
var a = output.required.concat(component[part]);
for(var k = 0; k < a.length; ++k) {
for(var j = k + 1; j < a.length; ++j) {
if(a[k] === a[j]) { a.splice(j--, 1); }
}
}
output.required = a;
}
else if(part === 'x-resolved-from') {
output['x-resolved-from'].push(source);
}
else {
// TODO: need to merge this property
// console.log('what to do with ' + part)
}
}
}
}
obj[key] = output;
}
}
}
};
},{"./http":5,"lodash-compat/lang/cloneDeep":139,"lodash-compat/lang/isArray":141,"lodash-compat/lang/isObject":145}],7:[function(require,module,exports){
'use strict';
var Helpers = require('./helpers');
var _ = {
isPlainObject: require('lodash-compat/lang/isPlainObject'),
isUndefined: require('lodash-compat/lang/isUndefined'),
isArray: require('lodash-compat/lang/isArray'),
isObject: require('lodash-compat/lang/isObject'),
isEmpty: require('lodash-compat/lang/isEmpty'),
map: require('lodash-compat/collection/map'),
indexOf: require('lodash-compat/array/indexOf'),
cloneDeep: require('lodash-compat/lang/cloneDeep'),
keys: require('lodash-compat/object/keys'),
forEach: require('lodash-compat/collection/forEach')
};
module.exports.optionHtml = optionHtml;
module.exports.typeFromJsonSchema = typeFromJsonSchema;
module.exports.getStringSignature = getStringSignature;
module.exports.schemaToHTML = schemaToHTML;
module.exports.schemaToJSON = schemaToJSON;
function optionHtml(label, value) {
return '<tr><td class="optionName">' + label + ':</td><td>' + value + '</td></tr>';
}
function typeFromJsonSchema(type, format) {
var str;
if (type === 'integer' && format === 'int32') {
str = 'integer';
} else if (type === 'integer' && format === 'int64') {
str = 'long';
} else if (type === 'integer' && typeof format === 'undefined') {
str = 'long';
} else if (type === 'string' && format === 'date-time') {
str = 'date-time';
} else if (type === 'string' && format === 'date') {
str = 'date';
} else if (type === 'number' && format === 'float') {
str = 'float';
} else if (type === 'number' && format === 'double') {
str = 'double';
} else if (type === 'number' && typeof format === 'undefined') {
str = 'double';
} else if (type === 'boolean') {
str = 'boolean';
} else if (type === 'string') {
str = 'string';
}
return str;
}
function getStringSignature(obj, baseComponent) {
var str = '';
if (typeof obj.$ref !== 'undefined') {
str += Helpers.simpleRef(obj.$ref);
} else if (typeof obj.type === 'undefined') {
str += 'object';
} else if (obj.type === 'array') {
if (baseComponent) {
str += getStringSignature((obj.items || obj.$ref || {}));
} else {
str += 'Array[';
str += getStringSignature((obj.items || obj.$ref || {}));
str += ']';
}
} else if (obj.type === 'integer' && obj.format === 'int32') {
str += 'integer';
} else if (obj.type === 'integer' && obj.format === 'int64') {
str += 'long';
} else if (obj.type === 'integer' && typeof obj.format === 'undefined') {
str += 'long';
} else if (obj.type === 'string' && obj.format === 'date-time') {
str += 'date-time';
} else if (obj.type === 'string' && obj.format === 'date') {
str += 'date';
} else if (obj.type === 'string' && typeof obj.format === 'undefined') {
str += 'string';
} else if (obj.type === 'number' && obj.format === 'float') {
str += 'float';
} else if (obj.type === 'number' && obj.format === 'double') {
str += 'double';
} else if (obj.type === 'number' && typeof obj.format === 'undefined') {
str += 'double';
} else if (obj.type === 'boolean') {
str += 'boolean';
} else if (obj.$ref) {
str += Helpers.simpleRef(obj.$ref);
} else {
str += obj.type;
}
return str;
}
function schemaToJSON(schema, models, modelsToIgnore, modelPropertyMacro) {
// Resolve the schema (Handle nested schemas)
schema = Helpers.resolveSchema(schema);
if(typeof modelPropertyMacro !== 'function') {
modelPropertyMacro = function(prop){
return (prop || {}).default;
};
}
modelsToIgnore= modelsToIgnore || {};
var type = schema.type || 'object';
var format = schema.format;
var model;
var output;
if (!_.isUndefined(schema.example)) {
output = schema.example;
} else if (_.isUndefined(schema.items) && _.isArray(schema.enum)) {
output = schema.enum[0];
}
if (_.isUndefined(output)) {
if (schema.$ref) {
model = models[Helpers.simpleRef(schema.$ref)];
if (!_.isUndefined(model)) {
if (_.isUndefined(modelsToIgnore[model.name])) {
modelsToIgnore[model.name] = model;
output = schemaToJSON(model.definition, models, modelsToIgnore, modelPropertyMacro);
delete modelsToIgnore[model.name];
} else {
if (model.type === 'array') {
output = [];
} else {
output = {};
}
}
}
} else if (!_.isUndefined(schema.default)) {
output = schema.default;
} else if (type === 'string') {
if (format === 'date-time') {
output = new Date().toISOString();
} else if (format === 'date') {
output = new Date().toISOString().split('T')[0];
} else {
output = 'string';
}
} else if (type === 'integer') {
output = 0;
} else if (type === 'number') {
output = 0.0;
} else if (type === 'boolean') {
output = true;
} else if (type === 'object') {
output = {};
_.forEach(schema.properties, function (property, name) {
var cProperty = _.cloneDeep(property);
// Allow macro to set the default value
cProperty.default = modelPropertyMacro(property);
output[name] = schemaToJSON(cProperty, models, modelsToIgnore, modelPropertyMacro);
});
} else if (type === 'array') {
output = [];
if (_.isArray(schema.items)) {
_.forEach(schema.items, function (item) {
output.push(schemaToJSON(item, models, modelsToIgnore, modelPropertyMacro));
});
} else if (_.isPlainObject(schema.items)) {
output.push(schemaToJSON(schema.items, models, modelsToIgnore, modelPropertyMacro));
} else if (_.isUndefined(schema.items)) {
output.push({});
} else {
Helpers.log('Array type\'s \'items\' property is not an array or an object, cannot process');
}
}
}
return output;
}
function schemaToHTML(name, schema, models, modelPropertyMacro) {
var strongOpen = '<span class="strong">';
var strongClose = '</span>';
// Allow for ignoring the 'name' argument.... shifting the rest
if(_.isObject(arguments[0])) {
name = void 0;
schema = arguments[0];
models = arguments[1];
modelPropertyMacro = arguments[2];
}
models = models || {};
// Resolve the schema (Handle nested schemas)
schema = Helpers.resolveSchema(schema);
// Return for empty object
if(_.isEmpty(schema)) {
return strongOpen + 'Empty' + strongClose;
}
// Dereference $ref from 'models'
if(typeof schema.$ref === 'string') {
name = Helpers.simpleRef(schema.$ref);
schema = models[name];
if(typeof schema === 'undefined')
{
return strongOpen + name + ' is not defined!' + strongClose;
}
}
if(typeof name !== 'string') {
name = schema.title || 'Inline Model';
}
// If we are a Model object... adjust accordingly
if(schema.definition) {
schema = schema.definition;
}
if(typeof modelPropertyMacro !== 'function') {
modelPropertyMacro = function(prop){
return (prop || {}).default;
};
}
var references = {};
var seenModels = [];
var inlineModels = 0;
// Generate current HTML
var html = processModel(schema, name);
// Generate references HTML
while (_.keys(references).length > 0) {
/* jshint ignore:start */
_.forEach(references, function (schema, name) {
var seenModel = _.indexOf(seenModels, name) > -1;
delete references[name];
if (!seenModel) {
seenModels.push(name);
html += '<br />' + processModel(schema, name);
}
});
/* jshint ignore:end */
}
return html;
/////////////////////////////////
function addReference(schema, name, skipRef) {
var modelName = name;
var model;
if (schema.$ref) {
modelName = schema.title || Helpers.simpleRef(schema.$ref);
model = models[modelName];
} else if (_.isUndefined(name)) {
modelName = schema.title || 'Inline Model ' + (++inlineModels);
model = {definition: schema};
}
if (skipRef !== true) {
references[modelName] = _.isUndefined(model) ? {} : model.definition;
}
return modelName;
}
function primitiveToHTML(schema) {
var html = '<span class="propType">';
var type = schema.type || 'object';
if (schema.$ref) {
html += addReference(schema, Helpers.simpleRef(schema.$ref));
} else if (type === 'object') {
if (!_.isUndefined(schema.properties)) {
html += addReference(schema);
} else {
html += 'object';
}
} else if (type === 'array') {
html += 'Array[';
if (_.isArray(schema.items)) {
html += _.map(schema.items, addReference).join(',');
} else if (_.isPlainObject(schema.items)) {
if (_.isUndefined(schema.items.$ref)) {
if (!_.isUndefined(schema.items.type) && _.indexOf(['array', 'object'], schema.items.type) === -1) {
html += schema.items.type;
} else {
html += addReference(schema.items);
}
} else {
html += addReference(schema.items, Helpers.simpleRef(schema.items.$ref));
}
} else {
Helpers.log('Array type\'s \'items\' schema is not an array or an object, cannot process');
html += 'object';
}
html += ']';
} else {
html += schema.type;
}
html += '</span>';
return html;
}
function primitiveToOptionsHTML(schema, html) {
var options = '';
var type = schema.type || 'object';
var isArray = type === 'array';
if (isArray) {
if (_.isPlainObject(schema.items) && !_.isUndefined(schema.items.type)) {
type = schema.items.type;
} else {
type = 'object';
}
}
if (!_.isUndefined(schema.default)) {
options += optionHtml('Default', schema.default);
}
switch (type) {
case 'string':
if (schema.minLength) {
options += optionHtml('Min. Length', schema.minLength);
}
if (schema.maxLength) {
options += optionHtml('Max. Length', schema.maxLength);
}
if (schema.pattern) {
options += optionHtml('Reg. Exp.', schema.pattern);
}
break;
case 'integer':
case 'number':
if (schema.minimum) {
options += optionHtml('Min. Value', schema.minimum);
}
if (schema.exclusiveMinimum) {
options += optionHtml('Exclusive Min.', 'true');
}
if (schema.maximum) {
options += optionHtml('Max. Value', schema.maximum);
}
if (schema.exclusiveMaximum) {
options += optionHtml('Exclusive Max.', 'true');
}
if (schema.multipleOf) {
options += optionHtml('Multiple Of', schema.multipleOf);
}
break;
}
if (isArray) {
if (schema.minItems) {
options += optionHtml('Min. Items', schema.minItems);
}
if (schema.maxItems) {
options += optionHtml('Max. Items', schema.maxItems);
}
if (schema.uniqueItems) {
options += optionHtml('Unique Items', 'true');
}
if (schema.collectionFormat) {
options += optionHtml('Coll. Format', schema.collectionFormat);
}
}
if (_.isUndefined(schema.items)) {
if (_.isArray(schema.enum)) {
var enumString;
if (type === 'number' || type === 'integer') {
enumString = schema.enum.join(', ');
} else {
enumString = '"' + schema.enum.join('", "') + '"';
}
options += optionHtml('Enum', enumString);
}
}
if (options.length > 0) {
html = '<span class="propWrap">' + html + '<table class="optionsWrapper"><tr><th colspan="2">' + type + '</th></tr>' + options + '</table></span>';
}
return html;
}
function processModel(schema, name) {
var type = schema.type || 'object';
var isArray = schema.type === 'array';
var html = strongOpen + name + ' ' + (isArray ? '[' : '{') + strongClose;
if (name) {
seenModels.push(name);
}
if (isArray) {
if (_.isArray(schema.items)) {
html += '<div>' + _.map(schema.items, function (item) {
var type = item.type || 'object';
if (_.isUndefined(item.$ref)) {
if (_.indexOf(['array', 'object'], type) > -1) {
if (type === 'object' && _.isUndefined(item.properties)) {
return 'object';
} else {
return addReference(item);
}
} else {
return primitiveToOptionsHTML(item, type);
}
} else {
return addReference(item, Helpers.simpleRef(item.$ref));
}
}).join(',</div><div>');
} else if (_.isPlainObject(schema.items)) {
if (_.isUndefined(schema.items.$ref)) {
if (_.indexOf(['array', 'object'], schema.items.type || 'object') > -1) {
if ((_.isUndefined(schema.items.type) || schema.items.type === 'object') && _.isUndefined(schema.items.properties)) {
html += '<div>object</div>';
} else {
html += '<div>' + addReference(schema.items) + '</div>';
}
} else {
html += '<div>' + primitiveToOptionsHTML(schema.items, schema.items.type) + '</div>';
}
} else {
html += '<div>' + addReference(schema.items, Helpers.simpleRef(schema.items.$ref)) + '</div>';
}
} else {
Helpers.log('Array type\'s \'items\' property is not an array or an object, cannot process');
html += '<div>object</div>';
}
} else {
if (schema.$ref) {
html += '<div>' + addReference(schema, name) + '</div>';
} else if (type === 'object') {
if (_.isPlainObject(schema.properties)) {
var contents = _.map(schema.properties, function (property, name) {
var propertyIsRequired = (_.indexOf(schema.required, name) >= 0);
var cProperty = _.cloneDeep(property);
var requiredClass = propertyIsRequired ? 'required' : '';
var html = '<span class="propName ' + requiredClass + '">' + name + '</span> (';
var model;
var propDescription;
// Allow macro to set the default value
cProperty.default = modelPropertyMacro(cProperty);
// Resolve the schema (Handle nested schemas)
cProperty = Helpers.resolveSchema(cProperty);
propDescription = property.description || cProperty.description;
// We need to handle property references to primitives (Issue 339)
if (!_.isUndefined(cProperty.$ref)) {
model = models[Helpers.simpleRef(cProperty.$ref)];
if (!_.isUndefined(model) && _.indexOf([undefined, 'array', 'object'], model.definition.type) === -1) {
// Use referenced schema
cProperty = Helpers.resolveSchema(model.definition);
}
}
html += primitiveToHTML(cProperty);
if(!propertyIsRequired) {
html += ', <span class="propOptKey">optional</span>';
}
if(property.readOnly) {
html += ', <span class="propReadOnly">read only</span>';
}
html += ')';
if (!_.isUndefined(propDescription)) {
html += ': ' + '<span class="propDesc">' + propDescription + '</span>';
}
if (cProperty.enum) {
html += ' = <span class="propVals">[\'' + cProperty.enum.join('\', \'') + '\']</span>';
}
return '<div' + (property.readOnly ? ' class="readOnly"' : '') + '>' + primitiveToOptionsHTML(cProperty, html);
}).join(',</div>');
if (contents) {
html += contents + '</div>';
}
}
} else {
html += '<div>' + primitiveToOptionsHTML(schema, type) + '</div>';
}
}
return html + strongOpen + (isArray ? ']' : '}') + strongClose;
}
}
},{"./helpers":4,"lodash-compat/array/indexOf":50,"lodash-compat/collection/forEach":55,"lodash-compat/collection/map":57,"lodash-compat/lang/cloneDeep":139,"lodash-compat/lang/isArray":141,"lodash-compat/lang/isEmpty":142,"lodash-compat/lang/isObject":145,"lodash-compat/lang/isPlainObject":146,"lodash-compat/lang/isUndefined":149,"lodash-compat/object/keys":150}],8:[function(require,module,exports){
'use strict';
var SwaggerHttp = require('./http');
var _ = {
isObject: require('lodash-compat/lang/isObject')
};
var SwaggerSpecConverter = module.exports = function () {
this.errors = [];
this.warnings = [];
this.modelMap = {};
};
SwaggerSpecConverter.prototype.setDocumentationLocation = function (location) {
this.docLocation = location;
};
/**
* converts a resource listing OR api declaration
**/
SwaggerSpecConverter.prototype.convert = function (obj, clientAuthorizations, opts, callback) {
// not a valid spec
if(!obj || !Array.isArray(obj.apis)) {
return this.finish(callback, null);
}
this.clientAuthorizations = clientAuthorizations;
// create a new swagger object to return
var swagger = { swagger: '2.0' };
swagger.originalVersion = obj.swaggerVersion;
// add the info
this.apiInfo(obj, swagger);
// add security definitions
this.securityDefinitions(obj, swagger);
// take basePath into account
if (obj.basePath) {
this.setDocumentationLocation(obj.basePath);
}
// see if this is a single-file swagger definition
var isSingleFileSwagger = false;
var i;
for(i = 0; i < obj.apis.length; i++) {
var api = obj.apis[i];
if(Array.isArray(api.operations)) {
isSingleFileSwagger = true;
}
}
if(isSingleFileSwagger) {
this.declaration(obj, swagger);
this.finish(callback, swagger);
}
else {
this.resourceListing(obj, swagger, opts, callback);
}
};
SwaggerSpecConverter.prototype.declaration = function(obj, swagger) {
var name, i, p, pos;
if(!obj.apis) {
return;
}
if (obj.basePath.indexOf('http://') === 0) {
p = obj.basePath.substring('http://'.length);
pos = p.indexOf('/');
if (pos > 0) {
swagger.host = p.substring(0, pos);
swagger.basePath = p.substring(pos);
}
else {
swagger.host = p;
swagger.basePath = '/';
}
} else if (obj.basePath.indexOf('https://') === 0) {
p = obj.basePath.substring('https://'.length);
pos = p.indexOf('/');
if (pos > 0) {
swagger.host = p.substring(0, pos);
swagger.basePath = p.substring(pos);
}
else {
swagger.host = p;
swagger.basePath = '/';
}
} else {
swagger.basePath = obj.basePath;
}
var resourceLevelAuth;
if(obj.authorizations) {
resourceLevelAuth = obj.authorizations;
}
if(obj.consumes) {
swagger.consumes = obj.consumes;
}
if(obj.produces) {
swagger.produces = obj.produces;
}
// build a mapping of id to name for 1.0 model resolutions
if(_.isObject(obj)) {
for(name in obj.models) {
var existingModel = obj.models[name];
var key = (existingModel.id || name);
this.modelMap[key] = name;
}
}
for(i = 0; i < obj.apis.length; i++) {
var api = obj.apis[i];
var path = api.path;
var operations = api.operations;
this.operations(path, obj.resourcePath, operations, resourceLevelAuth, swagger);
}
var models = obj.models || {};
this.models(models, swagger);
};
SwaggerSpecConverter.prototype.models = function(obj, swagger) {
if(!_.isObject(obj)) {
return;
}
var name;
swagger.definitions = swagger.definitions || {};
for(name in obj) {
var existingModel = obj[name];
var _required = [];
var schema = { properties: {}};
var propertyName;
for(propertyName in existingModel.properties) {
var existingProperty = existingModel.properties[propertyName];
var property = {};
this.dataType(existingProperty, property);
if(existingProperty.description) {
property.description = existingProperty.description;
}
if(existingProperty['enum']) {
property['enum'] = existingProperty['enum'];
}
if(typeof existingProperty.required === 'boolean' && existingProperty.required === true) {
_required.push(propertyName);
}
if(typeof existingProperty.required === 'string' && existingProperty.required === 'true') {
_required.push(propertyName);
}
schema.properties[propertyName] = property;
}
if(_required.length > 0) {
schema.required = _required;
} else {
schema.required = existingModel.required;
}
swagger.definitions[name] = schema;
}
};
SwaggerSpecConverter.prototype.extractTag = function(resourcePath) {
var pathString = resourcePath || 'default';
if(pathString.indexOf('http:') === 0 || pathString.indexOf('https:') === 0) {
pathString = pathString.split(['/']);
pathString = pathString[pathString.length -1].substring();
}
if(pathString.endsWith('.json')) {
pathString = pathString.substring(0, pathString.length - '.json'.length);
}
return pathString.replace('/','');
};
SwaggerSpecConverter.prototype.operations = function(path, resourcePath, obj, resourceLevelAuth, swagger) {
if(!Array.isArray(obj)) {
return;
}
var i;
if(!swagger.paths) {
swagger.paths = {};
}
var pathObj = swagger.paths[path] || {};
var tag = this.extractTag(resourcePath);
swagger.tags = swagger.tags || [];
var matched = false;
for(i = 0; i < swagger.tags.length; i++) {
var tagObject = swagger.tags[i];
if(tagObject.name === tag) {
matched = true;
}
}
if(!matched) {
swagger.tags.push({name: tag});
}
for(i = 0; i < obj.length; i++) {
var existingOperation = obj[i];
var method = (existingOperation.method || existingOperation.httpMethod).toLowerCase();
var operation = {tags: [tag]};
var existingAuthorizations = existingOperation.authorizations;
if(existingAuthorizations && Object.keys(existingAuthorizations).length === 0) {
existingAuthorizations = resourceLevelAuth;
}
if(typeof existingAuthorizations !== 'undefined') {
var scopesObject;
for(var key in existingAuthorizations) {
operation.security = operation.security || [];
var scopes = existingAuthorizations[key];
if(scopes) {
var securityScopes = [];
for(var j in scopes) {
securityScopes.push(scopes[j].scope);
}
scopesObject = {};
scopesObject[key] = securityScopes;
operation.security.push(scopesObject);
}
else {
scopesObject = {};
scopesObject[key] = [];
operation.security.push(scopesObject);
}
}
}
if(existingOperation.consumes) {
operation.consumes = existingOperation.consumes;
}
else if(swagger.consumes) {
operation.consumes = swagger.consumes;
}
if(existingOperation.produces) {
operation.produces = existingOperation.produces;
}
else if(swagger.produces) {
operation.produces = swagger.produces;
}
if(existingOperation.summary) {
operation.summary = existingOperation.summary;
}
if(existingOperation.notes) {
operation.description = existingOperation.notes;
}
if(existingOperation.nickname) {
operation.operationId = existingOperation.nickname;
}
if(existingOperation.deprecated) {
operation.deprecated = existingOperation.deprecated;
}
this.authorizations(existingAuthorizations, swagger);
this.parameters(operation, existingOperation.parameters, swagger);
this.responseMessages(operation, existingOperation, swagger);
pathObj[method] = operation;
}
swagger.paths[path] = pathObj;
};
SwaggerSpecConverter.prototype.responseMessages = function(operation, existingOperation) {
if(!_.isObject(existingOperation)) {
return;
}
// build default response from the operation (1.x)
var defaultResponse = {};
this.dataType(existingOperation, defaultResponse);
// TODO: look into the real problem of rendering responses in swagger-ui
// ....should reponseType have an implicit schema?
if(!defaultResponse.schema && defaultResponse.type) {
defaultResponse = {schema: defaultResponse};
}
operation.responses = operation.responses || {};
// grab from responseMessages (1.2)
var has200 = false;
if(Array.isArray(existingOperation.responseMessages)) {
var i;
var existingResponses = existingOperation.responseMessages;
for(i = 0; i < existingResponses.length; i++) {
var existingResponse = existingResponses[i];
var response = { description: existingResponse.message };
if(existingResponse.code === 200) {
has200 = true;
}
// Convert responseModel -> schema{$ref: responseModel}
if(existingResponse.responseModel) {
response.schema = {'$ref': '#/definitions/' + existingResponse.responseModel};
}
operation.responses['' + existingResponse.code] = response;
}
}
if(has200) {
operation.responses['default'] = defaultResponse;
}
else {
operation.responses['200'] = defaultResponse;
}
};
SwaggerSpecConverter.prototype.authorizations = function(obj) {
// TODO
if(!_.isObject(obj)) {
return;
}
};
SwaggerSpecConverter.prototype.parameters = function(operation, obj) {
if(!Array.isArray(obj)) {
return;
}
var i;
for(i = 0; i < obj.length; i++) {
var existingParameter = obj[i];
var parameter = {};
parameter.name = existingParameter.name;
parameter.description = existingParameter.description;
parameter.required = existingParameter.required;
parameter.in = existingParameter.paramType;
// per #168
if(parameter.in === 'body') {
parameter.name = 'body';
}
if(parameter.in === 'form') {
parameter.in = 'formData';
}
if(existingParameter.enum) {
parameter.enum = existingParameter.enum;
}
if(existingParameter.allowMultiple === true || existingParameter.allowMultiple === 'true') {
var innerType = {};
this.dataType(existingParameter, innerType);
parameter.type = 'array';
parameter.items = innerType;
if(existingParameter.allowableValues) {
var av = existingParameter.allowableValues;
if(av.valueType === 'LIST') {
parameter['enum'] = av.values;
}
}
}
else {
this.dataType(existingParameter, parameter);
}
if(typeof existingParameter.defaultValue !== 'undefined') {
parameter.default = existingParameter.defaultValue;
}
operation.parameters = operation.parameters || [];
operation.parameters.push(parameter);
}
};
SwaggerSpecConverter.prototype.dataType = function(source, target) {
if(!_.isObject(source)) {
return;
}
if(source.minimum) {
target.minimum = source.minimum;
}
if(source.maximum) {
target.maximum = source.maximum;
}
if (source.format) {
target.format = source.format;
}
// default can be 'false'
if(typeof source.defaultValue !== 'undefined') {
target.default = source.defaultValue;
}
var jsonSchemaType = this.toJsonSchema(source);
if(jsonSchemaType) {
target = target || {};
if(jsonSchemaType.type) {
target.type = jsonSchemaType.type;
}
if(jsonSchemaType.format) {
target.format = jsonSchemaType.format;
}
if(jsonSchemaType.$ref) {
target.schema = {$ref: jsonSchemaType.$ref};
}
if(jsonSchemaType.items) {
target.items = jsonSchemaType.items;
}
}
};
SwaggerSpecConverter.prototype.toJsonSchema = function(source) {
if(!source) {
return 'object';
}
var detectedType = (source.type || source.dataType || source.responseClass || '');
var lcType = detectedType.toLowerCase();
var format = (source.format || '').toLowerCase();
if(lcType.indexOf('list[') === 0) {
var innerType = detectedType.substring(5, detectedType.length - 1);
var jsonType = this.toJsonSchema({type: innerType});
return {type: 'array', items: jsonType};
} else if(lcType === 'int' || (lcType === 'integer' && format === 'int32')) {
{return {type: 'integer', format: 'int32'};}
} else if(lcType === 'long' || (lcType === 'integer' && format === 'int64')) {
{return {type: 'integer', format: 'int64'};}
} else if(lcType === 'integer') {
{return {type: 'integer', format: 'int64'};}
} else if(lcType === 'float' || (lcType === 'number' && format === 'float')) {
{return {type: 'number', format: 'float'};}
} else if(lcType === 'double' || (lcType === 'number' && format === 'double')) {
{return {type: 'number', format: 'double'};}
} else if((lcType === 'string' && format === 'date-time') || (lcType === 'date')) {
{return {type: 'string', format: 'date-time'};}
} else if(lcType === 'string') {
{return {type: 'string'};}
} else if(lcType === 'file') {
{return {type: 'file'};}
} else if(lcType === 'boolean') {
{return {type: 'boolean'};}
} else if(lcType === 'boolean') {
{return {type: 'boolean'};}
} else if(lcType === 'array' || lcType === 'list') {
if(source.items) {
var it = this.toJsonSchema(source.items);
return {type: 'array', items: it};
}
else {
return {type: 'array', items: {type: 'object'}};
}
} else if(source.$ref) {
return {$ref: this.modelMap[source.$ref] ? '#/definitions/' + this.modelMap[source.$ref] : source.$ref};
} else if(lcType === 'void' || lcType === '') {
{return {};}
} else if (this.modelMap[source.type]) {
// If this a model using `type` instead of `$ref`, that's fine.
return {$ref: '#/definitions/' + this.modelMap[source.type]};
} else {
// Unknown model type or 'object', pass it along.
return {type: source.type};
}
};
SwaggerSpecConverter.prototype.resourceListing = function(obj, swagger, opts, callback) {
var i;
var processedCount = 0; // jshint ignore:line
var self = this; // jshint ignore:line
var expectedCount = obj.apis.length;
var _swagger = swagger; // jshint ignore:line
var _opts = {};
if(opts && opts.requestInterceptor){
_opts.requestInterceptor = opts.requestInterceptor;
}
if(opts && opts.responseInterceptor){
_opts.responseInterceptor = opts.responseInterceptor;
}
if(expectedCount === 0) {
this.finish(callback, swagger);
}
for(i = 0; i < expectedCount; i++) {
var api = obj.apis[i];
var path = api.path;
var absolutePath = this.getAbsolutePath(obj.swaggerVersion, this.docLocation, path);
if(api.description) {
swagger.tags = swagger.tags || [];
swagger.tags.push({
name : this.extractTag(api.path),
description : api.description || ''
});
}
var http = {
url: absolutePath,
headers: {accept: 'application/json'},
on: {},
method: 'get'
};
/* jshint ignore:start */
http.on.response = function(data) {
processedCount += 1;
var obj = data.obj;
if(obj) {
self.declaration(obj, _swagger);
}
if(processedCount === expectedCount) {
self.finish(callback, _swagger);
}
};
http.on.error = function(data) {
console.error(data);
processedCount += 1;
if(processedCount === expectedCount) {
self.finish(callback, _swagger);
}
};
/* jshint ignore:end */
if(this.clientAuthorizations && typeof this.clientAuthorizations.apply === 'function') {
this.clientAuthorizations.apply(http);
}
new SwaggerHttp().execute(http, _opts);
}
};
SwaggerSpecConverter.prototype.getAbsolutePath = function(version, docLocation, path) {
if(version === '1.0') {
if(docLocation.endsWith('.json')) {
// get root path
var pos = docLocation.lastIndexOf('/');
if(pos > 0) {
docLocation = docLocation.substring(0, pos);
}
}
}
var location = docLocation;
if(path.indexOf('http://') === 0 || path.indexOf('https://') === 0) {
location = path;
}
else {
if(docLocation.endsWith('/')) {
location = docLocation.substring(0, docLocation.length - 1);
}
location += path;
}
location = location.replace('{format}', 'json');
return location;
};
SwaggerSpecConverter.prototype.securityDefinitions = function(obj, swagger) {
if(obj.authorizations) {
var name;
for(name in obj.authorizations) {
var isValid = false;
var securityDefinition = {};
var definition = obj.authorizations[name];
if(definition.type === 'apiKey') {
securityDefinition.type = 'apiKey';
securityDefinition.in = definition.passAs;
securityDefinition.name = definition.keyname || name;
isValid = true;
}
else if(definition.type === 'basicAuth') {
securityDefinition.type = 'basicAuth';
isValid = true;
}
else if(definition.type === 'oauth2') {
var existingScopes = definition.scopes || [];
var scopes = {};
var i;
for(i in existingScopes) {
var scope = existingScopes[i];
scopes[scope.scope] = scope.description;
}
securityDefinition.type = 'oauth2';
if(i > 0) {
securityDefinition.scopes = scopes;
}
if(definition.grantTypes) {
if(definition.grantTypes.implicit) {
var implicit = definition.grantTypes.implicit;
securityDefinition.flow = 'implicit';
securityDefinition.authorizationUrl = implicit.loginEndpoint;
isValid = true;
}
/* jshint ignore:start */
if(definition.grantTypes['authorization_code']) {
if(!securityDefinition.flow) {
// cannot set if flow is already defined
var authCode = definition.grantTypes['authorization_code'];
securityDefinition.flow = 'accessCode';
securityDefinition.authorizationUrl = authCode.tokenRequestEndpoint.url;
securityDefinition.tokenUrl = authCode.tokenEndpoint.url;
isValid = true;
}
}
/* jshint ignore:end */
}
}
if(isValid) {
swagger.securityDefinitions = swagger.securityDefinitions || {};
swagger.securityDefinitions[name] = securityDefinition;
}
}
}
};
SwaggerSpecConverter.prototype.apiInfo = function(obj, swagger) {
// info section
if(obj.info) {
var info = obj.info;
swagger.info = {};
if(info.contact) {
swagger.info.contact = {};
swagger.info.contact.email = info.contact;
}
if(info.description) {
swagger.info.description = info.description;
}
if(info.title) {
swagger.info.title = info.title;
}
if(info.termsOfServiceUrl) {
swagger.info.termsOfService = info.termsOfServiceUrl;
}
if(info.license || info.licenseUrl) {
swagger.license = {};
if(info.license) {
swagger.license.name = info.license;
}
if(info.licenseUrl) {
swagger.license.url = info.licenseUrl;
}
}
}
else {
this.warnings.push('missing info section');
}
};
SwaggerSpecConverter.prototype.finish = function (callback, obj) {
callback(obj);
};
},{"./http":5,"lodash-compat/lang/isObject":145}],9:[function(require,module,exports){
'use strict';
var log = require('../helpers').log;
var _ = {
isPlainObject: require('lodash-compat/lang/isPlainObject'),
isString: require('lodash-compat/lang/isString'),
};
var SchemaMarkup = require('../schema-markup.js');
var jsyaml = require('js-yaml');
var Model = module.exports = function (name, definition, models, modelPropertyMacro) {
this.definition = definition || {};
this.isArray = definition.type === 'array';
this.models = models || {};
this.name = definition.title || name || 'Inline Model';
this.modelPropertyMacro = modelPropertyMacro || function (property) {
return property.default;
};
return this;
};
// Note! This function will be removed in 2.2.x!
Model.prototype.createJSONSample = Model.prototype.getSampleValue = function (modelsToIgnore) {
modelsToIgnore = modelsToIgnore || {};
modelsToIgnore[this.name] = this;
// Response support
if (this.examples && _.isPlainObject(this.examples) && this.examples['application/json']) {
this.definition.example = this.examples['application/json'];
if (_.isString(this.definition.example)) {
this.definition.example = jsyaml.safeLoad(this.definition.example);
}
} else if (!this.definition.example) {
this.definition.example = this.examples;
}
return SchemaMarkup.schemaToJSON(this.definition, this.models, modelsToIgnore, this.modelPropertyMacro);
};
Model.prototype.getMockSignature = function () {
return SchemaMarkup.schemaToHTML(this.name, this.definition, this.models, this.modelPropertyMacro);
};
},{"../helpers":4,"../schema-markup.js":7,"js-yaml":20,"lodash-compat/lang/isPlainObject":146,"lodash-compat/lang/isString":147}],10:[function(require,module,exports){
'use strict';
var _ = {
cloneDeep: require('lodash-compat/lang/cloneDeep'),
isUndefined: require('lodash-compat/lang/isUndefined'),
isEmpty: require('lodash-compat/lang/isEmpty'),
isObject: require('lodash-compat/lang/isObject')
};
var helpers = require('../helpers');
var Model = require('./model');
var SwaggerHttp = require('../http');
var Q = require('q');
var Operation = module.exports = function (parent, scheme, operationId, httpMethod, path, args, definitions, models, clientAuthorizations) {
var errors = [];
parent = parent || {};
args = args || {};
if(parent && parent.options) {
this.client = parent.options.client || null;
this.requestInterceptor = parent.options.requestInterceptor || null;
this.responseInterceptor = parent.options.responseInterceptor || null;
}
this.authorizations = args.security;
this.basePath = parent.basePath || '/';
this.clientAuthorizations = clientAuthorizations;
this.consumes = args.consumes || parent.consumes || ['application/json'];
this.produces = args.produces || parent.produces || ['application/json'];
this.deprecated = args.deprecated;
this.description = args.description;
this.host = parent.host || 'localhost';
this.method = (httpMethod || errors.push('Operation ' + operationId + ' is missing method.'));
this.models = models || {};
this.nickname = (operationId || errors.push('Operations must have a nickname.'));
this.operation = args;
this.operations = {};
this.parameters = args !== null ? (args.parameters || []) : {};
this.parent = parent;
this.path = (path || errors.push('Operation ' + this.nickname + ' is missing path.'));
this.responses = (args.responses || {});
this.scheme = scheme || parent.scheme || 'http';
this.schemes = args.schemes || parent.schemes;
this.security = args.security;
this.summary = args.summary || '';
this.type = null;
this.useJQuery = parent.useJQuery;
this.enableCookies = parent.enableCookies;
this.parameterMacro = parent.parameterMacro || function (operation, parameter) {
return parameter.default;
};
this.inlineModels = [];
if (typeof this.deprecated === 'string') {
switch(this.deprecated.toLowerCase()) {
case 'true': case 'yes': case '1': {
this.deprecated = true;
break;
}
case 'false': case 'no': case '0': case null: {
this.deprecated = false;
break;
}
default: this.deprecated = Boolean(this.deprecated);
}
}
var i, model;
if (definitions) {
// add to global models
var key;
for (key in definitions) {
model = new Model(key, definitions[key], this.models, parent.modelPropertyMacro);
if (model) {
this.models[key] = model;
}
}
}
else {
definitions = {};
}
for (i = 0; i < this.parameters.length; i++) {
var param = this.parameters[i];
// Allow macro to set the default value
param.default = this.parameterMacro(this, param);
if (param.type === 'array') {
param.isList = true;
param.allowMultiple = true;
// the enum can be defined at the items level
//if (param.items && param.items.enum) {
// param['enum'] = param.items.enum;
//}
}
var innerType = this.getType(param);
if (innerType && innerType.toString().toLowerCase() === 'boolean') {
param.allowableValues = {};
param.isList = true;
param['enum'] = [true, false]; // use actual primitives
}
if(typeof param['x-example'] !== 'undefined') {
var d = param['x-example'];
param.default = d;
}
if(param['x-examples']) {
var d = param['x-examples'].default;
if(typeof d !== 'undefined') {
param.default = d;
}
}
if (typeof param['enum'] !== 'undefined') {
var id;
param.allowableValues = {};
param.allowableValues.values = [];
param.allowableValues.descriptiveValues = [];
for (id = 0; id < param['enum'].length; id++) {
var value = param['enum'][id];
var isDefault = (value === param.default || value+'' === param.default);
param.allowableValues.values.push(value);
// Always have string for descriptive values....
param.allowableValues.descriptiveValues.push({value : value+'', isDefault: isDefault});
}
}
if (param.type === 'array') {
innerType = [innerType];
if (typeof param.allowableValues === 'undefined') {
// can't show as a list if no values to select from
delete param.isList;
delete param.allowMultiple;
}
}
param.modelSignature = {type: innerType, definitions: this.models};
param.signature = this.getModelSignature(innerType, this.models).toString();
param.sampleJSON = this.getModelSampleJSON(innerType, this.models);
param.responseClassSignature = param.signature;
}
var defaultResponseCode, response, responses = this.responses;
if (responses['200']) {
response = responses['200'];
defaultResponseCode = '200';
} else if (responses['201']) {
response = responses['201'];
defaultResponseCode = '201';
} else if (responses['202']) {
response = responses['202'];
defaultResponseCode = '202';
} else if (responses['203']) {
response = responses['203'];
defaultResponseCode = '203';
} else if (responses['204']) {
response = responses['204'];
defaultResponseCode = '204';
} else if (responses['205']) {
response = responses['205'];
defaultResponseCode = '205';
} else if (responses['206']) {
response = responses['206'];
defaultResponseCode = '206';
} else if (responses['default']) {
response = responses['default'];
defaultResponseCode = 'default';
}
if (response && response.schema) {
var resolvedModel = this.resolveModel(response.schema, definitions);
var successResponse;
delete responses[defaultResponseCode];
if (resolvedModel) {
this.successResponse = {};
successResponse = this.successResponse[defaultResponseCode] = resolvedModel;
} else if (!response.schema.type || response.schema.type === 'object' || response.schema.type === 'array') {
// Inline model
this.successResponse = {};
successResponse = this.successResponse[defaultResponseCode] = new Model(undefined, response.schema || {}, this.models, parent.modelPropertyMacro);
} else {
// Primitive
this.successResponse = {};
successResponse = this.successResponse[defaultResponseCode] = response.schema;
}
if (successResponse) {
// Attach response properties
if (response.description) {
successResponse.description = response.description;
}
if (response.examples) {
successResponse.examples = response.examples;
}
if (response.headers) {
successResponse.headers = response.headers;
}
}
this.type = response;
}
if (errors.length > 0) {
if (this.resource && this.resource.api && this.resource.api.fail) {
this.resource.api.fail(errors);
}
}
return this;
};
Operation.prototype.isDefaultArrayItemValue = function(value, param) {
if (param.default && Array.isArray(param.default)) {
return param.default.indexOf(value) !== -1;
}
return value === param.default;
};
Operation.prototype.getType = function (param) {
var type = param.type;
var format = param.format;
var isArray = false;
var str;
if (type === 'integer' && format === 'int32') {
str = 'integer';
} else if (type === 'integer' && format === 'int64') {
str = 'long';
} else if (type === 'integer') {
str = 'integer';
} else if (type === 'string') {
if (format === 'date-time') {
str = 'date-time';
} else if (format === 'date') {
str = 'date';
} else {
str = 'string';
}
} else if (type === 'number' && format === 'float') {
str = 'float';
} else if (type === 'number' && format === 'double') {
str = 'double';
} else if (type === 'number') {
str = 'double';
} else if (type === 'boolean') {
str = 'boolean';
} else if (type === 'array') {
isArray = true;
if (param.items) {
str = this.getType(param.items);
}
} else if (type === 'file') {
str = 'file';
}
if (param.$ref) {
str = helpers.simpleRef(param.$ref);
}
var schema = param.schema;
if (schema) {
var ref = schema.$ref;
if (ref) {
ref = helpers.simpleRef(ref);
if (isArray) {
return [ ref ];
} else {
return ref;
}
} else {
// If inline schema, we add it our interal hash -> which gives us it's ID (int)
if(schema.type === 'object') {
return this.addInlineModel(schema);
}
return this.getType(schema);
}
}
if (isArray) {
return [ str ];
} else {
return str;
}
};
/**
* adds an inline schema (model) to a hash, where we can ref it later
* @param {object} schema a schema
* @return {number} the ID of the schema being added, or null
**/
Operation.prototype.addInlineModel = function (schema) {
var len = this.inlineModels.length;
var model = this.resolveModel(schema, {});
if(model) {
this.inlineModels.push(model);
return 'Inline Model '+len; // return string ref of the inline model (used with #getInlineModel)
}
return null; // report errors?
};
/**
* gets the internal ref to an inline model
* @param {string} inline_str a string reference to an inline model
* @return {Model} the model being referenced. Or null
**/
Operation.prototype.getInlineModel = function(inlineStr) {
if(/^Inline Model \d+$/.test(inlineStr)) {
var id = parseInt(inlineStr.substr('Inline Model'.length).trim(),10); //
var model = this.inlineModels[id];
return model;
}
// I'm returning null here, should I rather throw an error?
return null;
};
Operation.prototype.resolveModel = function (schema, definitions) {
if (typeof schema.$ref !== 'undefined') {
var ref = schema.$ref;
if (ref.indexOf('#/definitions/') === 0) {
ref = ref.substring('#/definitions/'.length);
}
if (definitions[ref]) {
return new Model(ref, definitions[ref], this.models, this.parent.modelPropertyMacro);
}
// schema must at least be an object to get resolved to an inline Model
} else if (schema && typeof schema === 'object' &&
(schema.type === 'object' || _.isUndefined(schema.type))) {
return new Model(undefined, schema, this.models, this.parent.modelPropertyMacro);
}
return null;
};
Operation.prototype.help = function (dontPrint) {
var out = this.nickname + ': ' + this.summary + '\n';
for (var i = 0; i < this.parameters.length; i++) {
var param = this.parameters[i];
var typeInfo = param.signature;
out += '\n * ' + param.name + ' (' + typeInfo + '): ' + param.description;
}
if (typeof dontPrint === 'undefined') {
helpers.log(out);
}
return out;
};
Operation.prototype.getModelSignature = function (type, definitions) {
var isPrimitive, listType;
if (type instanceof Array) {
listType = true;
type = type[0];
}
// Convert undefined to string of 'undefined'
if (typeof type === 'undefined') {
type = 'undefined';
isPrimitive = true;
} else if (definitions[type]){
// a model def exists?
type = definitions[type]; /* Model */
isPrimitive = false;
} else if (this.getInlineModel(type)) {
type = this.getInlineModel(type); /* Model */
isPrimitive = false;
} else {
// We default to primitive
isPrimitive = true;
}
if (isPrimitive) {
if (listType) {
return 'Array[' + type + ']';
} else {
return type.toString();
}
} else {
if (listType) {
return 'Array[' + type.getMockSignature() + ']';
} else {
return type.getMockSignature();
}
}
};
Operation.prototype.supportHeaderParams = function () {
return true;
};
Operation.prototype.supportedSubmitMethods = function () {
return this.parent.supportedSubmitMethods;
};
Operation.prototype.getHeaderParams = function (args) {
var headers = this.setContentTypes(args, {});
for (var i = 0; i < this.parameters.length; i++) {
var param = this.parameters[i];
if (typeof args[param.name] !== 'undefined') {
if (param.in === 'header') {
var value = args[param.name];
if (Array.isArray(value)) {
value = value.toString();
}
headers[param.name] = value;
}
}
}
return headers;
};
Operation.prototype.urlify = function (args) {
var formParams = {};
var requestUrl = this.path;
var querystring = ''; // grab params from the args, build the querystring along the way
for (var i = 0; i < this.parameters.length; i++) {
var param = this.parameters[i];
if (typeof args[param.name] !== 'undefined') {
if (param.in === 'path') {
var reg = new RegExp('\{' + param.name + '\}', 'gi');
var value = args[param.name];
if (Array.isArray(value)) {
value = this.encodePathCollection(param.collectionFormat, param.name, value);
} else {
value = this.encodePathParam(value);
}
requestUrl = requestUrl.replace(reg, value);
} else if (param.in === 'query' && typeof args[param.name] !== 'undefined') {
if (querystring === '') {
querystring += '?';
} else {
querystring += '&';
}
if (typeof param.collectionFormat !== 'undefined') {
var qp = args[param.name];
if (Array.isArray(qp)) {
querystring += this.encodeQueryCollection(param.collectionFormat, param.name, qp);
} else {
querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
}
} else {
querystring += this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);
}
} else if (param.in === 'formData') {
formParams[param.name] = args[param.name];
}
}
}
var url = this.scheme + '://' + this.host;
if (this.basePath !== '/') {
url += this.basePath;
}
return url + requestUrl + querystring;
};
Operation.prototype.getMissingParams = function (args) {
var missingParams = []; // check required params, track the ones that are missing
var i;
for (i = 0; i < this.parameters.length; i++) {
var param = this.parameters[i];
if (param.required === true) {
if (typeof args[param.name] === 'undefined') {
missingParams = param.name;
}
}
}
return missingParams;
};
Operation.prototype.getBody = function (headers, args, opts) {
var formParams = {}, hasFormParams, body, key, value, hasBody = false;
// look at each param and put form params in an object
for (var i = 0; i < this.parameters.length; i++) {
var param = this.parameters[i];
if (typeof args[param.name] !== 'undefined') {
if (param.in === 'body') {
body = args[param.name];
} else if (param.in === 'formData') {
formParams[param.name] = args[param.name];
hasFormParams = true;
}
}
else {
if(param.in === 'body') {
hasBody = true;
}
}
}
// if body is null and hasBody is true, AND a JSON body is requested, send empty {}
if(hasBody && typeof body === 'undefined') {
var contentType = headers['Content-Type'];
if(contentType && contentType.indexOf('application/json') === 0) {
body = '{}';
}
}
var isMultiPart = false;
if(headers['Content-Type'] && headers['Content-Type'].indexOf('multipart/form-data') >= 0) {
isMultiPart = true;
}
// handle form params
if (hasFormParams && !isMultiPart) {
var encoded = '';
for (key in formParams) {
value = formParams[key];
if (typeof value !== 'undefined') {
if (encoded !== '') {
encoded += '&';
}
encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value);
}
}
body = encoded;
} else if (isMultiPart) {
if (opts.useJQuery) {
var bodyParam = new FormData();
bodyParam.type = 'formData';
for (key in formParams) {
value = args[key];
if (typeof value !== 'undefined') {
// required for jquery file upload
if (value.type === 'file' && value.value) {
delete headers['Content-Type'];
bodyParam.append(key, value.value);
} else {
bodyParam.append(key, value);
}
}
}
body = bodyParam;
}
}
return body;
};
/**
* gets sample response for a single operation
**/
Operation.prototype.getModelSampleJSON = function (type, models) {
var listType, sampleJson, innerType;
models = models || {};
listType = (type instanceof Array);
innerType = listType ? type[0] : type;
if(models[innerType]) {
sampleJson = models[innerType].createJSONSample();
} else if (this.getInlineModel(innerType)){
sampleJson = this.getInlineModel(innerType).createJSONSample(); // may return null, if type isn't correct
}
if (sampleJson) {
sampleJson = listType ? [sampleJson] : sampleJson;
if (typeof sampleJson === 'string') {
return sampleJson;
} else if (_.isObject(sampleJson)) {
var t = sampleJson;
if (sampleJson instanceof Array && sampleJson.length > 0) {
t = sampleJson[0];
}
if (t.nodeName && typeof t === 'Node') {
var xmlString = new XMLSerializer().serializeToString(t);
return this.formatXml(xmlString);
} else {
return JSON.stringify(sampleJson, null, 2);
}
} else {
return sampleJson;
}
}
};
/**
* legacy binding
**/
Operation.prototype.do = function (args, opts, callback, error, parent) {
return this.execute(args, opts, callback, error, parent);
};
/**
* executes an operation
**/
Operation.prototype.execute = function (arg1, arg2, arg3, arg4, parent) {
var args = arg1 || {};
var opts = {}, success, error, deferred;
if (_.isObject(arg2)) {
opts = arg2;
success = arg3;
error = arg4;
}
if(this.client) {
opts.client = this.client;
}
// add the request interceptor from parent, if none sent from client
if(!opts.requestInterceptor && this.requestInterceptor ) {
opts.requestInterceptor = this.requestInterceptor ;
}
if(!opts.responseInterceptor && this.responseInterceptor) {
opts.responseInterceptor = this.responseInterceptor;
}
if (typeof arg2 === 'function') {
success = arg2;
error = arg3;
}
if (this.parent.usePromise) {
deferred = Q.defer();
} else {
success = (success || this.parent.defaultSuccessCallback || helpers.log);
error = (error || this.parent.defaultErrorCallback || helpers.log);
}
if (typeof opts.useJQuery === 'undefined') {
opts.useJQuery = this.useJQuery;
}
if (typeof opts.enableCookies === 'undefined') {
opts.enableCookies = this.enableCookies;
}
var missingParams = this.getMissingParams(args);
if (missingParams.length > 0) {
var message = 'missing required params: ' + missingParams;
helpers.fail(message);
if (this.parent.usePromise) {
deferred.reject(message);
return deferred.promise;
} else {
error(message, parent);
return {};
}
}
var allHeaders = this.getHeaderParams(args);
var contentTypeHeaders = this.setContentTypes(args, opts);
var headers = {}, attrname;
for (attrname in allHeaders) { headers[attrname] = allHeaders[attrname]; }
for (attrname in contentTypeHeaders) { headers[attrname] = contentTypeHeaders[attrname]; }
var body = this.getBody(contentTypeHeaders, args, opts);
var url = this.urlify(args);
if(url.indexOf('.{format}') > 0) {
if(headers) {
var format = headers.Accept || headers.accept;
if(format && format.indexOf('json') > 0) {
url = url.replace('.{format}', '.json');
}
else if(format && format.indexOf('xml') > 0) {
url = url.replace('.{format}', '.xml');
}
}
}
var obj = {
url: url,
method: this.method.toUpperCase(),
body: body,
enableCookies: opts.enableCookies,
useJQuery: opts.useJQuery,
deferred: deferred,
headers: headers,
on: {
response: function (response) {
if (deferred) {
deferred.resolve(response);
return deferred.promise;
} else {
return success(response, parent);
}
},
error: function (response) {
if (deferred) {
deferred.reject(response);
return deferred.promise;
} else {
return error(response, parent);
}
}
}
};
this.clientAuthorizations.apply(obj, this.operation.security);
if (opts.mock === true) {
return obj;
} else {
return new SwaggerHttp().execute(obj, opts);
}
};
function itemByPriority(col, itemPriority) {
// No priorities? return first...
if(_.isEmpty(itemPriority)) {
return col[0];
}
for (var i = 0, len = itemPriority.length; i < len; i++) {
if(col.indexOf(itemPriority[i]) > -1) {
return itemPriority[i];
}
}
// Otherwise return first
return col[0];
}
Operation.prototype.setContentTypes = function (args, opts) {
// default type
var allDefinedParams = this.parameters;
var body;
var consumes = args.parameterContentType || itemByPriority(this.consumes, ['application/json', 'application/yaml']);
var accepts = opts.responseContentType || itemByPriority(this.produces, ['application/json', 'application/yaml']);
var definedFileParams = [];
var definedFormParams = [];
var headers = {};
var i;
// get params from the operation and set them in definedFileParams, definedFormParams, headers
for (i = 0; i < allDefinedParams.length; i++) {
var param = allDefinedParams[i];
if (param.in === 'formData') {
if (param.type === 'file') {
definedFileParams.push(param);
} else {
definedFormParams.push(param);
}
} else if (param.in === 'header' && opts) {
var key = param.name;
var headerValue = opts[param.name];
if (typeof opts[param.name] !== 'undefined') {
headers[key] = headerValue;
}
} else if (param.in === 'body' && typeof args[param.name] !== 'undefined') {
body = args[param.name];
}
}
// if there's a body, need to set the consumes header via requestContentType
if (this.method === 'post' || this.method === 'put' || this.method === 'patch' ||
((this.method === 'delete' || this.method === 'get') && body) ) {
if (opts.requestContentType) {
consumes = opts.requestContentType;
}
// if any form params, content type must be set
if (definedFormParams.length > 0) {
if (opts.requestContentType) { // override if set
consumes = opts.requestContentType;
} else if (definedFileParams.length > 0) { // if a file, must be multipart/form-data
consumes = 'multipart/form-data';
} else { // default to x-www-from-urlencoded
consumes = 'application/x-www-form-urlencoded';
}
}
}
else {
consumes = null;
}
if (consumes && this.consumes) {
if (this.consumes.indexOf(consumes) === -1) {
helpers.log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes));
}
}
if (!this.matchesAccept(accepts)) {
helpers.log('server can\'t produce ' + accepts);
}
if ((consumes && body !== '') || (consumes === 'application/x-www-form-urlencoded')) {
headers['Content-Type'] = consumes;
}
if (accepts) {
headers.Accept = accepts;
}
return headers;
};
/**
* Returns true if the request accepts header matches anything in this.produces.
* If this.produces contains * / *, ignore the accept header.
* @param {string=} accepts The client request accept header.
* @return {boolean}
*/
Operation.prototype.matchesAccept = function(accepts) {
// no accepts or produces, no problem!
if (!accepts || !this.produces) {
return true;
}
return this.produces.indexOf(accepts) !== -1 || this.produces.indexOf('*/*') !== -1;
};
Operation.prototype.asCurl = function (args1, args2) {
var opts = {mock: true};
if (typeof args2 === 'object') {
for (var argKey in args2) {
opts[argKey] = args2[argKey];
}
}
var obj = this.execute(args1, opts);
this.clientAuthorizations.apply(obj, this.operation.security);
var results = [];
results.push('-X ' + this.method.toUpperCase());
if (typeof obj.headers !== 'undefined') {
var key;
for (key in obj.headers) {
var value = obj.headers[key];
if(typeof value === 'string'){
value = value.replace(/\'/g, '\\u0027');
}
results.push('--header \'' + key + ': ' + value + '\'');
}
}
if (obj.body) {
var body;
if (_.isObject(obj.body)) {
body = JSON.stringify(obj.body);
} else {
body = obj.body;
}
results.push('-d \'' + body.replace(/\'/g, '\\u0027') + '\'');
}
return 'curl ' + (results.join(' ')) + ' \'' + obj.url + '\'';
};
Operation.prototype.encodePathCollection = function (type, name, value) {
var encoded = '';
var i;
var separator = '';
if (type === 'ssv') {
separator = '%20';
} else if (type === 'tsv') {
separator = '\\t';
} else if (type === 'pipes') {
separator = '|';
} else {
separator = ',';
}
for (i = 0; i < value.length; i++) {
if (i === 0) {
encoded = this.encodeQueryParam(value[i]);
} else {
encoded += separator + this.encodeQueryParam(value[i]);
}
}
return encoded;
};
Operation.prototype.encodeQueryCollection = function (type, name, value) {
var encoded = '';
var i;
if (type === 'default' || type === 'multi') {
for (i = 0; i < value.length; i++) {
if (i > 0) {encoded += '&';}
encoded += this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
}
} else {
var separator = '';
if (type === 'csv') {
separator = ',';
} else if (type === 'ssv') {
separator = '%20';
} else if (type === 'tsv') {
separator = '\\t';
} else if (type === 'pipes') {
separator = '|';
} else if (type === 'brackets') {
for (i = 0; i < value.length; i++) {
if (i !== 0) {
encoded += '&';
}
encoded += this.encodeQueryParam(name) + '[]=' + this.encodeQueryParam(value[i]);
}
}
if (separator !== '') {
for (i = 0; i < value.length; i++) {
if (i === 0) {
encoded = this.encodeQueryParam(name) + '=' + this.encodeQueryParam(value[i]);
} else {
encoded += separator + this.encodeQueryParam(value[i]);
}
}
}
}
return encoded;
};
Operation.prototype.encodeQueryParam = function (arg) {
return encodeURIComponent(arg);
};
/**
* TODO revisit, might not want to leave '/'
**/
Operation.prototype.encodePathParam = function (pathParam) {
return encodeURIComponent(pathParam);
};
},{"../helpers":4,"../http":5,"./model":9,"lodash-compat/lang/cloneDeep":139,"lodash-compat/lang/isEmpty":142,"lodash-compat/lang/isObject":145,"lodash-compat/lang/isUndefined":149,"q":158}],11:[function(require,module,exports){
'use strict';
var OperationGroup = module.exports = function (tag, description, externalDocs, operation) {
this.description = description;
this.externalDocs = externalDocs;
this.name = tag;
this.operation = operation;
this.operationsArray = [];
this.path = tag;
this.tag = tag;
};
OperationGroup.prototype.sort = function () {
};
},{}],12:[function(require,module,exports){
},{}],13:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],14:[function(require,module,exports){
(function (Buffer){
(function () {
"use strict";
function btoa(str) {
var buffer
;
if (str instanceof Buffer) {
buffer = str;
} else {
buffer = new Buffer(str.toString(), 'binary');
}
return buffer.toString('base64');
}
module.exports = btoa;
}());
}).call(this,require("buffer").Buffer)
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9idG9hL2luZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiKGZ1bmN0aW9uICgpIHtcbiAgXCJ1c2Ugc3RyaWN0XCI7XG5cbiAgZnVuY3Rpb24gYnRvYShzdHIpIHtcbiAgICB2YXIgYnVmZmVyXG4gICAgICA7XG5cbiAgICBpZiAoc3RyIGluc3RhbmNlb2YgQnVmZmVyKSB7XG4gICAgICBidWZmZXIgPSBzdHI7XG4gICAgfSBlbHNlIHtcbiAgICAgIGJ1ZmZlciA9IG5ldyBCdWZmZXIoc3RyLnRvU3RyaW5nKCksICdiaW5hcnknKTtcbiAgICB9XG5cbiAgICByZXR1cm4gYnVmZmVyLnRvU3RyaW5nKCdiYXNlNjQnKTtcbiAgfVxuXG4gIG1vZHVsZS5leHBvcnRzID0gYnRvYTtcbn0oKSk7XG4iXX0=
},{"buffer":15}],15:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
* on objects.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
function Bar () {}
try {
var arr = new Uint8Array(1)
arr.foo = function () { return 42 }
arr.constructor = Bar
return arr.foo() === 42 && // typed array instances can be augmented
arr.constructor === Bar && // constructor can be set
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (arg) {
if (!(this instanceof Buffer)) {
// Avoid going through an ArgumentsAdaptorTrampoline in the common case.
if (arguments.length > 1) return new Buffer(arg, arguments[1])
return new Buffer(arg)
}
this.length = 0
this.parent = undefined
// Common case.
if (typeof arg === 'number') {
return fromNumber(this, arg)
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
}
// Unusual.
return fromObject(this, arg)
}
function fromNumber (that, length) {
that = allocate(that, length < 0 ? 0 : checked(length) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < length; i++) {
that[i] = 0
}
}
return that
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
// Assumption: byteLength() return value is always < kMaxLength.
var length = byteLength(string, encoding) | 0
that = allocate(that, length)
that.write(string, encoding)
return that
}
function fromObject (that, object) {
if (Buffer.isBuffer(object)) return fromBuffer(that, object)
if (isArray(object)) return fromArray(that, object)
if (object == null) {
throw new TypeError('must start with number, buffer, array or string')
}
if (typeof ArrayBuffer !== 'undefined') {
if (object.buffer instanceof ArrayBuffer) {
return fromTypedArray(that, object)
}
if (object instanceof ArrayBuffer) {
return fromArrayBuffer(that, object)
}
}
if (object.length) return fromArrayLike(that, object)
return fromJsonObject(that, object)
}
function fromBuffer (that, buffer) {
var length = checked(buffer.length) | 0
that = allocate(that, length)
buffer.copy(that, 0, 0, length)
return that
}
function fromArray (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
// Duplicate of fromArray() to keep fromArray() monomorphic.
function fromTypedArray (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
// Truncating the elements is probably not what people expect from typed
// arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
// of the old Buffer constructor.
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array) {
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
array.byteLength
that = Buffer._augment(new Uint8Array(array))
} else {
// Fallback: Return an object instance of the Buffer class
that = fromTypedArray(that, new Uint8Array(array))
}
return that
}
function fromArrayLike (that, array) {
var length = checked(array.length) | 0
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
// Returns a zero-length buffer for inputs that don't conform to the spec.
function fromJsonObject (that, object) {
var array
var length = 0
if (object.type === 'Buffer' && isArray(object.data)) {
array = object.data
length = checked(array.length) | 0
}
that = allocate(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function allocate (that, length) {
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = Buffer._augment(new Uint8Array(length))
} else {
// Fallback: Return an object instance of the Buffer class
that.length = length
that._isBuffer = true
}
var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
if (fromPool) that.parent = rootParent
return that
}
function checked (length) {
// Note: cannot use `length < kMaxLength` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (subject, encoding) {
if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
var buf = new Buffer(subject, encoding)
delete buf.parent
return buf
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
var i = 0
var len = Math.min(x, y)
while (i < len) {
if (a[i] !== b[i]) break
++i
}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; i++) {
length += list[i].length
}
}
var buf = new Buffer(length)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
function byteLength (string, encoding) {
if (typeof string !== 'string') string = '' + string
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'binary':
// Deprecated
case 'raw':
case 'raws':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
function slowToString (encoding, start, end) {
var loweredCase = false
start = start | 0
end = end === undefined || end === Infinity ? this.length : end | 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return 0
return Buffer.compare(this, b)
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
else if (byteOffset < -0x80000000) byteOffset = -0x80000000
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
if (val.length === 0) return -1 // special case: looking for empty string always fails
return String.prototype.indexOf.call(this, val, byteOffset)
}
if (Buffer.isBuffer(val)) {
return arrayIndexOf(this, val, byteOffset)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset)
}
function arrayIndexOf (arr, val, byteOffset) {
var foundIndex = -1
for (var i = 0; byteOffset + i < arr.length; i++) {
if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
} else {
foundIndex = -1
}
}
return -1
}
throw new TypeError('val must be string, number or Buffer')
}
// `get` is deprecated
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` is deprecated
Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) throw new Error('Invalid hex string')
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
var swap = encoding
encoding = offset
offset = length | 0
length = swap
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'binary':
return binaryWrite(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
if (newBuf.length) newBuf.parent = this.parent || this
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; i--) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; i++) {
target[i + targetStart] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), targetStart)
}
return len
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array set method before overwriting
arr._set = arr.set
// deprecated
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUIntLE = BP.readUIntLE
arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readIntLE = BP.readIntLE
arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUIntLE = BP.writeUIntLE
arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeIntLE = BP.writeIntLE
arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
},{"base64-js":16,"ieee754":17,"is-array":18}],16:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],17:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],18:[function(require,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],19:[function(require,module,exports){
/* jshint node: true */
(function () {
"use strict";
function CookieAccessInfo(domain, path, secure, script) {
if (this instanceof CookieAccessInfo) {
this.domain = domain || undefined;
this.path = path || "/";
this.secure = !!secure;
this.script = !!script;
return this;
}
return new CookieAccessInfo(domain, path, secure, script);
}
exports.CookieAccessInfo = CookieAccessInfo;
function Cookie(cookiestr, request_domain, request_path) {
if (cookiestr instanceof Cookie) {
return cookiestr;
}
if (this instanceof Cookie) {
this.name = null;
this.value = null;
this.expiration_date = Infinity;
this.path = String(request_path || "/");
this.explicit_path = false;
this.domain = request_domain || null;
this.explicit_domain = false;
this.secure = false; //how to define default?
this.noscript = false; //httponly
if (cookiestr) {
this.parse(cookiestr, request_domain, request_path);
}
return this;
}
return new Cookie(cookiestr, request_domain, request_path);
}
exports.Cookie = Cookie;
Cookie.prototype.toString = function toString() {
var str = [this.name + "=" + this.value];
if (this.expiration_date !== Infinity) {
str.push("expires=" + (new Date(this.expiration_date)).toGMTString());
}
if (this.domain) {
str.push("domain=" + this.domain);
}
if (this.path) {
str.push("path=" + this.path);
}
if (this.secure) {
str.push("secure");
}
if (this.noscript) {
str.push("httponly");
}
return str.join("; ");
};
Cookie.prototype.toValueString = function toValueString() {
return this.name + "=" + this.value;
};
var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g;
Cookie.prototype.parse = function parse(str, request_domain, request_path) {
if (this instanceof Cookie) {
var parts = str.split(";").filter(function (value) {
return !!value;
}),
pair = parts[0].match(/([^=]+)=([\s\S]*)/),
key = pair[1],
value = pair[2],
i;
this.name = key;
this.value = value;
for (i = 1; i < parts.length; i += 1) {
pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/);
key = pair[1].trim().toLowerCase();
value = pair[2];
switch (key) {
case "httponly":
this.noscript = true;
break;
case "expires":
this.expiration_date = value ?
Number(Date.parse(value)) :
Infinity;
break;
case "path":
this.path = value ?
value.trim() :
"";
this.explicit_path = true;
break;
case "domain":
this.domain = value ?
value.trim() :
"";
this.explicit_domain = !!this.domain;
break;
case "secure":
this.secure = true;
break;
}
}
if (!this.explicit_path) {
this.path = request_path || "/";
}
if (!this.explicit_domain) {
this.domain = request_domain;
}
return this;
}
return new Cookie().parse(str, request_domain, request_path);
};
Cookie.prototype.matches = function matches(access_info) {
if (this.noscript && access_info.script ||
this.secure && !access_info.secure ||
!this.collidesWith(access_info)) {
return false;
}
return true;
};
Cookie.prototype.collidesWith = function collidesWith(access_info) {
if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) {
return false;
}
if (this.path && access_info.path.indexOf(this.path) !== 0) {
return false;
}
if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) {
return false;
}
var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,'');
var cookie_domain = this.domain && this.domain.replace(/^[\.]/,'');
if (cookie_domain === access_domain) {
return true;
}
if (cookie_domain) {
if (!this.explicit_domain) {
return false; // we already checked if the domains were exactly the same
}
var wildcard = access_domain.indexOf(cookie_domain);
if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) {
return false;
}
return true;
}
return true;
};
function CookieJar() {
var cookies, cookies_list, collidable_cookie;
if (this instanceof CookieJar) {
cookies = Object.create(null); //name: [Cookie]
this.setCookie = function setCookie(cookie, request_domain, request_path) {
var remove, i;
cookie = new Cookie(cookie, request_domain, request_path);
//Delete the cookie if the set is past the current time
remove = cookie.expiration_date <= Date.now();
if (cookies[cookie.name] !== undefined) {
cookies_list = cookies[cookie.name];
for (i = 0; i < cookies_list.length; i += 1) {
collidable_cookie = cookies_list[i];
if (collidable_cookie.collidesWith(cookie)) {
if (remove) {
cookies_list.splice(i, 1);
if (cookies_list.length === 0) {
delete cookies[cookie.name];
}
return false;
}
cookies_list[i] = cookie;
return cookie;
}
}
if (remove) {
return false;
}
cookies_list.push(cookie);
return cookie;
}
if (remove) {
return false;
}
cookies[cookie.name] = [cookie];
return cookies[cookie.name];
};
//returns a cookie
this.getCookie = function getCookie(cookie_name, access_info) {
var cookie, i;
cookies_list = cookies[cookie_name];
if (!cookies_list) {
return;
}
for (i = 0; i < cookies_list.length; i += 1) {
cookie = cookies_list[i];
if (cookie.expiration_date <= Date.now()) {
if (cookies_list.length === 0) {
delete cookies[cookie.name];
}
continue;
}
if (cookie.matches(access_info)) {
return cookie;
}
}
};
//returns a list of cookies
this.getCookies = function getCookies(access_info) {
var matches = [], cookie_name, cookie;
for (cookie_name in cookies) {
cookie = this.getCookie(cookie_name, access_info);
if (cookie) {
matches.push(cookie);
}
}
matches.toString = function toString() {
return matches.join(":");
};
matches.toValueString = function toValueString() {
return matches.map(function (c) {
return c.toValueString();
}).join(';');
};
return matches;
};
return this;
}
return new CookieJar();
}
exports.CookieJar = CookieJar;
//returns list of cookies that were set correctly. Cookies that are expired and removed are not returned.
CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) {
cookies = Array.isArray(cookies) ?
cookies :
cookies.split(cookie_str_splitter);
var successful = [],
i,
cookie;
cookies = cookies.map(function(item){
return new Cookie(item, request_domain, request_path);
});
for (i = 0; i < cookies.length; i += 1) {
cookie = cookies[i];
if (this.setCookie(cookie, request_domain, request_path)) {
successful.push(cookie);
}
}
return successful;
};
}());
},{}],20:[function(require,module,exports){
'use strict';
var yaml = require('./lib/js-yaml.js');
module.exports = yaml;
},{"./lib/js-yaml.js":21}],21:[function(require,module,exports){
'use strict';
var loader = require('./js-yaml/loader');
var dumper = require('./js-yaml/dumper');
function deprecated(name) {
return function () {
throw new Error('Function ' + name + ' is deprecated and cannot be used.');
};
}
module.exports.Type = require('./js-yaml/type');
module.exports.Schema = require('./js-yaml/schema');
module.exports.FAILSAFE_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.JSON_SCHEMA = require('./js-yaml/schema/json');
module.exports.CORE_SCHEMA = require('./js-yaml/schema/core');
module.exports.DEFAULT_SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_FULL_SCHEMA = require('./js-yaml/schema/default_full');
module.exports.load = loader.load;
module.exports.loadAll = loader.loadAll;
module.exports.safeLoad = loader.safeLoad;
module.exports.safeLoadAll = loader.safeLoadAll;
module.exports.dump = dumper.dump;
module.exports.safeDump = dumper.safeDump;
module.exports.YAMLException = require('./js-yaml/exception');
// Deprecated schema names from JS-YAML 2.0.x
module.exports.MINIMAL_SCHEMA = require('./js-yaml/schema/failsafe');
module.exports.SAFE_SCHEMA = require('./js-yaml/schema/default_safe');
module.exports.DEFAULT_SCHEMA = require('./js-yaml/schema/default_full');
// Deprecated functions from JS-YAML 1.x.x
module.exports.scan = deprecated('scan');
module.exports.parse = deprecated('parse');
module.exports.compose = deprecated('compose');
module.exports.addConstructor = deprecated('addConstructor');
},{"./js-yaml/dumper":23,"./js-yaml/exception":24,"./js-yaml/loader":25,"./js-yaml/schema":27,"./js-yaml/schema/core":28,"./js-yaml/schema/default_full":29,"./js-yaml/schema/default_safe":30,"./js-yaml/schema/failsafe":31,"./js-yaml/schema/json":32,"./js-yaml/type":33}],22:[function(require,module,exports){
'use strict';
function isNothing(subject) {
return (typeof subject === 'undefined') || (subject === null);
}
function isObject(subject) {
return (typeof subject === 'object') && (subject !== null);
}
function toArray(sequence) {
if (Array.isArray(sequence)) return sequence;
else if (isNothing(sequence)) return [];
return [ sequence ];
}
function extend(target, source) {
var index, length, key, sourceKeys;
if (source) {
sourceKeys = Object.keys(source);
for (index = 0, length = sourceKeys.length; index < length; index += 1) {
key = sourceKeys[index];
target[key] = source[key];
}
}
return target;
}
function repeat(string, count) {
var result = '', cycle;
for (cycle = 0; cycle < count; cycle += 1) {
result += string;
}
return result;
}
function isNegativeZero(number) {
return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
}
module.exports.isNothing = isNothing;
module.exports.isObject = isObject;
module.exports.toArray = toArray;
module.exports.repeat = repeat;
module.exports.isNegativeZero = isNegativeZero;
module.exports.extend = extend;
},{}],23:[function(require,module,exports){
'use strict';
/*eslint-disable no-use-before-define*/
var common = require('./common');
var YAMLException = require('./exception');
var DEFAULT_FULL_SCHEMA = require('./schema/default_full');
var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');
var _toString = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CHAR_TAB = 0x09; /* Tab */
var CHAR_LINE_FEED = 0x0A; /* LF */
var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */
var CHAR_SPACE = 0x20; /* Space */
var CHAR_EXCLAMATION = 0x21; /* ! */
var CHAR_DOUBLE_QUOTE = 0x22; /* " */
var CHAR_SHARP = 0x23; /* # */
var CHAR_PERCENT = 0x25; /* % */
var CHAR_AMPERSAND = 0x26; /* & */
var CHAR_SINGLE_QUOTE = 0x27; /* ' */
var CHAR_ASTERISK = 0x2A; /* * */
var CHAR_COMMA = 0x2C; /* , */
var CHAR_MINUS = 0x2D; /* - */
var CHAR_COLON = 0x3A; /* : */
var CHAR_GREATER_THAN = 0x3E; /* > */
var CHAR_QUESTION = 0x3F; /* ? */
var CHAR_COMMERCIAL_AT = 0x40; /* @ */
var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */
var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
var CHAR_GRAVE_ACCENT = 0x60; /* ` */
var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */
var CHAR_VERTICAL_LINE = 0x7C; /* | */
var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */
var ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0x00] = '\\0';
ESCAPE_SEQUENCES[0x07] = '\\a';
ESCAPE_SEQUENCES[0x08] = '\\b';
ESCAPE_SEQUENCES[0x09] = '\\t';
ESCAPE_SEQUENCES[0x0A] = '\\n';
ESCAPE_SEQUENCES[0x0B] = '\\v';
ESCAPE_SEQUENCES[0x0C] = '\\f';
ESCAPE_SEQUENCES[0x0D] = '\\r';
ESCAPE_SEQUENCES[0x1B] = '\\e';
ESCAPE_SEQUENCES[0x22] = '\\"';
ESCAPE_SEQUENCES[0x5C] = '\\\\';
ESCAPE_SEQUENCES[0x85] = '\\N';
ESCAPE_SEQUENCES[0xA0] = '\\_';
ESCAPE_SEQUENCES[0x2028] = '\\L';
ESCAPE_SEQUENCES[0x2029] = '\\P';
var DEPRECATED_BOOLEANS_SYNTAX = [
'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
];
function compileStyleMap(schema, map) {
var result, keys, index, length, tag, style, type;
if (map === null) return {};
result = {};
keys = Object.keys(map);
for (index = 0, length = keys.length; index < length; index += 1) {
tag = keys[index];
style = String(map[tag]);
if (tag.slice(0, 2) === '!!') {
tag = 'tag:yaml.org,2002:' + tag.slice(2);
}
type = schema.compiledTypeMap[tag];
if (type && _hasOwnProperty.call(type.styleAliases, style)) {
style = type.styleAliases[style];
}
result[tag] = style;
}
return result;
}
function encodeHex(character) {
var string, handle, length;
string = character.toString(16).toUpperCase();
if (character <= 0xFF) {
handle = 'x';
length = 2;
} else if (character <= 0xFFFF) {
handle = 'u';
length = 4;
} else if (character <= 0xFFFFFFFF) {
handle = 'U';
length = 8;
} else {
throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
}
return '\\' + handle + common.repeat('0', length - string.length) + string;
}
function State(options) {
this.schema = options['schema'] || DEFAULT_FULL_SCHEMA;
this.indent = Math.max(1, (options['indent'] || 2));
this.skipInvalid = options['skipInvalid'] || false;
this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
this.styleMap = compileStyleMap(this.schema, options['styles'] || null);
this.sortKeys = options['sortKeys'] || false;
this.lineWidth = options['lineWidth'] || 80;
this.noRefs = options['noRefs'] || false;
this.implicitTypes = this.schema.compiledImplicit;
this.explicitTypes = this.schema.compiledExplicit;
this.tag = null;
this.result = '';
this.duplicates = [];
this.usedDuplicates = null;
}
function indentString(string, spaces) {
var ind = common.repeat(' ', spaces),
position = 0,
next = -1,
result = '',
line,
length = string.length;
while (position < length) {
next = string.indexOf('\n', position);
if (next === -1) {
line = string.slice(position);
position = length;
} else {
line = string.slice(position, next + 1);
position = next + 1;
}
if (line.length && line !== '\n') result += ind;
result += line;
}
return result;
}
function generateNextLine(state, level) {
return '\n' + common.repeat(' ', state.indent * level);
}
function testImplicitResolving(state, str) {
var index, length, type;
for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
type = state.implicitTypes[index];
if (type.resolve(str)) {
return true;
}
}
return false;
}
function StringBuilder(source) {
this.source = source;
this.result = '';
this.checkpoint = 0;
}
StringBuilder.prototype.takeUpTo = function (position) {
var er;
if (position < this.checkpoint) {
er = new Error('position should be > checkpoint');
er.position = position;
er.checkpoint = this.checkpoint;
throw er;
}
this.result += this.source.slice(this.checkpoint, position);
this.checkpoint = position;
return this;
};
StringBuilder.prototype.escapeChar = function () {
var character, esc;
character = this.source.charCodeAt(this.checkpoint);
esc = ESCAPE_SEQUENCES[character] || encodeHex(character);
this.result += esc;
this.checkpoint += 1;
return this;
};
StringBuilder.prototype.finish = function () {
if (this.source.length > this.checkpoint) {
this.takeUpTo(this.source.length);
}
};
function writeScalar(state, object, level, iskey) {
var simple, first, spaceWrap, folded, literal, single, double,
sawLineFeed, linePosition, longestLine, indent, max, character,
position, escapeSeq, hexEsc, previous, lineLength, modifier,
trailingLineBreaks, result;
if (object.length === 0) {
state.dump = "''";
return;
}
if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(object) !== -1) {
state.dump = "'" + object + "'";
return;
}
simple = true;
firs
gitextract_06y61mnm/
├── LICENSE
├── README.md
├── css/
│ └── layout.css
├── index.html
└── js/
├── swagger-client.js
└── ui.js
SYMBOL INDEX (342 symbols across 2 files)
FILE: js/swagger-client.js
function s (line 7) | function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&re...
function optionHtml (line 1918) | function optionHtml(label, value) {
function typeFromJsonSchema (line 1922) | function typeFromJsonSchema(type, format) {
function getStringSignature (line 1950) | function getStringSignature(obj, baseComponent) {
function schemaToJSON (line 1994) | function schemaToJSON(schema, models, modelsToIgnore, modelPropertyMacro) {
function schemaToHTML (line 2081) | function schemaToHTML(name, schema, models, modelPropertyMacro) {
function itemByPriority (line 3884) | function itemByPriority(col, itemPriority) {
function drainQueue (line 4141) | function drainQueue() {
function noop (line 4173) | function noop() {}
function btoa (line 4199) | function btoa(str) {
function Bar (line 4264) | function Bar () {}
function kMaxLength (line 4278) | function kMaxLength () {
function Buffer (line 4296) | function Buffer (arg) {
function fromNumber (line 4320) | function fromNumber (that, length) {
function fromString (line 4330) | function fromString (that, string, encoding) {
function fromObject (line 4341) | function fromObject (that, object) {
function fromBuffer (line 4364) | function fromBuffer (that, buffer) {
function fromArray (line 4371) | function fromArray (that, array) {
function fromTypedArray (line 4381) | function fromTypedArray (that, array) {
function fromArrayBuffer (line 4393) | function fromArrayBuffer (that, array) {
function fromArrayLike (line 4405) | function fromArrayLike (that, array) {
function fromJsonObject (line 4416) | function fromJsonObject (that, object) {
function allocate (line 4432) | function allocate (that, length) {
function checked (line 4448) | function checked (length) {
function SlowBuffer (line 4458) | function SlowBuffer (subject, encoding) {
function byteLength (line 4542) | function byteLength (string, encoding) {
function slowToString (line 4583) | function slowToString (encoding, start, end) {
function arrayIndexOf (line 4680) | function arrayIndexOf (arr, val, byteOffset) {
function hexWrite (line 4708) | function hexWrite (buf, string, offset, length) {
function utf8Write (line 4735) | function utf8Write (buf, string, offset, length) {
function asciiWrite (line 4739) | function asciiWrite (buf, string, offset, length) {
function binaryWrite (line 4743) | function binaryWrite (buf, string, offset, length) {
function base64Write (line 4747) | function base64Write (buf, string, offset, length) {
function ucs2Write (line 4751) | function ucs2Write (buf, string, offset, length) {
function base64Slice (line 4834) | function base64Slice (buf, start, end) {
function utf8Slice (line 4842) | function utf8Slice (buf, start, end) {
function decodeCodePointsArray (line 4920) | function decodeCodePointsArray (codePoints) {
function asciiSlice (line 4938) | function asciiSlice (buf, start, end) {
function binarySlice (line 4948) | function binarySlice (buf, start, end) {
function hexSlice (line 4958) | function hexSlice (buf, start, end) {
function utf16leSlice (line 4971) | function utf16leSlice (buf, start, end) {
function checkOffset (line 5020) | function checkOffset (offset, ext, length) {
function checkInt (line 5181) | function checkInt (buf, value, offset, ext, max, min) {
function objectWriteUInt16 (line 5228) | function objectWriteUInt16 (buf, value, offset, littleEndian) {
function objectWriteUInt32 (line 5262) | function objectWriteUInt32 (buf, value, offset, littleEndian) {
function checkIEEE754 (line 5406) | function checkIEEE754 (buf, value, offset, ext, max, min) {
function writeFloat (line 5412) | function writeFloat (buf, value, offset, littleEndian, noAssert) {
function writeDouble (line 5428) | function writeDouble (buf, value, offset, littleEndian, noAssert) {
function base64clean (line 5613) | function base64clean (str) {
function stringtrim (line 5625) | function stringtrim (str) {
function toHex (line 5630) | function toHex (n) {
function utf8ToBytes (line 5635) | function utf8ToBytes (string, units) {
function asciiToBytes (line 5715) | function asciiToBytes (str) {
function utf16leToBytes (line 5724) | function utf16leToBytes (str, units) {
function base64ToBytes (line 5740) | function base64ToBytes (str) {
function blitBuffer (line 5744) | function blitBuffer (src, dst, offset, length) {
function decode (line 5770) | function decode (elt) {
function b64ToByteArray (line 5788) | function b64ToByteArray (b64) {
function uint8ToBase64 (line 5834) | function uint8ToBase64 (uint8) {
function CookieAccessInfo (line 6004) | function CookieAccessInfo(domain, path, secure, script) {
function Cookie (line 6016) | function Cookie(cookiestr, request_domain, request_path) {
function CookieJar (line 6156) | function CookieJar() {
function deprecated (line 6279) | function deprecated(name) {
function isNothing (line 6316) | function isNothing(subject) {
function isObject (line 6321) | function isObject(subject) {
function toArray (line 6326) | function toArray(sequence) {
function extend (line 6334) | function extend(target, source) {
function repeat (line 6350) | function repeat(string, count) {
function isNegativeZero (line 6361) | function isNegativeZero(number) {
function compileStyleMap (line 6433) | function compileStyleMap(schema, map) {
function encodeHex (line 6461) | function encodeHex(character) {
function State (line 6482) | function State(options) {
function indentString (line 6502) | function indentString(string, spaces) {
function generateNextLine (line 6528) | function generateNextLine(state, level) {
function testImplicitResolving (line 6532) | function testImplicitResolving(state, str) {
function StringBuilder (line 6546) | function StringBuilder(source) {
function writeScalar (line 6584) | function writeScalar(state, object, level, iskey) {
function fold (line 6751) | function fold(object, max) {
function foldLine (line 6781) | function foldLine(line, max) {
function simpleChar (line 6827) | function simpleChar(character) {
function needsHexEscape (line 6851) | function needsHexEscape(character) {
function writeFlowSequence (line 6859) | function writeFlowSequence(state, level, object) {
function writeBlockSequence (line 6877) | function writeBlockSequence(state, level, object, compact) {
function writeFlowMapping (line 6897) | function writeFlowMapping(state, level, object) {
function writeBlockMapping (line 6937) | function writeBlockMapping(state, level, object, compact) {
function detectType (line 7011) | function detectType(state, object, explicit) {
function writeNode (line 7049) | function writeNode(state, level, object, block, compact, iskey) {
function getDuplicateReferences (line 7123) | function getDuplicateReferences(object, state) {
function inspectNode (line 7137) | function inspectNode(object, objects, duplicatesIndexes) {
function dump (line 7166) | function dump(input, options) {
function safeDump (line 7178) | function safeDump(input, options) {
function YAMLException (line 7190) | function YAMLException(reason, mark) {
function is_EOL (line 7263) | function is_EOL(c) {
function is_WHITE_SPACE (line 7267) | function is_WHITE_SPACE(c) {
function is_WS_OR_EOL (line 7271) | function is_WS_OR_EOL(c) {
function is_FLOW_INDICATOR (line 7278) | function is_FLOW_INDICATOR(c) {
function fromHexCode (line 7286) | function fromHexCode(c) {
function escapedHexLen (line 7303) | function escapedHexLen(c) {
function fromDecimalCode (line 7310) | function fromDecimalCode(c) {
function simpleEscapeSequence (line 7318) | function simpleEscapeSequence(c) {
function charFromCodepoint (line 7339) | function charFromCodepoint(c) {
function State (line 7357) | function State(input, options) {
function generateError (line 7391) | function generateError(state, message) {
function throwError (line 7397) | function throwError(state, message) {
function throwWarning (line 7401) | function throwWarning(state, message) {
function captureSegment (line 7471) | function captureSegment(state, start, end, checkJson) {
function mergeMappings (line 7495) | function mergeMappings(state, destination, source, overridableKeys) {
function storeMappingPair (line 7514) | function storeMappingPair(state, _result, overridableKeys, keyTag, keyNo...
function readLineBreak (line 7544) | function readLineBreak(state) {
function skipSeparationSpace (line 7564) | function skipSeparationSpace(state, allowComments, checkIndent) {
function testDocumentSeparator (line 7602) | function testDocumentSeparator(state) {
function writeFoldedLines (line 7626) | function writeFoldedLines(state, count) {
function readPlainScalar (line 7635) | function readPlainScalar(state, nodeIndent, withinFlowCollection) {
function readSingleQuotedScalar (line 7744) | function readSingleQuotedScalar(state, nodeIndent) {
function readDoubleQuotedScalar (line 7788) | function readDoubleQuotedScalar(state, nodeIndent) {
function readFlowCollection (line 7867) | function readFlowCollection(state, nodeIndent) {
function readBlockScalar (line 7972) | function readBlockScalar(state, nodeIndent) {
function readBlockSequence (line 8115) | function readBlockSequence(state, nodeIndent) {
function readBlockMapping (line 8177) | function readBlockMapping(state, nodeIndent, flowIndent) {
function readTagProperty (line 8330) | function readTagProperty(state) {
function readAnchorProperty (line 8424) | function readAnchorProperty(state) {
function readAlias (line 8451) | function readAlias(state) {
function composeNode (line 8481) | function composeNode(state, parentIndent, nodeContext, allowToSeek, allo...
function readDocument (line 8637) | function readDocument(state) {
function loadDocuments (line 8745) | function loadDocuments(input, options) {
function loadAll (line 8781) | function loadAll(input, iterator, options) {
function load (line 8790) | function load(input, options) {
function safeLoadAll (line 8803) | function safeLoadAll(input, output, options) {
function safeLoad (line 8808) | function safeLoad(input, options) {
function Mark (line 8825) | function Mark(name, buffer, position, line, column) {
function compileList (line 8906) | function compileList(schema, name, result) {
function compileMap (line 8929) | function compileMap(/* lists... */) {
function Schema (line 8944) | function Schema(definition) {
function compileStyleAliases (line 9147) | function compileStyleAliases(map) {
function Type (line 9161) | function Type(tag, options) {
function resolveYamlBinary (line 9203) | function resolveYamlBinary(data) {
function constructYamlBinary (line 9225) | function constructYamlBinary(data) {
function representYamlBinary (line 9266) | function representYamlBinary(object /*, style*/) {
function isBinary (line 9308) | function isBinary(object) {
function resolveYamlBoolean (line 9325) | function resolveYamlBoolean(data) {
function constructYamlBoolean (line 9334) | function constructYamlBoolean(data) {
function isBoolean (line 9340) | function isBoolean(object) {
function resolveYamlFloat (line 9370) | function resolveYamlFloat(data) {
function constructYamlFloat (line 9378) | function constructYamlFloat(data) {
function representYamlFloat (line 9417) | function representYamlFloat(object, style) {
function isFloat (line 9450) | function isFloat(object) {
function isHexCode (line 9470) | function isHexCode(c) {
function isOctCode (line 9476) | function isOctCode(c) {
function isDecCode (line 9480) | function isDecCode(c) {
function resolveYamlInteger (line 9484) | function resolveYamlInteger(data) {
function constructYamlInteger (line 9566) | function constructYamlInteger(data) {
function isInteger (line 9609) | function isInteger(object) {
function resolveJavascriptFunction (line 9657) | function resolveJavascriptFunction(data) {
function constructJavascriptFunction (line 9677) | function constructJavascriptFunction(data) {
function representJavascriptFunction (line 9704) | function representJavascriptFunction(object /*, style*/) {
function isFunction (line 9708) | function isFunction(object) {
function resolveJavascriptRegExp (line 9725) | function resolveJavascriptRegExp(data) {
function constructJavascriptRegExp (line 9746) | function constructJavascriptRegExp(data) {
function representJavascriptRegExp (line 9760) | function representJavascriptRegExp(object /*, style*/) {
function isRegExp (line 9770) | function isRegExp(object) {
function resolveJavascriptUndefined (line 9787) | function resolveJavascriptUndefined() {
function constructJavascriptUndefined (line 9791) | function constructJavascriptUndefined() {
function representJavascriptUndefined (line 9796) | function representJavascriptUndefined() {
function isUndefined (line 9800) | function isUndefined(object) {
function resolveYamlMerge (line 9827) | function resolveYamlMerge(data) {
function resolveYamlNull (line 9841) | function resolveYamlNull(data) {
function constructYamlNull (line 9850) | function constructYamlNull() {
function isNull (line 9854) | function isNull(object) {
function resolveYamlOmap (line 9880) | function resolveYamlOmap(data) {
function constructYamlOmap (line 9908) | function constructYamlOmap(data) {
function resolveYamlPairs (line 9925) | function resolveYamlPairs(data) {
function constructYamlPairs (line 9948) | function constructYamlPairs(data) {
function resolveYamlSet (line 9990) | function resolveYamlSet(data) {
function constructYamlSet (line 10004) | function constructYamlSet(data) {
function resolveYamlTimestamp (line 10041) | function resolveYamlTimestamp(data) {
function constructYamlTimestamp (line 10047) | function constructYamlTimestamp(data) {
function representYamlTimestamp (line 10095) | function representYamlTimestamp(object /*, style*/) {
function indexOf (line 10142) | function indexOf(array, value, fromIndex) {
function last (line 10176) | function last(array) {
function lodash (line 10293) | function lodash(value) {
function includes (line 10451) | function includes(collection, target, fromIndex, guard) {
function map (line 10531) | function map(collection, iteratee, thisArg) {
function restParam (line 10652) | function restParam(func, start) {
function LazyWrapper (line 10696) | function LazyWrapper(value) {
function LodashWrapper (line 10723) | function LodashWrapper(value, chainAll, actions) {
function arrayCopy (line 10743) | function arrayCopy(source, array) {
function arrayEach (line 10766) | function arrayEach(array, iteratee) {
function arrayMap (line 10790) | function arrayMap(array, iteratee) {
function arraySome (line 10814) | function arraySome(array, predicate) {
function baseAssign (line 10841) | function baseAssign(object, source) {
function baseCallback (line 10866) | function baseCallback(func, thisArg, argCount) {
function baseClone (line 10962) | function baseClone(value, isDeep, customizer, key, object, stackA, stack...
function baseCopy (line 11030) | function baseCopy(source, props, object) {
function object (line 11057) | function object() {}
function baseFind (line 11101) | function baseFind(collection, predicate, eachFunc, retKey) {
function baseFindIndex (line 11125) | function baseFindIndex(array, predicate, fromRight) {
function baseForIn (line 11171) | function baseForIn(object, iteratee) {
function baseForOwn (line 11190) | function baseForOwn(object, iteratee) {
function baseGet (line 11209) | function baseGet(object, path, pathKey) {
function baseIndexOf (line 11240) | function baseIndexOf(array, value, fromIndex) {
function baseIsEqual (line 11275) | function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
function baseIsEqualDeep (line 11327) | function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, ...
function baseIsMatch (line 11406) | function baseIsMatch(object, matchData, customizer) {
function baseLodash (line 11452) | function baseLodash() {
function baseMap (line 11471) | function baseMap(collection, iteratee) {
function baseMatches (line 11495) | function baseMatches(source) {
function baseMatchesProperty (line 11535) | function baseMatchesProperty(path, srcValue) {
function baseProperty (line 11573) | function baseProperty(key) {
function basePropertyDeep (line 11592) | function basePropertyDeep(path) {
function baseSlice (line 11631) | function baseSlice(array, start, end) {
function baseToString (line 11664) | function baseToString(value) {
function baseValues (line 11681) | function baseValues(object, props) {
function binaryIndex (line 11713) | function binaryIndex(array, value, retHighest) {
function binaryIndexBy (line 11757) | function binaryIndexBy(array, value, iteratee, retHighest) {
function bindCallback (line 11807) | function bindCallback(func, thisArg, argCount) {
function bufferClone (line 11848) | function bufferClone(buffer) {
function composeArgs (line 11874) | function composeArgs(args, partials, holders) {
function composeArgsRight (line 11910) | function composeArgsRight(args, partials, holders) {
function createBaseEach (line 11947) | function createBaseEach(eachFunc, fromRight) {
function createBaseFor (line 11977) | function createBaseFor(fromRight) {
function createBindWrapper (line 12009) | function createBindWrapper(func, thisArg) {
function createCtorWrapper (line 12035) | function createCtorWrapper(Ctor) {
function createFind (line 12076) | function createFind(eachFunc, fromRight) {
function createForEach (line 12101) | function createForEach(arrayFunc, eachFunc) {
function createHybridWrapper (line 12152) | function createHybridWrapper(func, bitmask, thisArg, partials, holders, ...
function createPartialWrapper (line 12246) | function createPartialWrapper(func, bitmask, thisArg, partials) {
function createWrapper (line 12321) | function createWrapper(func, bitmask, thisArg, partials, holders, argPos...
function equalArrays (line 12380) | function equalArrays(array, other, equalFunc, customizer, isLoose, stack...
function equalByTag (line 12438) | function equalByTag(object, other, tag) {
function equalObjects (line 12489) | function equalObjects(object, other, equalFunc, customizer, isLoose, sta...
function getFuncName (line 12562) | function getFuncName(func) {
function getMatchData (line 12607) | function getMatchData(object) {
function getNative (line 12630) | function getNative(object, key) {
function indexOfNaN (line 12647) | function indexOfNaN(array, fromIndex, fromRight) {
function initCloneArray (line 12676) | function initCloneArray(array) {
function initCloneByTag (line 12742) | function initCloneByTag(object, tag, isDeep) {
function initCloneObject (line 12785) | function initCloneObject(object) {
function isArrayLike (line 12806) | function isArrayLike(value) {
function isIndex (line 12853) | function isIndex(value, length) {
function isIterateeCall (line 12875) | function isIterateeCall(value, index, object) {
function isKey (line 12907) | function isKey(value, object) {
function isLaziable (line 12934) | function isLaziable(func) {
function isLength (line 12966) | function isLength(value) {
function isObjectLike (line 12980) | function isObjectLike(value) {
function isStrictComparable (line 12997) | function isStrictComparable(value) {
function mergeData (line 13037) | function mergeData(data, source) {
function reorder (line 13131) | function reorder(array, indexes) {
function replaceHolders (line 13158) | function replaceHolders(array, placeholder) {
function shimKeys (line 13240) | function shimKeys(object) {
function toObject (line 13274) | function toObject(value) {
function toPath (line 13307) | function toPath(value) {
function wrapperClone (line 13332) | function wrapperClone(wrapper) {
function cloneDeep (line 13389) | function cloneDeep(value, customizer, thisArg) {
function isArguments (line 13426) | function isArguments(value) {
function isEmpty (line 13511) | function isEmpty(value) {
function isFunction (line 13555) | function isFunction(value) {
function isNative (line 13603) | function isNative(value) {
function isObject (line 13636) | function isObject(value) {
function isPlainObject (line 13697) | function isPlainObject(value) {
function isString (line 13758) | function isString(value) {
function isTypedArray (line 13834) | function isTypedArray(value) {
function isUndefined (line 13857) | function isUndefined(value) {
function keysIn (line 13991) | function keysIn(object) {
function pairs (line 14067) | function pairs(object) {
function values (line 14113) | function values(object) {
function identity (line 14233) | function identity(value) {
function noop (line 14254) | function noop() {
function property (line 14287) | function property(path) {
function flush (line 14405) | function flush() {
function runSingle (line 14429) | function runSingle(task, domain) {
function uncurryThis (line 14555) | function uncurryThis(f) {
function Type (line 14619) | function Type() { }
function isObject (line 14638) | function isObject(value) {
function isStopIteration (line 14645) | function isStopIteration(exception) {
function makeStackTraceLong (line 14667) | function makeStackTraceLong(error, promise) {
function filterStackString (line 14690) | function filterStackString(stackString) {
function isNodeFrame (line 14703) | function isNodeFrame(stackLine) {
function getFileNameAndLineNumber (line 14708) | function getFileNameAndLineNumber(stackLine) {
function isInternalFrame (line 14729) | function isInternalFrame(stackLine) {
function captureLine (line 14746) | function captureLine() {
function deprecate (line 14766) | function deprecate(callback, name, alternative) {
function Q (line 14785) | function Q(value) {
function defer (line 14829) | function defer() {
function promise (line 14970) | function promise(resolver) {
function race (line 15033) | function race(answerPs) {
function Promise (line 15062) | function Promise(descriptor, fallback, inspect) {
function _fulfilled (line 15126) | function _fulfilled(value) {
function _rejected (line 15134) | function _rejected(exception) {
function _progressed (line 15146) | function _progressed(value) {
function when (line 15232) | function when(value, fulfilled, rejected, progressed) {
function nearer (line 15264) | function nearer(value) {
function isPromise (line 15279) | function isPromise(object) {
function isPromiseAlike (line 15284) | function isPromiseAlike(object) {
function isPending (line 15293) | function isPending(object) {
function isFulfilled (line 15306) | function isFulfilled(object) {
function isRejected (line 15318) | function isRejected(object) {
function resetUnhandledRejections (line 15337) | function resetUnhandledRejections() {
function trackRejection (line 15346) | function trackRejection(promise, reason) {
function untrackRejection (line 15367) | function untrackRejection(promise) {
function reject (line 15409) | function reject(reason) {
function fulfill (line 15435) | function fulfill(value) {
function coerce (line 15474) | function coerce(promise) {
function master (line 15496) | function master(object) {
function spread (line 15517) | function spread(value, fulfilled, rejected) {
function async (line 15554) | function async(makeGenerator) {
function spawn (line 15611) | function spawn(makeGenerator) {
function _return (line 15641) | function _return(value) {
function promised (line 15661) | function promised(callback) {
function dispatch (line 15677) | function dispatch(object, op, args) {
function all (line 15855) | function all(promises) {
function any (line 15903) | function any(promises) {
function allResolved (line 15953) | function allResolved(promises) {
function allSettled (line 15972) | function allSettled(promises) {
function regardless (line 15987) | function regardless() {
function progress (line 16023) | function progress(object, progressed) {
function bound (line 16235) | function bound() {
function nodeify (line 16313) | function nodeify(object, nodeback) {
function noop (line 16371) | function noop(){}
function isHost (line 16384) | function isHost(obj) {
function isObject (line 16435) | function isObject(obj) {
function serialize (line 16447) | function serialize(obj) {
function pushEncodedKeyValuePair (line 16467) | function pushEncodedKeyValuePair(pairs, key, val) {
function parseString (line 16491) | function parseString(str) {
function parseHeader (line 16565) | function parseHeader(str) {
function isJSON (line 16594) | function isJSON(mime) {
function type (line 16606) | function type(str){
function params (line 16618) | function params(str){
function Response (line 16675) | function Response(req, options) {
function Request (line 16835) | function Request(method, url) {
function request (line 17411) | function request(method, url) {
function del (line 17470) | function del(url, fn){
function Emitter (line 17553) | function Emitter(obj) {
function mixin (line 17565) | function mixin(obj) {
function on (line 17600) | function on() {
FILE: js/ui.js
function getKeys (line 3) | function getKeys(obj){
function getParams (line 8) | function getParams(apis) {
function updateParams (line 44) | function updateParams(param){
function requestOutput (line 56) | function requestOutput(method,url,status){
function autoFill (line 63) | function autoFill(){
function executeAll (line 84) | function executeAll(apis){
function buildForm (line 105) | function buildForm(parentId, elementTag, elementId,type) {
function init (line 126) | function init(json){
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,629K chars).
[
{
"path": "LICENSE",
"chars": 1519,
"preview": "BSD 3-Clause License\n\nCopyright (c) 2018, Rhino Security Labs\nAll rights reserved.\n\nRedistribution and use in source and"
},
{
"path": "README.md",
"chars": 1033,
"preview": "# Swagger-EZ\nA tool geared towards pentesting APIs using OpenAPI definitions.\n\nWe have a version hosted here: https://rh"
},
{
"path": "css/layout.css",
"chars": 1640,
"preview": "* {box-sizing: border-box;}\n\nbody {\n margin: 0;\n font-family: Arial, Helvetica, sans-serif;\n}\n\n.topnav {\n overflow: h"
},
{
"path": "index.html",
"chars": 1652,
"preview": "<html>\n<head>\n<title>\nSwagger-EZ\n</title>\n \t<link rel = \"stylesheet\" type = \"text/css\" href = \"css/layout.css\" />\n\t<link"
},
{
"path": "js/swagger-client.js",
"chars": 1597519,
"preview": "/**\n * swagger-client - swagger-client is a javascript client for use with swaggering APIs.\n * @version v2.1.13\n * @link"
},
{
"path": "js/ui.js",
"chars": 5293,
"preview": "var PARAMS = {};\n\nfunction getKeys(obj){\n\t//return a list of keys for an object\n\treturn Object.keys(obj);\n}\n\nfunction ge"
}
]
About this extraction
This page contains the full source code of the RhinoSecurityLabs/Swagger-EZ GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (1.5 MB), approximately 835.1k tokens, and a symbol index with 342 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.