diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..441b400726b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +* text eol=lf + +dist/**/* binary \ No newline at end of file diff --git a/.gitignore b/.gitignore index d6ef64143d4..1f2db9b5320 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ swagger-ui.sublime-workspace .idea .project node_modules/* +/nbproject/private/ \ No newline at end of file diff --git a/.jshintignore b/.jshintignore new file mode 100644 index 00000000000..66f42480d19 --- /dev/null +++ b/.jshintignore @@ -0,0 +1,5 @@ +node_modules +src/main/javascript/doc.js +dist +lib +.log \ No newline at end of file diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 00000000000..9a1b0c8b523 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,39 @@ +{ + "node": true, + "browser": true, + "esnext": true, + "bitwise": true, + "curly": true, + "eqeqeq": true, + "immed": true, + "indent": 2, + "latedef": false, + "newcap": true, + "noarg": true, + "quotmark": "single", + "regexp": true, + "undef": true, + "unused": true, + "strict": true, + "trailing": true, + "smarttabs": true, + "validthis": true, + "globals": { + + // Libraries + "_": false, + "$": false, + "Backbone": false, + "Handlebars": false, + "jQuery": false, + "marked": false, + "SwaggerClient": false, + "hljs": false, + "SwaggerUi": false, + "define": false, + + // Global object + // TODO: remove these + "Docs": false + } +} \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index e275ba28c88..37245c73e19 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,10 @@ +sudo: false language: node_js node_js: - '0.10' + - '0.12' install: - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start - - npm install \ No newline at end of file + - npm i -g jshint + - npm install diff --git a/README.md b/README.md index 8f447bd742d..342416255a4 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,9 @@ Swagger UI Version | Release Date | Swagger Spec compatibility | Notes | Status ### Download You can use the swagger-ui code AS-IS! No need to build or recompile--just clone this repo and use the pre-built files in the `dist` folder. If you like swagger-ui as-is, stop here. +##### Browser support +Swagger UI works in all evergreen desktop browsers (Chrome, Safari, Firefox). Internet Explorer support is version 8 (IE8) and above. + ### Build You can rebuild swagger-ui on your own to tweak it or just so you can say you did. To do so, follow these steps: @@ -57,24 +60,24 @@ Once you open the Swagger UI, it will load the [Swagger Petstore](http://petstor You may choose to customize Swagger UI for your organization. Here is an overview of whats in its various directories: - dist: Contains a distribution which you can deploy on a server or load from your local machine. +- dist/lang: The swagger localisation - lib: Contains javascript dependencies which swagger-ui depends on - node_modules: Contains node modules which swagger-ui uses for its development. - src -- src/main/coffeescript: main code in CoffeeScript - src/main/templates: [handlebars](http://handlebarsjs.com/) templates used to render swagger-ui - src/main/html: the html files, some images and css -- src/main/javascript: some legacy javascript referenced by CoffeeScript code +- src/main/javascript: main code ### SwaggerUi To use swagger-ui you should take a look at the [source of swagger-ui html page](https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html) and customize it. This basically requires you to instantiate a SwaggerUi object and call load() on it as below: ```javascript - window.swaggerUi = new SwaggerUi({ + var swaggerUi = new SwaggerUi({ url:"http://petstore.swagger.io/v2/swagger.json", dom_id:"swagger-ui-container" }); - window.swaggerUi.load(); + swaggerUi.load(); ``` ##### Parameters @@ -87,11 +90,13 @@ validatorUrl | By default, Swagger-UI attempts to validate specs against swagger dom_id | The id of a dom element inside which SwaggerUi will put the user interface for swagger. booleanValues | SwaggerUI renders boolean data types as a dropdown. By default it provides a 'true' and 'false' string as the possible choices. You can use this parameter to change the values in dropdown to be something else, for example 0 and 1 by setting booleanValues to new Array(0, 1). docExpansion | Controls how the API listing is displayed. It can be set to 'none' (default), 'list' (shows operations for each resource), or 'full' (fully expanded: shows operations and their details). -sorter | Apply a sort to the API list. It can be 'alpha' (sort paths alphanumerically) or 'method' (sort operations by HTTP method). Default is the order returned by the server unchanged. +apisSorter | Apply a sort to the API/tags list. It can be 'alpha' (sort by name) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged. +operationsSorter | Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged. onComplete | This is a callback function parameter which can be passed to be notified of when SwaggerUI has completed rendering successfully. onFailure | This is a callback function parameter which can be passed to be notified of when SwaggerUI encountered a failure was unable to render. highlightSizeThreshold | Any size response below this threshold will be highlighted syntactically, attempting to highlight large responses can lead to browser hangs, not including a threshold will default to highlight all returned responses. supportedSubmitMethods | An array of of the HTTP operations that will have the 'Try it out!` option. An empty array disables all operations. This does not filter the operations from the display. +oauth2RedirectUrl | OAuth redirect URL * All other parameters are explained in greater detail below @@ -104,11 +109,11 @@ swagger-ui supports invocation of all HTTP methods APIs including GET, PUT, POST Header params are supported through a pluggable mechanism in [swagger-js](https://github.com/swagger-api/swagger-js). You can see the [index.html](https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html) for a sample of how to dynamically set headers: ```js -// add a new ApiKeyAuthorization when the api-key changes in the ui. +// add a new SwaggerClient.ApiKeyAuthorization when the api-key changes in the ui. $('#input_apiKey').change(function() { var key = $('#input_apiKey')[0].value; if(key && key.trim() != "") { - window.authorizations.add("key", new ApiKeyAuthorization("api_key", key, "header")); + swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("api_key", key, "header")); } }) ``` @@ -119,11 +124,36 @@ This will add header `api_key` with value `key` on every call to the server. Yo If you have some header parameters which you need to send with every request, use the headers as below: ```js -window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "XXXX", "header")); +swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "XXXX", "header")); ``` Note! You can pass multiple header params on a single request, just use unique names for them (`key` is used in the above example). +### Localization and translation +The localization files are in the dist/lang directory. + +To enable translation you should append next two lines in your Swagger's index.html (or another entry point you use) +```html + + +``` +The first line script is a translator and the second one is your language lexemes. + +If you wish to append support for new language you just need to create lang/your_lang.js and fill it like it's done in existing files. + +To append new lexemex for translation you shoul do two things: +1. Add lexeme into the language file. + Example of new line: "new sentence":"translation of new sentence". +2. Mark this lexeme in source html with attribute data-sw-translate. + Example of changed source: +```html + new sentence + or +``` +. + +At this moment only inner html, title-attribute and value-attribute are going to be translated. + ## CORS Support CORS is a technique to prevent websites from doing bad things with your personal data. Most browsers + javascript toolkits not only support CORS but enforce it, which has implications for your API server which supports Swagger. @@ -191,7 +221,8 @@ Create your own fork of [swagger-api/swagger-ui](https://github.com/swagger-api/ To share your changes, [submit a pull request](https://github.com/swagger-api/swagger-ui/pull/new/master). -Since the javascript files are compiled from coffeescript, please submit changes in the *.coffee files! We have to reject changes only in the .js files as they will be lost on each build of the ui. +## Change Log +Plsee see [releases](https://github.com/swagger-api/swagger-ui/releases) for change log. ## License diff --git a/bower.json b/bower.json new file mode 100644 index 00000000000..4808bbafd6c --- /dev/null +++ b/bower.json @@ -0,0 +1,26 @@ +{ + "name": "swagger-ui", + "main": "dist/index.html", + "version": "2.1.8-M1", + "authors": [ + "Mohsen Azimi " + ], + "description": "Swagger UI", + "moduleType": [ + "globals" + ], + "keywords": [ + "Swagger", + "API" + ], + "license": "Copyright 2015 Reverb Technologies, Inc.", + "homepage": "http://swagger.io", + "private": true, + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/dist/css/print.css b/dist/css/print.css new file mode 100644 index 00000000000..b4fc18036ef --- /dev/null +++ b/dist/css/print.css @@ -0,0 +1,1155 @@ +/* Original style from softwaremaniacs.org (c) Ivan Sagalaev */ +.swagger-section pre code { + display: block; + padding: 0.5em; + background: #F0F0F0; +} +.swagger-section pre code, +.swagger-section pre .subst, +.swagger-section pre .tag .title, +.swagger-section pre .lisp .title, +.swagger-section pre .clojure .built_in, +.swagger-section pre .nginx .title { + color: black; +} +.swagger-section pre .string, +.swagger-section pre .title, +.swagger-section pre .constant, +.swagger-section pre .parent, +.swagger-section pre .tag .value, +.swagger-section pre .rules .value, +.swagger-section pre .rules .value .number, +.swagger-section pre .preprocessor, +.swagger-section pre .ruby .symbol, +.swagger-section pre .ruby .symbol .string, +.swagger-section pre .aggregate, +.swagger-section pre .template_tag, +.swagger-section pre .django .variable, +.swagger-section pre .smalltalk .class, +.swagger-section pre .addition, +.swagger-section pre .flow, +.swagger-section pre .stream, +.swagger-section pre .bash .variable, +.swagger-section pre .apache .tag, +.swagger-section pre .apache .cbracket, +.swagger-section pre .tex .command, +.swagger-section pre .tex .special, +.swagger-section pre .erlang_repl .function_or_atom, +.swagger-section pre .markdown .header { + color: #800; +} +.swagger-section pre .comment, +.swagger-section pre .annotation, +.swagger-section pre .template_comment, +.swagger-section pre .diff .header, +.swagger-section pre .chunk, +.swagger-section pre .markdown .blockquote { + color: #888; +} +.swagger-section pre .number, +.swagger-section pre .date, +.swagger-section pre .regexp, +.swagger-section pre .literal, +.swagger-section pre .smalltalk .symbol, +.swagger-section pre .smalltalk .char, +.swagger-section pre .go .constant, +.swagger-section pre .change, +.swagger-section pre .markdown .bullet, +.swagger-section pre .markdown .link_url { + color: #080; +} +.swagger-section pre .label, +.swagger-section pre .javadoc, +.swagger-section pre .ruby .string, +.swagger-section pre .decorator, +.swagger-section pre .filter .argument, +.swagger-section pre .localvars, +.swagger-section pre .array, +.swagger-section pre .attr_selector, +.swagger-section pre .important, +.swagger-section pre .pseudo, +.swagger-section pre .pi, +.swagger-section pre .doctype, +.swagger-section pre .deletion, +.swagger-section pre .envvar, +.swagger-section pre .shebang, +.swagger-section pre .apache .sqbracket, +.swagger-section pre .nginx .built_in, +.swagger-section pre .tex .formula, +.swagger-section pre .erlang_repl .reserved, +.swagger-section pre .prompt, +.swagger-section pre .markdown .link_label, +.swagger-section pre .vhdl .attribute, +.swagger-section pre .clojure .attribute, +.swagger-section pre .coffeescript .property { + color: #8888ff; +} +.swagger-section pre .keyword, +.swagger-section pre .id, +.swagger-section pre .phpdoc, +.swagger-section pre .title, +.swagger-section pre .built_in, +.swagger-section pre .aggregate, +.swagger-section pre .css .tag, +.swagger-section pre .javadoctag, +.swagger-section pre .phpdoc, +.swagger-section pre .yardoctag, +.swagger-section pre .smalltalk .class, +.swagger-section pre .winutils, +.swagger-section pre .bash .variable, +.swagger-section pre .apache .tag, +.swagger-section pre .go .typename, +.swagger-section pre .tex .command, +.swagger-section pre .markdown .strong, +.swagger-section pre .request, +.swagger-section pre .status { + font-weight: bold; +} +.swagger-section pre .markdown .emphasis { + font-style: italic; +} +.swagger-section pre .nginx .built_in { + font-weight: normal; +} +.swagger-section pre .coffeescript .javascript, +.swagger-section pre .javascript .xml, +.swagger-section pre .tex .formula, +.swagger-section pre .xml .javascript, +.swagger-section pre .xml .vbscript, +.swagger-section pre .xml .css, +.swagger-section pre .xml .cdata { + opacity: 0.5; +} +.swagger-section .swagger-ui-wrap { + line-height: 1; + font-family: "Droid Sans", sans-serif; + max-width: 960px; + margin-left: auto; + margin-right: auto; +} +.swagger-section .swagger-ui-wrap b, +.swagger-section .swagger-ui-wrap strong { + font-family: "Droid Sans", sans-serif; + font-weight: bold; +} +.swagger-section .swagger-ui-wrap q, +.swagger-section .swagger-ui-wrap blockquote { + quotes: none; +} +.swagger-section .swagger-ui-wrap p { + line-height: 1.4em; + padding: 0 0 10px; + color: #333333; +} +.swagger-section .swagger-ui-wrap q:before, +.swagger-section .swagger-ui-wrap q:after, +.swagger-section .swagger-ui-wrap blockquote:before, +.swagger-section .swagger-ui-wrap blockquote:after { + content: none; +} +.swagger-section .swagger-ui-wrap .heading_with_menu h1, +.swagger-section .swagger-ui-wrap .heading_with_menu h2, +.swagger-section .swagger-ui-wrap .heading_with_menu h3, +.swagger-section .swagger-ui-wrap .heading_with_menu h4, +.swagger-section .swagger-ui-wrap .heading_with_menu h5, +.swagger-section .swagger-ui-wrap .heading_with_menu h6 { + display: block; + clear: none; + float: left; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + -ms-box-sizing: border-box; + box-sizing: border-box; + width: 60%; +} +.swagger-section .swagger-ui-wrap table { + border-collapse: collapse; + border-spacing: 0; +} +.swagger-section .swagger-ui-wrap table thead tr th { + padding: 5px; + font-size: 0.9em; + color: #666666; + border-bottom: 1px solid #999999; +} +.swagger-section .swagger-ui-wrap table tbody tr:last-child td { + border-bottom: none; +} +.swagger-section .swagger-ui-wrap table tbody tr.offset { + background-color: #f0f0f0; +} +.swagger-section .swagger-ui-wrap table tbody tr td { + padding: 6px; + font-size: 0.9em; + border-bottom: 1px solid #cccccc; + vertical-align: top; + line-height: 1.3em; +} +.swagger-section .swagger-ui-wrap ol { + margin: 0px 0 10px; + padding: 0 0 0 18px; + list-style-type: decimal; +} +.swagger-section .swagger-ui-wrap ol li { + padding: 5px 0px; + font-size: 0.9em; + color: #333333; +} +.swagger-section .swagger-ui-wrap ol, +.swagger-section .swagger-ui-wrap ul { + list-style: none; +} +.swagger-section .swagger-ui-wrap h1 a, +.swagger-section .swagger-ui-wrap h2 a, +.swagger-section .swagger-ui-wrap h3 a, +.swagger-section .swagger-ui-wrap h4 a, +.swagger-section .swagger-ui-wrap h5 a, +.swagger-section .swagger-ui-wrap h6 a { + text-decoration: none; +} +.swagger-section .swagger-ui-wrap h1 a:hover, +.swagger-section .swagger-ui-wrap h2 a:hover, +.swagger-section .swagger-ui-wrap h3 a:hover, +.swagger-section .swagger-ui-wrap h4 a:hover, +.swagger-section .swagger-ui-wrap h5 a:hover, +.swagger-section .swagger-ui-wrap h6 a:hover { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap h1 span.divider, +.swagger-section .swagger-ui-wrap h2 span.divider, +.swagger-section .swagger-ui-wrap h3 span.divider, +.swagger-section .swagger-ui-wrap h4 span.divider, +.swagger-section .swagger-ui-wrap h5 span.divider, +.swagger-section .swagger-ui-wrap h6 span.divider { + color: #aaaaaa; +} +.swagger-section .swagger-ui-wrap a { + color: #547f00; +} +.swagger-section .swagger-ui-wrap a img { + border: none; +} +.swagger-section .swagger-ui-wrap article, +.swagger-section .swagger-ui-wrap aside, +.swagger-section .swagger-ui-wrap details, +.swagger-section .swagger-ui-wrap figcaption, +.swagger-section .swagger-ui-wrap figure, +.swagger-section .swagger-ui-wrap footer, +.swagger-section .swagger-ui-wrap header, +.swagger-section .swagger-ui-wrap hgroup, +.swagger-section .swagger-ui-wrap menu, +.swagger-section .swagger-ui-wrap nav, +.swagger-section .swagger-ui-wrap section, +.swagger-section .swagger-ui-wrap summary { + display: block; +} +.swagger-section .swagger-ui-wrap pre { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + background-color: #fcf6db; + border: 1px solid #e5e0c6; + padding: 10px; +} +.swagger-section .swagger-ui-wrap pre code { + line-height: 1.6em; + background: none; +} +.swagger-section .swagger-ui-wrap .content > .content-type > div > label { + clear: both; + display: block; + color: #0F6AB4; + font-size: 1.1em; + margin: 0; + padding: 15px 0 5px; +} +.swagger-section .swagger-ui-wrap .content pre { + font-size: 12px; + margin-top: 5px; + padding: 5px; +} +.swagger-section .swagger-ui-wrap .icon-btn { + cursor: pointer; +} +.swagger-section .swagger-ui-wrap .info_title { + padding-bottom: 10px; + font-weight: bold; + font-size: 25px; +} +.swagger-section .swagger-ui-wrap p.big, +.swagger-section .swagger-ui-wrap div.big p { + font-size: 1em; + margin-bottom: 10px; +} +.swagger-section .swagger-ui-wrap form.fullwidth ol li.string input, +.swagger-section .swagger-ui-wrap form.fullwidth ol li.url input, +.swagger-section .swagger-ui-wrap form.fullwidth ol li.text textarea, +.swagger-section .swagger-ui-wrap form.fullwidth ol li.numeric input { + width: 500px !important; +} +.swagger-section .swagger-ui-wrap .info_license { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_tos { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .message-fail { + color: #cc0000; +} +.swagger-section .swagger-ui-wrap .info_url { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_email { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_name { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_description { + padding-bottom: 10px; + font-size: 15px; +} +.swagger-section .swagger-ui-wrap .markdown ol li, +.swagger-section .swagger-ui-wrap .markdown ul li { + padding: 3px 0px; + line-height: 1.4em; + color: #333333; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input { + display: block; + padding: 4px; + width: auto; + clear: both; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input.title, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input.title, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input.title { + font-size: 1.3em; +} +.swagger-section .swagger-ui-wrap table.fullwidth { + width: 100%; +} +.swagger-section .swagger-ui-wrap .model-signature { + font-family: "Droid Sans", sans-serif; + font-size: 1em; + line-height: 1.5em; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-nav a { + text-decoration: none; + color: #AAA; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-nav a:hover { + text-decoration: underline; + color: black; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-nav .selected { + color: black; + text-decoration: none; +} +.swagger-section .swagger-ui-wrap .model-signature .propType { + color: #5555aa; +} +.swagger-section .swagger-ui-wrap .model-signature pre:hover { + background-color: #ffffdd; +} +.swagger-section .swagger-ui-wrap .model-signature pre { + font-size: .85em; + line-height: 1.2em; + overflow: auto; + max-height: 200px; + cursor: pointer; +} +.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav { + display: block; + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li:last-child { + padding-right: 0; + border-right: none; +} +.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li { + float: left; + margin: 0 5px 5px 0; + padding: 2px 5px 2px 0; + border-right: 1px solid #ddd; +} +.swagger-section .swagger-ui-wrap .model-signature .propOpt { + color: #555; +} +.swagger-section .swagger-ui-wrap .model-signature .snippet small { + font-size: 0.75em; +} +.swagger-section .swagger-ui-wrap .model-signature .propOptKey { + font-style: italic; +} +.swagger-section .swagger-ui-wrap .model-signature .description .strong { + font-weight: bold; + color: #000; + font-size: .9em; +} +.swagger-section .swagger-ui-wrap .model-signature .description div { + font-size: 0.9em; + line-height: 1.5em; + margin-left: 1em; +} +.swagger-section .swagger-ui-wrap .model-signature .description .stronger { + font-weight: bold; + color: #000; +} +.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper { + border-spacing: 0; + position: absolute; + background-color: #ffffff; + border: 1px solid #bbbbbb; + display: none; + font-size: 11px; + max-width: 400px; + line-height: 30px; + color: black; + padding: 5px; + margin-left: 10px; +} +.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper th { + text-align: center; + background-color: #eeeeee; + border: 1px solid #bbbbbb; + font-size: 11px; + color: #666666; + font-weight: bold; + padding: 5px; + line-height: 15px; +} +.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper .optionName { + font-weight: bold; +} +.swagger-section .swagger-ui-wrap .model-signature .propName { + font-weight: bold; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-container { + clear: both; +} +.swagger-section .swagger-ui-wrap .body-textarea { + width: 300px; + height: 100px; + border: 1px solid #aaa; +} +.swagger-section .swagger-ui-wrap .markdown p code, +.swagger-section .swagger-ui-wrap .markdown li code { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + background-color: #f0f0f0; + color: black; + padding: 1px 3px; +} +.swagger-section .swagger-ui-wrap .required { + font-weight: bold; +} +.swagger-section .swagger-ui-wrap input.parameter { + width: 300px; + border: 1px solid #aaa; +} +.swagger-section .swagger-ui-wrap h1 { + color: black; + font-size: 1.5em; + line-height: 1.3em; + padding: 10px 0 10px 0; + font-family: "Droid Sans", sans-serif; + font-weight: bold; +} +.swagger-section .swagger-ui-wrap .heading_with_menu { + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap .heading_with_menu ul { + display: block; + clear: none; + float: right; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + -ms-box-sizing: border-box; + box-sizing: border-box; + margin-top: 10px; +} +.swagger-section .swagger-ui-wrap h2 { + color: black; + font-size: 1.3em; + padding: 10px 0 10px 0; +} +.swagger-section .swagger-ui-wrap h2 a { + color: black; +} +.swagger-section .swagger-ui-wrap h2 span.sub { + font-size: 0.7em; + color: #999999; + font-style: italic; +} +.swagger-section .swagger-ui-wrap h2 span.sub a { + color: #777777; +} +.swagger-section .swagger-ui-wrap span.weak { + color: #666666; +} +.swagger-section .swagger-ui-wrap .message-success { + color: #89BF04; +} +.swagger-section .swagger-ui-wrap caption, +.swagger-section .swagger-ui-wrap th, +.swagger-section .swagger-ui-wrap td { + text-align: left; + font-weight: normal; + vertical-align: middle; +} +.swagger-section .swagger-ui-wrap .code { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.text textarea { + font-family: "Droid Sans", sans-serif; + height: 250px; + padding: 4px; + display: block; + clear: both; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.select select { + display: block; + clear: both; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean { + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean label { + display: block; + float: left; + clear: none; + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean input { + display: block; + float: left; + clear: none; + margin: 0 5px 0 0; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.required label { + color: black; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label { + display: block; + clear: both; + width: auto; + padding: 0 0 3px; + color: #666666; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label abbr { + padding-left: 3px; + color: #888888; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li p.inline-hints { + margin-left: 0; + font-style: italic; + font-size: 0.9em; + margin: 0; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.buttons { + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap span.blank, +.swagger-section .swagger-ui-wrap span.empty { + color: #888888; + font-style: italic; +} +.swagger-section .swagger-ui-wrap .markdown h3 { + color: #547f00; +} +.swagger-section .swagger-ui-wrap .markdown h4 { + color: #666666; +} +.swagger-section .swagger-ui-wrap .markdown pre { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + background-color: #fcf6db; + border: 1px solid #e5e0c6; + padding: 10px; + margin: 0 0 10px 0; +} +.swagger-section .swagger-ui-wrap .markdown pre code { + line-height: 1.6em; +} +.swagger-section .swagger-ui-wrap div.gist { + margin: 20px 0 25px 0 !important; +} +.swagger-section .swagger-ui-wrap ul#resources { + font-family: "Droid Sans", sans-serif; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource { + border-bottom: 1px solid #dddddd; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading h2 a, +.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading h2 a { + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading ul.options li a, +.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading ul.options li a { + color: #555555; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource:last-child { + border-bottom: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading { + border: 1px solid transparent; + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options { + overflow: hidden; + padding: 0; + display: block; + clear: none; + float: right; + margin: 14px 10px 0 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li { + float: left; + clear: none; + margin: 0; + padding: 2px 10px; + border-right: 1px solid #dddddd; + color: #666666; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a { + color: #aaaaaa; + text-decoration: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover { + text-decoration: underline; + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:active, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a.active { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.last { + padding-right: 0; + border-right: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 { + color: #999999; + padding-left: 0; + display: block; + clear: none; + float: left; + font-family: "Droid Sans", sans-serif; + font-weight: bold; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a { + color: #999999; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a:hover { + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation { + float: none; + clear: both; + overflow: hidden; + display: block; + margin: 0 0 10px; + padding: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading { + float: none; + clear: both; + overflow: hidden; + display: block; + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 { + display: block; + clear: none; + float: left; + width: auto; + margin: 0; + padding: 0; + line-height: 1.1em; + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path { + padding-left: 10px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a { + color: black; + text-decoration: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a:hover { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.http_method a { + text-transform: uppercase; + text-decoration: none; + color: white; + display: inline-block; + width: 50px; + font-size: 0.7em; + text-align: center; + padding: 7px 0 4px; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + -o-border-radius: 2px; + -ms-border-radius: 2px; + -khtml-border-radius: 2px; + border-radius: 2px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span { + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options { + overflow: hidden; + padding: 0; + display: block; + clear: none; + float: right; + margin: 6px 10px 0 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li { + float: left; + clear: none; + margin: 0; + padding: 2px 10px; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a { + text-decoration: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li.access { + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content { + border-top: none; + padding: 10px; + -moz-border-radius-bottomleft: 6px; + -webkit-border-bottom-left-radius: 6px; + -o-border-bottom-left-radius: 6px; + -ms-border-bottom-left-radius: 6px; + -khtml-border-bottom-left-radius: 6px; + border-bottom-left-radius: 6px; + -moz-border-radius-bottomright: 6px; + -webkit-border-bottom-right-radius: 6px; + -o-border-bottom-right-radius: 6px; + -ms-border-bottom-right-radius: 6px; + -khtml-border-bottom-right-radius: 6px; + border-bottom-right-radius: 6px; + margin: 0 0 20px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content h4 { + font-size: 1.1em; + margin: 0; + padding: 15px 0 5px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header { + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header a { + padding: 4px 0 0 10px; + display: inline-block; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header input.submit { + display: block; + clear: none; + float: left; + padding: 6px 8px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header span.response_throbber { + background-image: url('../images/throbber.gif'); + width: 128px; + height: 16px; + display: block; + clear: none; + float: right; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content form input[type='text'].error { + outline: 2px solid black; + outline-color: #cc0000; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.response div.block pre { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + padding: 10px; + font-size: 0.9em; + max-height: 400px; + overflow-y: auto; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading { + background-color: #f9f2e9; + border: 1px solid #f0e0ca; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading h3 span.http_method a { + background-color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #f0e0ca; + color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li a { + color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content { + background-color: #faf5ee; + border: 1px solid #f0e0ca; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content h4 { + color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content div.sandbox_header a { + color: #dcb67f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading { + background-color: #fcffcd; + border: 1px solid black; + border-color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading h3 span.http_method a { + text-transform: uppercase; + background-color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #ffd20f; + color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li a { + color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content { + background-color: #fcffcd; + border: 1px solid black; + border-color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content h4 { + color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content div.sandbox_header a { + color: #6fc992; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading { + background-color: #f5e8e8; + border: 1px solid #e8c6c7; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading h3 span.http_method a { + text-transform: uppercase; + background-color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #e8c6c7; + color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li a { + color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content { + background-color: #f7eded; + border: 1px solid #e8c6c7; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content h4 { + color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content div.sandbox_header a { + color: #c8787a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading { + background-color: #e7f6ec; + border: 1px solid #c3e8d1; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading h3 span.http_method a { + background-color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #c3e8d1; + color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li a { + color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content { + background-color: #ebf7f0; + border: 1px solid #c3e8d1; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content h4 { + color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content div.sandbox_header a { + color: #6fc992; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading { + background-color: #FCE9E3; + border: 1px solid #F5D5C3; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading h3 span.http_method a { + background-color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #f0cecb; + color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li a { + color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content { + background-color: #faf0ef; + border: 1px solid #f0cecb; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content h4 { + color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content div.sandbox_header a { + color: #dcb67f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading { + background-color: #e7f0f7; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading h3 span.http_method a { + background-color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #c3d9ec; + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li a { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content { + background-color: #ebf3f9; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content h4 { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content div.sandbox_header a { + color: #6fa5d2; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading { + background-color: #e7f0f7; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading h3 span.http_method a { + background-color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #c3d9ec; + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li a { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content { + background-color: #ebf3f9; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content h4 { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content div.sandbox_header a { + color: #6fa5d2; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content { + border-top: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li.last { + padding-right: 0; + border-right: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:hover, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:active, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a.active { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap p#colophon { + margin: 0 15px 40px 15px; + padding: 10px 0; + font-size: 0.8em; + border-top: 1px solid #dddddd; + font-family: "Droid Sans", sans-serif; + color: #999999; + font-style: italic; +} +.swagger-section .swagger-ui-wrap p#colophon a { + text-decoration: none; + color: #547f00; +} +.swagger-section .swagger-ui-wrap h3 { + color: black; + font-size: 1.1em; + padding: 10px 0 10px 0; +} +.swagger-section .swagger-ui-wrap .markdown ol, +.swagger-section .swagger-ui-wrap .markdown ul { + font-family: "Droid Sans", sans-serif; + margin: 5px 0 10px; + padding: 0 0 0 18px; + list-style-type: disc; +} +.swagger-section .swagger-ui-wrap form.form_box { + background-color: #ebf3f9; + border: 1px solid #c3d9ec; + padding: 10px; +} +.swagger-section .swagger-ui-wrap form.form_box label { + color: #0f6ab4 !important; +} +.swagger-section .swagger-ui-wrap form.form_box input[type=submit] { + display: block; + padding: 10px; +} +.swagger-section .swagger-ui-wrap form.form_box p.weak { + font-size: 0.8em; +} +.swagger-section .swagger-ui-wrap form.form_box p { + font-size: 0.9em; + padding: 0 0 15px; + color: #7e7b6d; +} +.swagger-section .swagger-ui-wrap form.form_box p a { + color: #646257; +} +.swagger-section .swagger-ui-wrap form.form_box p strong { + color: black; +} +.swagger-section .title { + font-style: bold; +} +.swagger-section .secondary_form { + display: none; +} +.swagger-section .main_image { + display: block; + margin-left: auto; + margin-right: auto; +} +.swagger-section .oauth_body { + margin-left: 100px; + margin-right: 100px; +} +.swagger-section .oauth_submit { + text-align: center; +} +.swagger-section .api-popup-dialog { + z-index: 10000; + position: absolute; + width: 500px; + background: #FFF; + padding: 20px; + border: 1px solid #ccc; + border-radius: 5px; + display: none; + font-size: 13px; + color: #777; +} +.swagger-section .api-popup-dialog .api-popup-title { + font-size: 24px; + padding: 10px 0; +} +.swagger-section .api-popup-dialog .api-popup-title { + font-size: 24px; + padding: 10px 0; +} +.swagger-section .api-popup-dialog p.error-msg { + padding-left: 5px; + padding-bottom: 5px; +} +.swagger-section .api-popup-dialog button.api-popup-authbtn { + height: 30px; +} +.swagger-section .api-popup-dialog button.api-popup-cancel { + height: 30px; +} +.swagger-section .api-popup-scopes { + padding: 10px 20px; +} +.swagger-section .api-popup-scopes li { + padding: 5px 0; + line-height: 20px; +} +.swagger-section .api-popup-scopes .api-scope-desc { + padding-left: 20px; + font-style: italic; +} +.swagger-section .api-popup-scopes li input { + position: relative; + top: 2px; +} +.swagger-section .api-popup-actions { + padding-top: 10px; +} +#header { + display: none; +} +.swagger-section .swagger-ui-wrap .model-signature pre { + max-height: none; +} +.swagger-section .swagger-ui-wrap .body-textarea { + width: 100px; +} +.swagger-section .swagger-ui-wrap input.parameter { + width: 100px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options { + display: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints { + display: block !important; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content { + display: block !important; +} diff --git a/dist/fonts/droid-sans-v6-latin-700.eot b/dist/fonts/droid-sans-v6-latin-700.eot index 2250b71a3cc..d8524983ad8 100644 Binary files a/dist/fonts/droid-sans-v6-latin-700.eot and b/dist/fonts/droid-sans-v6-latin-700.eot differ diff --git a/dist/fonts/droid-sans-v6-latin-700.ttf b/dist/fonts/droid-sans-v6-latin-700.ttf index 523cb92d512..15896c441fd 100644 Binary files a/dist/fonts/droid-sans-v6-latin-700.ttf and b/dist/fonts/droid-sans-v6-latin-700.ttf differ diff --git a/dist/fonts/droid-sans-v6-latin-regular.ttf b/dist/fonts/droid-sans-v6-latin-regular.ttf index 76aede27f9d..fb8cea662b2 100644 Binary files a/dist/fonts/droid-sans-v6-latin-regular.ttf and b/dist/fonts/droid-sans-v6-latin-regular.ttf differ diff --git a/dist/images/explorer_icons.png b/dist/images/explorer_icons.png index ed9d2fffb64..91549877df4 100644 Binary files a/dist/images/explorer_icons.png and b/dist/images/explorer_icons.png differ diff --git a/dist/images/favicon-16x16.png b/dist/images/favicon-16x16.png new file mode 100755 index 00000000000..b8b453f50ae Binary files /dev/null and b/dist/images/favicon-16x16.png differ diff --git a/dist/images/favicon-32x32.png b/dist/images/favicon-32x32.png new file mode 100755 index 00000000000..6fd2bfbeb0c Binary files /dev/null and b/dist/images/favicon-32x32.png differ diff --git a/dist/images/favicon.ico b/dist/images/favicon.ico new file mode 100755 index 00000000000..8b60bcf06a7 Binary files /dev/null and b/dist/images/favicon.ico differ diff --git a/dist/images/logo_small.png b/dist/images/logo_small.png index 5496a65579a..3e73cdee405 100644 Binary files a/dist/images/logo_small.png and b/dist/images/logo_small.png differ diff --git a/dist/images/pet_store_api.png b/dist/images/pet_store_api.png index f9f9cd4aeb3..0d51abceb74 100644 Binary files a/dist/images/pet_store_api.png and b/dist/images/pet_store_api.png differ diff --git a/dist/images/wordnik_api.png b/dist/images/wordnik_api.png index dca4f1455ac..5c15755c541 100644 Binary files a/dist/images/wordnik_api.png and b/dist/images/wordnik_api.png differ diff --git a/dist/index.html b/dist/index.html index 8ce4d1d9055..10a0d9021f5 100644 --- a/dist/index.html +++ b/dist/index.html @@ -1,98 +1,101 @@ - - - - Swagger UI - - - - - - - - - - - - - - - - - - - - - - - - - - -
 
-
- - + + + + Swagger UI + + + + + + + + + + + + + + + + + + + + + + + + +
 
+
+ + diff --git a/dist/lib/jquery-1.8.0.min.js b/dist/lib/jquery-1.8.0.min.js index f121291c4c7..066d72c7e3a 100644 --- a/dist/lib/jquery-1.8.0.min.js +++ b/dist/lib/jquery-1.8.0.min.js @@ -1,2 +1,2 @@ -/*! jQuery v@1.8.0 jquery.com | jquery.org/license */ +/*! jQuery v@1.8.0 jquery.com | jquery.org/license */ (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write(""),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b
a",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="
t
",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="
",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;jq&&u.push({elem:this,matches:o.slice(q)});for(d=0;d0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;ai){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="
",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="

",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b0)for(e=d;e=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*\s*$/g,bz={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X
","
"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1>");try{for(;d1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]===""&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("
").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); \ No newline at end of file diff --git a/dist/lib/shred.bundle.js b/dist/lib/shred.bundle.js deleted file mode 100644 index 22ea396dcb5..00000000000 --- a/dist/lib/shred.bundle.js +++ /dev/null @@ -1,2765 +0,0 @@ -var require = function (file, cwd) { - var resolved = require.resolve(file, cwd || '/'); - var mod = require.modules[resolved]; - if (!mod) throw new Error( - 'Failed to resolve module ' + file + ', tried ' + resolved - ); - var res = mod._cached ? mod._cached : mod(); - return res; -} - -require.paths = []; -require.modules = {}; -require.extensions = [".js",".coffee"]; - -require._core = { - 'assert': true, - 'events': true, - 'fs': true, - 'path': true, - 'vm': true -}; - -require.resolve = (function () { - return function (x, cwd) { - if (!cwd) cwd = '/'; - - if (require._core[x]) return x; - var path = require.modules.path(); - var y = cwd || '.'; - - if (x.match(/^(?:\.\.?\/|\/)/)) { - var m = loadAsFileSync(path.resolve(y, x)) - || loadAsDirectorySync(path.resolve(y, x)); - if (m) return m; - } - - var n = loadNodeModulesSync(x, y); - if (n) return n; - - throw new Error("Cannot find module '" + x + "'"); - - function loadAsFileSync (x) { - if (require.modules[x]) { - return x; - } - - for (var i = 0; i < require.extensions.length; i++) { - var ext = require.extensions[i]; - if (require.modules[x + ext]) return x + ext; - } - } - - function loadAsDirectorySync (x) { - x = x.replace(/\/+$/, ''); - var pkgfile = x + '/package.json'; - if (require.modules[pkgfile]) { - var pkg = require.modules[pkgfile](); - var b = pkg.browserify; - if (typeof b === 'object' && b.main) { - var m = loadAsFileSync(path.resolve(x, b.main)); - if (m) return m; - } - else if (typeof b === 'string') { - var m = loadAsFileSync(path.resolve(x, b)); - if (m) return m; - } - else if (pkg.main) { - var m = loadAsFileSync(path.resolve(x, pkg.main)); - if (m) return m; - } - } - - return loadAsFileSync(x + '/index'); - } - - function loadNodeModulesSync (x, start) { - var dirs = nodeModulesPathsSync(start); - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - var m = loadAsFileSync(dir + '/' + x); - if (m) return m; - var n = loadAsDirectorySync(dir + '/' + x); - if (n) return n; - } - - var m = loadAsFileSync(x); - if (m) return m; - } - - function nodeModulesPathsSync (start) { - var parts; - if (start === '/') parts = [ '' ]; - else parts = path.normalize(start).split('/'); - - var dirs = []; - for (var i = parts.length - 1; i >= 0; i--) { - if (parts[i] === 'node_modules') continue; - var dir = parts.slice(0, i + 1).join('/') + '/node_modules'; - dirs.push(dir); - } - - return dirs; - } - }; -})(); - -require.alias = function (from, to) { - var path = require.modules.path(); - var res = null; - try { - res = require.resolve(from + '/package.json', '/'); - } - catch (err) { - res = require.resolve(from, '/'); - } - var basedir = path.dirname(res); - - var keys = (Object.keys || function (obj) { - var res = []; - for (var key in obj) res.push(key) - return res; - })(require.modules); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key.slice(0, basedir.length + 1) === basedir + '/') { - var f = key.slice(basedir.length); - require.modules[to + f] = require.modules[basedir + f]; - } - else if (key === basedir) { - require.modules[to] = require.modules[basedir]; - } - } -}; - -require.define = function (filename, fn) { - var dirname = require._core[filename] - ? '' - : require.modules.path().dirname(filename) - ; - - var require_ = function (file) { - return require(file, dirname) - }; - require_.resolve = function (name) { - return require.resolve(name, dirname); - }; - require_.modules = require.modules; - require_.define = require.define; - var module_ = { exports : {} }; - - require.modules[filename] = function () { - require.modules[filename]._cached = module_.exports; - fn.call( - module_.exports, - require_, - module_, - module_.exports, - dirname, - filename - ); - require.modules[filename]._cached = module_.exports; - return module_.exports; - }; -}; - -if (typeof process === 'undefined') process = {}; - -if (!process.nextTick) process.nextTick = (function () { - var queue = []; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; - - if (canPost) { - window.addEventListener('message', function (ev) { - if (ev.source === window && ev.data === 'browserify-tick') { - ev.stopPropagation(); - if (queue.length > 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); - } - - return function (fn) { - if (canPost) { - queue.push(fn); - window.postMessage('browserify-tick', '*'); - } - else setTimeout(fn, 0); - }; -})(); - -if (!process.title) process.title = 'browser'; - -if (!process.binding) process.binding = function (name) { - if (name === 'evals') return require('vm') - else throw new Error('No such module') -}; - -if (!process.cwd) process.cwd = function () { return '.' }; - -require.define("path", function (require, module, exports, __dirname, __filename) { - function filter (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - if (fn(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length; i >= 0; i--) { - var last = parts[i]; - if (last == '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Regex to split a filename into [*, dir, basename, ext] -// posix version -var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { -var resolvedPath = '', - resolvedAbsolute = false; - -for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) - ? arguments[i] - : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string' || !path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; -} - -// At this point the path should be resolved to a full absolute path, but -// handle relative paths to be safe (might happen when process.cwd() fails) - -// Normalize the path -resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { -var isAbsolute = path.charAt(0) === '/', - trailingSlash = path.slice(-1) === '/'; - -// Normalize the path -path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - return p && typeof p === 'string'; - }).join('/')); -}; - - -exports.dirname = function(path) { - var dir = splitPathRe.exec(path)[1] || ''; - var isWindows = false; - if (!dir) { - // No dirname - return '.'; - } else if (dir.length === 1 || - (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { - // It is just a slash or a drive letter with a slash - return dir; - } else { - // It is a full dirname, strip trailing slash - return dir.substring(0, dir.length - 1); - } -}; - - -exports.basename = function(path, ext) { - var f = splitPathRe.exec(path)[2] || ''; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPathRe.exec(path)[3] || ''; -}; - -}); - -require.define("/shred.js", function (require, module, exports, __dirname, __filename) { - // Shred is an HTTP client library intended to simplify the use of Node's -// built-in HTTP library. In particular, we wanted to make it easier to interact -// with HTTP-based APIs. -// -// See the [examples](./examples.html) for more details. - -// Ax is a nice logging library we wrote. You can use any logger, providing it -// has `info`, `warn`, `debug`, and `error` methods that take a string. -var Ax = require("ax") - , CookieJarLib = require( "cookiejar" ) - , CookieJar = CookieJarLib.CookieJar -; - -// Shred takes some options, including a logger and request defaults. - -var Shred = function(options) { - options = (options||{}); - this.agent = options.agent; - this.defaults = options.defaults||{}; - this.log = options.logger||(new Ax({ level: "info" })); - this._sharedCookieJar = new CookieJar(); - this.logCurl = options.logCurl || false; -}; - -// Most of the real work is done in the request and reponse classes. - -Shred.Request = require("./shred/request"); -Shred.Response = require("./shred/response"); - -// The `request` method kicks off a new request, instantiating a new `Request` -// object and passing along whatever default options we were given. - -Shred.prototype = { - request: function(options) { - options.logger = this.log; - options.logCurl = options.logCurl || this.logCurl; - options.cookieJar = ( 'cookieJar' in options ) ? options.cookieJar : this._sharedCookieJar; // let them set cookieJar = null - options.agent = options.agent || this.agent; - // fill in default options - for (var key in this.defaults) { - if (this.defaults.hasOwnProperty(key) && !options[key]) { - options[key] = this.defaults[key] - } - } - return new Shred.Request(options); - } -}; - -// Define a bunch of convenience methods so that you don't have to include -// a `method` property in your request options. - -"get put post delete".split(" ").forEach(function(method) { - Shred.prototype[method] = function(options) { - options.method = method; - return this.request(options); - }; -}); - - -module.exports = Shred; - -}); - -require.define("/node_modules/ax/package.json", function (require, module, exports, __dirname, __filename) { - module.exports = {"main":"./lib/ax.js"} -}); - -require.define("/node_modules/ax/lib/ax.js", function (require, module, exports, __dirname, __filename) { - var inspect = require("util").inspect - , fs = require("fs") -; - - -// this is a quick-and-dirty logger. there are other nicer loggers out there -// but the ones i found were also somewhat involved. this one has a Ruby -// logger type interface -// -// we can easily replace this, provide the info, debug, etc. methods are the -// same. or, we can change Haiku to use a more standard node.js interface - -var format = function(level,message) { - var debug = (level=="debug"||level=="error"); - if (!message) { return message.toString(); } - if (typeof(message) == "object") { - if (message instanceof Error && debug) { - return message.stack; - } else { - return inspect(message); - } - } else { - return message.toString(); - } -}; - -var noOp = function(message) { return this; } -var makeLogger = function(level,fn) { - return function(message) { - this.stream.write(this.format(level, message)+"\n"); - return this; - } -}; - -var Logger = function(options) { - var logger = this; - var options = options||{}; - - // Default options - options.level = options.level || "info"; - options.timestamp = options.timestamp || true; - options.prefix = options.prefix || ""; - logger.options = options; - - // Allows a prefix to be added to the message. - // - // var logger = new Ax({ module: 'Haiku' }) - // logger.warn('this is going to be awesome!'); - // //=> Haiku: this is going to be awesome! - // - if (logger.options.module){ - logger.options.prefix = logger.options.module; - } - - // Write to stderr or a file - if (logger.options.file){ - logger.stream = fs.createWriteStream(logger.options.file, {"flags": "a"}); - } else { - if(process.title === "node") - logger.stream = process.stderr; - else if(process.title === "browser") - logger.stream = function () { - // Work around weird console context issue: http://code.google.com/p/chromium/issues/detail?id=48662 - return console[logger.options.level].apply(console, arguments); - }; - } - - switch(logger.options.level){ - case 'debug': - ['debug', 'info', 'warn'].forEach(function (level) { - logger[level] = Logger.writer(level); - }); - case 'info': - ['info', 'warn'].forEach(function (level) { - logger[level] = Logger.writer(level); - }); - case 'warn': - logger.warn = Logger.writer('warn'); - } -} - -// Used to define logger methods -Logger.writer = function(level){ - return function(message){ - var logger = this; - - if(process.title === "node") - logger.stream.write(logger.format(level, message) + '\n'); - else if(process.title === "browser") - logger.stream(logger.format(level, message) + '\n'); - - }; -} - - -Logger.prototype = { - info: function(){}, - debug: function(){}, - warn: function(){}, - error: Logger.writer('error'), - format: function(level, message){ - if (! message) return ''; - - var logger = this - , prefix = logger.options.prefix - , timestamp = logger.options.timestamp ? " " + (new Date().toISOString()) : "" - ; - - return (prefix + timestamp + ": " + message); - } -}; - -module.exports = Logger; - -}); - -require.define("util", function (require, module, exports, __dirname, __filename) { - // todo - -}); - -require.define("fs", function (require, module, exports, __dirname, __filename) { - // nothing to see here... no file methods for the browser - -}); - -require.define("/node_modules/cookiejar/package.json", function (require, module, exports, __dirname, __filename) { - module.exports = {"main":"cookiejar.js"} -}); - -require.define("/node_modules/cookiejar/cookiejar.js", function (require, module, exports, __dirname, __filename) { - exports.CookieAccessInfo=CookieAccessInfo=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; - } - else { - return new CookieAccessInfo(domain,path,secure,script) - } -} - -exports.Cookie=Cookie=function Cookie(cookiestr) { - if(cookiestr instanceof Cookie) { - return cookiestr; - } - else { - if(this instanceof Cookie) { - this.name = null; - this.value = null; - this.expiration_date = Infinity; - this.path = "/"; - this.domain = null; - this.secure = false; //how to define? - this.noscript = false; //httponly - if(cookiestr) { - this.parse(cookiestr) - } - return this; - } - return new Cookie(cookiestr) - } -} - -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) { - if(this instanceof Cookie) { - var parts=str.split(";") - , pair=parts[0].match(/([^=]+)=((?:.|\n)*)/) - , key=pair[1] - , value=pair[2]; - this.name = key; - this.value = value; - - for(var i=1;i ", request.method.toUpperCase(), - request.url].join(" ") - return [ summary, "- Headers:", headers].join("\n"); -}; - -Request.prototype.format_headers = function () { - var array = [] - var headers = this._headers - for (var key in headers) { - if (headers.hasOwnProperty(key)) { - var value = headers[key] - array.push("\t" + key + ": " + value); - } - } - return array.join("\n"); -}; - -// Allow chainable 'on's: shred.get({ ... }).on( ... ). You can pass in a -// single function, a pair (event, function), or a hash: -// { event: function, event: function } -Request.prototype.on = function (eventOrHash, listener) { - var emitter = this.emitter; - // Pass in a single argument as a function then make it the default response handler - if (arguments.length === 1 && typeof(eventOrHash) === 'function') { - emitter.on('response', eventOrHash); - } else if (arguments.length === 1 && typeof(eventOrHash) === 'object') { - for (var key in eventOrHash) { - if (eventOrHash.hasOwnProperty(key)) { - emitter.on(key, eventOrHash[key]); - } - } - } else { - emitter.on(eventOrHash, listener); - } - return this; -}; - -// Add in the header methods. Again, these ensure we don't get the same header -// multiple times with different case conventions. -HeaderMixins.gettersAndSetters(Request); - -// `processOptions` is called from the constructor to handle all the work -// associated with making sure we do our best to ensure we have a valid request. - -var processOptions = function(request,options) { - - request.log.debug("Processing request options .."); - - // We'll use `request.emitter` to manage the `on` event handlers. - request.emitter = (new Emitter); - - request.agent = options.agent; - - // Set up the handlers ... - if (options.on) { - for (var key in options.on) { - if (options.on.hasOwnProperty(key)) { - request.emitter.on(key, options.on[key]); - } - } - } - - // Make sure we were give a URL or a host - if (!options.url && !options.host) { - request.emitter.emit("request_error", - new Error("No url or url options (host, port, etc.)")); - return; - } - - // Allow for the [use of a proxy](http://www.jmarshall.com/easy/http/#proxies). - - if (options.url) { - if (options.proxy) { - request.url = options.proxy; - request.path = options.url; - } else { - request.url = options.url; - } - } - - // Set the remaining options. - request.query = options.query||options.parameters||request.query ; - request.method = options.method; - request.setHeader("user-agent",options.agent||"Shred"); - request.setHeaders(options.headers); - - if (request.cookieJar) { - var cookies = request.cookieJar.getCookies( CookieAccessInfo( request.host, request.path ) ); - if (cookies.length) { - var cookieString = request.getHeader('cookie')||''; - for (var cookieIndex = 0; cookieIndex < cookies.length; ++cookieIndex) { - if ( cookieString.length && cookieString[ cookieString.length - 1 ] != ';' ) - { - cookieString += ';'; - } - cookieString += cookies[ cookieIndex ].name + '=' + cookies[ cookieIndex ].value + ';'; - } - request.setHeader("cookie", cookieString); - } - } - - // The content entity can be set either using the `body` or `content` attributes. - if (options.body||options.content) { - request.content = options.body||options.content; - } - request.timeout = options.timeout; - -}; - -// `createRequest` is also called by the constructor, after `processOptions`. -// This actually makes the request and processes the response, so `createRequest` -// is a bit of a misnomer. - -var createRequest = function(request) { - var timeout ; - - request.log.debug("Creating request .."); - request.log.debug(request); - - var reqParams = { - host: request.host, - port: request.port, - method: request.method, - path: request.path + (request.query ? '?'+request.query : ""), - headers: request.getHeaders(), - // Node's HTTP/S modules will ignore this, but we are using the - // browserify-http module in the browser for both HTTP and HTTPS, and this - // is how you differentiate the two. - scheme: request.scheme, - // Use a provided agent. 'Undefined' is the default, which uses a global - // agent. - agent: request.agent - }; - - if (request.logCurl) { - logCurl(request); - } - - var http = request.scheme == "http" ? HTTP : HTTPS; - - // Set up the real request using the selected library. The request won't be - // sent until we call `.end()`. - request._raw = http.request(reqParams, function(response) { - request.log.debug("Received response .."); - - // We haven't timed out and we have a response, so make sure we clear the - // timeout so it doesn't fire while we're processing the response. - clearTimeout(timeout); - - // Construct a Shred `Response` object from the response. This will stream - // the response, thus the need for the callback. We can access the response - // entity safely once we're in the callback. - response = new Response(response, request, function(response) { - - // Set up some event magic. The precedence is given first to - // status-specific handlers, then to responses for a given event, and then - // finally to the more general `response` handler. In the last case, we - // need to first make sure we're not dealing with a a redirect. - var emit = function(event) { - var emitter = request.emitter; - var textStatus = STATUS_CODES[response.status] ? STATUS_CODES[response.status].toLowerCase() : null; - if (emitter.listeners(response.status).length > 0 || emitter.listeners(textStatus).length > 0) { - emitter.emit(response.status, response); - emitter.emit(textStatus, response); - } else { - if (emitter.listeners(event).length>0) { - emitter.emit(event, response); - } else if (!response.isRedirect) { - emitter.emit("response", response); - //console.warn("Request has no event listener for status code " + response.status); - } - } - }; - - // Next, check for a redirect. We simply repeat the request with the URL - // given in the `Location` header. We fire a `redirect` event. - if (response.isRedirect) { - request.log.debug("Redirecting to " - + response.getHeader("Location")); - request.url = response.getHeader("Location"); - emit("redirect"); - createRequest(request); - - // Okay, it's not a redirect. Is it an error of some kind? - } else if (response.isError) { - emit("error"); - } else { - // It looks like we're good shape. Trigger the `success` event. - emit("success"); - } - }); - }); - - // We're still setting up the request. Next, we're going to handle error cases - // where we have no response. We don't emit an error event because that event - // takes a response. We don't response handlers to have to check for a null - // value. However, we [should introduce a different event - // type](https://github.com/spire-io/shred/issues/3) for this type of error. - request._raw.on("error", function(error) { - request.emitter.emit("request_error", error); - }); - - request._raw.on("socket", function(socket) { - request.emitter.emit("socket", socket); - }); - - // TCP timeouts should also trigger the "response_error" event. - request._raw.on('socket', function () { - request._raw.socket.on('timeout', function () { - // This should trigger the "error" event on the raw request, which will - // trigger the "response_error" on the shred request. - request._raw.abort(); - }); - }); - - - // We're almost there. Next, we need to write the request entity to the - // underlying request object. - if (request.content) { - request.log.debug("Streaming body: '" + - request.content.data.slice(0,59) + "' ... "); - request._raw.write(request.content.data); - } - - // Finally, we need to set up the timeout. We do this last so that we don't - // start the clock ticking until the last possible moment. - if (request.timeout) { - timeout = setTimeout(function() { - request.log.debug("Timeout fired, aborting request ..."); - request._raw.abort(); - request.emitter.emit("timeout", request); - },request.timeout); - } - - // The `.end()` method will cause the request to fire. Technically, it might - // have already sent the headers and body. - request.log.debug("Sending request ..."); - request._raw.end(); -}; - -// Logs the curl command for the request. -var logCurl = function (req) { - var headers = req.getHeaders(); - var headerString = ""; - - for (var key in headers) { - headerString += '-H "' + key + ": " + headers[key] + '" '; - } - - var bodyString = "" - - if (req.content) { - bodyString += "-d '" + req.content.body + "' "; - } - - var query = req.query ? '?' + req.query : ""; - - console.log("curl " + - "-X " + req.method.toUpperCase() + " " + - req.scheme + "://" + req.host + ":" + req.port + req.path + query + " " + - headerString + - bodyString - ); -}; - - -module.exports = Request; - -}); - -require.define("http", function (require, module, exports, __dirname, __filename) { - // todo - -}); - -require.define("https", function (require, module, exports, __dirname, __filename) { - // todo - -}); - -require.define("/shred/parseUri.js", function (require, module, exports, __dirname, __filename) { - // parseUri 1.2.2 -// (c) Steven Levithan -// MIT License - -function parseUri (str) { - var o = parseUri.options, - m = o.parser[o.strictMode ? "strict" : "loose"].exec(str), - uri = {}, - i = 14; - - while (i--) uri[o.key[i]] = m[i] || ""; - - uri[o.q.name] = {}; - uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { - if ($1) uri[o.q.name][$1] = $2; - }); - - return uri; -}; - -parseUri.options = { - strictMode: false, - key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], - q: { - name: "queryKey", - parser: /(?:^|&)([^&=]*)=?([^&]*)/g - }, - parser: { - strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, - loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ - } -}; - -module.exports = parseUri; - -}); - -require.define("events", function (require, module, exports, __dirname, __filename) { - if (!process.EventEmitter) process.EventEmitter = function () {}; - -var EventEmitter = exports.EventEmitter = process.EventEmitter; -var isArray = typeof Array.isArray === 'function' - ? Array.isArray - : function (xs) { - return Object.toString.call(xs) === '[object Array]' - } -; - -// By default EventEmitters will print a warning if more than -// 10 listeners are added to it. This is a useful default which -// helps finding memory leaks. -// -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -var defaultMaxListeners = 10; -EventEmitter.prototype.setMaxListeners = function(n) { - if (!this._events) this._events = {}; - this._events.maxListeners = n; -}; - - -EventEmitter.prototype.emit = function(type) { - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events || !this._events.error || - (isArray(this._events.error) && !this._events.error.length)) - { - if (arguments[1] instanceof Error) { - throw arguments[1]; // Unhandled 'error' event - } else { - throw new Error("Uncaught, unspecified 'error' event."); - } - return false; - } - } - - if (!this._events) return false; - var handler = this._events[type]; - if (!handler) return false; - - if (typeof handler == 'function') { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - var args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - return true; - - } else if (isArray(handler)) { - var args = Array.prototype.slice.call(arguments, 1); - - var listeners = handler.slice(); - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - return true; - - } else { - return false; - } -}; - -// EventEmitter is defined in src/node_events.cc -// EventEmitter.prototype.emit() is also defined there. -EventEmitter.prototype.addListener = function(type, listener) { - if ('function' !== typeof listener) { - throw new Error('addListener only takes instances of Function'); - } - - if (!this._events) this._events = {}; - - // To avoid recursion in the case that type == "newListeners"! Before - // adding it to the listeners, first emit "newListeners". - this.emit('newListener', type, listener); - - if (!this._events[type]) { - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - } else if (isArray(this._events[type])) { - - // Check for listener leak - if (!this._events[type].warned) { - var m; - if (this._events.maxListeners !== undefined) { - m = this._events.maxListeners; - } else { - m = defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - console.trace(); - } - } - - // If we've already got an array, just append. - this._events[type].push(listener); - } else { - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - var self = this; - self.on(type, function g() { - self.removeListener(type, g); - listener.apply(this, arguments); - }); - - return this; -}; - -EventEmitter.prototype.removeListener = function(type, listener) { - if ('function' !== typeof listener) { - throw new Error('removeListener only takes instances of Function'); - } - - // does not use listeners(), so no side effect of creating _events[type] - if (!this._events || !this._events[type]) return this; - - var list = this._events[type]; - - if (isArray(list)) { - var i = list.indexOf(listener); - if (i < 0) return this; - list.splice(i, 1); - if (list.length == 0) - delete this._events[type]; - } else if (this._events[type] === listener) { - delete this._events[type]; - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - // does not use listeners(), so no side effect of creating _events[type] - if (type && this._events && this._events[type]) this._events[type] = null; - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - if (!this._events) this._events = {}; - if (!this._events[type]) this._events[type] = []; - if (!isArray(this._events[type])) { - this._events[type] = [this._events[type]]; - } - return this._events[type]; -}; - -}); - -require.define("/node_modules/sprintf/package.json", function (require, module, exports, __dirname, __filename) { - module.exports = {"main":"./lib/sprintf"} -}); - -require.define("/node_modules/sprintf/lib/sprintf.js", function (require, module, exports, __dirname, __filename) { - /** -sprintf() for JavaScript 0.7-beta1 -http://www.diveintojavascript.com/projects/javascript-sprintf - -Copyright (c) Alexandru Marasteanu -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 sprintf() for JavaScript 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 Alexandru Marasteanu 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. - - -Changelog: -2010.11.07 - 0.7-beta1-node - - converted it to a node.js compatible module - -2010.09.06 - 0.7-beta1 - - features: vsprintf, support for named placeholders - - enhancements: format cache, reduced global namespace pollution - -2010.05.22 - 0.6: - - reverted to 0.4 and fixed the bug regarding the sign of the number 0 - Note: - Thanks to Raphael Pigulla (http://www.n3rd.org/) - who warned me about a bug in 0.5, I discovered that the last update was - a regress. I appologize for that. - -2010.05.09 - 0.5: - - bug fix: 0 is now preceeded with a + sign - - bug fix: the sign was not at the right position on padded results (Kamal Abdali) - - switched from GPL to BSD license - -2007.10.21 - 0.4: - - unit test and patch (David Baird) - -2007.09.17 - 0.3: - - bug fix: no longer throws exception on empty paramenters (Hans Pufal) - -2007.09.11 - 0.2: - - feature: added argument swapping - -2007.04.03 - 0.1: - - initial release -**/ - -var sprintf = (function() { - function get_type(variable) { - return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); - } - function str_repeat(input, multiplier) { - for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} - return output.join(''); - } - - var str_format = function() { - if (!str_format.cache.hasOwnProperty(arguments[0])) { - str_format.cache[arguments[0]] = str_format.parse(arguments[0]); - } - return str_format.format.call(null, str_format.cache[arguments[0]], arguments); - }; - - str_format.format = function(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; - for (i = 0; i < tree_length; i++) { - node_type = get_type(parse_tree[i]); - if (node_type === 'string') { - output.push(parse_tree[i]); - } - else if (node_type === 'array') { - match = parse_tree[i]; // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor]; - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw(sprintf('[sprintf] property "%s" does not exist', match[2][k])); - } - arg = arg[match[2][k]]; - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]]; - } - else { // positional argument (implicit) - arg = argv[cursor++]; - } - - if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { - throw(sprintf('[sprintf] expecting number but found %s', get_type(arg))); - } - switch (match[8]) { - case 'b': arg = arg.toString(2); break; - case 'c': arg = String.fromCharCode(arg); break; - case 'd': arg = parseInt(arg, 10); break; - case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; - case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; - case 'o': arg = arg.toString(8); break; - case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; - case 'u': arg = Math.abs(arg); break; - case 'x': arg = arg.toString(16); break; - case 'X': arg = arg.toString(16).toUpperCase(); break; - } - arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg); - pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; - pad_length = match[6] - String(arg).length; - pad = match[6] ? str_repeat(pad_character, pad_length) : ''; - output.push(match[5] ? arg + pad : pad + arg); - } - } - return output.join(''); - }; - - str_format.cache = {}; - - str_format.parse = function(fmt) { - var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; - while (_fmt) { - if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { - parse_tree.push(match[0]); - } - else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { - parse_tree.push('%'); - } - else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1; - var field_list = [], replacement_field = match[2], field_match = []; - if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { - if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - } - else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - } - else { - throw('[sprintf] huh?'); - } - } - } - else { - throw('[sprintf] huh?'); - } - match[2] = field_list; - } - else { - arg_names |= 2; - } - if (arg_names === 3) { - throw('[sprintf] mixing positional and named placeholders is not (yet) supported'); - } - parse_tree.push(match); - } - else { - throw('[sprintf] huh?'); - } - _fmt = _fmt.substring(match[0].length); - } - return parse_tree; - }; - - return str_format; -})(); - -var vsprintf = function(fmt, argv) { - argv.unshift(fmt); - return sprintf.apply(null, argv); -}; - -exports.sprintf = sprintf; -exports.vsprintf = vsprintf; -}); - -require.define("/shred/response.js", function (require, module, exports, __dirname, __filename) { - // The `Response object` encapsulates a Node.js HTTP response. - -var Content = require("./content") - , HeaderMixins = require("./mixins/headers") - , CookieJarLib = require( "cookiejar" ) - , Cookie = CookieJarLib.Cookie -; - -// Browser doesn't have zlib. -var zlib = null; -try { - zlib = require('zlib'); -} catch (e) { - // console.warn("no zlib library"); -} - -// Iconv doesn't work in browser -var Iconv = null; -try { - Iconv = require('iconv-lite'); -} catch (e) { - // console.warn("no iconv library"); -} - -// Construct a `Response` object. You should never have to do this directly. The -// `Request` object handles this, getting the raw response object and passing it -// in here, along with the request. The callback allows us to stream the response -// and then use the callback to let the request know when it's ready. -var Response = function(raw, request, callback) { - var response = this; - this._raw = raw; - - // The `._setHeaders` method is "private"; you can't otherwise set headers on - // the response. - this._setHeaders.call(this,raw.headers); - - // store any cookies - if (request.cookieJar && this.getHeader('set-cookie')) { - var cookieStrings = this.getHeader('set-cookie'); - var cookieObjs = [] - , cookie; - - for (var i = 0; i < cookieStrings.length; i++) { - var cookieString = cookieStrings[i]; - if (!cookieString) { - continue; - } - - if (!cookieString.match(/domain\=/i)) { - cookieString += '; domain=' + request.host; - } - - if (!cookieString.match(/path\=/i)) { - cookieString += '; path=' + request.path; - } - - try { - cookie = new Cookie(cookieString); - if (cookie) { - cookieObjs.push(cookie); - } - } catch (e) { - console.warn("Tried to set bad cookie: " + cookieString); - } - } - - request.cookieJar.setCookies(cookieObjs); - } - - this.request = request; - this.client = request.client; - this.log = this.request.log; - - // Stream the response content entity and fire the callback when we're done. - // Store the incoming data in a array of Buffers which we concatinate into one - // buffer at the end. We need to use buffers instead of strings here in order - // to preserve binary data. - var chunkBuffers = []; - var dataLength = 0; - raw.on("data", function(chunk) { - chunkBuffers.push(chunk); - dataLength += chunk.length; - }); - raw.on("end", function() { - var body; - if (typeof Buffer === 'undefined') { - // Just concatinate into a string - body = chunkBuffers.join(''); - } else { - // Initialize new buffer and add the chunks one-at-a-time. - body = new Buffer(dataLength); - for (var i = 0, pos = 0; i < chunkBuffers.length; i++) { - chunkBuffers[i].copy(body, pos); - pos += chunkBuffers[i].length; - } - } - - var setBodyAndFinish = function (body) { - response._body = new Content({ - body: body, - type: response.getHeader("Content-Type") - }); - callback(response); - } - - if (zlib && response.getHeader("Content-Encoding") === 'gzip'){ - zlib.gunzip(body, function (err, gunzippedBody) { - if (Iconv && response.request.encoding){ - body = Iconv.fromEncoding(gunzippedBody,response.request.encoding); - } else { - body = gunzippedBody.toString(); - } - setBodyAndFinish(body); - }) - } - else{ - if (response.request.encoding){ - body = Iconv.fromEncoding(body,response.request.encoding); - } - setBodyAndFinish(body); - } - }); -}; - -// The `Response` object can be pretty overwhelming to view using the built-in -// Node.js inspect method. We want to make it a bit more manageable. This -// probably goes [too far in the other -// direction](https://github.com/spire-io/shred/issues/2). - -Response.prototype = { - inspect: function() { - var response = this; - var headers = this.format_headers(); - var summary = [" ", response.status].join(" ") - return [ summary, "- Headers:", headers].join("\n"); - }, - format_headers: function () { - var array = [] - var headers = this._headers - for (var key in headers) { - if (headers.hasOwnProperty(key)) { - var value = headers[key] - array.push("\t" + key + ": " + value); - } - } - return array.join("\n"); - } -}; - -// `Response` object properties, all of which are read-only: -Object.defineProperties(Response.prototype, { - -// - **status**. The HTTP status code for the response. - status: { - get: function() { return this._raw.statusCode; }, - enumerable: true - }, - -// - **content**. The HTTP content entity, if any. Provided as a [content -// object](./content.html), which will attempt to convert the entity based upon -// the `content-type` header. The converted value is available as -// `content.data`. The original raw content entity is available as -// `content.body`. - body: { - get: function() { return this._body; } - }, - content: { - get: function() { return this.body; }, - enumerable: true - }, - -// - **isRedirect**. Is the response a redirect? These are responses with 3xx -// status and a `Location` header. - isRedirect: { - get: function() { - return (this.status>299 - &&this.status<400 - &&this.getHeader("Location")); - }, - enumerable: true - }, - -// - **isError**. Is the response an error? These are responses with status of -// 400 or greater. - isError: { - get: function() { - return (this.status === 0 || this.status > 399) - }, - enumerable: true - } -}); - -// Add in the [getters for accessing the normalized headers](./headers.js). -HeaderMixins.getters(Response); -HeaderMixins.privateSetters(Response); - -// Work around Mozilla bug #608735 [https://bugzil.la/608735], which causes -// getAllResponseHeaders() to return {} if the response is a CORS request. -// xhr.getHeader still works correctly. -var getHeader = Response.prototype.getHeader; -Response.prototype.getHeader = function (name) { - return (getHeader.call(this,name) || - (typeof this._raw.getHeader === 'function' && this._raw.getHeader(name))); -}; - -module.exports = Response; - -}); - -require.define("/shred/content.js", function (require, module, exports, __dirname, __filename) { - -// The purpose of the `Content` object is to abstract away the data conversions -// to and from raw content entities as strings. For example, you want to be able -// to pass in a Javascript object and have it be automatically converted into a -// JSON string if the `content-type` is set to a JSON-based media type. -// Conversely, you want to be able to transparently get back a Javascript object -// in the response if the `content-type` is a JSON-based media-type. - -// One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5). - -// The `Content` constructor takes an options object, which *must* have either a -// `body` or `data` property and *may* have a `type` property indicating the -// media type. If there is no `type` attribute, a default will be inferred. -var Content = function(options) { - this.body = options.body; - this.data = options.data; - this.type = options.type; -}; - -Content.prototype = { - // Treat `toString()` as asking for the `content.body`. That is, the raw content entity. - // - // toString: function() { return this.body; } - // - // Commented out, but I've forgotten why. :/ -}; - - -// `Content` objects have the following attributes: -Object.defineProperties(Content.prototype,{ - -// - **type**. Typically accessed as `content.type`, reflects the `content-type` -// header associated with the request or response. If not passed as an options -// to the constructor or set explicitly, it will infer the type the `data` -// attribute, if possible, and, failing that, will default to `text/plain`. - type: { - get: function() { - if (this._type) { - return this._type; - } else { - if (this._data) { - switch(typeof this._data) { - case "string": return "text/plain"; - case "object": return "application/json"; - } - } - } - return "text/plain"; - }, - set: function(value) { - this._type = value; - return this; - }, - enumerable: true - }, - -// - **data**. Typically accessed as `content.data`, reflects the content entity -// converted into Javascript data. This can be a string, if the `type` is, say, -// `text/plain`, but can also be a Javascript object. The conversion applied is -// based on the `processor` attribute. The `data` attribute can also be set -// directly, in which case the conversion will be done the other way, to infer -// the `body` attribute. - data: { - get: function() { - if (this._body) { - return this.processor.parser(this._body); - } else { - return this._data; - } - }, - set: function(data) { - if (this._body&&data) Errors.setDataWithBody(this); - this._data = data; - return this; - }, - enumerable: true - }, - -// - **body**. Typically accessed as `content.body`, reflects the content entity -// as a UTF-8 string. It is the mirror of the `data` attribute. If you set the -// `data` attribute, the `body` attribute will be inferred and vice-versa. If -// you attempt to set both, an exception is raised. - body: { - get: function() { - if (this._data) { - return this.processor.stringify(this._data); - } else { - return this.processor.stringify(this._body); - } - }, - set: function(body) { - if (this._data&&body) Errors.setBodyWithData(this); - this._body = body; - return this; - }, - enumerable: true - }, - -// - **processor**. The functions that will be used to convert to/from `data` and -// `body` attributes. You can add processors. The two that are built-in are for -// `text/plain`, which is basically an identity transformation and -// `application/json` and other JSON-based media types (including custom media -// types with `+json`). You can add your own processors. See below. - processor: { - get: function() { - var processor = Content.processors[this.type]; - if (processor) { - return processor; - } else { - // Return the first processor that matches any part of the - // content type. ex: application/vnd.foobar.baz+json will match json. - var main = this.type.split(";")[0]; - var parts = main.split(/\+|\//); - for (var i=0, l=parts.length; i < l; i++) { - processor = Content.processors[parts[i]] - } - return processor || {parser:identity,stringify:toString}; - } - }, - enumerable: true - }, - -// - **length**. Typically accessed as `content.length`, returns the length in -// bytes of the raw content entity. - length: { - get: function() { - if (typeof Buffer !== 'undefined') { - return Buffer.byteLength(this.body); - } - return this.body.length; - } - } -}); - -Content.processors = {}; - -// The `registerProcessor` function allows you to add your own processors to -// convert content entities. Each processor consists of a Javascript object with -// two properties: -// - **parser**. The function used to parse a raw content entity and convert it -// into a Javascript data type. -// - **stringify**. The function used to convert a Javascript data type into a -// raw content entity. -Content.registerProcessor = function(types,processor) { - -// You can pass an array of types that will trigger this processor, or just one. -// We determine the array via duck-typing here. - if (types.forEach) { - types.forEach(function(type) { - Content.processors[type] = processor; - }); - } else { - // If you didn't pass an array, we just use what you pass in. - Content.processors[types] = processor; - } -}; - -// Register the identity processor, which is used for text-based media types. -var identity = function(x) { return x; } - , toString = function(x) { return x.toString(); } -Content.registerProcessor( - ["text/html","text/plain","text"], - { parser: identity, stringify: toString }); - -// Register the JSON processor, which is used for JSON-based media types. -Content.registerProcessor( - ["application/json; charset=utf-8","application/json","json"], - { - parser: function(string) { - return JSON.parse(string); - }, - stringify: function(data) { - return JSON.stringify(data); }}); - -// Error functions are defined separately here in an attempt to make the code -// easier to read. -var Errors = { - setDataWithBody: function(object) { - throw new Error("Attempt to set data attribute of a content object " + - "when the body attributes was already set."); - }, - setBodyWithData: function(object) { - throw new Error("Attempt to set body attribute of a content object " + - "when the data attributes was already set."); - } -} -module.exports = Content; - -}); - -require.define("/shred/mixins/headers.js", function (require, module, exports, __dirname, __filename) { - // The header mixins allow you to add HTTP header support to any object. This -// might seem pointless: why not simply use a hash? The main reason is that, per -// the [HTTP spec](http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2), -// headers are case-insensitive. So, for example, `content-type` is the same as -// `CONTENT-TYPE` which is the same as `Content-Type`. Since there is no way to -// overload the index operator in Javascript, using a hash to represent the -// headers means it's possible to have two conflicting values for a single -// header. -// -// The solution to this is to provide explicit methods to set or get headers. -// This also has the benefit of allowing us to introduce additional variations, -// including snake case, which we automatically convert to what Matthew King has -// dubbed "corset case" - the hyphen-separated names with initial caps: -// `Content-Type`. We use corset-case just in case we're dealing with servers -// that haven't properly implemented the spec. - -// Convert headers to corset-case. **Example:** `CONTENT-TYPE` will be converted -// to `Content-Type`. - -var corsetCase = function(string) { - return string;//.toLowerCase() - //.replace("_","-") - // .replace(/(^|-)(\w)/g, - // function(s) { return s.toUpperCase(); }); -}; - -// We suspect that `initializeHeaders` was once more complicated ... -var initializeHeaders = function(object) { - return {}; -}; - -// Access the `_headers` property using lazy initialization. **Warning:** If you -// mix this into an object that is using the `_headers` property already, you're -// going to have trouble. -var $H = function(object) { - return object._headers||(object._headers=initializeHeaders(object)); -}; - -// Hide the implementations as private functions, separate from how we expose them. - -// The "real" `getHeader` function: get the header after normalizing the name. -var getHeader = function(object,name) { - return $H(object)[corsetCase(name)]; -}; - -// The "real" `getHeader` function: get one or more headers, or all of them -// if you don't ask for any specifics. -var getHeaders = function(object,names) { - var keys = (names && names.length>0) ? names : Object.keys($H(object)); - var hash = keys.reduce(function(hash,key) { - hash[key] = getHeader(object,key); - return hash; - },{}); - // Freeze the resulting hash so you don't mistakenly think you're modifying - // the real headers. - Object.freeze(hash); - return hash; -}; - -// The "real" `setHeader` function: set a header, after normalizing the name. -var setHeader = function(object,name,value) { - $H(object)[corsetCase(name)] = value; - return object; -}; - -// The "real" `setHeaders` function: set multiple headers based on a hash. -var setHeaders = function(object,hash) { - for( var key in hash ) { setHeader(object,key,hash[key]); }; - return this; -}; - -// Here's where we actually bind the functionality to an object. These mixins work by -// exposing mixin functions. Each function mixes in a specific batch of features. -module.exports = { - - // Add getters. - getters: function(constructor) { - constructor.prototype.getHeader = function(name) { return getHeader(this,name); }; - constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); }; - }, - // Add setters but as "private" methods. - privateSetters: function(constructor) { - constructor.prototype._setHeader = function(key,value) { return setHeader(this,key,value); }; - constructor.prototype._setHeaders = function(hash) { return setHeaders(this,hash); }; - }, - // Add setters. - setters: function(constructor) { - constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); }; - constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); }; - }, - // Add both getters and setters. - gettersAndSetters: function(constructor) { - constructor.prototype.getHeader = function(name) { return getHeader(this,name); }; - constructor.prototype.getHeaders = function() { return getHeaders(this,arguments); }; - constructor.prototype.setHeader = function(key,value) { return setHeader(this,key,value); }; - constructor.prototype.setHeaders = function(hash) { return setHeaders(this,hash); }; - } -}; - -}); - -require.define("/node_modules/iconv-lite/package.json", function (require, module, exports, __dirname, __filename) { - module.exports = {} -}); - -require.define("/node_modules/iconv-lite/index.js", function (require, module, exports, __dirname, __filename) { - // Module exports -var iconv = module.exports = { - toEncoding: function(str, encoding) { - return iconv.getCodec(encoding).toEncoding(str); - }, - fromEncoding: function(buf, encoding) { - return iconv.getCodec(encoding).fromEncoding(buf); - }, - - defaultCharUnicode: '�', - defaultCharSingleByte: '?', - - // Get correct codec for given encoding. - getCodec: function(encoding) { - var enc = encoding || "utf8"; - var codecOptions = undefined; - while (1) { - if (getType(enc) === "String") - enc = enc.replace(/[- ]/g, "").toLowerCase(); - var codec = iconv.encodings[enc]; - var type = getType(codec); - if (type === "String") { - // Link to other encoding. - codecOptions = {originalEncoding: enc}; - enc = codec; - } - else if (type === "Object" && codec.type != undefined) { - // Options for other encoding. - codecOptions = codec; - enc = codec.type; - } - else if (type === "Function") - // Codec itself. - return codec(codecOptions); - else - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } - }, - - // Define basic encodings - encodings: { - internal: function(options) { - return { - toEncoding: function(str) { - return new Buffer(ensureString(str), options.originalEncoding); - }, - fromEncoding: function(buf) { - return ensureBuffer(buf).toString(options.originalEncoding); - } - }; - }, - utf8: "internal", - ucs2: "internal", - binary: "internal", - ascii: "internal", - base64: "internal", - - // Codepage single-byte encodings. - singlebyte: function(options) { - // Prepare chars if needed - if (!options.chars || (options.chars.length !== 128 && options.chars.length !== 256)) - throw new Error("Encoding '"+options.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (options.chars.length === 128) - options.chars = asciiString + options.chars; - - if (!options.charsBuf) { - options.charsBuf = new Buffer(options.chars, 'ucs2'); - } - - if (!options.revCharsBuf) { - options.revCharsBuf = new Buffer(65536); - var defChar = iconv.defaultCharSingleByte.charCodeAt(0); - for (var i = 0; i < options.revCharsBuf.length; i++) - options.revCharsBuf[i] = defChar; - for (var i = 0; i < options.chars.length; i++) - options.revCharsBuf[options.chars.charCodeAt(i)] = i; - } - - return { - toEncoding: function(str) { - str = ensureString(str); - - var buf = new Buffer(str.length); - var revCharsBuf = options.revCharsBuf; - for (var i = 0; i < str.length; i++) - buf[i] = revCharsBuf[str.charCodeAt(i)]; - - return buf; - }, - fromEncoding: function(buf) { - buf = ensureBuffer(buf); - - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var charsBuf = options.charsBuf; - var newBuf = new Buffer(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0, _len = buf.length; i < _len; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = charsBuf[idx1]; - newBuf[idx2+1] = charsBuf[idx1+1]; - } - return newBuf.toString('ucs2'); - } - }; - }, - - // Codepage double-byte encodings. - table: function(options) { - var table = options.table, key, revCharsTable = options.revCharsTable; - if (!table) { - throw new Error("Encoding '" + options.type +"' has incorect 'table' option"); - } - if(!revCharsTable) { - revCharsTable = options.revCharsTable = {}; - for (key in table) { - revCharsTable[table[key]] = parseInt(key); - } - } - - return { - toEncoding: function(str) { - str = ensureString(str); - var strLen = str.length; - var bufLen = strLen; - for (var i = 0; i < strLen; i++) - if (str.charCodeAt(i) >> 7) - bufLen++; - - var newBuf = new Buffer(bufLen), gbkcode, unicode, - defaultChar = revCharsTable[iconv.defaultCharUnicode.charCodeAt(0)]; - - for (var i = 0, j = 0; i < strLen; i++) { - unicode = str.charCodeAt(i); - if (unicode >> 7) { - gbkcode = revCharsTable[unicode] || defaultChar; - newBuf[j++] = gbkcode >> 8; //high byte; - newBuf[j++] = gbkcode & 0xFF; //low byte - } else {//ascii - newBuf[j++] = unicode; - } - } - return newBuf; - }, - fromEncoding: function(buf) { - buf = ensureBuffer(buf); - var bufLen = buf.length, strLen = 0; - for (var i = 0; i < bufLen; i++) { - strLen++; - if (buf[i] & 0x80) //the high bit is 1, so this byte is gbkcode's high byte.skip next byte - i++; - } - var newBuf = new Buffer(strLen*2), unicode, gbkcode, - defaultChar = iconv.defaultCharUnicode.charCodeAt(0); - - for (var i = 0, j = 0; i < bufLen; i++, j+=2) { - gbkcode = buf[i]; - if (gbkcode & 0x80) { - gbkcode = (gbkcode << 8) + buf[++i]; - unicode = table[gbkcode] || defaultChar; - } else { - unicode = gbkcode; - } - newBuf[j] = unicode & 0xFF; //low byte - newBuf[j+1] = unicode >> 8; //high byte - } - return newBuf.toString('ucs2'); - } - } - } - } -}; - -// Add aliases to convert functions -iconv.encode = iconv.toEncoding; -iconv.decode = iconv.fromEncoding; - -// Load other encodings from files in /encodings dir. -var encodingsDir = __dirname+"/encodings/", - fs = require('fs'); -fs.readdirSync(encodingsDir).forEach(function(file) { - if(fs.statSync(encodingsDir + file).isDirectory()) return; - var encodings = require(encodingsDir + file) - for (var key in encodings) - iconv.encodings[key] = encodings[key] -}); - -// Utilities -var asciiString = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f'+ - ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'; - -var ensureBuffer = function(buf) { - buf = buf || new Buffer(0); - return (buf instanceof Buffer) ? buf : new Buffer(buf.toString(), "utf8"); -} - -var ensureString = function(str) { - str = str || ""; - return (str instanceof String) ? str : str.toString((str instanceof Buffer) ? 'utf8' : undefined); -} - -var getType = function(obj) { - return Object.prototype.toString.call(obj).slice(8, -1); -} - - -}); - -require.define("/node_modules/http-browserify/package.json", function (require, module, exports, __dirname, __filename) { - module.exports = {"main":"index.js","browserify":"browser.js"} -}); - -require.define("/node_modules/http-browserify/browser.js", function (require, module, exports, __dirname, __filename) { - var http = module.exports; -var EventEmitter = require('events').EventEmitter; -var Request = require('./lib/request'); - -http.request = function (params, cb) { - if (!params) params = {}; - if (!params.host) params.host = window.location.host.split(':')[0]; - if (!params.port) params.port = window.location.port; - - var req = new Request(new xhrHttp, params); - if (cb) req.on('response', cb); - return req; -}; - -http.get = function (params, cb) { - params.method = 'GET'; - var req = http.request(params, cb); - req.end(); - return req; -}; - -var xhrHttp = (function () { - if (typeof window === 'undefined') { - throw new Error('no window object present'); - } - else if (window.XMLHttpRequest) { - return window.XMLHttpRequest; - } - else if (window.ActiveXObject) { - var axs = [ - 'Msxml2.XMLHTTP.6.0', - 'Msxml2.XMLHTTP.3.0', - 'Microsoft.XMLHTTP' - ]; - for (var i = 0; i < axs.length; i++) { - try { - var ax = new(window.ActiveXObject)(axs[i]); - return function () { - if (ax) { - var ax_ = ax; - ax = null; - return ax_; - } - else { - return new(window.ActiveXObject)(axs[i]); - } - }; - } - catch (e) {} - } - throw new Error('ajax not supported in this browser') - } - else { - throw new Error('ajax not supported in this browser'); - } -})(); - -http.STATUS_CODES = { - 100 : 'Continue', - 101 : 'Switching Protocols', - 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918 - 200 : 'OK', - 201 : 'Created', - 202 : 'Accepted', - 203 : 'Non-Authoritative Information', - 204 : 'No Content', - 205 : 'Reset Content', - 206 : 'Partial Content', - 207 : 'Multi-Status', // RFC 4918 - 300 : 'Multiple Choices', - 301 : 'Moved Permanently', - 302 : 'Moved Temporarily', - 303 : 'See Other', - 304 : 'Not Modified', - 305 : 'Use Proxy', - 307 : 'Temporary Redirect', - 400 : 'Bad Request', - 401 : 'Unauthorized', - 402 : 'Payment Required', - 403 : 'Forbidden', - 404 : 'Not Found', - 405 : 'Method Not Allowed', - 406 : 'Not Acceptable', - 407 : 'Proxy Authentication Required', - 408 : 'Request Time-out', - 409 : 'Conflict', - 410 : 'Gone', - 411 : 'Length Required', - 412 : 'Precondition Failed', - 413 : 'Request Entity Too Large', - 414 : 'Request-URI Too Large', - 415 : 'Unsupported Media Type', - 416 : 'Requested Range Not Satisfiable', - 417 : 'Expectation Failed', - 418 : 'I\'m a teapot', // RFC 2324 - 422 : 'Unprocessable Entity', // RFC 4918 - 423 : 'Locked', // RFC 4918 - 424 : 'Failed Dependency', // RFC 4918 - 425 : 'Unordered Collection', // RFC 4918 - 426 : 'Upgrade Required', // RFC 2817 - 500 : 'Internal Server Error', - 501 : 'Not Implemented', - 502 : 'Bad Gateway', - 503 : 'Service Unavailable', - 504 : 'Gateway Time-out', - 505 : 'HTTP Version not supported', - 506 : 'Variant Also Negotiates', // RFC 2295 - 507 : 'Insufficient Storage', // RFC 4918 - 509 : 'Bandwidth Limit Exceeded', - 510 : 'Not Extended' // RFC 2774 -}; - -}); - -require.define("/node_modules/http-browserify/lib/request.js", function (require, module, exports, __dirname, __filename) { - var EventEmitter = require('events').EventEmitter; -var Response = require('./response'); -var isSafeHeader = require('./isSafeHeader'); - -var Request = module.exports = function (xhr, params) { - var self = this; - self.xhr = xhr; - self.body = ''; - - var uri = params.host + ':' + params.port + (params.path || '/'); - - xhr.open( - params.method || 'GET', - (params.scheme || 'http') + '://' + uri, - true - ); - - if (params.headers) { - Object.keys(params.headers).forEach(function (key) { - if (!isSafeHeader(key)) return; - var value = params.headers[key]; - if (Array.isArray(value)) { - value.forEach(function (v) { - xhr.setRequestHeader(key, v); - }); - } - else xhr.setRequestHeader(key, value) - }); - } - - var res = new Response(xhr); - res.on('ready', function () { - self.emit('response', res); - }); - - xhr.onreadystatechange = function () { - res.handle(xhr); - }; -}; - -Request.prototype = new EventEmitter; - -Request.prototype.setHeader = function (key, value) { - if ((Array.isArray && Array.isArray(value)) - || value instanceof Array) { - for (var i = 0; i < value.length; i++) { - this.xhr.setRequestHeader(key, value[i]); - } - } - else { - this.xhr.setRequestHeader(key, value); - } -}; - -Request.prototype.write = function (s) { - this.body += s; -}; - -Request.prototype.end = function (s) { - if (s !== undefined) this.write(s); - this.xhr.send(this.body); -}; - -}); - -require.define("/node_modules/http-browserify/lib/response.js", function (require, module, exports, __dirname, __filename) { - var EventEmitter = require('events').EventEmitter; -var isSafeHeader = require('./isSafeHeader'); - -var Response = module.exports = function (xhr) { - this.xhr = xhr; - this.offset = 0; -}; - -Response.prototype = new EventEmitter; - -var capable = { - streaming : true, - status2 : true -}; - -function parseHeaders (xhr) { - var lines = xhr.getAllResponseHeaders().split(/\r?\n/); - var headers = {}; - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line === '') continue; - - var m = line.match(/^([^:]+):\s*(.*)/); - if (m) { - var key = m[1].toLowerCase(), value = m[2]; - - if (headers[key] !== undefined) { - if ((Array.isArray && Array.isArray(headers[key])) - || headers[key] instanceof Array) { - headers[key].push(value); - } - else { - headers[key] = [ headers[key], value ]; - } - } - else { - headers[key] = value; - } - } - else { - headers[line] = true; - } - } - return headers; -} - -Response.prototype.getHeader = function (key) { - var header = this.headers ? this.headers[key.toLowerCase()] : null; - if (header) return header; - - // Work around Mozilla bug #608735 [https://bugzil.la/608735], which causes - // getAllResponseHeaders() to return {} if the response is a CORS request. - // xhr.getHeader still works correctly. - if (isSafeHeader(key)) { - return this.xhr.getResponseHeader(key); - } - return null; -}; - -Response.prototype.handle = function () { - var xhr = this.xhr; - if (xhr.readyState === 2 && capable.status2) { - try { - this.statusCode = xhr.status; - this.headers = parseHeaders(xhr); - } - catch (err) { - capable.status2 = false; - } - - if (capable.status2) { - this.emit('ready'); - } - } - else if (capable.streaming && xhr.readyState === 3) { - try { - if (!this.statusCode) { - this.statusCode = xhr.status; - this.headers = parseHeaders(xhr); - this.emit('ready'); - } - } - catch (err) {} - - try { - this.write(); - } - catch (err) { - capable.streaming = false; - } - } - else if (xhr.readyState === 4) { - if (!this.statusCode) { - this.statusCode = xhr.status; - this.emit('ready'); - } - this.write(); - - if (xhr.error) { - this.emit('error', xhr.responseText); - } - else this.emit('end'); - } -}; - -Response.prototype.write = function () { - var xhr = this.xhr; - if (xhr.responseText.length > this.offset) { - this.emit('data', xhr.responseText.slice(this.offset)); - this.offset = xhr.responseText.length; - } -}; - -}); - -require.define("/node_modules/http-browserify/lib/isSafeHeader.js", function (require, module, exports, __dirname, __filename) { - // Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html -var unsafeHeaders = [ - "accept-charset", - "accept-encoding", - "access-control-request-headers", - "access-control-request-method", - "connection", - "content-length", - "cookie", - "cookie2", - "content-transfer-encoding", - "date", - "expect", - "host", - "keep-alive", - "origin", - "referer", - "set-cookie", - "te", - "trailer", - "transfer-encoding", - "upgrade", - "user-agent", - "via" -]; - -module.exports = function (headerName) { - if (!headerName) return false; - return (unsafeHeaders.indexOf(headerName.toLowerCase()) === -1) -}; - -}); - -require.alias("http-browserify", "/node_modules/http"); - -require.alias("http-browserify", "/node_modules/https"); \ No newline at end of file diff --git a/dist/lib/shred/content.js b/dist/lib/shred/content.js deleted file mode 100644 index b8051fedd9e..00000000000 --- a/dist/lib/shred/content.js +++ /dev/null @@ -1,193 +0,0 @@ - -// The purpose of the `Content` object is to abstract away the data conversions -// to and from raw content entities as strings. For example, you want to be able -// to pass in a Javascript object and have it be automatically converted into a -// JSON string if the `content-type` is set to a JSON-based media type. -// Conversely, you want to be able to transparently get back a Javascript object -// in the response if the `content-type` is a JSON-based media-type. - -// One limitation of the current implementation is that it [assumes the `charset` is UTF-8](https://github.com/spire-io/shred/issues/5). - -// The `Content` constructor takes an options object, which *must* have either a -// `body` or `data` property and *may* have a `type` property indicating the -// media type. If there is no `type` attribute, a default will be inferred. -var Content = function(options) { - this.body = options.body; - this.data = options.data; - this.type = options.type; -}; - -Content.prototype = { - // Treat `toString()` as asking for the `content.body`. That is, the raw content entity. - // - // toString: function() { return this.body; } - // - // Commented out, but I've forgotten why. :/ -}; - - -// `Content` objects have the following attributes: -Object.defineProperties(Content.prototype,{ - -// - **type**. Typically accessed as `content.type`, reflects the `content-type` -// header associated with the request or response. If not passed as an options -// to the constructor or set explicitly, it will infer the type the `data` -// attribute, if possible, and, failing that, will default to `text/plain`. - type: { - get: function() { - if (this._type) { - return this._type; - } else { - if (this._data) { - switch(typeof this._data) { - case "string": return "text/plain"; - case "object": return "application/json"; - } - } - } - return "text/plain"; - }, - set: function(value) { - this._type = value; - return this; - }, - enumerable: true - }, - -// - **data**. Typically accessed as `content.data`, reflects the content entity -// converted into Javascript data. This can be a string, if the `type` is, say, -// `text/plain`, but can also be a Javascript object. The conversion applied is -// based on the `processor` attribute. The `data` attribute can also be set -// directly, in which case the conversion will be done the other way, to infer -// the `body` attribute. - data: { - get: function() { - if (this._body) { - return this.processor.parser(this._body); - } else { - return this._data; - } - }, - set: function(data) { - if (this._body&&data) Errors.setDataWithBody(this); - this._data = data; - return this; - }, - enumerable: true - }, - -// - **body**. Typically accessed as `content.body`, reflects the content entity -// as a UTF-8 string. It is the mirror of the `data` attribute. If you set the -// `data` attribute, the `body` attribute will be inferred and vice-versa. If -// you attempt to set both, an exception is raised. - body: { - get: function() { - if (this._data) { - return this.processor.stringify(this._data); - } else { - return this._body.toString(); - } - }, - set: function(body) { - if (this._data&&body) Errors.setBodyWithData(this); - this._body = body; - return this; - }, - enumerable: true - }, - -// - **processor**. The functions that will be used to convert to/from `data` and -// `body` attributes. You can add processors. The two that are built-in are for -// `text/plain`, which is basically an identity transformation and -// `application/json` and other JSON-based media types (including custom media -// types with `+json`). You can add your own processors. See below. - processor: { - get: function() { - var processor = Content.processors[this.type]; - if (processor) { - return processor; - } else { - // Return the first processor that matches any part of the - // content type. ex: application/vnd.foobar.baz+json will match json. - var main = this.type.split(";")[0]; - var parts = main.split(/\+|\//); - for (var i=0, l=parts.length; i < l; i++) { - processor = Content.processors[parts[i]] - } - return processor || {parser:identity,stringify:toString}; - } - }, - enumerable: true - }, - -// - **length**. Typically accessed as `content.length`, returns the length in -// bytes of the raw content entity. - length: { - get: function() { - if (typeof Buffer !== 'undefined') { - return Buffer.byteLength(this.body); - } - return this.body.length; - } - } -}); - -Content.processors = {}; - -// The `registerProcessor` function allows you to add your own processors to -// convert content entities. Each processor consists of a Javascript object with -// two properties: -// - **parser**. The function used to parse a raw content entity and convert it -// into a Javascript data type. -// - **stringify**. The function used to convert a Javascript data type into a -// raw content entity. -Content.registerProcessor = function(types,processor) { - -// You can pass an array of types that will trigger this processor, or just one. -// We determine the array via duck-typing here. - if (types.forEach) { - types.forEach(function(type) { - Content.processors[type] = processor; - }); - } else { - // If you didn't pass an array, we just use what you pass in. - Content.processors[types] = processor; - } -}; - -// Register the identity processor, which is used for text-based media types. -var identity = function(x) { return x; } - , toString = function(x) { return x.toString(); } -Content.registerProcessor( - ["text/html","text/plain","text"], - { parser: identity, stringify: toString }); - -// Register the JSON processor, which is used for JSON-based media types. -Content.registerProcessor( - ["application/json; charset=utf-8","application/json","json"], - { - parser: function(string) { - return JSON.parse(string); - }, - stringify: function(data) { - return JSON.stringify(data); }}); - -var qs = require('querystring'); -// Register the post processor, which is used for JSON-based media types. -Content.registerProcessor( - ["application/x-www-form-urlencoded"], - { parser : qs.parse, stringify : qs.stringify }); - -// Error functions are defined separately here in an attempt to make the code -// easier to read. -var Errors = { - setDataWithBody: function(object) { - throw new Error("Attempt to set data attribute of a content object " + - "when the body attributes was already set."); - }, - setBodyWithData: function(object) { - throw new Error("Attempt to set body attribute of a content object " + - "when the data attributes was already set."); - } -} -module.exports = Content; \ No newline at end of file diff --git a/dist/lib/swagger-client.js b/dist/lib/swagger-client.js deleted file mode 100644 index 5be9552b907..00000000000 --- a/dist/lib/swagger-client.js +++ /dev/null @@ -1,3294 +0,0 @@ -/** - * swagger-client - swagger.js is a javascript client for use with swaggering APIs. - * @version v2.1.9-M1 - * @link http://swagger.io - * @license apache 2.0 - */ -(function(){ -var ArrayModel = function(definition) { - this.name = "arrayModel"; - this.definition = definition || {}; - this.properties = []; - - var requiredFields = definition.enum || []; - var innerType = definition.items; - if(innerType) { - if(innerType.type) { - this.type = typeFromJsonSchema(innerType.type, innerType.format); - } - else { - this.ref = innerType.$ref; - } - } - return this; -}; - -ArrayModel.prototype.createJSONSample = function(modelsToIgnore) { - var result; - modelsToIgnore = (modelsToIgnore||{}); - if(this.type) { - result = this.type; - } - else if (this.ref) { - var name = simpleRef(this.ref); - if(typeof modelsToIgnore[name] === 'undefined') { - modelsToIgnore[name] = this; - result = models[name].createJSONSample(modelsToIgnore); - } - else { - return name; - } - } - return [ result ]; -}; - -ArrayModel.prototype.getSampleValue = function(modelsToIgnore) { - var result; - modelsToIgnore = (modelsToIgnore || {}); - if(this.type) { - result = type; - } - else if (this.ref) { - var name = simpleRef(this.ref); - result = models[name].getSampleValue(modelsToIgnore); - } - return [ result ]; -}; - -ArrayModel.prototype.getMockSignature = function(modelsToIgnore) { - var propertiesStr = []; - var i, prop; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - propertiesStr.push(prop.toString()); - } - - var strong = ''; - var stronger = ''; - var strongClose = ''; - var classOpen = strong + 'array' + ' {' + strongClose; - var classClose = strong + '}' + strongClose; - var returnVal = classOpen + '
' + propertiesStr.join(',
') + '
' + classClose; - - if (!modelsToIgnore) - modelsToIgnore = {}; - modelsToIgnore[this.name] = this; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - var ref = prop.$ref; - var model = models[ref]; - if (model && typeof modelsToIgnore[ref] === 'undefined') { - returnVal = returnVal + ('
' + model.getMockSignature(modelsToIgnore)); - } - } - return returnVal; -}; - - -/** - * SwaggerAuthorizations applys the correct authorization to an operation being executed - */ -var SwaggerAuthorizations = function() { - this.authz = {}; -}; - -SwaggerAuthorizations.prototype.add = function(name, auth) { - this.authz[name] = auth; - return auth; -}; - -SwaggerAuthorizations.prototype.remove = function(name) { - return delete this.authz[name]; -}; - -SwaggerAuthorizations.prototype.apply = function (obj, authorizations) { - var status = null; - var key, name, value, result; - - // if the "authorizations" key is undefined, or has an empty array, add all keys - if (typeof authorizations === 'undefined' || Object.keys(authorizations).length === 0) { - for (key in this.authz) { - value = this.authz[key]; - result = value.apply(obj, authorizations); - if (result === true) - status = true; - } - } - else { - // 2.0 support - if (Array.isArray(authorizations)) { - - for (var i = 0; i < authorizations.length; i++) { - var auth = authorizations[i]; - for (name in auth) { - for (key in this.authz) { - if (key == name) { - value = this.authz[key]; - result = value.apply(obj, authorizations); - if (result === true) - status = true; - } - } - } - } - } - else { - // 1.2 support - for (name in authorizations) { - for (key in this.authz) { - if (key == name) { - value = this.authz[key]; - result = value.apply(obj, authorizations); - if (result === true) - status = true; - } - } - } - } - } - - return status; -}; - -/** - * ApiKeyAuthorization allows a query param or header to be injected - */ -var ApiKeyAuthorization = function(name, value, type) { - this.name = name; - this.value = value; - this.type = type; -}; - -ApiKeyAuthorization.prototype.apply = function(obj, authorizations) { - if (this.type === "query") { - 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") { - obj.headers[this.name] = this.value; - return true; - } -}; - -var CookieAuthorization = function(cookie) { - this.cookie = cookie; -}; - -CookieAuthorization.prototype.apply = function(obj, authorizations) { - obj.cookieJar = obj.cookieJar || CookieJar(); - obj.cookieJar.setCookie(this.cookie); - return true; -}; - -/** - * Password Authorization is a basic auth implementation - */ -var PasswordAuthorization = function(name, username, password) { - this.name = name; - this.username = username; - this.password = password; - this._btoa = null; - if (typeof window !== 'undefined') - this._btoa = btoa; - else - this._btoa = require("btoa"); -}; - -PasswordAuthorization.prototype.apply = function(obj, authorizations) { - var base64encoder = this._btoa; - obj.headers.Authorization = "Basic " + base64encoder(this.username + ":" + this.password); - return true; -}; -var __bind = function(fn, me){ - return function(){ - return fn.apply(me, arguments); - }; -}; - -fail = function(message) { - log(message); -}; - -log = function(){ - log.history = log.history || []; - log.history.push(arguments); - if(this.console){ - console.log( Array.prototype.slice.call(arguments)[0] ); - } -}; - -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; - }; -} - -/** - * allows override of the default value based on the parameter being - * supplied - **/ -var applyParameterMacro = function (operation, parameter) { - var e = (typeof window !== 'undefined' ? window : exports); - if(e.parameterMacro) - return e.parameterMacro(operation, parameter); - else - return parameter.defaultValue; -}; - -/** - * allows overriding the default value of an model property - **/ -var applyModelPropertyMacro = function (model, property) { - var e = (typeof window !== 'undefined' ? window : exports); - if(e.modelPropertyMacro) - return e.modelPropertyMacro(model, property); - else - return property.defaultValue; -}; - -/** - * PrimitiveModel - **/ -var PrimitiveModel = function(definition) { - this.name = "name"; - this.definition = definition || {}; - this.properties = []; - - var requiredFields = definition.enum || []; - this.type = typeFromJsonSchema(definition.type, definition.format); -}; - -PrimitiveModel.prototype.createJSONSample = function(modelsToIgnore) { - var result = this.type; - return result; -}; - -PrimitiveModel.prototype.getSampleValue = function() { - var result = this.type; - return null; -}; - -PrimitiveModel.prototype.getMockSignature = function(modelsToIgnore) { - var propertiesStr = []; - var i, prop; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - propertiesStr.push(prop.toString()); - } - - var strong = ''; - var stronger = ''; - var strongClose = ''; - var classOpen = strong + this.name + ' {' + strongClose; - var classClose = strong + '}' + strongClose; - var returnVal = classOpen + '
' + propertiesStr.join(',
') + '
' + classClose; - - if (!modelsToIgnore) - modelsToIgnore = {}; - modelsToIgnore[this.name] = this; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - var ref = prop.$ref; - var model = models[ref]; - if (model && typeof modelsToIgnore[ref] === 'undefined') { - returnVal = returnVal + ('
' + model.getMockSignature(modelsToIgnore)); - } - } - return returnVal; -}; -/** - * Resolves a spec's remote references - */ -var Resolver = function (){}; - -Resolver.prototype.resolve = function(spec, callback, scope) { - this.scope = (scope || this); - var host, name, path, property, propertyName, type; - var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {}; - - // store objects for dereferencing - var resolutionTable = {}; - - // models - for(name in spec.definitions) { - var model = spec.definitions[name]; - for(propertyName in model.properties) { - property = model.properties[propertyName]; - this.resolveTo(property, resolutionTable); - } - } - // operations - for(name in spec.paths) { - var method, operation, responseCode; - path = spec.paths[name]; - for(method in path) { - operation = path[method]; - var i, parameters = operation.parameters; - for(i in parameters) { - var parameter = parameters[i]; - if(parameter.in === 'body' && parameter.schema) { - this.resolveTo(parameter.schema, resolutionTable); - } - if(parameter.$ref) { - this.resolveInline(spec, parameter, resolutionTable, unresolvedRefs); - } - } - for(responseCode in operation.responses) { - var response = operation.responses[responseCode]; - if(response.schema) { - this.resolveTo(response.schema, resolutionTable); - } - } - } - } - // get hosts - var opts = {}, expectedCalls = 0; - for(name in resolutionTable) { - var parts = name.split('#'); - if(parts.length == 2) { - host = parts[0]; path = parts[1]; - if(!Array.isArray(opts[host])) { - opts[host] = []; - expectedCalls += 1; - } - opts[host].push(path); - } - } - - for(name in opts) { - var self = this, opt = opts[name]; - host = name; - - var obj = { - useJQuery: false, // TODO - url: host, - method: "get", - headers: { - accept: this.scope.swaggerRequestHeaders || 'application/json' - }, - on: { - error: function(response) { - processedCalls += 1; - var i; - for(i = 0; i < opt.length; i++) { - // fail all of these - var resolved = host + '#' + opt[i]; - unresolvedRefs[resolved] = null; - } - if(processedCalls === expectedCalls) - self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback); - }, - response: function(response) { - var i, j, swagger = response.obj; - processedCalls += 1; - for(i = 0; i < opt.length; i++) { - var location = swagger, path = opt[i], parts = path.split('/'); - for(j = 0; j < parts.length; j++) { - var segment = parts[j]; - if(typeof location === 'undefined') - break; - if(segment.length > 0) - location = location[segment]; - } - var resolved = host + '#' + path, resolvedName = parts[j-1]; - if(typeof location !== 'undefined') { - resolvedRefs[resolved] = { - name: resolvedName, - obj: location - }; - } - else unresolvedRefs[resolved] = null; - } - if(processedCalls === expectedCalls) - self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback); - } - } - }; - authorizations.apply(obj); - new SwaggerHttp().execute(obj); - } - if(Object.keys(opts).length === 0) - callback.call(this.scope, spec, unresolvedRefs); -}; - -Resolver.prototype.finish = function(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback) { - // walk resolution table and replace with resolved refs - var ref; - for(ref in resolutionTable) { - var i, locations = resolutionTable[ref]; - for(i = 0; i < locations.length; i++) { - var resolvedTo = resolvedRefs[locations[i].obj.$ref]; - if(resolvedTo) { - if(!spec.definitions) - spec.definitions = {}; - if(locations[i].resolveAs === '$ref') { - spec.definitions[resolvedTo.name] = resolvedTo.obj; - locations[i].obj.$ref = '#/definitions/' + resolvedTo.name; - } - else if (locations[i].resolveAs === 'inline') { - var key; - var targetObj = locations[i].obj; - delete targetObj.$ref; - for(key in resolvedTo.obj) { - targetObj[key] = resolvedTo.obj[key]; - } - } - } - } - } - callback.call(this.scope, spec, unresolvedRefs); -}; - -/** - * immediately in-lines local refs, queues remote refs - * for inline resolution - */ -Resolver.prototype.resolveInline = function (spec, property, objs, unresolvedRefs) { - var ref = property.$ref; - if(ref) { - if(ref.indexOf('http') === 0) { - if(Array.isArray(objs[ref])) { - objs[ref].push({obj: property, resolveAs: 'inline'}); - } - else { - objs[ref] = [{obj: property, resolveAs: 'inline'}]; - } - } - else if (ref.indexOf('#') === 0) { - // local resolve - var shortenedRef = ref.substring(1); - var i, parts = shortenedRef.split('/'), location = spec; - for(i = 0; i < parts.length; i++) { - var part = parts[i]; - if(part.length > 0) { - location = location[part]; - } - } - if(location) { - delete property.$ref; - var key; - for(key in location) { - property[key] = location[key]; - } - } - else unresolvedRefs[ref] = null; - } - } - else if(property.type === 'array') { - this.resolveTo(property.items, objs); - } -}; - -Resolver.prototype.resolveTo = function (property, objs) { - var ref = property.$ref; - if(ref) { - if(ref.indexOf('http') === 0) { - if(Array.isArray(objs[ref])) { - objs[ref].push({obj: property, resolveAs: '$ref'}); - } - else { - objs[ref] = [{obj: property, resolveAs: '$ref'}]; - } - } - } - else if(property.type === 'array') { - var items = property.items; - this.resolveTo(items, objs); - } -}; -var addModel = function(name, model) { - models[name] = model; -}; - -var SwaggerClient = function(url, options) { - this.isBuilt = false; - this.url = null; - this.debug = false; - this.basePath = null; - this.modelsArray = []; - this.authorizations = null; - this.authorizationScheme = null; - this.isValid = false; - this.info = null; - this.useJQuery = false; - this.resourceCount = 0; - - if(typeof url !== 'undefined') - return this.initialize(url, options); -}; - -SwaggerClient.prototype.initialize = function (url, options) { - this.models = models = {}; - - options = (options||{}); - - if(typeof url === 'string') - this.url = url; - else if(typeof url === 'object') { - options = url; - this.url = options.url; - } - this.swaggerRequstHeaders = options.swaggerRequstHeaders || 'application/json;charset=utf-8,*/*'; - this.defaultSuccessCallback = options.defaultSuccessCallback || null; - this.defaultErrorCallback = options.defaultErrorCallback || null; - - if (typeof options.success === 'function') - this.success = options.success; - - if (options.useJQuery) - this.useJQuery = options.useJQuery; - - if (options.authorizations) { - this.clientAuthorizations = options.authorizations; - } else { - this.clientAuthorizations = authorizations; - } - - this.supportedSubmitMethods = options.supportedSubmitMethods || []; - this.failure = options.failure || function() {}; - this.progress = options.progress || function() {}; - this.spec = options.spec; - this.options = options; - - if (typeof options.success === 'function') { - this.ready = true; - this.build(); - } -}; - -SwaggerClient.prototype.build = function(mock) { - if (this.isBuilt) return this; - var self = this; - this.progress('fetching resource list: ' + this.url); - var obj = { - useJQuery: this.useJQuery, - url: this.url, - method: "get", - headers: { - accept: this.swaggerRequstHeaders - }, - 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 || JSON.parse(resp.data); - self.swaggerVersion = responseObj.swaggerVersion; - - if(responseObj.swagger && parseInt(responseObj.swagger) === 2) { - self.swaggerVersion = responseObj.swagger; - new Resolver().resolve(responseObj, self.buildFromSpec, self); - self.isValid = true; - } - else { - if (self.swaggerVersion === '1.2') { - return self.buildFrom1_2Spec(responseObj); - } else { - return self.buildFrom1_1Spec(responseObj); - } - } - } - } - }; - if(this.spec) { - setTimeout(function() { - new Resolver().resolve(self.spec, self.buildFromSpec, self); - }, 10); - } - else { - authorizations.apply(obj); - if(mock) - return obj; - new SwaggerHttp().execute(obj); - } - return this; -}; - -SwaggerClient.prototype.buildFromSpec = function(response) { - if(this.isBuilt) return this; - - this.info = response.info || {}; - this.title = response.title || ''; - this.host = response.host || ''; - this.schemes = response.schemes || []; - this.basePath = response.basePath || ''; - this.apis = {}; - this.apisArray = []; - this.consumes = response.consumes; - this.produces = response.produces; - this.securityDefinitions = response.securityDefinitions; - - // legacy support - this.authSchemes = response.securityDefinitions; - - var definedTags = {}; - 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.schemes === 'undefined' || this.schemes.length === 0) { - this.scheme = location.scheme || 'http'; - } - else { - this.scheme = this.schemes[0]; - } - - if(typeof this.host === 'undefined' || this.host === '') { - this.host = location.host; - if (location.port) { - this.host = this.host + ':' + location.port; - } - } - - this.definitions = response.definitions; - var key; - for(key in this.definitions) { - var model = new Model(key, this.definitions[key]); - if(model) { - models[key] = model; - } - } - - // get paths, create functions for each operationId - var path; - var operations = []; - for(path in response.paths) { - if(typeof response.paths[path] === 'object') { - var httpMethod; - for(httpMethod in response.paths[path]) { - if(['delete', 'get', 'head', 'options', 'patch', 'post', 'put'].indexOf(httpMethod) === -1) { - continue; - } - var operation = response.paths[path][httpMethod]; - var tags = operation.tags; - if(typeof tags === 'undefined') { - operation.tags = [ 'default' ]; - tags = operation.tags; - } - var operationId = this.idFromOp(path, httpMethod, operation); - var operationObject = new Operation ( - this, - operation.scheme, - operationId, - httpMethod, - path, - operation, - this.definitions - ); - // bind this operation's execute command to the api - if(tags.length > 0) { - var i; - for(i = 0; i < tags.length; i++) { - var tag = this.tagFromLabel(tags[i]); - var operationGroup = this[tag]; - if(typeof this.apis[tag] === 'undefined') - this.apis[tag] = {}; - if(typeof operationGroup === 'undefined') { - this[tag] = []; - operationGroup = this[tag]; - operationGroup.operations = {}; - operationGroup.label = tag; - operationGroup.apis = []; - var tagObject = definedTags[tag]; - if(typeof tagObject === 'object') { - operationGroup.description = tagObject.description; - operationGroup.externalDocs = tagObject.externalDocs; - } - this[tag].help = this.help.bind(operationGroup); - this.apisArray.push(new OperationGroup(tag, operationGroup.description, operationGroup.externalDocs, operationObject)); - } - if(typeof this.apis[tag].help !== 'function') - this.apis[tag].help = this.help.bind(operationGroup); - // bind to the apis object - this.apis[tag][operationId] = operationObject.execute.bind(operationObject); - this.apis[tag][operationId].help = operationObject.help.bind(operationObject); - this.apis[tag][operationId].asCurl = operationObject.asCurl.bind(operationObject); - operationGroup[operationId] = operationObject.execute.bind(operationObject); - operationGroup[operationId].help = operationObject.help.bind(operationObject); - operationGroup[operationId].asCurl = operationObject.asCurl.bind(operationObject); - - operationGroup.apis.push(operationObject); - operationGroup.operations[operationId] = operationObject; - - // legacy UI feature - var j; - var api; - for(j = 0; j < this.apisArray.length; j++) { - if(this.apisArray[j].tag === tag) { - api = this.apisArray[j]; - } - } - if(api) { - api.operationsArray.push(operationObject); - } - } - } - else { - log('no group to bind to'); - } - } - } - } - this.isBuilt = true; - if (this.success) { - this.isValid = true; - this.isBuilt = true; - this.success(); - } - return this; -}; - -SwaggerClient.prototype.parseUri = function(uri) { - var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/; - var parts = urlParseRE.exec(uri); - return { - scheme: parts[4].replace(':',''), - host: parts[11], - port: parts[12], - path: parts[15] - }; -}; - -SwaggerClient.prototype.help = function(dontPrint) { - var i; - var output = 'operations for the "' + this.label + '" tag'; - for(i = 0; i < this.apis.length; i++) { - var api = this.apis[i]; - output += '\n * ' + api.nickname + ': ' + api.operation.summary; - } - if(dontPrint) - return output; - else { - log(output); - return output; - } -}; - -SwaggerClient.prototype.tagFromLabel = function(label) { - return label; -}; - -SwaggerClient.prototype.idFromOp = function(path, httpMethod, op) { - var opId = op.operationId || (path.substring(1) + '_' + httpMethod); - return opId.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()\+\s]/g,'_'); -}; - -SwaggerClient.prototype.fail = function(message) { - this.failure(message); - throw message; -}; - -var OperationGroup = function(tag, description, externalDocs, operation) { - this.tag = tag; - this.path = tag; - this.description = description; - this.externalDocs = externalDocs; - this.name = tag; - this.operation = operation; - this.operationsArray = []; -}; - -var Operation = function(parent, scheme, operationId, httpMethod, path, args, definitions) { - var errors = []; - parent = parent||{}; - args = args||{}; - - this.operations = {}; - this.operation = args; - this.deprecated = args.deprecated; - this.consumes = args.consumes; - this.produces = args.produces; - this.parent = parent; - this.host = parent.host || 'localhost'; - this.schemes = parent.schemes; - this.scheme = scheme || parent.scheme || 'http'; - this.basePath = parent.basePath || '/'; - this.nickname = (operationId||errors.push('Operations must have a nickname.')); - this.method = (httpMethod||errors.push('Operation ' + operationId + ' is missing method.')); - this.path = (path||errors.push('Operation ' + this.nickname + ' is missing path.')); - this.parameters = args !== null ? (args.parameters||[]) : {}; - this.summary = args.summary || ''; - this.responses = (args.responses||{}); - this.type = null; - this.security = args.security; - this.authorizations = args.security; - this.description = args.description; - this.useJQuery = parent.useJQuery; - - 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 this.definitions) { - model = new Model(key, definitions[key]); - if(model) { - models[key] = model; - } - } - } - for(i = 0; i < this.parameters.length; i++) { - var param = this.parameters[i]; - if(param.type === 'array') { - param.isList = true; - param.allowMultiple = true; - } - var innerType = this.getType(param); - if(innerType && innerType.toString().toLowerCase() === 'boolean') { - param.allowableValues = {}; - param.isList = true; - param['enum'] = ["true", "false"]; - } - 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) ? true : false; - param.allowableValues.values.push(value); - 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.signature = this.getModelSignature(innerType, models).toString(); - param.sampleJSON = this.getModelSampleJSON(innerType, 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); - delete responses[defaultResponseCode]; - if(resolvedModel) { - this.successResponse = {}; - this.successResponse[defaultResponseCode] = resolvedModel; - } - else { - this.successResponse = {}; - this.successResponse[defaultResponseCode] = response.schema.type; - } - this.type = response; - } - - if (errors.length > 0) { - if(this.resource && this.resource.api && this.resource.api.fail) - this.resource.api.fail(errors); - } - - return this; -}; - -OperationGroup.prototype.sort = function(sorter) { - -}; - -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); - } - if(param.$ref) - str = param.$ref; - - var schema = param.schema; - if(schema) { - var ref = schema.$ref; - if(ref) { - ref = simpleRef(ref); - if(isArray) - return [ ref ]; - else - return ref; - } - else - return this.getType(schema); - } - if(isArray) - return [ str ]; - else - return str; -}; - -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]); - } - } - if(schema.type === 'array') - return new ArrayModel(schema); - else - 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') - log(out); - return out; -}; - -Operation.prototype.getModelSignature = function(type, definitions) { - var isPrimitive, listType; - - if(type instanceof Array) { - listType = true; - type = type[0]; - } - else if(typeof type === 'undefined') - type = 'undefined'; - - if(type === 'string') - isPrimitive = true; - else - isPrimitive = (listType && definitions[listType]) || (definitions[type]) ? false : true; - if (isPrimitive) { - if(listType) - return 'Array[' + type + ']'; - else - return type.toString(); - } else { - if (listType) - return 'Array[' + definitions[type].getMockSignature() + ']'; - else - return definitions[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; - - // grab params from the args, build the querystring along the way - var querystring = ''; - 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 = {}, body, key; - - 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]; - } - } - } - - // handle form params - if(headers['Content-Type'] === 'application/x-www-form-urlencoded') { - 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 (headers['Content-Type'] && headers['Content-Type'].indexOf('multipart/form-data') >= 0) { - 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 isPrimitive, listType, sampleJson; - - listType = (type instanceof Array); - isPrimitive = models[type] ? false : true; - sampleJson = isPrimitive ? void 0 : models[type].createJSONSample(); - if (sampleJson) { - sampleJson = listType ? [sampleJson] : sampleJson; - if(typeof sampleJson == 'string') - return sampleJson; - else if(typeof sampleJson === 'object') { - var t = sampleJson; - if(sampleJson instanceof Array && sampleJson.length > 0) { - t = sampleJson[0]; - } - if(t.nodeName) { - 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; - if(typeof arg2 === 'object') { - opts = arg2; - success = arg3; - error = arg4; - } - - if(typeof arg2 === 'function') { - success = arg2; - error = arg3; - } - - success = (success||log); - error = (error||log); - - if(opts.useJQuery) - this.useJQuery = opts.useJQuery; - - var missingParams = this.getMissingParams(args); - if(missingParams.length > 0) { - var message = 'missing required params: ' + missingParams; - fail(message); - 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(headers, args, opts); - var url = this.urlify(args); - - var obj = { - url: url, - method: this.method.toUpperCase(), - body: body, - useJQuery: this.useJQuery, - headers: headers, - on: { - response: function(response) { - return success(response, parent); - }, - error: function(response) { - return error(response, parent); - } - } - }; - var status = authorizations.apply(obj, this.operation.security); - if(opts.mock === true) - return obj; - else - new SwaggerHttp().execute(obj, opts); -}; - -Operation.prototype.setContentTypes = function(args, opts) { - // default type - var accepts = 'application/json'; - var consumes = args.parameterContentType || 'application/json'; - var allDefinedParams = this.parameters; - var definedFormParams = []; - var definedFileParams = []; - var body; - var headers = {}; - - // get params from the operation and set them in definedFileParams, definedFormParams, headers - var i; - 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 (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) { - if (opts.requestContentType) - consumes = opts.requestContentType; - } else { - // 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 if (this.type == 'DELETE') - body = '{}'; - else if (this.type != 'DELETE') - consumes = null; - } - - if (consumes && this.consumes) { - if (this.consumes.indexOf(consumes) === -1) { - log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.consumes)); - } - } - - if (opts.responseContentType) { - accepts = opts.responseContentType; - } else { - accepts = 'application/json'; - } - if (accepts && this.produces) { - if (this.produces.indexOf(accepts) === -1) { - 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; -}; - -Operation.prototype.asCurl = function (args) { - var obj = this.execute(args, {mock: true}); - authorizations.apply(obj); - var results = []; - results.push('-X ' + this.method.toUpperCase()); - if (obj.headers) { - var key; - for (key in obj.headers) - results.push('--header "' + key + ': ' + obj.headers[key] + '"'); - } - if(obj.body) { - var body; - if(typeof obj.body === 'object') - body = JSON.stringify(obj.body); - else - body = obj.body; - results.push('-d "' + body.replace(/"/g, '\\"') + '"'); - } - 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) { - var encParts, part, parts, i, len; - pathParam = pathParam.toString(); - if (pathParam.indexOf('/') === -1) { - return encodeURIComponent(pathParam); - } else { - parts = pathParam.split('/'); - encParts = []; - for (i = 0, len = parts.length; i < len; i++) { - encParts.push(encodeURIComponent(parts[i])); - } - return encParts.join('/'); - } -}; - -var Model = function(name, definition) { - this.name = name; - this.definition = definition || {}; - this.properties = []; - var requiredFields = definition.required || []; - if(definition.type === 'array') { - var out = new ArrayModel(definition); - return out; - } - var key; - var props = definition.properties; - if(props) { - for(key in props) { - var required = false; - var property = props[key]; - if(requiredFields.indexOf(key) >= 0) - required = true; - this.properties.push(new Property(key, property, required)); - } - } -}; - -Model.prototype.createJSONSample = function(modelsToIgnore) { - var i, result = {}, representations = {}; - modelsToIgnore = (modelsToIgnore||{}); - modelsToIgnore[this.name] = this; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - var sample = prop.getSampleValue(modelsToIgnore, representations); - result[prop.name] = sample; - } - delete modelsToIgnore[this.name]; - return result; -}; - -Model.prototype.getSampleValue = function(modelsToIgnore) { - var i, obj = {}, representations = {}; - for(i = 0; i < this.properties.length; i++ ) { - var property = this.properties[i]; - obj[property.name] = property.sampleValue(false, modelsToIgnore, representations); - } - return obj; -}; - -Model.prototype.getMockSignature = function(modelsToIgnore) { - var i, prop, propertiesStr = []; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - propertiesStr.push(prop.toString()); - } - var strong = ''; - var stronger = ''; - var strongClose = ''; - var classOpen = strong + this.name + ' {' + strongClose; - var classClose = strong + '}' + strongClose; - var returnVal = classOpen + '
' + propertiesStr.join(',
') + '
' + classClose; - if (!modelsToIgnore) - modelsToIgnore = {}; - - modelsToIgnore[this.name] = this; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - var ref = prop.$ref; - var model = models[ref]; - if (model && typeof modelsToIgnore[model.name] === 'undefined') { - returnVal = returnVal + ('
' + model.getMockSignature(modelsToIgnore)); - } - } - return returnVal; -}; - -var Property = function(name, obj, required) { - this.schema = obj; - this.required = required; - if(obj.$ref) - this.$ref = simpleRef(obj.$ref); - else if (obj.type === 'array' && obj.items) { - if(obj.items.$ref) - this.$ref = simpleRef(obj.items.$ref); - else - obj = obj.items; - } - this.name = name; - this.description = obj.description; - this.obj = obj; - this.optional = true; - this.optional = !required; - this.default = obj.default || null; - this.example = obj.example !== undefined ? obj.example : null; - this.collectionFormat = obj.collectionFormat || null; - this.maximum = obj.maximum || null; - this.exclusiveMaximum = obj.exclusiveMaximum || null; - this.minimum = obj.minimum || null; - this.exclusiveMinimum = obj.exclusiveMinimum || null; - this.maxLength = obj.maxLength || null; - this.minLength = obj.minLength || null; - this.pattern = obj.pattern || null; - this.maxItems = obj.maxItems || null; - this.minItems = obj.minItems || null; - this.uniqueItems = obj.uniqueItems || null; - this['enum'] = obj['enum'] || null; - this.multipleOf = obj.multipleOf || null; -}; - -Property.prototype.getSampleValue = function (modelsToIgnore, representations) { - return this.sampleValue(false, modelsToIgnore, representations); -}; - -Property.prototype.isArray = function () { - var schema = this.schema; - if(schema.type === 'array') - return true; - else - return false; -}; - -Property.prototype.sampleValue = function(isArray, ignoredModels, representations) { - isArray = (isArray || this.isArray()); - ignoredModels = (ignoredModels || {}); - // representations = (representations || {}); - - var type = getStringSignature(this.obj, true); - var output; - - if(this.$ref) { - var refModelName = simpleRef(this.$ref); - var refModel = models[refModelName]; - if(typeof representations[type] !== 'undefined') { - return representations[type]; - } - else - - if(refModel && typeof ignoredModels[type] === 'undefined') { - ignoredModels[type] = this; - output = refModel.getSampleValue(ignoredModels, representations); - representations[type] = output; - } - else { - output = (representations[type] || refModelName); - } - } - else if(this.example) - output = this.example; - else if(this.default) - output = this.default; - else if(type === 'date-time') - output = new Date().toISOString(); - else if(type === 'date') - output = new Date().toISOString().split("T")[0]; - else if(type === 'string') - output = 'string'; - else if(type === 'integer') - output = 0; - else if(type === 'long') - output = 0; - else if(type === 'float') - output = 0.0; - else if(type === 'double') - output = 0.0; - else if(type === 'boolean') - output = true; - else - output = {}; - ignoredModels[type] = output; - if(isArray) - return [output]; - else - return output; -}; - -getStringSignature = function(obj, baseComponent) { - var str = ''; - if(typeof obj.$ref !== 'undefined') - str += 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 += simpleRef(obj.$ref); - else - str += obj.type; - return str; -}; - -simpleRef = function(name) { - if(typeof name === 'undefined') - return null; - if(name.indexOf("#/definitions/") === 0) - return name.substring('#/definitions/'.length); - else - return name; -}; - -Property.prototype.toString = function() { - var str = getStringSignature(this.obj); - if(str !== '') { - str = '' + this.name + ' (' + str + ''; - if(!this.required) - str += ', optional'; - str += ')'; - } - else - str = this.name + ' (' + JSON.stringify(this.obj) + ')'; - - if(typeof this.description !== 'undefined') - str += ': ' + this.description; - - if (this['enum']) { - str += ' = [\'' + this['enum'].join('\' or \'') + '\']'; - } - if (this.descr) { - str += ': ' + this.descr + ''; - } - - - var options = ''; - var isArray = this.schema.type === 'array'; - var type; - - if(isArray) { - if(this.schema.items) - type = this.schema.items.type; - else - type = ''; - } - else { - type = this.schema.type; - } - - if (this.default) - options += optionHtml('Default', this.default); - - switch (type) { - case 'string': - if (this.minLength) - options += optionHtml('Min. Length', this.minLength); - if (this.maxLength) - options += optionHtml('Max. Length', this.maxLength); - if (this.pattern) - options += optionHtml('Reg. Exp.', this.pattern); - break; - case 'integer': - case 'number': - if (this.minimum) - options += optionHtml('Min. Value', this.minimum); - if (this.exclusiveMinimum) - options += optionHtml('Exclusive Min.', "true"); - if (this.maximum) - options += optionHtml('Max. Value', this.maximum); - if (this.exclusiveMaximum) - options += optionHtml('Exclusive Max.', "true"); - if (this.multipleOf) - options += optionHtml('Multiple Of', this.multipleOf); - break; - } - - if (isArray) { - if (this.minItems) - options += optionHtml('Min. Items', this.minItems); - if (this.maxItems) - options += optionHtml('Max. Items', this.maxItems); - if (this.uniqueItems) - options += optionHtml('Unique Items', "true"); - if (this.collectionFormat) - options += optionHtml('Coll. Format', this.collectionFormat); - } - - if (this['enum']) { - var enumString; - - if (type === 'number' || type === 'integer') - enumString = this['enum'].join(', '); - else { - enumString = '"' + this['enum'].join('", "') + '"'; - } - - options += optionHtml('Enum', enumString); - } - - if (options.length > 0) - str = '' + str + '
' + options + '
' + this.name + '
'; - - return str; -}; - -optionHtml = function(label, value) { - return '' + label + ':' + value + ''; -}; - -typeFromJsonSchema = function(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; -}; - -var sampleModels = {}; -var cookies = {}; -var models = {}; - -SwaggerClient.prototype.buildFrom1_2Spec = function (response) { - if (response.apiVersion !== null) { - this.apiVersion = response.apiVersion; - } - this.apis = {}; - this.apisArray = []; - this.consumes = response.consumes; - this.produces = response.produces; - this.authSchemes = response.authorizations; - this.info = this.convertInfo(response.info); - - var isApi = false, i, res; - for (i = 0; i < response.apis.length; i++) { - var api = response.apis[i]; - if (api.operations) { - var j; - for (j = 0; j < api.operations.length; j++) { - operation = api.operations[j]; - isApi = true; - } - } - } - if (response.basePath) - this.basePath = response.basePath; - else if (this.url.indexOf('?') > 0) - this.basePath = this.url.substring(0, this.url.lastIndexOf('?')); - else - this.basePath = this.url; - - if (isApi) { - var newName = response.resourcePath.replace(/\//g, ''); - this.resourcePath = response.resourcePath; - res = new SwaggerResource(response, this); - this.apis[newName] = res; - this.apisArray.push(res); - this.finish(); - } else { - var k; - this.expectedResourceCount = response.apis.length; - for (k = 0; k < response.apis.length; k++) { - var resource = response.apis[k]; - res = new SwaggerResource(resource, this); - this.apis[res.name] = res; - this.apisArray.push(res); - } - } - this.isValid = true; - return this; -}; - -SwaggerClient.prototype.finish = function() { - if (typeof this.success === 'function') { - this.isValid = true; - this.ready = true; - this.isBuilt = true; - this.selfReflect(); - this.success(); - } -}; - -SwaggerClient.prototype.buildFrom1_1Spec = function (response) { - log('This API is using a deprecated version of Swagger! Please see http://github.com/wordnik/swagger-core/wiki for more info'); - if (response.apiVersion !== null) - this.apiVersion = response.apiVersion; - this.apis = {}; - this.apisArray = []; - this.produces = response.produces; - this.info = this.convertInfo(response.info); - var isApi = false, res; - for (var i = 0; i < response.apis.length; i++) { - var api = response.apis[i]; - if (api.operations) { - for (var j = 0; j < api.operations.length; j++) { - operation = api.operations[j]; - isApi = true; - } - } - } - if (response.basePath) { - this.basePath = response.basePath; - } else if (this.url.indexOf('?') > 0) { - this.basePath = this.url.substring(0, this.url.lastIndexOf('?')); - } else { - this.basePath = this.url; - } - if (isApi) { - var newName = response.resourcePath.replace(/\//g, ''); - this.resourcePath = response.resourcePath; - res = new SwaggerResource(response, this); - this.apis[newName] = res; - this.apisArray.push(res); - this.finish(); - } else { - this.expectedResourceCount = response.apis.length; - for (k = 0; k < response.apis.length; k++) { - resource = response.apis[k]; - res = new SwaggerResource(resource, this); - this.apis[res.name] = res; - this.apisArray.push(res); - } - } - this.isValid = true; - return this; -}; - -SwaggerClient.prototype.convertInfo = function (resp) { - if(typeof resp == 'object') { - var info = {}; - - info.title = resp.title; - info.description = resp.description; - info.termsOfService = resp.termsOfServiceUrl; - info.contact = {}; - info.contact.name = resp.contact; - info.license = {}; - info.license.name = resp.license; - info.license.url = resp.licenseUrl; - - return info; - } -}; - -SwaggerClient.prototype.selfReflect = function () { - var resource, tag, ref; - if (this.apis === null) { - return false; - } - ref = this.apis; - for (tag in ref) { - api = ref[tag]; - if (api.ready === null) { - return false; - } - this[tag] = api; - this[tag].help = __bind(api.help, api); - } - this.setConsolidatedModels(); - this.ready = true; -}; - -SwaggerClient.prototype.setConsolidatedModels = function () { - var model, modelName, resource, resource_name, i, apis, models, results; - this.models = {}; - apis = this.apis; - for (resource_name in apis) { - resource = apis[resource_name]; - for (modelName in resource.models) { - if (typeof this.models[modelName] === 'undefined') { - this.models[modelName] = resource.models[modelName]; - this.modelsArray.push(resource.models[modelName]); - } - } - } - models = this.modelsArray; - results = []; - for (i = 0; i < models.length; i++) { - model = models[i]; - results.push(model.setReferencedModels(this.models)); - } - return results; -}; - -var SwaggerResource = function (resourceObj, api) { - var _this = this; - this.api = api; - this.swaggerRequstHeaders = api.swaggerRequstHeaders; - this.path = (typeof this.api.resourcePath === 'string') ? this.api.resourcePath : resourceObj.path; - this.description = resourceObj.description; - this.authorizations = (resourceObj.authorizations || {}); - - var parts = this.path.split('/'); - this.name = parts[parts.length - 1].replace('.{format}', ''); - this.basePath = this.api.basePath; - this.operations = {}; - this.operationsArray = []; - this.modelsArray = []; - this.models = api.models || {}; - this.rawModels = {}; - this.useJQuery = (typeof api.useJQuery !== 'undefined') ? api.useJQuery : null; - - if ((resourceObj.apis) && this.api.resourcePath) { - this.addApiDeclaration(resourceObj); - } else { - if (typeof this.path === 'undefined') { - this.api.fail('SwaggerResources must have a path.'); - } - if (this.path.substring(0, 4) === 'http') { - this.url = this.path.replace('{format}', 'json'); - } else { - this.url = this.api.basePath + this.path.replace('{format}', 'json'); - } - this.api.progress('fetching resource ' + this.name + ': ' + this.url); - var obj = { - url: this.url, - method: 'GET', - useJQuery: this.useJQuery, - headers: { - accept: this.swaggerRequstHeaders - }, - on: { - response: function (resp) { - var responseObj = resp.obj || JSON.parse(resp.data); - _this.api.resourceCount += 1; - return _this.addApiDeclaration(responseObj); - }, - error: function (response) { - _this.api.resourceCount += 1; - return _this.api.fail('Unable to read api \'' + - _this.name + '\' from path ' + _this.url + ' (server returned ' + response.statusText + ')'); - } - } - }; - var e = typeof window !== 'undefined' ? window : exports; - e.authorizations.apply(obj); - new SwaggerHttp().execute(obj); - } -}; - -SwaggerResource.prototype.help = function (dontPrint) { - var i; - var output = 'operations for the "' + this.name + '" tag'; - for(i = 0; i < this.operationsArray.length; i++) { - var api = this.operationsArray[i]; - output += '\n * ' + api.nickname + ': ' + api.description; - } - if(dontPrint) - return output; - else { - log(output); - return output; - } -}; - -SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) { - var pos, url; - url = this.api.basePath; - pos = url.lastIndexOf(relativeBasePath); - var parts = url.split('/'); - var rootUrl = parts[0] + '//' + parts[2]; - - if (relativeBasePath.indexOf('http') === 0) - return relativeBasePath; - if (relativeBasePath === '/') - return rootUrl; - if (relativeBasePath.substring(0, 1) == '/') { - // use root + relative - return rootUrl + relativeBasePath; - } - else { - pos = this.basePath.lastIndexOf('/'); - var base = this.basePath.substring(0, pos); - if (base.substring(base.length - 1) == '/') - return base + relativeBasePath; - else - return base + '/' + relativeBasePath; - } -}; - -SwaggerResource.prototype.addApiDeclaration = function (response) { - if (typeof response.produces === 'string') - this.produces = response.produces; - if (typeof response.consumes === 'string') - this.consumes = response.consumes; - if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0) - this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath; - this.resourcePath = response.resourcePath; - this.addModels(response.models); - if (response.apis) { - for (var i = 0 ; i < response.apis.length; i++) { - var endpoint = response.apis[i]; - this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces); - } - } - this.api[this.name] = this; - this.ready = true; - if(this.api.resourceCount === this.api.expectedResourceCount) - this.api.finish(); - return this; -}; - -SwaggerResource.prototype.addModels = function (models) { - if (typeof models === 'object') { - var modelName; - for (modelName in models) { - if (typeof this.models[modelName] === 'undefined') { - var swaggerModel = new SwaggerModel(modelName, models[modelName]); - this.modelsArray.push(swaggerModel); - this.models[modelName] = swaggerModel; - this.rawModels[modelName] = models[modelName]; - } - } - var output = []; - for (var i = 0; i < this.modelsArray.length; i++) { - var model = this.modelsArray[i]; - output.push(model.setReferencedModels(this.models)); - } - return output; - } -}; - -SwaggerResource.prototype.addOperations = function (resource_path, ops, consumes, produces) { - if (ops) { - var output = []; - for (var i = 0; i < ops.length; i++) { - var o = ops[i]; - consumes = this.consumes; - produces = this.produces; - if (typeof o.consumes !== 'undefined') - consumes = o.consumes; - else - consumes = this.consumes; - - if (typeof o.produces !== 'undefined') - produces = o.produces; - else - produces = this.produces; - var type = (o.type || o.responseClass); - - if (type === 'array') { - ref = null; - if (o.items) - ref = o.items.type || o.items.$ref; - type = 'array[' + ref + ']'; - } - var responseMessages = o.responseMessages; - var method = o.method; - if (o.httpMethod) { - method = o.httpMethod; - } - if (o.supportedContentTypes) { - consumes = o.supportedContentTypes; - } - if (o.errorResponses) { - responseMessages = o.errorResponses; - for (var j = 0; j < responseMessages.length; j++) { - r = responseMessages[j]; - r.message = r.reason; - r.reason = null; - } - } - o.nickname = this.sanitize(o.nickname); - var op = new SwaggerOperation(o.nickname, - resource_path, - method, - o.parameters, - o.summary, - o.notes, - type, - responseMessages, - this, - consumes, - produces, - o.authorizations, - o.deprecated); - - this.operations[op.nickname] = op; - output.push(this.operationsArray.push(op)); - } - return output; - } -}; - -SwaggerResource.prototype.sanitize = function (nickname) { - var op; - op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_'); - op = op.replace(/((_){2,})/g, '_'); - op = op.replace(/^(_)*/g, ''); - op = op.replace(/([_])*$/g, ''); - return op; -}; - -var SwaggerModel = function (modelName, obj) { - this.name = typeof obj.id !== 'undefined' ? obj.id : modelName; - this.properties = []; - var propertyName; - for (propertyName in obj.properties) { - if (obj.required) { - var value; - for (value in obj.required) { - if (propertyName === obj.required[value]) { - obj.properties[propertyName].required = true; - } - } - } - var prop = new SwaggerModelProperty(propertyName, obj.properties[propertyName], this); - this.properties.push(prop); - } -}; - -SwaggerModel.prototype.setReferencedModels = function (allModels) { - var results = []; - for (var i = 0; i < this.properties.length; i++) { - var property = this.properties[i]; - var type = property.type || property.dataType; - if (allModels[type]) - results.push(property.refModel = allModels[type]); - else if ((property.refDataType) && (allModels[property.refDataType])) - results.push(property.refModel = allModels[property.refDataType]); - else - results.push(void 0); - } - return results; -}; - -SwaggerModel.prototype.getMockSignature = function (modelsToIgnore) { - var i, prop, propertiesStr = []; - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - propertiesStr.push(prop.toString()); - } - - var strong = ''; - var strongClose = ''; - var classOpen = strong + this.name + ' {' + strongClose; - var classClose = strong + '}' + strongClose; - var returnVal = classOpen + '
' + propertiesStr.join(',
') + '
' + classClose; - if (!modelsToIgnore) - modelsToIgnore = []; - modelsToIgnore.push(this.name); - - for (i = 0; i < this.properties.length; i++) { - prop = this.properties[i]; - if ((prop.refModel) && modelsToIgnore.indexOf(prop.refModel.name) === -1) { - returnVal = returnVal + ('
' + prop.refModel.getMockSignature(modelsToIgnore)); - } - } - return returnVal; -}; - -SwaggerModel.prototype.createJSONSample = function (modelsToIgnore) { - if (sampleModels[this.name]) { - return sampleModels[this.name]; - } - else { - var result = {}; - modelsToIgnore = (modelsToIgnore || []); - modelsToIgnore.push(this.name); - for (var i = 0; i < this.properties.length; i++) { - var prop = this.properties[i]; - result[prop.name] = prop.getSampleValue(modelsToIgnore); - } - modelsToIgnore.pop(this.name); - return result; - } -}; - -var SwaggerModelProperty = function (name, obj, model) { - this.name = name; - this.dataType = obj.type || obj.dataType || obj.$ref; - this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set'); - this.descr = obj.description; - this.required = obj.required; - this.defaultValue = applyModelPropertyMacro(obj, model); - if (obj.items) { - if (obj.items.type) { - this.refDataType = obj.items.type; - } - if (obj.items.$ref) { - this.refDataType = obj.items.$ref; - } - } - this.dataTypeWithRef = this.refDataType ? (this.dataType + '[' + this.refDataType + ']') : this.dataType; - if (obj.allowableValues) { - this.valueType = obj.allowableValues.valueType; - this.values = obj.allowableValues.values; - if (this.values) { - this.valuesString = '\'' + this.values.join('\' or \'') + '\''; - } - } - if (obj['enum']) { - this.valueType = 'string'; - this.values = obj['enum']; - if (this.values) { - this.valueString = '\'' + this.values.join('\' or \'') + '\''; - } - } -}; - -SwaggerModelProperty.prototype.getSampleValue = function (modelsToIgnore) { - var result; - if ((this.refModel) && (modelsToIgnore.indexOf(this.refModel.name) === -1)) { - result = this.refModel.createJSONSample(modelsToIgnore); - } else { - if (this.isCollection) { - result = this.toSampleValue(this.refDataType); - } else { - result = this.toSampleValue(this.dataType); - } - } - if (this.isCollection) { - return [result]; - } else { - return result; - } -}; - -SwaggerModelProperty.prototype.toSampleValue = function (value) { - var result; - if ((typeof this.defaultValue !== 'undefined') && this.defaultValue) { - result = this.defaultValue; - } else if (value === 'integer') { - result = 0; - } else if (value === 'boolean') { - result = false; - } else if (value === 'double' || value === 'number') { - result = 0.0; - } else if (value === 'string') { - result = ''; - } else { - result = value; - } - return result; -}; - -SwaggerModelProperty.prototype.toString = function () { - var req = this.required ? 'propReq' : 'propOpt'; - var str = '' + this.name + ' (' + this.dataTypeWithRef + ''; - if (!this.required) { - str += ', optional'; - } - str += ')'; - if (this.values) { - str += ' = [\'' + this.values.join('\' or \'') + '\']'; - } - if (this.descr) { - str += ': ' + this.descr + ''; - } - return str; -}; - -var SwaggerOperation = function (nickname, path, method, parameters, summary, notes, type, responseMessages, resource, consumes, produces, authorizations, deprecated) { - var _this = this; - - var errors = []; - this.nickname = (nickname || errors.push('SwaggerOperations must have a nickname.')); - this.path = (path || errors.push('SwaggerOperation ' + nickname + ' is missing path.')); - this.method = (method || errors.push('SwaggerOperation ' + nickname + ' is missing method.')); - this.parameters = parameters ? parameters : []; - this.summary = summary; - this.notes = notes; - this.type = type; - this.responseMessages = (responseMessages || []); - this.resource = (resource || errors.push('Resource is required')); - this.consumes = consumes; - this.produces = produces; - this.authorizations = typeof authorizations !== 'undefined' ? authorizations : resource.authorizations; - this.deprecated = deprecated; - this['do'] = __bind(this['do'], this); - - - 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); - } - } - - if (errors.length > 0) { - console.error('SwaggerOperation errors', errors, arguments); - this.resource.api.fail(errors); - } - - this.path = this.path.replace('{format}', 'json'); - this.method = this.method.toLowerCase(); - this.isGetMethod = this.method === 'get'; - - var i, j, v; - this.resourceName = this.resource.name; - if (typeof this.type !== 'undefined' && this.type === 'void') - this.type = null; - else { - this.responseClassSignature = this.getSignature(this.type, this.resource.models); - this.responseSampleJSON = this.getSampleJSON(this.type, this.resource.models); - } - - for (i = 0; i < this.parameters.length; i++) { - var param = this.parameters[i]; - // might take this away - param.name = param.name || param.type || param.dataType; - // for 1.1 compatibility - type = param.type || param.dataType; - if (type === 'array') { - type = 'array[' + (param.items.$ref ? param.items.$ref : param.items.type) + ']'; - } - param.type = type; - - if (type && type.toLowerCase() === 'boolean') { - param.allowableValues = {}; - param.allowableValues.values = ['true', 'false']; - } - param.signature = this.getSignature(type, this.resource.models); - param.sampleJSON = this.getSampleJSON(type, this.resource.models); - - var enumValue = param['enum']; - if (typeof enumValue !== 'undefined') { - param.isList = true; - param.allowableValues = {}; - param.allowableValues.descriptiveValues = []; - - for (j = 0; j < enumValue.length; j++) { - v = enumValue[j]; - if (param.defaultValue) { - param.allowableValues.descriptiveValues.push({ - value: String(v), - isDefault: (v === param.defaultValue) - }); - } - else { - param.allowableValues.descriptiveValues.push({ - value: String(v), - isDefault: false - }); - } - } - } - else if (param.allowableValues) { - if (param.allowableValues.valueType === 'RANGE') - param.isRange = true; - else - param.isList = true; - if (param.allowableValues) { - param.allowableValues.descriptiveValues = []; - if (param.allowableValues.values) { - for (j = 0; j < param.allowableValues.values.length; j++) { - v = param.allowableValues.values[j]; - if (param.defaultValue !== null) { - param.allowableValues.descriptiveValues.push({ - value: String(v), - isDefault: (v === param.defaultValue) - }); - } - else { - param.allowableValues.descriptiveValues.push({ - value: String(v), - isDefault: false - }); - } - } - } - } - } - param.defaultValue = applyParameterMacro(this, param); - } - var defaultSuccessCallback = this.resource.api.defaultSuccessCallback || null; - var defaultErrorCallback = this.resource.api.defaultErrorCallback || null; - - this.resource[this.nickname] = function (args, opts, callback, error) { - var arg1, arg2, arg3, arg4; - if(typeof args === 'function') { // right shift 3 - arg1 = {}; arg2 = {}; arg3 = args; arg4 = opts; - } - else if(typeof args === 'object' && typeof opts === 'function') { // right shift 2 - arg1 = args; arg2 = {}; arg3 = opts; arg4 = callback; - } - else { - arg1 = args; arg2 = opts; arg3 = callback; arg4 = error; - } - return _this['do'](arg1 || {}, arg2 || {}, arg3 || defaultSuccessCallback, arg4 || defaultErrorCallback); - }; - - this.resource[this.nickname].help = function (dontPrint) { - return _this.help(dontPrint); - }; - this.resource[this.nickname].asCurl = function (args) { - return _this.asCurl(args); - }; -}; - -SwaggerOperation.prototype.isListType = function (type) { - if (type && type.indexOf('[') >= 0) { - return type.substring(type.indexOf('[') + 1, type.indexOf(']')); - } else { - return void 0; - } -}; - -SwaggerOperation.prototype.getSignature = function (type, models) { - var isPrimitive, listType; - listType = this.isListType(type); - isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true; - if (isPrimitive) { - return type; - } else { - if (typeof listType !== 'undefined') { - return models[listType].getMockSignature(); - } else { - return models[type].getMockSignature(); - } - } -}; - -SwaggerOperation.prototype.getSampleJSON = function (type, models) { - var isPrimitive, listType, val; - listType = this.isListType(type); - isPrimitive = ((typeof listType !== 'undefined') && models[listType]) || (typeof models[type] !== 'undefined') ? false : true; - val = isPrimitive ? void 0 : (listType ? models[listType].createJSONSample() : models[type].createJSONSample()); - if (val) { - val = listType ? [val] : val; - if (typeof val == 'string') - return val; - else if (typeof val === 'object') { - var t = val; - if (val instanceof Array && val.length > 0) { - t = val[0]; - } - if (t.nodeName) { - var xmlString = new XMLSerializer().serializeToString(t); - return this.formatXml(xmlString); - } - else - return JSON.stringify(val, null, 2); - } - else - return val; - } -}; - -SwaggerOperation.prototype['do'] = function (args, opts, callback, error) { - var key, param, params, possibleParams = [], req, value; - - if (typeof error !== 'function') { - error = function (xhr, textStatus, error) { - return log(xhr, textStatus, error); - }; - } - - if (typeof callback !== 'function') { - callback = function (response) { - var content; - content = null; - if (response !== null) { - content = response.data; - } else { - content = 'no data'; - } - return log('default callback: ' + content); - }; - } - - params = {}; - params.headers = []; - if (args.headers) { - params.headers = args.headers; - delete args.headers; - } - // allow override from the opts - if(opts && opts.responseContentType) { - params.headers['Content-Type'] = opts.responseContentType; - } - if(opts && opts.requestContentType) { - params.headers.Accept = opts.requestContentType; - } - - for (var i = 0; i < this.parameters.length; i++) { - param = this.parameters[i]; - if (param.paramType === 'header') { - if (typeof args[param.name] !== 'undefined') - params.headers[param.name] = args[param.name]; - } - else if (param.paramType === 'form' || param.paramType.toLowerCase() === 'file') - possibleParams.push(param); - else if (param.paramType === 'body' && param.name !== 'body' && typeof args[param.name] !== 'undefined') { - if (args.body) { - throw new Error('Saw two body params in an API listing; expecting a max of one.'); - } - args.body = args[param.name]; - } - } - - if (typeof args.body !== 'undefined') { - params.body = args.body; - delete args.body; - } - - if (possibleParams) { - for (key in possibleParams) { - value = possibleParams[key]; - if (args[value.name]) { - params[value.name] = args[value.name]; - } - } - } - - req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); - if (opts.mock) { - return req; - } else { - return true; - } -}; - -SwaggerOperation.prototype.pathJson = function () { - return this.path.replace('{format}', 'json'); -}; - -SwaggerOperation.prototype.pathXml = function () { - return this.path.replace('{format}', 'xml'); -}; - -SwaggerOperation.prototype.encodePathParam = function (pathParam) { - var encParts, part, parts, _i, _len; - pathParam = pathParam.toString(); - if (pathParam.indexOf('/') === -1) { - return encodeURIComponent(pathParam); - } else { - parts = pathParam.split('/'); - encParts = []; - for (_i = 0, _len = parts.length; _i < _len; _i++) { - part = parts[_i]; - encParts.push(encodeURIComponent(part)); - } - return encParts.join('/'); - } -}; - -SwaggerOperation.prototype.urlify = function (args) { - var i, j, param, url; - // ensure no double slashing... - if(this.resource.basePath.length > 1 && this.resource.basePath.slice(-1) === '/' && this.pathJson().charAt(0) === '/') - url = this.resource.basePath + this.pathJson().substring(1); - else - url = this.resource.basePath + this.pathJson(); - var params = this.parameters; - for (i = 0; i < params.length; i++) { - param = params[i]; - if (param.paramType === 'path') { - if (typeof args[param.name] !== 'undefined') { - // apply path params and remove from args - var reg = new RegExp('\\{\\s*?' + param.name + '[^\\{\\}\\/]*(?:\\{.*?\\}[^\\{\\}\\/]*)*\\}(?=(\\/?|$))', 'gi'); - url = url.replace(reg, this.encodePathParam(args[param.name])); - delete args[param.name]; - } - else - throw '' + param.name + ' is a required path param.'; - } - } - - var queryParams = ''; - for (i = 0; i < params.length; i++) { - param = params[i]; - if(param.paramType === 'query') { - if (queryParams !== '') - queryParams += '&'; - if (Array.isArray(param)) { - var output = ''; - for(j = 0; j < param.length; j++) { - if(j > 0) - output += ','; - output += encodeURIComponent(param[j]); - } - queryParams += encodeURIComponent(param.name) + '=' + output; - } - else { - if (typeof args[param.name] !== 'undefined') { - queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]); - } else { - if (param.required) - throw '' + param.name + ' is a required query param.'; - } - } - } - } - if ((queryParams) && queryParams.length > 0) - url += '?' + queryParams; - return url; -}; - -SwaggerOperation.prototype.supportHeaderParams = function () { - return this.resource.api.supportHeaderParams; -}; - -SwaggerOperation.prototype.supportedSubmitMethods = function () { - return this.resource.api.supportedSubmitMethods; -}; - -SwaggerOperation.prototype.getQueryParams = function (args) { - return this.getMatchingParams(['query'], args); -}; - -SwaggerOperation.prototype.getHeaderParams = function (args) { - return this.getMatchingParams(['header'], args); -}; - -SwaggerOperation.prototype.getMatchingParams = function (paramTypes, args) { - var matchingParams = {}; - var params = this.parameters; - for (var i = 0; i < params.length; i++) { - param = params[i]; - if (args && args[param.name]) - matchingParams[param.name] = args[param.name]; - } - var headers = this.resource.api.headers; - var name; - for (name in headers) { - var value = headers[name]; - matchingParams[name] = value; - } - return matchingParams; -}; - -SwaggerOperation.prototype.help = function (dontPrint) { - var msg = this.nickname + ': ' + this.summary; - var params = this.parameters; - for (var i = 0; i < params.length; i++) { - var param = params[i]; - msg += '\n* ' + param.name + (param.required ? ' (required)' : '') + " - " + param.description; - } - if(dontPrint) - return msg; - else { - console.log(msg); - return msg; - } -}; - -SwaggerOperation.prototype.asCurl = function (args) { - var results = []; - var i; - - var headers = SwaggerRequest.prototype.setHeaders(args, {}, this); - for(i = 0; i < this.parameters.length; i++) { - var param = this.parameters[i]; - if(param.paramType && param.paramType === 'header' && args[param.name]) { - headers[param.name] = args[param.name]; - } - } - - var key; - for (key in headers) { - results.push('--header "' + key + ': ' + headers[key] + '"'); - } - return 'curl ' + (results.join(' ')) + ' ' + this.urlify(args); -}; - -SwaggerOperation.prototype.formatXml = function (xml) { - var contexp, formatted, indent, lastType, lines, ln, pad, reg, transitions, wsexp, _fn, _i, _len; - reg = /(>)(<)(\/*)/g; - wsexp = /[ ]*(.*)[ ]+\n/g; - contexp = /(<.+>)(.+\n)/g; - xml = xml.replace(reg, '$1\n$2$3').replace(wsexp, '$1\n').replace(contexp, '$1\n$2'); - pad = 0; - formatted = ''; - lines = xml.split('\n'); - indent = 0; - lastType = 'other'; - transitions = { - 'single->single': 0, - 'single->closing': -1, - 'single->opening': 0, - 'single->other': 0, - 'closing->single': 0, - 'closing->closing': -1, - 'closing->opening': 0, - 'closing->other': 0, - 'opening->single': 1, - 'opening->closing': 0, - 'opening->opening': 1, - 'opening->other': 1, - 'other->single': 0, - 'other->closing': -1, - 'other->opening': 0, - 'other->other': 0 - }; - _fn = function (ln) { - var fromTo, j, key, padding, type, types, value; - types = { - single: Boolean(ln.match(/<.+\/>/)), - closing: Boolean(ln.match(/<\/.+>/)), - opening: Boolean(ln.match(/<[^!?].*>/)) - }; - type = ((function () { - var _results; - _results = []; - for (key in types) { - value = types[key]; - if (value) { - _results.push(key); - } - } - return _results; - })())[0]; - type = type === void 0 ? 'other' : type; - fromTo = lastType + '->' + type; - lastType = type; - padding = ''; - indent += transitions[fromTo]; - padding = ((function () { - var _j, _ref5, _results; - _results = []; - for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) { - _results.push(' '); - } - return _results; - })()).join(''); - if (fromTo === 'opening->closing') { - formatted = formatted.substr(0, formatted.length - 1) + ln + '\n'; - } else { - formatted += padding + ln + '\n'; - } - }; - for (_i = 0, _len = lines.length; _i < _len; _i++) { - ln = lines[_i]; - _fn(ln); - } - return formatted; -}; - -var SwaggerRequest = function (type, url, params, opts, successCallback, errorCallback, operation, execution) { - var _this = this; - var errors = []; - - this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null); - this.type = (type || errors.push('SwaggerRequest type is required (get/post/put/delete/patch/options).')); - this.url = (url || errors.push('SwaggerRequest url is required.')); - this.params = params; - this.opts = opts; - this.successCallback = (successCallback || errors.push('SwaggerRequest successCallback is required.')); - this.errorCallback = (errorCallback || errors.push('SwaggerRequest error callback is required.')); - this.operation = (operation || errors.push('SwaggerRequest operation is required.')); - this.execution = execution; - this.headers = (params.headers || {}); - - if (errors.length > 0) { - throw errors; - } - - this.type = this.type.toUpperCase(); - - // set request, response content type headers - var headers = this.setHeaders(params, opts, this.operation); - var body = params.body; - - // encode the body for form submits - if (headers['Content-Type']) { - var key, value, values = {}, i; - var operationParams = this.operation.parameters; - for (i = 0; i < operationParams.length; i++) { - var param = operationParams[i]; - if (param.paramType === 'form') - values[param.name] = param; - } - - if (headers['Content-Type'].indexOf('application/x-www-form-urlencoded') === 0) { - var encoded = ''; - for (key in values) { - value = this.params[key]; - if (typeof value !== 'undefined') { - if (encoded !== '') - encoded += '&'; - encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); - } - } - body = encoded; - } - else if (headers['Content-Type'].indexOf('multipart/form-data') === 0) { - // encode the body for form submits - var data = ''; - var boundary = '----SwaggerFormBoundary' + Date.now(); - for (key in values) { - value = this.params[key]; - if (typeof value !== 'undefined') { - data += '--' + boundary + '\n'; - data += 'Content-Disposition: form-data; name="' + key + '"'; - data += '\n\n'; - data += value + '\n'; - } - } - data += '--' + boundary + '--\n'; - headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary; - body = data; - } - } - - var obj; - if (!((this.headers) && (this.headers.mock))) { - obj = { - url: this.url, - method: this.type, - headers: headers, - body: body, - useJQuery: this.useJQuery, - on: { - error: function (response) { - return _this.errorCallback(response, _this.opts.parent); - }, - redirect: function (response) { - return _this.successCallback(response, _this.opts.parent); - }, - 307: function (response) { - return _this.successCallback(response, _this.opts.parent); - }, - response: function (response) { - return _this.successCallback(response, _this.opts.parent); - } - } - }; - - var status = false; - if (this.operation.resource && this.operation.resource.api && this.operation.resource.api.clientAuthorizations) { - // Get the client authorizations from the resource declaration - status = this.operation.resource.api.clientAuthorizations.apply(obj, this.operation.authorizations); - } else { - // Get the client authorization from the default authorization declaration - var e; - if (typeof window !== 'undefined') { - e = window; - } else { - e = exports; - } - status = e.authorizations.apply(obj, this.operation.authorizations); - } - - if (!opts.mock) { - if (status !== false) { - new SwaggerHttp().execute(obj); - } else { - obj.canceled = true; - } - } else { - return obj; - } - } - return obj; -}; - -SwaggerRequest.prototype.setHeaders = function (params, opts, operation) { - // default type - var accepts = opts.responseContentType || 'application/json'; - var consumes = opts.requestContentType || 'application/json'; - - var allDefinedParams = operation.parameters; - var definedFormParams = []; - var definedFileParams = []; - var body = params.body; - var headers = {}; - - // get params from the operation and set them in definedFileParams, definedFormParams, headers - var i; - for (i = 0; i < allDefinedParams.length; i++) { - var param = allDefinedParams[i]; - if (param.paramType === 'form') - definedFormParams.push(param); - else if (param.paramType === 'file') - definedFileParams.push(param); - else if (param.paramType === 'header' && this.params.headers) { - var key = param.name; - var headerValue = this.params.headers[param.name]; - if (typeof this.params.headers[param.name] !== 'undefined') - headers[key] = headerValue; - } - } - - // if there's a body, need to set the accepts header via requestContentType - if (body && (this.type === 'POST' || this.type === 'PUT' || this.type === 'PATCH' || this.type === 'DELETE')) { - if (this.opts.requestContentType) - consumes = this.opts.requestContentType; - } else { - // if any form params, content type must be set - if (definedFormParams.length > 0) { - if (definedFileParams.length > 0) - consumes = 'multipart/form-data'; - else - consumes = 'application/x-www-form-urlencoded'; - } - else if (this.type === 'DELETE') - body = '{}'; - else if (this.type != 'DELETE') - consumes = null; - } - - if (consumes && this.operation.consumes) { - if (this.operation.consumes.indexOf(consumes) === -1) { - log('server doesn\'t consume ' + consumes + ', try ' + JSON.stringify(this.operation.consumes)); - } - } - - if (this.opts && this.opts.responseContentType) { - accepts = this.opts.responseContentType; - } else { - accepts = 'application/json'; - } - if (accepts && operation.produces) { - if (operation.produces.indexOf(accepts) === -1) { - 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; -}; - -/** - * SwaggerHttp is a wrapper for executing requests - */ -var SwaggerHttp = function() {}; - -SwaggerHttp.prototype.execute = function(obj, opts) { - if(obj && (typeof obj.useJQuery === 'boolean')) - this.useJQuery = obj.useJQuery; - else - this.useJQuery = this.isIE8(); - - if(obj && typeof obj.body === 'object') { - if(obj.body.type && obj.body.type !== 'formData') - obj.body = JSON.stringify(obj.body); - else { - obj.contentType = false; - obj.processData = false; - // delete obj.cache; - delete obj.headers['Content-Type']; - } - } - - if(this.useJQuery) - return new JQueryHttpClient(opts).execute(obj); - else - return new ShredHttpClient(opts).execute(obj); -}; - -SwaggerHttp.prototype.isIE8 = function() { - var detectedIE = false; - if (typeof navigator !== 'undefined' && navigator.userAgent) { - nav = navigator.userAgent.toLowerCase(); - if (nav.indexOf('msie') !== -1) { - var version = parseInt(nav.split('msie')[1]); - if (version <= 8) { - detectedIE = true; - } - } - } - return detectedIE; -}; - -/* - * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic. - * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space. - * Since we are using closures here we need to alias it for internal use. - */ -var JQueryHttpClient = function(options) { - "use strict"; - if(!jQuery){ - var jQuery = window.jQuery; - } -}; - -JQueryHttpClient.prototype.execute = function(obj) { - var cb = obj.on; - var request = obj; - - 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, textStatus, opts) { - var headers = {}, - 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(), - 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 - }; - - var contentType = (headers["content-type"]||headers["Content-Type"]||null); - if(contentType) { - if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) { - try { - out.obj = response.responseJSON || JSON.parse(out.data) || {}; - } catch (ex) { - // do not set out.obj - log("unable to parse JSON content"); - } - } - } - - 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); - }; - - jQuery.support.cors = true; - return jQuery.ajax(obj); -}; - -/* - * ShredHttpClient is a light-weight, node or browser HTTP client - */ -var ShredHttpClient = function(opts) { - this.opts = (opts||{}); - this.isInitialized = false; - - var identity, toString; - - if (typeof window !== 'undefined') { - this.Shred = require("./shred"); - this.content = require("./shred/content"); - } - else - this.Shred = require("shred"); - this.shred = new this.Shred(opts); -}; - -ShredHttpClient.prototype.initShred = function () { - this.isInitialized = true; - this.registerProcessors(this.shred); -}; - -ShredHttpClient.prototype.registerProcessors = function(shred) { - var identity = function(x) { - return x; - }; - var toString = function(x) { - return x.toString(); - }; - - if (typeof window !== 'undefined') { - this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { - parser: identity, - stringify: toString - }); - } else { - this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { - parser: identity, - stringify: toString - }); - } -}; - -ShredHttpClient.prototype.execute = function(obj) { - if(!this.isInitialized) - this.initShred(); - - var cb = obj.on, res; - var transform = function(response) { - var out = { - headers: response._headers, - url: response.request.url, - method: response.request.method, - status: response.status, - data: response.content.data - }; - - var headers = response._headers.normalized || response._headers; - var contentType = (headers["content-type"]||headers["Content-Type"]||null); - - if(contentType) { - if(contentType.indexOf("application/json") === 0 || contentType.indexOf("+json") > 0) { - if(response.content.data && response.content.data !== "") - try{ - out.obj = JSON.parse(response.content.data); - } - catch (e) { - // unable to parse - } - else - out.obj = {}; - } - } - return out; - }; - - // Transform an error into a usable response-like object - var transformError = function (error) { - var out = { - // Default to a status of 0 - The client will treat this as a generic permissions sort of error - status: 0, - data: error.message || error - }; - - if (error.code) { - out.obj = error; - - if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') { - // We can tell the client that this should be treated as a missing resource and not as a permissions thing - out.status = 404; - } - } - return out; - }; - - res = { - error: function (response) { - if (obj) - return cb.error(transform(response)); - }, - // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming) - request_error: function (err) { - if (obj) - return cb.error(transformError(err)); - }, - response: function (response) { - if (obj) { - return cb.response(transform(response)); - } - } - }; - if (obj) { - obj.on = res; - } - return this.shred.request(obj); -}; - - -var e = (typeof window !== 'undefined' ? window : exports); - -e.authorizations = authorizations = new SwaggerAuthorizations(); -e.ApiKeyAuthorization = ApiKeyAuthorization; -e.PasswordAuthorization = PasswordAuthorization; -e.CookieAuthorization = CookieAuthorization; -e.SwaggerClient = SwaggerClient; -e.SwaggerApi = SwaggerClient; -e.Operation = Operation; -e.Model = Model; -e.addModel = addModel; -e.Resolver = Resolver; -})(); \ No newline at end of file diff --git a/dist/lib/swagger-oauth.js b/dist/lib/swagger-oauth.js index c4e144fa298..b2254b7f529 100644 --- a/dist/lib/swagger-oauth.js +++ b/dist/lib/swagger-oauth.js @@ -97,18 +97,19 @@ function handleLogin() { var authSchemes = window.swaggerUi.api.authSchemes; var host = window.location; var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/")); - var redirectUrl = host.protocol + '//' + host.host + pathname + '/o2c.html'; + var defaultRedirectUrl = host.protocol + '//' + host.host + pathname + '/o2c.html'; + var redirectUrl = window.oAuthRedirectUrl || defaultRedirectUrl; var url = null; for (var key in authSchemes) { if (authSchemes.hasOwnProperty(key)) { var flow = authSchemes[key].flow; - + if(authSchemes[key].type === 'oauth2' && flow && (flow === 'implicit' || flow === 'accessCode')) { var dets = authSchemes[key]; url = dets.authorizationUrl + '?response_type=' + (flow === 'implicit' ? 'token' : 'code'); window.swaggerUi.tokenName = dets.tokenName || 'access_token'; - window.swaggerUi.tokenUrl = (flow === 'accessCode' ? dets.tokenUrl : null); + window.swaggerUi.tokenUrl = (flow === 'accessCode' ? dets.tokenUrl : null); } else if(authSchemes[key].grantTypes) { // 1.2 support @@ -135,11 +136,14 @@ function handleLogin() { for(k =0; k < o.length; k++) { var scope = $(o[k]).attr('scope'); - + if (scopes.indexOf(scope) === -1) scopes.push(scope); } + // Implicit auth recommends a state parameter. + var state = Math.random (); + window.enabledScopes=scopes; redirect_uri = redirectUrl; @@ -147,7 +151,8 @@ function handleLogin() { url += '&redirect_uri=' + encodeURIComponent(redirectUrl); url += '&realm=' + encodeURIComponent(realm); url += '&client_id=' + encodeURIComponent(clientId); - url += '&scope=' + encodeURIComponent(scopes); + url += '&scope=' + encodeURIComponent(scopes.join(' ')); + url += '&state=' + encodeURIComponent(state); window.open(url); }); @@ -198,7 +203,7 @@ function initOAuth(opts) { }); } -function processOAuthCode(data) { +window.processOAuthCode = function processOAuthCode(data) { var params = { 'client_id': clientId, 'code': data.code, @@ -210,18 +215,18 @@ function processOAuthCode(data) { url : window.swaggerUi.tokenUrl, type: "POST", data: params, - success:function(data, textStatus, jqXHR) + success:function(data, textStatus, jqXHR) { onOAuthComplete(data); }, - error: function(jqXHR, textStatus, errorThrown) + error: function(jqXHR, textStatus, errorThrown) { onOAuthComplete(""); } }); } -function onOAuthComplete(token) { +window.onOAuthComplete = function onOAuthComplete(token) { if(token) { if(token.error) { var checkbox = $('input[type=checkbox],.secured') @@ -268,7 +273,7 @@ function onOAuthComplete(token) { // all scopes are satisfied $(o).find('.api-ic').addClass('ic-info'); $(o).find('.api-ic').removeClass('ic-warning'); - $(o).find('.api-ic').removeClass('ic-error'); + $(o).find('.api-ic').removeClass('ic-error'); } } }); diff --git a/dist/lib/underscore-min.map b/dist/lib/underscore-min.map new file mode 100644 index 00000000000..b31e43590a0 --- /dev/null +++ b/dist/lib/underscore-min.map @@ -0,0 +1 @@ +{"version":3,"file":"underscore-min.js","sources":["underscore.js"],"names":["createReduce","dir","iterator","obj","iteratee","memo","keys","index","length","currentKey","context","optimizeCb","isArrayLike","_","arguments","createIndexFinder","array","predicate","cb","collectNonEnumProps","nonEnumIdx","nonEnumerableProps","constructor","proto","isFunction","prototype","ObjProto","prop","has","contains","push","root","this","previousUnderscore","ArrayProto","Array","Object","FuncProto","Function","slice","toString","hasOwnProperty","nativeIsArray","isArray","nativeKeys","nativeBind","bind","nativeCreate","create","Ctor","_wrapped","exports","module","VERSION","func","argCount","value","call","other","collection","accumulator","apply","identity","isObject","matcher","property","Infinity","createAssigner","keysFunc","undefinedOnly","source","l","i","key","baseCreate","result","MAX_ARRAY_INDEX","Math","pow","each","forEach","map","collect","results","reduce","foldl","inject","reduceRight","foldr","find","detect","findIndex","findKey","filter","select","list","reject","negate","every","all","some","any","includes","include","target","fromIndex","values","indexOf","invoke","method","args","isFunc","pluck","where","attrs","findWhere","max","computed","lastComputed","min","shuffle","rand","set","shuffled","random","sample","n","guard","sortBy","criteria","sort","left","right","a","b","group","behavior","groupBy","indexBy","countBy","toArray","size","partition","pass","fail","first","head","take","initial","last","rest","tail","drop","compact","flatten","input","shallow","strict","startIndex","output","idx","isArguments","j","len","without","difference","uniq","unique","isSorted","isBoolean","seen","union","intersection","argsLength","item","zip","unzip","object","sortedIndex","isNaN","lastIndexOf","from","findLastIndex","low","high","mid","floor","range","start","stop","step","ceil","executeBound","sourceFunc","boundFunc","callingContext","self","TypeError","bound","concat","partial","boundArgs","position","bindAll","Error","memoize","hasher","cache","address","delay","wait","setTimeout","defer","throttle","options","timeout","previous","later","leading","now","remaining","clearTimeout","trailing","debounce","immediate","timestamp","callNow","wrap","wrapper","compose","after","times","before","once","hasEnumBug","propertyIsEnumerable","allKeys","mapObject","pairs","invert","functions","methods","names","extend","extendOwn","assign","pick","oiteratee","omit","String","defaults","clone","tap","interceptor","isMatch","eq","aStack","bStack","className","areArrays","aCtor","bCtor","pop","isEqual","isEmpty","isString","isElement","nodeType","type","name","Int8Array","isFinite","parseFloat","isNumber","isNull","isUndefined","noConflict","constant","noop","propertyOf","matches","accum","Date","getTime","escapeMap","&","<",">","\"","'","`","unescapeMap","createEscaper","escaper","match","join","testRegexp","RegExp","replaceRegexp","string","test","replace","escape","unescape","fallback","idCounter","uniqueId","prefix","id","templateSettings","evaluate","interpolate","noMatch","escapes","\\","\r","\n","
","
","escapeChar","template","text","settings","oldSettings","offset","variable","render","e","data","argument","chain","instance","_chain","mixin","valueOf","toJSON","define","amd"],"mappings":";;;;CAKC,WAoKC,QAASA,GAAaC,GAGpB,QAASC,GAASC,EAAKC,EAAUC,EAAMC,EAAMC,EAAOC,GAClD,KAAOD,GAAS,GAAaC,EAARD,EAAgBA,GAASN,EAAK,CACjD,GAAIQ,GAAaH,EAAOA,EAAKC,GAASA,CACtCF,GAAOD,EAASC,EAAMF,EAAIM,GAAaA,EAAYN,GAErD,MAAOE,GAGT,MAAO,UAASF,EAAKC,EAAUC,EAAMK,GACnCN,EAAWO,EAAWP,EAAUM,EAAS,EACzC,IAAIJ,IAAQM,EAAYT,IAAQU,EAAEP,KAAKH,GACnCK,GAAUF,GAAQH,GAAKK,OACvBD,EAAQN,EAAM,EAAI,EAAIO,EAAS,CAMnC,OAJIM,WAAUN,OAAS,IACrBH,EAAOF,EAAIG,EAAOA,EAAKC,GAASA,GAChCA,GAASN,GAEJC,EAASC,EAAKC,EAAUC,EAAMC,EAAMC,EAAOC,IA+btD,QAASO,GAAkBd,GACzB,MAAO,UAASe,EAAOC,EAAWP,GAChCO,EAAYC,EAAGD,EAAWP,EAG1B,KAFA,GAAIF,GAAkB,MAATQ,GAAiBA,EAAMR,OAChCD,EAAQN,EAAM,EAAI,EAAIO,EAAS,EAC5BD,GAAS,GAAaC,EAARD,EAAgBA,GAASN,EAC5C,GAAIgB,EAAUD,EAAMT,GAAQA,EAAOS,GAAQ,MAAOT,EAEpD,QAAQ,GAgQZ,QAASY,GAAoBhB,EAAKG,GAChC,GAAIc,GAAaC,EAAmBb,OAChCc,EAAcnB,EAAImB,YAClBC,EAASV,EAAEW,WAAWF,IAAgBA,EAAYG,WAAcC,EAGhEC,EAAO,aAGX,KAFId,EAAEe,IAAIzB,EAAKwB,KAAUd,EAAEgB,SAASvB,EAAMqB,IAAOrB,EAAKwB,KAAKH,GAEpDP,KACLO,EAAON,EAAmBD,GACtBO,IAAQxB,IAAOA,EAAIwB,KAAUJ,EAAMI,KAAUd,EAAEgB,SAASvB,EAAMqB,IAChErB,EAAKwB,KAAKH,GAt4BhB,GAAII,GAAOC,KAGPC,EAAqBF,EAAKlB,EAG1BqB,EAAaC,MAAMV,UAAWC,EAAWU,OAAOX,UAAWY,EAAYC,SAASb,UAIlFK,EAAmBI,EAAWJ,KAC9BS,EAAmBL,EAAWK,MAC9BC,EAAmBd,EAASc,SAC5BC,EAAmBf,EAASe,eAK5BC,EAAqBP,MAAMQ,QAC3BC,EAAqBR,OAAO9B,KAC5BuC,EAAqBR,EAAUS,KAC/BC,EAAqBX,OAAOY,OAG1BC,EAAO,aAGPpC,EAAI,SAASV,GACf,MAAIA,aAAeU,GAAUV,EACvB6B,eAAgBnB,QACtBmB,KAAKkB,SAAW/C,GADiB,GAAIU,GAAEV,GAOlB,oBAAZgD,UACa,mBAAXC,SAA0BA,OAAOD,UAC1CA,QAAUC,OAAOD,QAAUtC,GAE7BsC,QAAQtC,EAAIA,GAEZkB,EAAKlB,EAAIA,EAIXA,EAAEwC,QAAU,OAKZ,IAAI1C,GAAa,SAAS2C,EAAM5C,EAAS6C,GACvC,GAAI7C,QAAiB,GAAG,MAAO4C,EAC/B,QAAoB,MAAZC,EAAmB,EAAIA,GAC7B,IAAK,GAAG,MAAO,UAASC,GACtB,MAAOF,GAAKG,KAAK/C,EAAS8C,GAE5B,KAAK,GAAG,MAAO,UAASA,EAAOE,GAC7B,MAAOJ,GAAKG,KAAK/C,EAAS8C,EAAOE,GAEnC,KAAK,GAAG,MAAO,UAASF,EAAOjD,EAAOoD,GACpC,MAAOL,GAAKG,KAAK/C,EAAS8C,EAAOjD,EAAOoD,GAE1C,KAAK,GAAG,MAAO,UAASC,EAAaJ,EAAOjD,EAAOoD,GACjD,MAAOL,GAAKG,KAAK/C,EAASkD,EAAaJ,EAAOjD,EAAOoD,IAGzD,MAAO,YACL,MAAOL,GAAKO,MAAMnD,EAASI,aAO3BI,EAAK,SAASsC,EAAO9C,EAAS6C,GAChC,MAAa,OAATC,EAAsB3C,EAAEiD,SACxBjD,EAAEW,WAAWgC,GAAe7C,EAAW6C,EAAO9C,EAAS6C,GACvD1C,EAAEkD,SAASP,GAAe3C,EAAEmD,QAAQR,GACjC3C,EAAEoD,SAAST,GAEpB3C,GAAET,SAAW,SAASoD,EAAO9C,GAC3B,MAAOQ,GAAGsC,EAAO9C,EAASwD,KAI5B,IAAIC,GAAiB,SAASC,EAAUC,GACtC,MAAO,UAASlE,GACd,GAAIK,GAASM,UAAUN,MACvB,IAAa,EAATA,GAAqB,MAAPL,EAAa,MAAOA,EACtC,KAAK,GAAII,GAAQ,EAAWC,EAARD,EAAgBA,IAIlC,IAAK,GAHD+D,GAASxD,UAAUP,GACnBD,EAAO8D,EAASE,GAChBC,EAAIjE,EAAKE,OACJgE,EAAI,EAAOD,EAAJC,EAAOA,IAAK,CAC1B,GAAIC,GAAMnE,EAAKkE,EACVH,IAAiBlE,EAAIsE,SAAc,KAAGtE,EAAIsE,GAAOH,EAAOG,IAGjE,MAAOtE,KAKPuE,EAAa,SAASjD,GACxB,IAAKZ,EAAEkD,SAAStC,GAAY,QAC5B,IAAIsB,EAAc,MAAOA,GAAatB,EACtCwB,GAAKxB,UAAYA,CACjB,IAAIkD,GAAS,GAAI1B,EAEjB,OADAA,GAAKxB,UAAY,KACVkD,GAMLC,EAAkBC,KAAKC,IAAI,EAAG,IAAM,EACpClE,EAAc,SAAS+C,GACzB,GAAInD,GAASmD,GAAcA,EAAWnD,MACtC,OAAwB,gBAAVA,IAAsBA,GAAU,GAAeoE,GAAVpE,EASrDK,GAAEkE,KAAOlE,EAAEmE,QAAU,SAAS7E,EAAKC,EAAUM,GAC3CN,EAAWO,EAAWP,EAAUM,EAChC,IAAI8D,GAAGhE,CACP,IAAII,EAAYT,GACd,IAAKqE,EAAI,EAAGhE,EAASL,EAAIK,OAAYA,EAAJgE,EAAYA,IAC3CpE,EAASD,EAAIqE,GAAIA,EAAGrE,OAEjB,CACL,GAAIG,GAAOO,EAAEP,KAAKH,EAClB,KAAKqE,EAAI,EAAGhE,EAASF,EAAKE,OAAYA,EAAJgE,EAAYA,IAC5CpE,EAASD,EAAIG,EAAKkE,IAAKlE,EAAKkE,GAAIrE,GAGpC,MAAOA,IAITU,EAAEoE,IAAMpE,EAAEqE,QAAU,SAAS/E,EAAKC,EAAUM,GAC1CN,EAAWc,EAAGd,EAAUM,EAIxB,KAAK,GAHDJ,IAAQM,EAAYT,IAAQU,EAAEP,KAAKH,GACnCK,GAAUF,GAAQH,GAAKK,OACvB2E,EAAUhD,MAAM3B,GACXD,EAAQ,EAAWC,EAARD,EAAgBA,IAAS,CAC3C,GAAIE,GAAaH,EAAOA,EAAKC,GAASA,CACtC4E,GAAQ5E,GAASH,EAASD,EAAIM,GAAaA,EAAYN,GAEzD,MAAOgF,IA+BTtE,EAAEuE,OAASvE,EAAEwE,MAAQxE,EAAEyE,OAAStF,EAAa,GAG7Ca,EAAE0E,YAAc1E,EAAE2E,MAAQxF,GAAc,GAGxCa,EAAE4E,KAAO5E,EAAE6E,OAAS,SAASvF,EAAKc,EAAWP,GAC3C,GAAI+D,EAMJ,OAJEA,GADE7D,EAAYT,GACRU,EAAE8E,UAAUxF,EAAKc,EAAWP,GAE5BG,EAAE+E,QAAQzF,EAAKc,EAAWP,GAE9B+D,QAAa,IAAKA,KAAS,EAAUtE,EAAIsE,GAA7C,QAKF5D,EAAEgF,OAAShF,EAAEiF,OAAS,SAAS3F,EAAKc,EAAWP,GAC7C,GAAIyE,KAKJ,OAJAlE,GAAYC,EAAGD,EAAWP,GAC1BG,EAAEkE,KAAK5E,EAAK,SAASqD,EAAOjD,EAAOwF,GAC7B9E,EAAUuC,EAAOjD,EAAOwF,IAAOZ,EAAQrD,KAAK0B,KAE3C2B,GAITtE,EAAEmF,OAAS,SAAS7F,EAAKc,EAAWP,GAClC,MAAOG,GAAEgF,OAAO1F,EAAKU,EAAEoF,OAAO/E,EAAGD,IAAaP,IAKhDG,EAAEqF,MAAQrF,EAAEsF,IAAM,SAAShG,EAAKc,EAAWP,GACzCO,EAAYC,EAAGD,EAAWP,EAG1B,KAAK,GAFDJ,IAAQM,EAAYT,IAAQU,EAAEP,KAAKH,GACnCK,GAAUF,GAAQH,GAAKK,OAClBD,EAAQ,EAAWC,EAARD,EAAgBA,IAAS,CAC3C,GAAIE,GAAaH,EAAOA,EAAKC,GAASA,CACtC,KAAKU,EAAUd,EAAIM,GAAaA,EAAYN,GAAM,OAAO,EAE3D,OAAO,GAKTU,EAAEuF,KAAOvF,EAAEwF,IAAM,SAASlG,EAAKc,EAAWP,GACxCO,EAAYC,EAAGD,EAAWP,EAG1B,KAAK,GAFDJ,IAAQM,EAAYT,IAAQU,EAAEP,KAAKH,GACnCK,GAAUF,GAAQH,GAAKK,OAClBD,EAAQ,EAAWC,EAARD,EAAgBA,IAAS,CAC3C,GAAIE,GAAaH,EAAOA,EAAKC,GAASA,CACtC,IAAIU,EAAUd,EAAIM,GAAaA,EAAYN,GAAM,OAAO,EAE1D,OAAO,GAKTU,EAAEgB,SAAWhB,EAAEyF,SAAWzF,EAAE0F,QAAU,SAASpG,EAAKqG,EAAQC,GAE1D,MADK7F,GAAYT,KAAMA,EAAMU,EAAE6F,OAAOvG,IAC/BU,EAAE8F,QAAQxG,EAAKqG,EAA4B,gBAAbC,IAAyBA,IAAc,GAI9E5F,EAAE+F,OAAS,SAASzG,EAAK0G,GACvB,GAAIC,GAAOvE,EAAMkB,KAAK3C,UAAW,GAC7BiG,EAASlG,EAAEW,WAAWqF,EAC1B,OAAOhG,GAAEoE,IAAI9E,EAAK,SAASqD,GACzB,GAAIF,GAAOyD,EAASF,EAASrD,EAAMqD,EACnC,OAAe,OAARvD,EAAeA,EAAOA,EAAKO,MAAML,EAAOsD,MAKnDjG,EAAEmG,MAAQ,SAAS7G,EAAKsE,GACtB,MAAO5D,GAAEoE,IAAI9E,EAAKU,EAAEoD,SAASQ,KAK/B5D,EAAEoG,MAAQ,SAAS9G,EAAK+G,GACtB,MAAOrG,GAAEgF,OAAO1F,EAAKU,EAAEmD,QAAQkD,KAKjCrG,EAAEsG,UAAY,SAAShH,EAAK+G,GAC1B,MAAOrG,GAAE4E,KAAKtF,EAAKU,EAAEmD,QAAQkD,KAI/BrG,EAAEuG,IAAM,SAASjH,EAAKC,EAAUM,GAC9B,GACI8C,GAAO6D,EADP1C,GAAUT,IAAUoD,GAAgBpD,GAExC,IAAgB,MAAZ9D,GAA2B,MAAPD,EAAa,CACnCA,EAAMS,EAAYT,GAAOA,EAAMU,EAAE6F,OAAOvG,EACxC,KAAK,GAAIqE,GAAI,EAAGhE,EAASL,EAAIK,OAAYA,EAAJgE,EAAYA,IAC/ChB,EAAQrD,EAAIqE,GACRhB,EAAQmB,IACVA,EAASnB,OAIbpD,GAAWc,EAAGd,EAAUM,GACxBG,EAAEkE,KAAK5E,EAAK,SAASqD,EAAOjD,EAAOwF,GACjCsB,EAAWjH,EAASoD,EAAOjD,EAAOwF,IAC9BsB,EAAWC,GAAgBD,KAAcnD,KAAYS,KAAYT,OACnES,EAASnB,EACT8D,EAAeD,IAIrB,OAAO1C,IAIT9D,EAAE0G,IAAM,SAASpH,EAAKC,EAAUM,GAC9B,GACI8C,GAAO6D,EADP1C,EAAST,IAAUoD,EAAepD,GAEtC,IAAgB,MAAZ9D,GAA2B,MAAPD,EAAa,CACnCA,EAAMS,EAAYT,GAAOA,EAAMU,EAAE6F,OAAOvG,EACxC,KAAK,GAAIqE,GAAI,EAAGhE,EAASL,EAAIK,OAAYA,EAAJgE,EAAYA,IAC/ChB,EAAQrD,EAAIqE,GACAG,EAARnB,IACFmB,EAASnB,OAIbpD,GAAWc,EAAGd,EAAUM,GACxBG,EAAEkE,KAAK5E,EAAK,SAASqD,EAAOjD,EAAOwF,GACjCsB,EAAWjH,EAASoD,EAAOjD,EAAOwF,IACnBuB,EAAXD,GAAwCnD,MAAbmD,GAAoCnD,MAAXS,KACtDA,EAASnB,EACT8D,EAAeD,IAIrB,OAAO1C,IAKT9D,EAAE2G,QAAU,SAASrH,GAInB,IAAK,GAAesH,GAHhBC,EAAM9G,EAAYT,GAAOA,EAAMU,EAAE6F,OAAOvG,GACxCK,EAASkH,EAAIlH,OACbmH,EAAWxF,MAAM3B,GACZD,EAAQ,EAAiBC,EAARD,EAAgBA,IACxCkH,EAAO5G,EAAE+G,OAAO,EAAGrH,GACfkH,IAASlH,IAAOoH,EAASpH,GAASoH,EAASF,IAC/CE,EAASF,GAAQC,EAAInH,EAEvB,OAAOoH,IAMT9G,EAAEgH,OAAS,SAAS1H,EAAK2H,EAAGC,GAC1B,MAAS,OAALD,GAAaC,GACVnH,EAAYT,KAAMA,EAAMU,EAAE6F,OAAOvG,IAC/BA,EAAIU,EAAE+G,OAAOzH,EAAIK,OAAS,KAE5BK,EAAE2G,QAAQrH,GAAKoC,MAAM,EAAGsC,KAAKuC,IAAI,EAAGU,KAI7CjH,EAAEmH,OAAS,SAAS7H,EAAKC,EAAUM,GAEjC,MADAN,GAAWc,EAAGd,EAAUM,GACjBG,EAAEmG,MAAMnG,EAAEoE,IAAI9E,EAAK,SAASqD,EAAOjD,EAAOwF,GAC/C,OACEvC,MAAOA,EACPjD,MAAOA,EACP0H,SAAU7H,EAASoD,EAAOjD,EAAOwF,MAElCmC,KAAK,SAASC,EAAMC,GACrB,GAAIC,GAAIF,EAAKF,SACTK,EAAIF,EAAMH,QACd,IAAII,IAAMC,EAAG,CACX,GAAID,EAAIC,GAAKD,QAAW,GAAG,MAAO,EAClC,IAAQC,EAAJD,GAASC,QAAW,GAAG,OAAQ,EAErC,MAAOH,GAAK5H,MAAQ6H,EAAM7H,QACxB,SAIN,IAAIgI,GAAQ,SAASC,GACnB,MAAO,UAASrI,EAAKC,EAAUM,GAC7B,GAAIiE,KAMJ,OALAvE,GAAWc,EAAGd,EAAUM,GACxBG,EAAEkE,KAAK5E,EAAK,SAASqD,EAAOjD,GAC1B,GAAIkE,GAAMrE,EAASoD,EAAOjD,EAAOJ,EACjCqI,GAAS7D,EAAQnB,EAAOiB,KAEnBE,GAMX9D,GAAE4H,QAAUF,EAAM,SAAS5D,EAAQnB,EAAOiB,GACpC5D,EAAEe,IAAI+C,EAAQF,GAAME,EAAOF,GAAK3C,KAAK0B,GAAamB,EAAOF,IAAQjB,KAKvE3C,EAAE6H,QAAUH,EAAM,SAAS5D,EAAQnB,EAAOiB,GACxCE,EAAOF,GAAOjB,IAMhB3C,EAAE8H,QAAUJ,EAAM,SAAS5D,EAAQnB,EAAOiB,GACpC5D,EAAEe,IAAI+C,EAAQF,GAAME,EAAOF,KAAaE,EAAOF,GAAO,IAI5D5D,EAAE+H,QAAU,SAASzI,GACnB,MAAKA,GACDU,EAAE8B,QAAQxC,GAAaoC,EAAMkB,KAAKtD,GAClCS,EAAYT,GAAaU,EAAEoE,IAAI9E,EAAKU,EAAEiD,UACnCjD,EAAE6F,OAAOvG,OAIlBU,EAAEgI,KAAO,SAAS1I,GAChB,MAAW,OAAPA,EAAoB,EACjBS,EAAYT,GAAOA,EAAIK,OAASK,EAAEP,KAAKH,GAAKK,QAKrDK,EAAEiI,UAAY,SAAS3I,EAAKc,EAAWP,GACrCO,EAAYC,EAAGD,EAAWP,EAC1B,IAAIqI,MAAWC,IAIf,OAHAnI,GAAEkE,KAAK5E,EAAK,SAASqD,EAAOiB,EAAKtE,IAC9Bc,EAAUuC,EAAOiB,EAAKtE,GAAO4I,EAAOC,GAAMlH,KAAK0B,MAE1CuF,EAAMC,IAShBnI,EAAEoI,MAAQpI,EAAEqI,KAAOrI,EAAEsI,KAAO,SAASnI,EAAO8G,EAAGC,GAC7C,MAAa,OAAT/G,MAA2B,GACtB,MAAL8G,GAAaC,EAAc/G,EAAM,GAC9BH,EAAEuI,QAAQpI,EAAOA,EAAMR,OAASsH,IAMzCjH,EAAEuI,QAAU,SAASpI,EAAO8G,EAAGC,GAC7B,MAAOxF,GAAMkB,KAAKzC,EAAO,EAAG6D,KAAKuC,IAAI,EAAGpG,EAAMR,QAAe,MAALsH,GAAaC,EAAQ,EAAID,MAKnFjH,EAAEwI,KAAO,SAASrI,EAAO8G,EAAGC,GAC1B,MAAa,OAAT/G,MAA2B,GACtB,MAAL8G,GAAaC,EAAc/G,EAAMA,EAAMR,OAAS,GAC7CK,EAAEyI,KAAKtI,EAAO6D,KAAKuC,IAAI,EAAGpG,EAAMR,OAASsH,KAMlDjH,EAAEyI,KAAOzI,EAAE0I,KAAO1I,EAAE2I,KAAO,SAASxI,EAAO8G,EAAGC,GAC5C,MAAOxF,GAAMkB,KAAKzC,EAAY,MAAL8G,GAAaC,EAAQ,EAAID,IAIpDjH,EAAE4I,QAAU,SAASzI,GACnB,MAAOH,GAAEgF,OAAO7E,EAAOH,EAAEiD,UAI3B,IAAI4F,GAAU,SAASC,EAAOC,EAASC,EAAQC,GAE7C,IAAK,GADDC,MAAaC,EAAM,EACdxF,EAAIsF,GAAc,EAAGtJ,EAASmJ,GAASA,EAAMnJ,OAAYA,EAAJgE,EAAYA,IAAK,CAC7E,GAAIhB,GAAQmG,EAAMnF,EAClB,IAAI5D,EAAY4C,KAAW3C,EAAE8B,QAAQa,IAAU3C,EAAEoJ,YAAYzG,IAAS,CAE/DoG,IAASpG,EAAQkG,EAAQlG,EAAOoG,EAASC,GAC9C,IAAIK,GAAI,EAAGC,EAAM3G,EAAMhD,MAEvB,KADAuJ,EAAOvJ,QAAU2J,EACNA,EAAJD,GACLH,EAAOC,KAASxG,EAAM0G,SAEdL,KACVE,EAAOC,KAASxG,GAGpB,MAAOuG,GAITlJ,GAAE6I,QAAU,SAAS1I,EAAO4I,GAC1B,MAAOF,GAAQ1I,EAAO4I,GAAS,IAIjC/I,EAAEuJ,QAAU,SAASpJ,GACnB,MAAOH,GAAEwJ,WAAWrJ,EAAOuB,EAAMkB,KAAK3C,UAAW,KAMnDD,EAAEyJ,KAAOzJ,EAAE0J,OAAS,SAASvJ,EAAOwJ,EAAUpK,EAAUM,GACtD,GAAa,MAATM,EAAe,QACdH,GAAE4J,UAAUD,KACf9J,EAAUN,EACVA,EAAWoK,EACXA,GAAW,GAEG,MAAZpK,IAAkBA,EAAWc,EAAGd,EAAUM,GAG9C,KAAK,GAFDiE,MACA+F,KACKlG,EAAI,EAAGhE,EAASQ,EAAMR,OAAYA,EAAJgE,EAAYA,IAAK,CACtD,GAAIhB,GAAQxC,EAAMwD,GACd6C,EAAWjH,EAAWA,EAASoD,EAAOgB,EAAGxD,GAASwC,CAClDgH,IACGhG,GAAKkG,IAASrD,GAAU1C,EAAO7C,KAAK0B,GACzCkH,EAAOrD,GACEjH,EACJS,EAAEgB,SAAS6I,EAAMrD,KACpBqD,EAAK5I,KAAKuF,GACV1C,EAAO7C,KAAK0B,IAEJ3C,EAAEgB,SAAS8C,EAAQnB,IAC7BmB,EAAO7C,KAAK0B,GAGhB,MAAOmB,IAKT9D,EAAE8J,MAAQ,WACR,MAAO9J,GAAEyJ,KAAKZ,EAAQ5I,WAAW,GAAM,KAKzCD,EAAE+J,aAAe,SAAS5J,GACxB,GAAa,MAATA,EAAe,QAGnB,KAAK,GAFD2D,MACAkG,EAAa/J,UAAUN,OAClBgE,EAAI,EAAGhE,EAASQ,EAAMR,OAAYA,EAAJgE,EAAYA,IAAK,CACtD,GAAIsG,GAAO9J,EAAMwD,EACjB,KAAI3D,EAAEgB,SAAS8C,EAAQmG,GAAvB,CACA,IAAK,GAAIZ,GAAI,EAAOW,EAAJX,GACTrJ,EAAEgB,SAASf,UAAUoJ,GAAIY,GADAZ,KAG5BA,IAAMW,GAAYlG,EAAO7C,KAAKgJ,IAEpC,MAAOnG,IAKT9D,EAAEwJ,WAAa,SAASrJ,GACtB,GAAIsI,GAAOI,EAAQ5I,WAAW,GAAM,EAAM,EAC1C,OAAOD,GAAEgF,OAAO7E,EAAO,SAASwC,GAC9B,OAAQ3C,EAAEgB,SAASyH,EAAM9F,MAM7B3C,EAAEkK,IAAM,WACN,MAAOlK,GAAEmK,MAAMlK,YAKjBD,EAAEmK,MAAQ,SAAShK,GAIjB,IAAK,GAHDR,GAASQ,GAASH,EAAEuG,IAAIpG,EAAO,UAAUR,QAAU,EACnDmE,EAASxC,MAAM3B,GAEVD,EAAQ,EAAWC,EAARD,EAAgBA,IAClCoE,EAAOpE,GAASM,EAAEmG,MAAMhG,EAAOT,EAEjC,OAAOoE,IAMT9D,EAAEoK,OAAS,SAASlF,EAAMW,GAExB,IAAK,GADD/B,MACKH,EAAI,EAAGhE,EAASuF,GAAQA,EAAKvF,OAAYA,EAAJgE,EAAYA,IACpDkC,EACF/B,EAAOoB,EAAKvB,IAAMkC,EAAOlC,GAEzBG,EAAOoB,EAAKvB,GAAG,IAAMuB,EAAKvB,GAAG,EAGjC,OAAOG,IAOT9D,EAAE8F,QAAU,SAAS3F,EAAO8J,EAAMN,GAChC,GAAIhG,GAAI,EAAGhE,EAASQ,GAASA,EAAMR,MACnC,IAAuB,gBAAZgK,GACThG,EAAe,EAAXgG,EAAe3F,KAAKuC,IAAI,EAAG5G,EAASgK,GAAYA,MAC/C,IAAIA,GAAYhK,EAErB,MADAgE,GAAI3D,EAAEqK,YAAYlK,EAAO8J,GAClB9J,EAAMwD,KAAOsG,EAAOtG,GAAK,CAElC,IAAIsG,IAASA,EACX,MAAOjK,GAAE8E,UAAUpD,EAAMkB,KAAKzC,EAAOwD,GAAI3D,EAAEsK,MAE7C,MAAW3K,EAAJgE,EAAYA,IAAK,GAAIxD,EAAMwD,KAAOsG,EAAM,MAAOtG,EACtD,QAAQ,GAGV3D,EAAEuK,YAAc,SAASpK,EAAO8J,EAAMO,GACpC,GAAIrB,GAAMhJ,EAAQA,EAAMR,OAAS,CAIjC,IAHmB,gBAAR6K,KACTrB,EAAa,EAAPqB,EAAWrB,EAAMqB,EAAO,EAAIxG,KAAK0C,IAAIyC,EAAKqB,EAAO,IAErDP,IAASA,EACX,MAAOjK,GAAEyK,cAAc/I,EAAMkB,KAAKzC,EAAO,EAAGgJ,GAAMnJ,EAAEsK,MAEtD,QAASnB,GAAO,GAAG,GAAIhJ,EAAMgJ,KAASc,EAAM,MAAOd,EACnD,QAAQ,GAiBVnJ,EAAE8E,UAAY5E,EAAkB,GAEhCF,EAAEyK,cAAgBvK,GAAmB,GAIrCF,EAAEqK,YAAc,SAASlK,EAAOb,EAAKC,EAAUM,GAC7CN,EAAWc,EAAGd,EAAUM,EAAS,EAGjC,KAFA,GAAI8C,GAAQpD,EAASD,GACjBoL,EAAM,EAAGC,EAAOxK,EAAMR,OACbgL,EAAND,GAAY,CACjB,GAAIE,GAAM5G,KAAK6G,OAAOH,EAAMC,GAAQ,EAChCpL,GAASY,EAAMyK,IAAQjI,EAAO+H,EAAME,EAAM,EAAQD,EAAOC,EAE/D,MAAOF,IAMT1K,EAAE8K,MAAQ,SAASC,EAAOC,EAAMC,GAC1BhL,UAAUN,QAAU,IACtBqL,EAAOD,GAAS,EAChBA,EAAQ,GAEVE,EAAOA,GAAQ,CAKf,KAAK,GAHDtL,GAASqE,KAAKuC,IAAIvC,KAAKkH,MAAMF,EAAOD,GAASE,GAAO,GACpDH,EAAQxJ,MAAM3B,GAETwJ,EAAM,EAASxJ,EAANwJ,EAAcA,IAAO4B,GAASE,EAC9CH,EAAM3B,GAAO4B,CAGf,OAAOD,GAQT,IAAIK,GAAe,SAASC,EAAYC,EAAWxL,EAASyL,EAAgBrF,GAC1E,KAAMqF,YAA0BD,IAAY,MAAOD,GAAWpI,MAAMnD,EAASoG,EAC7E,IAAIsF,GAAO1H,EAAWuH,EAAWxK,WAC7BkD,EAASsH,EAAWpI,MAAMuI,EAAMtF,EACpC,OAAIjG,GAAEkD,SAASY,GAAgBA,EACxByH,EAMTvL,GAAEiC,KAAO,SAASQ,EAAM5C,GACtB,GAAImC,GAAcS,EAAKR,OAASD,EAAY,MAAOA,GAAWgB,MAAMP,EAAMf,EAAMkB,KAAK3C,UAAW,GAChG,KAAKD,EAAEW,WAAW8B,GAAO,KAAM,IAAI+I,WAAU,oCAC7C,IAAIvF,GAAOvE,EAAMkB,KAAK3C,UAAW,GAC7BwL,EAAQ,WACV,MAAON,GAAa1I,EAAMgJ,EAAO5L,EAASsB,KAAM8E,EAAKyF,OAAOhK,EAAMkB,KAAK3C,aAEzE,OAAOwL,IAMTzL,EAAE2L,QAAU,SAASlJ,GACnB,GAAImJ,GAAYlK,EAAMkB,KAAK3C,UAAW,GAClCwL,EAAQ,WAGV,IAAK,GAFDI,GAAW,EAAGlM,EAASiM,EAAUjM,OACjCsG,EAAO3E,MAAM3B,GACRgE,EAAI,EAAOhE,EAAJgE,EAAYA,IAC1BsC,EAAKtC,GAAKiI,EAAUjI,KAAO3D,EAAIC,UAAU4L,KAAcD,EAAUjI,EAEnE,MAAOkI,EAAW5L,UAAUN,QAAQsG,EAAKhF,KAAKhB,UAAU4L,KACxD,OAAOV,GAAa1I,EAAMgJ,EAAOtK,KAAMA,KAAM8E,GAE/C,OAAOwF,IAMTzL,EAAE8L,QAAU,SAASxM,GACnB,GAAIqE,GAA8BC,EAA3BjE,EAASM,UAAUN,MAC1B,IAAc,GAAVA,EAAa,KAAM,IAAIoM,OAAM,wCACjC,KAAKpI,EAAI,EAAOhE,EAAJgE,EAAYA,IACtBC,EAAM3D,UAAU0D,GAChBrE,EAAIsE,GAAO5D,EAAEiC,KAAK3C,EAAIsE,GAAMtE,EAE9B,OAAOA,IAITU,EAAEgM,QAAU,SAASvJ,EAAMwJ,GACzB,GAAID,GAAU,SAASpI,GACrB,GAAIsI,GAAQF,EAAQE,MAChBC,EAAU,IAAMF,EAASA,EAAOjJ,MAAM7B,KAAMlB,WAAa2D,EAE7D,OADK5D,GAAEe,IAAImL,EAAOC,KAAUD,EAAMC,GAAW1J,EAAKO,MAAM7B,KAAMlB,YACvDiM,EAAMC,GAGf,OADAH,GAAQE,SACDF,GAKThM,EAAEoM,MAAQ,SAAS3J,EAAM4J,GACvB,GAAIpG,GAAOvE,EAAMkB,KAAK3C,UAAW,EACjC,OAAOqM,YAAW,WAChB,MAAO7J,GAAKO,MAAM,KAAMiD,IACvBoG,IAKLrM,EAAEuM,MAAQvM,EAAE2L,QAAQ3L,EAAEoM,MAAOpM,EAAG,GAOhCA,EAAEwM,SAAW,SAAS/J,EAAM4J,EAAMI,GAChC,GAAI5M,GAASoG,EAAMnC,EACf4I,EAAU,KACVC,EAAW,CACVF,KAASA,KACd,IAAIG,GAAQ,WACVD,EAAWF,EAAQI,WAAY,EAAQ,EAAI7M,EAAE8M,MAC7CJ,EAAU,KACV5I,EAASrB,EAAKO,MAAMnD,EAASoG,GACxByG,IAAS7M,EAAUoG,EAAO,MAEjC,OAAO,YACL,GAAI6G,GAAM9M,EAAE8M,KACPH,IAAYF,EAAQI,WAAY,IAAOF,EAAWG,EACvD,IAAIC,GAAYV,GAAQS,EAAMH,EAc9B,OAbA9M,GAAUsB,KACV8E,EAAOhG,UACU,GAAb8M,GAAkBA,EAAYV,GAC5BK,IACFM,aAAaN,GACbA,EAAU,MAEZC,EAAWG,EACXhJ,EAASrB,EAAKO,MAAMnD,EAASoG,GACxByG,IAAS7M,EAAUoG,EAAO,OACrByG,GAAWD,EAAQQ,YAAa,IAC1CP,EAAUJ,WAAWM,EAAOG,IAEvBjJ,IAQX9D,EAAEkN,SAAW,SAASzK,EAAM4J,EAAMc,GAChC,GAAIT,GAASzG,EAAMpG,EAASuN,EAAWtJ,EAEnC8I,EAAQ,WACV,GAAIpE,GAAOxI,EAAE8M,MAAQM,CAEVf,GAAP7D,GAAeA,GAAQ,EACzBkE,EAAUJ,WAAWM,EAAOP,EAAO7D,IAEnCkE,EAAU,KACLS,IACHrJ,EAASrB,EAAKO,MAAMnD,EAASoG,GACxByG,IAAS7M,EAAUoG,EAAO,QAKrC,OAAO,YACLpG,EAAUsB,KACV8E,EAAOhG,UACPmN,EAAYpN,EAAE8M,KACd,IAAIO,GAAUF,IAAcT,CAO5B,OANKA,KAASA,EAAUJ,WAAWM,EAAOP,IACtCgB,IACFvJ,EAASrB,EAAKO,MAAMnD,EAASoG,GAC7BpG,EAAUoG,EAAO,MAGZnC,IAOX9D,EAAEsN,KAAO,SAAS7K,EAAM8K,GACtB,MAAOvN,GAAE2L,QAAQ4B,EAAS9K,IAI5BzC,EAAEoF,OAAS,SAAShF,GAClB,MAAO,YACL,OAAQA,EAAU4C,MAAM7B,KAAMlB,aAMlCD,EAAEwN,QAAU,WACV,GAAIvH,GAAOhG,UACP8K,EAAQ9E,EAAKtG,OAAS,CAC1B,OAAO,YAGL,IAFA,GAAIgE,GAAIoH,EACJjH,EAASmC,EAAK8E,GAAO/H,MAAM7B,KAAMlB,WAC9B0D,KAAKG,EAASmC,EAAKtC,GAAGf,KAAKzB,KAAM2C,EACxC,OAAOA,KAKX9D,EAAEyN,MAAQ,SAASC,EAAOjL,GACxB,MAAO,YACL,QAAMiL,EAAQ,EACLjL,EAAKO,MAAM7B,KAAMlB,WAD1B,SAOJD,EAAE2N,OAAS,SAASD,EAAOjL,GACzB,GAAIjD,EACJ,OAAO,YAKL,QAJMkO,EAAQ,IACZlO,EAAOiD,EAAKO,MAAM7B,KAAMlB,YAEb,GAATyN,IAAYjL,EAAO,MAChBjD,IAMXQ,EAAE4N,KAAO5N,EAAE2L,QAAQ3L,EAAE2N,OAAQ,EAM7B,IAAIE,KAAelM,SAAU,MAAMmM,qBAAqB,YACpDtN,GAAsB,UAAW,gBAAiB,WAClC,uBAAwB,iBAAkB,iBAqB9DR,GAAEP,KAAO,SAASH,GAChB,IAAKU,EAAEkD,SAAS5D,GAAM,QACtB,IAAIyC,EAAY,MAAOA,GAAWzC,EAClC,IAAIG,KACJ,KAAK,GAAImE,KAAOtE,GAASU,EAAEe,IAAIzB,EAAKsE,IAAMnE,EAAKwB,KAAK2C,EAGpD,OADIiK,IAAYvN,EAAoBhB,EAAKG,GAClCA,GAITO,EAAE+N,QAAU,SAASzO,GACnB,IAAKU,EAAEkD,SAAS5D,GAAM,QACtB,IAAIG,KACJ,KAAK,GAAImE,KAAOtE,GAAKG,EAAKwB,KAAK2C,EAG/B,OADIiK,IAAYvN,EAAoBhB,EAAKG,GAClCA,GAITO,EAAE6F,OAAS,SAASvG,GAIlB,IAAK,GAHDG,GAAOO,EAAEP,KAAKH,GACdK,EAASF,EAAKE,OACdkG,EAASvE,MAAM3B,GACVgE,EAAI,EAAOhE,EAAJgE,EAAYA,IAC1BkC,EAAOlC,GAAKrE,EAAIG,EAAKkE,GAEvB,OAAOkC,IAKT7F,EAAEgO,UAAY,SAAS1O,EAAKC,EAAUM,GACpCN,EAAWc,EAAGd,EAAUM,EAKtB,KAAK,GADDD,GAHFH,EAAQO,EAAEP,KAAKH,GACbK,EAASF,EAAKE,OACd2E,KAEK5E,EAAQ,EAAWC,EAARD,EAAgBA,IAClCE,EAAaH,EAAKC,GAClB4E,EAAQ1E,GAAcL,EAASD,EAAIM,GAAaA,EAAYN,EAE9D,OAAOgF,IAIXtE,EAAEiO,MAAQ,SAAS3O,GAIjB,IAAK,GAHDG,GAAOO,EAAEP,KAAKH,GACdK,EAASF,EAAKE,OACdsO,EAAQ3M,MAAM3B,GACTgE,EAAI,EAAOhE,EAAJgE,EAAYA,IAC1BsK,EAAMtK,IAAMlE,EAAKkE,GAAIrE,EAAIG,EAAKkE,IAEhC,OAAOsK,IAITjO,EAAEkO,OAAS,SAAS5O,GAGlB,IAAK,GAFDwE,MACArE,EAAOO,EAAEP,KAAKH,GACTqE,EAAI,EAAGhE,EAASF,EAAKE,OAAYA,EAAJgE,EAAYA,IAChDG,EAAOxE,EAAIG,EAAKkE,KAAOlE,EAAKkE,EAE9B,OAAOG,IAKT9D,EAAEmO,UAAYnO,EAAEoO,QAAU,SAAS9O,GACjC,GAAI+O,KACJ,KAAK,GAAIzK,KAAOtE,GACVU,EAAEW,WAAWrB,EAAIsE,KAAOyK,EAAMpN,KAAK2C,EAEzC,OAAOyK,GAAMhH,QAIfrH,EAAEsO,OAAShL,EAAetD,EAAE+N,SAI5B/N,EAAEuO,UAAYvO,EAAEwO,OAASlL,EAAetD,EAAEP,MAG1CO,EAAE+E,QAAU,SAASzF,EAAKc,EAAWP,GACnCO,EAAYC,EAAGD,EAAWP,EAE1B,KAAK,GADmB+D,GAApBnE,EAAOO,EAAEP,KAAKH,GACTqE,EAAI,EAAGhE,EAASF,EAAKE,OAAYA,EAAJgE,EAAYA,IAEhD,GADAC,EAAMnE,EAAKkE,GACPvD,EAAUd,EAAIsE,GAAMA,EAAKtE,GAAM,MAAOsE,IAK9C5D,EAAEyO,KAAO,SAASrE,EAAQsE,EAAW7O,GACnC,GAA+BN,GAAUE,EAArCqE,KAAaxE,EAAM8K,CACvB,IAAW,MAAP9K,EAAa,MAAOwE,EACpB9D,GAAEW,WAAW+N,IACfjP,EAAOO,EAAE+N,QAAQzO,GACjBC,EAAWO,EAAW4O,EAAW7O,KAEjCJ,EAAOoJ,EAAQ5I,WAAW,GAAO,EAAO,GACxCV,EAAW,SAASoD,EAAOiB,EAAKtE,GAAO,MAAOsE,KAAOtE,IACrDA,EAAMiC,OAAOjC,GAEf,KAAK,GAAIqE,GAAI,EAAGhE,EAASF,EAAKE,OAAYA,EAAJgE,EAAYA,IAAK,CACrD,GAAIC,GAAMnE,EAAKkE,GACXhB,EAAQrD,EAAIsE,EACZrE,GAASoD,EAAOiB,EAAKtE,KAAMwE,EAAOF,GAAOjB,GAE/C,MAAOmB,IAIT9D,EAAE2O,KAAO,SAASrP,EAAKC,EAAUM,GAC/B,GAAIG,EAAEW,WAAWpB,GACfA,EAAWS,EAAEoF,OAAO7F,OACf,CACL,GAAIE,GAAOO,EAAEoE,IAAIyE,EAAQ5I,WAAW,GAAO,EAAO,GAAI2O,OACtDrP,GAAW,SAASoD,EAAOiB,GACzB,OAAQ5D,EAAEgB,SAASvB,EAAMmE,IAG7B,MAAO5D,GAAEyO,KAAKnP,EAAKC,EAAUM,IAI/BG,EAAE6O,SAAWvL,EAAetD,EAAE+N,SAAS,GAGvC/N,EAAE8O,MAAQ,SAASxP,GACjB,MAAKU,GAAEkD,SAAS5D,GACTU,EAAE8B,QAAQxC,GAAOA,EAAIoC,QAAU1B,EAAEsO,UAAWhP,GADtBA,GAO/BU,EAAE+O,IAAM,SAASzP,EAAK0P,GAEpB,MADAA,GAAY1P,GACLA,GAITU,EAAEiP,QAAU,SAAS7E,EAAQ/D,GAC3B,GAAI5G,GAAOO,EAAEP,KAAK4G,GAAQ1G,EAASF,EAAKE,MACxC,IAAc,MAAVyK,EAAgB,OAAQzK,CAE5B,KAAK,GADDL,GAAMiC,OAAO6I,GACRzG,EAAI,EAAOhE,EAAJgE,EAAYA,IAAK,CAC/B,GAAIC,GAAMnE,EAAKkE,EACf,IAAI0C,EAAMzC,KAAStE,EAAIsE,MAAUA,IAAOtE,IAAM,OAAO,EAEvD,OAAO,EAKT,IAAI4P,GAAK,SAAS1H,EAAGC,EAAG0H,EAAQC,GAG9B,GAAI5H,IAAMC,EAAG,MAAa,KAAND,GAAW,EAAIA,IAAM,EAAIC,CAE7C,IAAS,MAALD,GAAkB,MAALC,EAAW,MAAOD,KAAMC,CAErCD,aAAaxH,KAAGwH,EAAIA,EAAEnF,UACtBoF,YAAazH,KAAGyH,EAAIA,EAAEpF,SAE1B,IAAIgN,GAAY1N,EAASiB,KAAK4E,EAC9B,IAAI6H,IAAc1N,EAASiB,KAAK6E,GAAI,OAAO,CAC3C,QAAQ4H,GAEN,IAAK,kBAEL,IAAK,kBAGH,MAAO,GAAK7H,GAAM,GAAKC,CACzB,KAAK,kBAGH,OAAKD,KAAOA,GAAWC,KAAOA,EAEhB,KAAND,EAAU,GAAKA,IAAM,EAAIC,GAAKD,KAAOC,CAC/C,KAAK,gBACL,IAAK,mBAIH,OAAQD,KAAOC,EAGnB,GAAI6H,GAA0B,mBAAdD,CAChB,KAAKC,EAAW,CACd,GAAgB,gBAAL9H,IAA6B,gBAALC,GAAe,OAAO,CAIzD,IAAI8H,GAAQ/H,EAAE/G,YAAa+O,EAAQ/H,EAAEhH,WACrC,IAAI8O,IAAUC,KAAWxP,EAAEW,WAAW4O,IAAUA,YAAiBA,IACxCvP,EAAEW,WAAW6O,IAAUA,YAAiBA,KACzC,eAAiBhI,IAAK,eAAiBC,GAC7D,OAAO,EAQX0H,EAASA,MACTC,EAASA,KAET,KADA,GAAIzP,GAASwP,EAAOxP,OACbA,KAGL,GAAIwP,EAAOxP,KAAY6H,EAAG,MAAO4H,GAAOzP,KAAY8H,CAQtD,IAJA0H,EAAOlO,KAAKuG,GACZ4H,EAAOnO,KAAKwG,GAGR6H,EAAW,CAGb,GADA3P,EAAS6H,EAAE7H,OACPA,IAAW8H,EAAE9H,OAAQ,OAAO,CAEhC,MAAOA,KACL,IAAKuP,EAAG1H,EAAE7H,GAAS8H,EAAE9H,GAASwP,EAAQC,GAAS,OAAO,MAEnD,CAEL,GAAsBxL,GAAlBnE,EAAOO,EAAEP,KAAK+H,EAGlB,IAFA7H,EAASF,EAAKE,OAEVK,EAAEP,KAAKgI,GAAG9H,SAAWA,EAAQ,OAAO,CACxC,MAAOA,KAGL,GADAiE,EAAMnE,EAAKE,IACLK,EAAEe,IAAI0G,EAAG7D,KAAQsL,EAAG1H,EAAE5D,GAAM6D,EAAE7D,GAAMuL,EAAQC,GAAU,OAAO,EAMvE,MAFAD,GAAOM,MACPL,EAAOK,OACA,EAITzP,GAAE0P,QAAU,SAASlI,EAAGC,GACtB,MAAOyH,GAAG1H,EAAGC,IAKfzH,EAAE2P,QAAU,SAASrQ,GACnB,MAAW,OAAPA,GAAoB,EACpBS,EAAYT,KAASU,EAAE8B,QAAQxC,IAAQU,EAAE4P,SAAStQ,IAAQU,EAAEoJ,YAAY9J,IAA6B,IAAfA,EAAIK,OAChE,IAAvBK,EAAEP,KAAKH,GAAKK,QAIrBK,EAAE6P,UAAY,SAASvQ,GACrB,SAAUA,GAAwB,IAAjBA,EAAIwQ,WAKvB9P,EAAE8B,QAAUD,GAAiB,SAASvC,GACpC,MAA8B,mBAAvBqC,EAASiB,KAAKtD,IAIvBU,EAAEkD,SAAW,SAAS5D,GACpB,GAAIyQ,SAAczQ,EAClB,OAAgB,aAATyQ,GAAgC,WAATA,KAAuBzQ,GAIvDU,EAAEkE,MAAM,YAAa,WAAY,SAAU,SAAU,OAAQ,SAAU,SAAU,SAAS8L,GACxFhQ,EAAE,KAAOgQ,GAAQ,SAAS1Q,GACxB,MAAOqC,GAASiB,KAAKtD,KAAS,WAAa0Q,EAAO,OAMjDhQ,EAAEoJ,YAAYnJ,aACjBD,EAAEoJ,YAAc,SAAS9J,GACvB,MAAOU,GAAEe,IAAIzB,EAAK,YAMJ,kBAAP,KAAyC,gBAAb2Q,aACrCjQ,EAAEW,WAAa,SAASrB,GACtB,MAAqB,kBAAPA,KAAqB,IAKvCU,EAAEkQ,SAAW,SAAS5Q,GACpB,MAAO4Q,UAAS5Q,KAASgL,MAAM6F,WAAW7Q,KAI5CU,EAAEsK,MAAQ,SAAShL,GACjB,MAAOU,GAAEoQ,SAAS9Q,IAAQA,KAASA,GAIrCU,EAAE4J,UAAY,SAAStK,GACrB,MAAOA,MAAQ,GAAQA,KAAQ,GAAgC,qBAAvBqC,EAASiB,KAAKtD,IAIxDU,EAAEqQ,OAAS,SAAS/Q,GAClB,MAAe,QAARA,GAITU,EAAEsQ,YAAc,SAAShR,GACvB,MAAOA,SAAa,IAKtBU,EAAEe,IAAM,SAASzB,EAAKsE,GACpB,MAAc,OAAPtE,GAAesC,EAAegB,KAAKtD,EAAKsE,IAQjD5D,EAAEuQ,WAAa,WAEb,MADArP,GAAKlB,EAAIoB,EACFD,MAITnB,EAAEiD,SAAW,SAASN,GACpB,MAAOA,IAIT3C,EAAEwQ,SAAW,SAAS7N,GACpB,MAAO,YACL,MAAOA,KAIX3C,EAAEyQ,KAAO,aAETzQ,EAAEoD,SAAW,SAASQ,GACpB,MAAO,UAAStE,GACd,MAAc,OAAPA,MAAmB,GAAIA,EAAIsE,KAKtC5D,EAAE0Q,WAAa,SAASpR,GACtB,MAAc,OAAPA,EAAc,aAAe,SAASsE,GAC3C,MAAOtE,GAAIsE,KAMf5D,EAAEmD,QAAUnD,EAAE2Q,QAAU,SAAStK,GAE/B,MADAA,GAAQrG,EAAEuO,aAAclI,GACjB,SAAS/G,GACd,MAAOU,GAAEiP,QAAQ3P,EAAK+G,KAK1BrG,EAAE0N,MAAQ,SAASzG,EAAG1H,EAAUM,GAC9B,GAAI+Q,GAAQtP,MAAM0C,KAAKuC,IAAI,EAAGU,GAC9B1H,GAAWO,EAAWP,EAAUM,EAAS,EACzC,KAAK,GAAI8D,GAAI,EAAOsD,EAAJtD,EAAOA,IAAKiN,EAAMjN,GAAKpE,EAASoE,EAChD,OAAOiN,IAIT5Q,EAAE+G,OAAS,SAASL,EAAKH,GAKvB,MAJW,OAAPA,IACFA,EAAMG,EACNA,EAAM,GAEDA,EAAM1C,KAAK6G,MAAM7G,KAAK+C,UAAYR,EAAMG,EAAM,KAIvD1G,EAAE8M,IAAM+D,KAAK/D,KAAO,WAClB,OAAO,GAAI+D,OAAOC,UAIpB,IAAIC,IACFC,IAAK,QACLC,IAAK,OACLC,IAAK,OACLC,IAAK,SACLC,IAAK,SACLC,IAAK,UAEHC,EAActR,EAAEkO,OAAO6C,GAGvBQ,EAAgB,SAASnN,GAC3B,GAAIoN,GAAU,SAASC,GACrB,MAAOrN,GAAIqN,IAGThO,EAAS,MAAQzD,EAAEP,KAAK2E,GAAKsN,KAAK,KAAO,IACzCC,EAAaC,OAAOnO,GACpBoO,EAAgBD,OAAOnO,EAAQ,IACnC,OAAO,UAASqO,GAEd,MADAA,GAAmB,MAAVA,EAAiB,GAAK,GAAKA,EAC7BH,EAAWI,KAAKD,GAAUA,EAAOE,QAAQH,EAAeL,GAAWM,GAG9E9R,GAAEiS,OAASV,EAAcR,GACzB/Q,EAAEkS,SAAWX,EAAcD,GAI3BtR,EAAE8D,OAAS,SAASsG,EAAQhH,EAAU+O,GACpC,GAAIxP,GAAkB,MAAVyH,MAAsB,GAAIA,EAAOhH,EAI7C,OAHIT,SAAe,KACjBA,EAAQwP,GAEHnS,EAAEW,WAAWgC,GAASA,EAAMC,KAAKwH,GAAUzH,EAKpD,IAAIyP,GAAY,CAChBpS,GAAEqS,SAAW,SAASC,GACpB,GAAIC,KAAOH,EAAY,EACvB,OAAOE,GAASA,EAASC,EAAKA,GAKhCvS,EAAEwS,kBACAC,SAAc,kBACdC,YAAc,mBACdT,OAAc,mBAMhB,IAAIU,GAAU,OAIVC,GACFxB,IAAU,IACVyB,KAAU,KACVC,KAAU,IACVC,KAAU,IACVC,SAAU,QACVC,SAAU,SAGRzB,EAAU,4BAEV0B,EAAa,SAASzB,GACxB,MAAO,KAAOmB,EAAQnB,GAOxBzR,GAAEmT,SAAW,SAASC,EAAMC,EAAUC,IAC/BD,GAAYC,IAAaD,EAAWC,GACzCD,EAAWrT,EAAE6O,YAAawE,EAAUrT,EAAEwS,iBAGtC,IAAIrP,GAAUyO,SACXyB,EAASpB,QAAUU,GAASlP,QAC5B4P,EAASX,aAAeC,GAASlP,QACjC4P,EAASZ,UAAYE,GAASlP,QAC/BiO,KAAK,KAAO,KAAM,KAGhBhS,EAAQ,EACR+D,EAAS,QACb2P,GAAKpB,QAAQ7O,EAAS,SAASsO,EAAOQ,EAAQS,EAAaD,EAAUc,GAanE,MAZA9P,IAAU2P,EAAK1R,MAAMhC,EAAO6T,GAAQvB,QAAQR,EAAS0B,GACrDxT,EAAQ6T,EAAS9B,EAAM9R,OAEnBsS,EACFxO,GAAU,cAAgBwO,EAAS,iCAC1BS,EACTjP,GAAU,cAAgBiP,EAAc,uBAC/BD,IACThP,GAAU,OAASgP,EAAW,YAIzBhB,IAEThO,GAAU,OAGL4P,EAASG,WAAU/P,EAAS,mBAAqBA,EAAS,OAE/DA,EAAS,2CACP,oDACAA,EAAS,eAEX,KACE,GAAIgQ,GAAS,GAAIhS,UAAS4R,EAASG,UAAY,MAAO,IAAK/P,GAC3D,MAAOiQ,GAEP,KADAA,GAAEjQ,OAASA,EACLiQ,EAGR,GAAIP,GAAW,SAASQ,GACtB,MAAOF,GAAO7Q,KAAKzB,KAAMwS,EAAM3T,IAI7B4T,EAAWP,EAASG,UAAY,KAGpC,OAFAL,GAAS1P,OAAS,YAAcmQ,EAAW,OAASnQ,EAAS,IAEtD0P,GAITnT,EAAE6T,MAAQ,SAASvU,GACjB,GAAIwU,GAAW9T,EAAEV,EAEjB,OADAwU,GAASC,QAAS,EACXD,EAUT,IAAIhQ,GAAS,SAASgQ,EAAUxU,GAC9B,MAAOwU,GAASC,OAAS/T,EAAEV,GAAKuU,QAAUvU,EAI5CU,GAAEgU,MAAQ,SAAS1U,GACjBU,EAAEkE,KAAKlE,EAAEmO,UAAU7O,GAAM,SAAS0Q,GAChC,GAAIvN,GAAOzC,EAAEgQ,GAAQ1Q,EAAI0Q,EACzBhQ,GAAEY,UAAUoP,GAAQ,WAClB,GAAI/J,IAAQ9E,KAAKkB,SAEjB,OADApB,GAAK+B,MAAMiD,EAAMhG,WACV6D,EAAO3C,KAAMsB,EAAKO,MAAMhD,EAAGiG,QAMxCjG,EAAEgU,MAAMhU,GAGRA,EAAEkE,MAAM,MAAO,OAAQ,UAAW,QAAS,OAAQ,SAAU,WAAY,SAAS8L,GAChF,GAAIhK,GAAS3E,EAAW2O,EACxBhQ,GAAEY,UAAUoP,GAAQ,WAClB,GAAI1Q,GAAM6B,KAAKkB,QAGf,OAFA2D,GAAOhD,MAAM1D,EAAKW,WACJ,UAAT+P,GAA6B,WAATA,GAAqC,IAAf1Q,EAAIK,cAAqBL,GAAI,GACrEwE,EAAO3C,KAAM7B,MAKxBU,EAAEkE,MAAM,SAAU,OAAQ,SAAU,SAAS8L,GAC3C,GAAIhK,GAAS3E,EAAW2O,EACxBhQ,GAAEY,UAAUoP,GAAQ,WAClB,MAAOlM,GAAO3C,KAAM6E,EAAOhD,MAAM7B,KAAKkB,SAAUpC,eAKpDD,EAAEY,UAAU+B,MAAQ,WAClB,MAAOxB,MAAKkB,UAKdrC,EAAEY,UAAUqT,QAAUjU,EAAEY,UAAUsT,OAASlU,EAAEY,UAAU+B,MAEvD3C,EAAEY,UAAUe,SAAW,WACrB,MAAO,GAAKR,KAAKkB,UAUG,kBAAX8R,SAAyBA,OAAOC,KACzCD,OAAO,gBAAkB,WACvB,MAAOnU,OAGX4C,KAAKzB"} \ No newline at end of file diff --git a/dist/swagger-ui.js b/dist/swagger-ui.js index c85636b795c..59dc8adb1ec 100644 --- a/dist/swagger-ui.js +++ b/dist/swagger-ui.js @@ -1,406 +1,276 @@ /** - * swagger-ui - Swagger UI is a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API - * @version v2.1.8-M1 + * swagger-ui - Swagger UI is a dependency-free collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API + * @version v2.1.0-M2 * @link http://swagger.io * @license Apache 2.0 */ -$(function() { - - // Helper function for vertically aligning DOM elements - // http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/ - $.fn.vAlign = function() { - return this.each(function(i){ - var ah = $(this).height(); - var ph = $(this).parent().height(); - var mh = (ph - ah) / 2; - $(this).css('margin-top', mh); - }); - }; - - $.fn.stretchFormtasticInputWidthToParent = function() { - return this.each(function(i){ - var p_width = $(this).closest("form").innerWidth(); - var p_padding = parseInt($(this).closest("form").css('padding-left') ,10) + parseInt($(this).closest("form").css('padding-right'), 10); - var this_padding = parseInt($(this).css('padding-left'), 10) + parseInt($(this).css('padding-right'), 10); - $(this).css('width', p_width - p_padding - this_padding); - }); - }; - - $('form.formtastic li.string input, form.formtastic textarea').stretchFormtasticInputWidthToParent(); - - // Vertically center these paragraphs - // Parent may need a min-height for this to work.. - $('ul.downplayed li div.content p').vAlign(); - - // When a sandbox form is submitted.. - $("form.sandbox").submit(function(){ - - var error_free = true; - - // Cycle through the forms required inputs - $(this).find("input.required").each(function() { - - // Remove any existing error styles from the input - $(this).removeClass('error'); - - // Tack the error style on if the input is empty.. - if ($(this).val() == '') { - $(this).addClass('error'); - $(this).wiggle(); - error_free = false; - } - - }); - - return error_free; - }); - -}); - -function clippyCopiedCallback(a) { - $('#api_key_copied').fadeIn().delay(1000).fadeOut(); - - // var b = $("#clippy_tooltip_" + a); - // b.length != 0 && (b.attr("title", "copied!").trigger("tipsy.reload"), setTimeout(function() { - // b.attr("title", "copy to clipboard") - // }, - // 500)) -} - -// Logging function that accounts for browsers that don't have window.console -log = function(){ - log.history = log.history || []; - log.history.push(arguments); - if(this.console){ - console.log( Array.prototype.slice.call(arguments)[0] ); - } -}; - -// Handle browsers that do console incorrectly (IE9 and below, see http://stackoverflow.com/a/5539378/7913) -if (Function.prototype.bind && console && typeof console.log == "object") { - [ - "log","info","warn","error","assert","dir","clear","profile","profileEnd" - ].forEach(function (method) { - console[method] = this.bind(console[method], console); - }, Function.prototype.call); -} - -var Docs = { - - shebang: function() { - - // If shebang has an operation nickname in it.. - // e.g. /docs/#!/words/get_search - var fragments = $.param.fragment().split('/'); - fragments.shift(); // get rid of the bang - - switch (fragments.length) { - case 1: - // Expand all operations for the resource and scroll to it - var dom_id = 'resource_' + fragments[0]; - - Docs.expandEndpointListForResource(fragments[0]); - $("#"+dom_id).slideto({highlight: false}); - break; - case 2: - // Refer to the endpoint DOM element, e.g. #words_get_search - - // Expand Resource - Docs.expandEndpointListForResource(fragments[0]); - $("#"+dom_id).slideto({highlight: false}); - - // Expand operation - var li_dom_id = fragments.join('_'); - var li_content_dom_id = li_dom_id + "_content"; - - - Docs.expandOperation($('#'+li_content_dom_id)); - $('#'+li_dom_id).slideto({highlight: false}); - break; - } - - }, - - toggleEndpointListForResource: function(resource) { - var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints'); - if (elem.is(':visible')) { - Docs.collapseEndpointListForResource(resource); - } else { - Docs.expandEndpointListForResource(resource); - } - }, - - // Expand resource - expandEndpointListForResource: function(resource) { - var resource = Docs.escapeResourceName(resource); - if (resource == '') { - $('.resource ul.endpoints').slideDown(); - return; - } - - $('li#resource_' + resource).addClass('active'); - - var elem = $('li#resource_' + resource + ' ul.endpoints'); - elem.slideDown(); - }, - - // Collapse resource and mark as explicitly closed - collapseEndpointListForResource: function(resource) { - var resource = Docs.escapeResourceName(resource); - if (resource == '') { - $('.resource ul.endpoints').slideUp(); - return; - } - - $('li#resource_' + resource).removeClass('active'); - - var elem = $('li#resource_' + resource + ' ul.endpoints'); - elem.slideUp(); - }, - - expandOperationsForResource: function(resource) { - // Make sure the resource container is open.. - Docs.expandEndpointListForResource(resource); - - if (resource == '') { - $('.resource ul.endpoints li.operation div.content').slideDown(); - return; - } - - $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { - Docs.expandOperation($(this)); - }); - }, - - collapseOperationsForResource: function(resource) { - // Make sure the resource container is open.. - Docs.expandEndpointListForResource(resource); - - if (resource == '') { - $('.resource ul.endpoints li.operation div.content').slideUp(); - return; - } - - $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { - Docs.collapseOperation($(this)); - }); - }, - - escapeResourceName: function(resource) { - return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&"); - }, - - expandOperation: function(elem) { - elem.slideDown(); - }, - - collapseOperation: function(elem) { - elem.slideUp(); - } -}; +(function(){'use strict'; -this["Handlebars"] = this["Handlebars"] || {}; -this["Handlebars"]["templates"] = this["Handlebars"]["templates"] || {}; -this["Handlebars"]["templates"]["apikey_button_view"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { - var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; - return "\n
\n
\n
" - + escapeExpression(((helper = (helper = helpers.keyName || (depth0 != null ? depth0.keyName : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"keyName","hash":{},"data":data}) : helper))) - + "
\n \n \n
\n
\n\n"; -},"useData":true}); -var SwaggerUi, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - __hasProp = {}.hasOwnProperty; +window.SwaggerUi = Backbone.Router.extend({ -SwaggerUi = (function(_super) { - __extends(SwaggerUi, _super); + dom_id: 'swagger_ui', - function SwaggerUi() { - return SwaggerUi.__super__.constructor.apply(this, arguments); - } - - SwaggerUi.prototype.dom_id = "swagger_ui"; - - SwaggerUi.prototype.options = null; - - SwaggerUi.prototype.api = null; + // Attributes + options: null, + api: null, + headerView: null, + mainView: null, - SwaggerUi.prototype.headerView = null; + // SwaggerUi accepts all the same options as SwaggerApi + initialize: function(options) { + options = options || {}; - SwaggerUi.prototype.mainView = null; - - SwaggerUi.prototype.initialize = function(options) { - if (options == null) { - options = {}; - } - if (options.dom_id != null) { + // Allow dom_id to be overridden + if (options.dom_id) { this.dom_id = options.dom_id; delete options.dom_id; } - if (options.supportedSubmitMethods == null) { - options.supportedSubmitMethods = ['get', 'put', 'post', 'delete', 'head', 'options', 'patch']; + + if (!options.supportedSubmitMethods){ + options.supportedSubmitMethods = [ + 'get', + 'put', + 'post', + 'delete', + 'head', + 'options', + 'patch' + ]; + } + + if (typeof options.oauth2RedirectUrl === 'string') { + window.oAuthRedirectUrl = options.redirectUrl; } - if ($('#' + this.dom_id) == null) { - $('body').append('
'); + + // Create an empty div which contains the dom_id + if (! $('#' + this.dom_id).length){ + $('body').append('
') ; } + this.options = options; - this.options.success = (function(_this) { - return function() { - return _this.render(); - }; - })(this); - this.options.progress = (function(_this) { - return function(d) { - return _this.showMessage(d); - }; - })(this); - this.options.failure = (function(_this) { - return function(d) { - return _this.onLoadFailure(d); - }; - })(this); - this.headerView = new HeaderView({ - el: $('#header') + + // set marked options + marked.setOptions({gfm: true}); + + // Set the callbacks + var that = this; + this.options.success = function() { return that.render(); }; + this.options.progress = function(d) { return that.showMessage(d); }; + this.options.failure = function(d) { return that.onLoadFailure(d); }; + + // Create view to handle the header inputs + this.headerView = new SwaggerUi.Views.HeaderView({el: $('#header')}); + + // Event handler for when the baseUrl/apiKey is entered by user + this.headerView.on('update-swagger-ui', function(data) { + return that.updateSwaggerUi(data); }); - return this.headerView.on('update-swagger-ui', (function(_this) { - return function(data) { - return _this.updateSwaggerUi(data); - }; - })(this)); - }; + }, - SwaggerUi.prototype.setOption = function(option, value) { - return this.options[option] = value; - }; + // Set an option after initializing + setOption: function(option, value) { + this.options[option] = value; + }, - SwaggerUi.prototype.getOption = function(option) { + // Get the value of a previously set option + getOption: function(option) { return this.options[option]; - }; + }, - SwaggerUi.prototype.updateSwaggerUi = function(data) { + // Event handler for when url/key is received from user + updateSwaggerUi: function(data){ this.options.url = data.url; - return this.load(); - }; + this.load(); + }, - SwaggerUi.prototype.load = function() { - var url, _ref; - if ((_ref = this.mainView) != null) { - _ref.clear(); + // Create an api and render + load: function(){ + // Initialize the API object + if (this.mainView) { + this.mainView.clear(); } - url = this.options.url; - if (url && url.indexOf("http") !== 0) { + var url = this.options.url; + if (url && url.indexOf('http') !== 0) { url = this.buildUrl(window.location.href.toString(), url); } + this.options.url = url; this.headerView.update(url); - return this.api = new SwaggerClient(this.options); - }; - SwaggerUi.prototype.collapseAll = function() { - return Docs.collapseEndpointListForResource(''); - }; + this.api = new SwaggerClient(this.options); + }, - SwaggerUi.prototype.listAll = function() { - return Docs.collapseOperationsForResource(''); - }; + // collapse all sections + collapseAll: function(){ + Docs.collapseEndpointListForResource(''); + }, - SwaggerUi.prototype.expandAll = function() { - return Docs.expandOperationsForResource(''); - }; + // list operations for all sections + listAll: function(){ + Docs.collapseOperationsForResource(''); + }, - SwaggerUi.prototype.render = function() { + // expand operations for all sections + expandAll: function(){ + Docs.expandOperationsForResource(''); + }, + + // This is bound to success handler for SwaggerApi + // so it gets called when SwaggerApi completes loading + render: function(){ this.showMessage('Finished Loading Resource Information. Rendering Swagger UI...'); - this.mainView = new MainView({ + this.mainView = new SwaggerUi.Views.MainView({ model: this.api, el: $('#' + this.dom_id), - swaggerOptions: this.options + swaggerOptions: this.options, + router: this }).render(); this.showMessage(); switch (this.options.docExpansion) { - case "full": - this.expandAll(); + case 'full': + this.expandAll(); break; + case 'list': + this.listAll(); break; + default: break; - case "list": - this.listAll(); } this.renderGFM(); - if (this.options.onComplete) { + + if (this.options.onComplete){ this.options.onComplete(this.api, this); } - return setTimeout((function(_this) { - return function() { - return Docs.shebang(); - }; - })(this), 100); - }; - SwaggerUi.prototype.buildUrl = function(base, url) { - var endOfPath, parts; - if (url.indexOf("/") === 0) { - parts = base.split("/"); - base = parts[0] + "//" + parts[2]; + setTimeout(Docs.shebang.bind(this), 100); + }, + + buildUrl: function(base, url){ + if (url.indexOf('/') === 0) { + var parts = base.split('/'); + base = parts[0] + '//' + parts[2]; return base + url; } else { - endOfPath = base.length; - if (base.indexOf("?") > -1) { - endOfPath = Math.min(endOfPath, base.indexOf("?")); + var endOfPath = base.length; + + if (base.indexOf('?') > -1){ + endOfPath = Math.min(endOfPath, base.indexOf('?')); } - if (base.indexOf("#") > -1) { - endOfPath = Math.min(endOfPath, base.indexOf("#")); + + if (base.indexOf('#') > -1){ + endOfPath = Math.min(endOfPath, base.indexOf('#')); } + base = base.substring(0, endOfPath); - if (base.indexOf("/", base.length - 1) !== -1) { + + if (base.indexOf('/', base.length - 1 ) !== -1){ return base + url; } - return base + "/" + url; + + return base + '/' + url; } - }; + }, - SwaggerUi.prototype.showMessage = function(data) { - if (data == null) { + // Shows message on topbar of the ui + showMessage: function(data){ + if (data === undefined) { data = ''; } $('#message-bar').removeClass('message-fail'); $('#message-bar').addClass('message-success'); - return $('#message-bar').html(data); - }; + $('#message-bar').html(data); + }, - SwaggerUi.prototype.onLoadFailure = function(data) { - var val; - if (data == null) { + // shows message in red + onLoadFailure: function(data){ + if (data === undefined) { data = ''; } $('#message-bar').removeClass('message-success'); $('#message-bar').addClass('message-fail'); - val = $('#message-bar').html(data); - if (this.options.onFailure != null) { + + var val = $('#message-bar').html(data); + + if (this.options.onFailure) { this.options.onFailure(data); } + return val; - }; + }, - SwaggerUi.prototype.renderGFM = function(data) { - if (data == null) { - data = ''; - } - return $('.markdown').each(function(index) { - return $(this).html(marked($(this).html())); + // Renders GFM for elements with 'markdown' class + renderGFM: function(){ + $('.markdown').each(function(){ + $(this).html(marked($(this).html())); }); + } + +}); + +window.SwaggerUi.Views = {}; + +// don't break backward compatibility with previous versions and warn users to upgrade their code +(function(){ + window.authorizations = { + add: function() { + warn('Using window.authorizations is deprecated. Please use SwaggerUi.api.clientAuthorizations.add().'); + + if (typeof window.swaggerUi === 'undefined') { + throw new TypeError('window.swaggerUi is not defined'); + } + + if (window.swaggerUi instanceof SwaggerUi) { + window.swaggerUi.api.clientAuthorizations.add.apply(window.swaggerUi.api.clientAuthorizations, arguments); + } + } }; - return SwaggerUi; + window.ApiKeyAuthorization = function() { + warn('window.ApiKeyAuthorization is deprecated. Please use SwaggerClient.ApiKeyAuthorization.'); + SwaggerClient.ApiKeyAuthorization.apply(window, arguments); + }; + + window.PasswordAuthorization = function() { + warn('window.PasswordAuthorization is deprecated. Please use SwaggerClient.PasswordAuthorization.'); + SwaggerClient.PasswordAuthorization.apply(window, arguments); + }; -})(Backbone.Router); + function warn(message) { + if ('console' in window && typeof window.console.warn === 'function') { + console.warn(message); + } + } +})(); -window.SwaggerUi = SwaggerUi; +// UMD +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['b'], function (b) { + return (root.SwaggerUi = factory(b)); + }); + } else if (typeof exports === 'object') { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like enviroments that support module.exports, + // like Node. + module.exports = factory(require('b')); + } else { + // Browser globals + root.SwaggerUi = factory(root.b); + } +}(this, function () { + return SwaggerUi; +})); +this["Handlebars"] = this["Handlebars"] || {}; +this["Handlebars"]["templates"] = this["Handlebars"]["templates"] || {}; +this["Handlebars"]["templates"]["apikey_button_view"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return "\n
\n
\n
" + + escapeExpression(((helper = (helper = helpers.keyName || (depth0 != null ? depth0.keyName : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"keyName","hash":{},"data":data}) : helper))) + + "
\n \n \n
\n
\n\n"; +},"useData":true}); this["Handlebars"]["templates"]["basic_auth_button_view"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { return "
\n
\n
\n
Username
\n \n
Password
\n \n \n
\n
\n\n"; },"useData":true}); -Handlebars.registerHelper('sanitize', function(html) { - html = html.replace(/)<[^<]*)*<\/script>/gi, ''); - return new Handlebars.SafeString(html); -}); - this["Handlebars"]["templates"]["content_type"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var stack1, buffer = ""; stack1 = helpers.each.call(depth0, (depth0 != null ? depth0.produces : depth0), {"name":"each","hash":{},"fn":this.program(2, data),"inverse":this.noop,"data":data}); @@ -422,118 +292,282 @@ this["Handlebars"]["templates"]["content_type"] = Handlebars.template({"1":funct if (stack1 != null) { buffer += stack1; } return buffer + "\n"; },"useData":true}); -var ApiKeyButton, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - __hasProp = {}.hasOwnProperty; +'use strict'; + + +$(function() { + + // Helper function for vertically aligning DOM elements + // http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/ + $.fn.vAlign = function() { + return this.each(function(){ + var ah = $(this).height(); + var ph = $(this).parent().height(); + var mh = (ph - ah) / 2; + $(this).css('margin-top', mh); + }); + }; + + $.fn.stretchFormtasticInputWidthToParent = function() { + return this.each(function(){ + var p_width = $(this).closest("form").innerWidth(); + var p_padding = parseInt($(this).closest("form").css('padding-left') ,10) + parseInt($(this).closest('form').css('padding-right'), 10); + var this_padding = parseInt($(this).css('padding-left'), 10) + parseInt($(this).css('padding-right'), 10); + $(this).css('width', p_width - p_padding - this_padding); + }); + }; + + $('form.formtastic li.string input, form.formtastic textarea').stretchFormtasticInputWidthToParent(); + + // Vertically center these paragraphs + // Parent may need a min-height for this to work.. + $('ul.downplayed li div.content p').vAlign(); + + // When a sandbox form is submitted.. + $("form.sandbox").submit(function(){ + + var error_free = true; + + // Cycle through the forms required inputs + $(this).find("input.required").each(function() { + + // Remove any existing error styles from the input + $(this).removeClass('error'); + + // Tack the error style on if the input is empty.. + if ($(this).val() === '') { + $(this).addClass('error'); + $(this).wiggle(); + error_free = false; + } + + }); + + return error_free; + }); -ApiKeyButton = (function(_super) { - __extends(ApiKeyButton, _super); +}); + +function clippyCopiedCallback() { + $('#api_key_copied').fadeIn().delay(1000).fadeOut(); - function ApiKeyButton() { - return ApiKeyButton.__super__.constructor.apply(this, arguments); + // var b = $("#clippy_tooltip_" + a); + // b.length != 0 && (b.attr("title", "copied!").trigger("tipsy.reload"), setTimeout(function() { + // b.attr("title", "copy to clipboard") + // }, + // 500)) +} + +// Logging function that accounts for browsers that don't have window.console +function log(){ + log.history = log.history || []; + log.history.push(arguments); + if(this.console){ + console.log( Array.prototype.slice.call(arguments)[0] ); } +} - ApiKeyButton.prototype.initialize = function() {}; +// Handle browsers that do console incorrectly (IE9 and below, see http://stackoverflow.com/a/5539378/7913) +if (Function.prototype.bind && console && typeof console.log === "object") { + [ + "log","info","warn","error","assert","dir","clear","profile","profileEnd" + ].forEach(function (method) { + console[method] = this.bind(console[method], console); + }, Function.prototype.call); +} - ApiKeyButton.prototype.render = function() { - var template; - template = this.template(); - $(this.el).html(template(this.model)); - return this; - }; +window.Docs = { - ApiKeyButton.prototype.events = { - "click #apikey_button": "toggleApiKeyContainer", - "click #apply_api_key": "applyApiKey" - }; + shebang: function() { - ApiKeyButton.prototype.applyApiKey = function() { - var elem; - window.authorizations.add(this.model.name, new ApiKeyAuthorization(this.model.name, $("#input_apiKey_entry").val(), this.model["in"])); - window.swaggerUi.load(); - return elem = $('#apikey_container').show(); - }; + // If shebang has an operation nickname in it.. + // e.g. /docs/#!/words/get_search + var fragments = $.param.fragment().split('/'); + fragments.shift(); // get rid of the bang - ApiKeyButton.prototype.toggleApiKeyContainer = function() { - var elem; - if ($('#apikey_container').length > 0) { - elem = $('#apikey_container').first(); - if (elem.is(':visible')) { - return elem.hide(); - } else { - $('.auth_container').hide(); - return elem.show(); - } - } - }; + switch (fragments.length) { + case 1: + // Expand all operations for the resource and scroll to it + var dom_id = 'resource_' + fragments[0]; - ApiKeyButton.prototype.template = function() { - return Handlebars.templates.apikey_button_view; - }; + Docs.expandEndpointListForResource(fragments[0]); + $("#"+dom_id).slideto({highlight: false}); + break; + case 2: + // Refer to the endpoint DOM element, e.g. #words_get_search + + // Expand Resource + Docs.expandEndpointListForResource(fragments[0]); + $("#"+dom_id).slideto({highlight: false}); + + // Expand operation + var li_dom_id = fragments.join('_'); + var li_content_dom_id = li_dom_id + "_content"; + + + Docs.expandOperation($('#'+li_content_dom_id)); + $('#'+li_dom_id).slideto({highlight: false}); + break; + } + + }, + + toggleEndpointListForResource: function(resource) { + var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints'); + if (elem.is(':visible')) { + Docs.collapseEndpointListForResource(resource); + } else { + Docs.expandEndpointListForResource(resource); + } + }, + + // Expand resource + expandEndpointListForResource: function(resource) { + var resource = Docs.escapeResourceName(resource); + if (resource == '') { + $('.resource ul.endpoints').slideDown(); + return; + } + + $('li#resource_' + resource).addClass('active'); + + var elem = $('li#resource_' + resource + ' ul.endpoints'); + elem.slideDown(); + }, + + // Collapse resource and mark as explicitly closed + collapseEndpointListForResource: function(resource) { + var resource = Docs.escapeResourceName(resource); + if (resource == '') { + $('.resource ul.endpoints').slideUp(); + return; + } + + $('li#resource_' + resource).removeClass('active'); + + var elem = $('li#resource_' + resource + ' ul.endpoints'); + elem.slideUp(); + }, + + expandOperationsForResource: function(resource) { + // Make sure the resource container is open.. + Docs.expandEndpointListForResource(resource); + + if (resource == '') { + $('.resource ul.endpoints li.operation div.content').slideDown(); + return; + } + + $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { + Docs.expandOperation($(this)); + }); + }, + + collapseOperationsForResource: function(resource) { + // Make sure the resource container is open.. + Docs.expandEndpointListForResource(resource); + + if (resource == '') { + $('.resource ul.endpoints li.operation div.content').slideUp(); + return; + } - return ApiKeyButton; + $('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { + Docs.collapseOperation($(this)); + }); + }, -})(Backbone.View); + escapeResourceName: function(resource) { + return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&"); + }, + expandOperation: function(elem) { + elem.slideDown(); + }, + + collapseOperation: function(elem) { + elem.slideUp(); + } +}; + +'use strict'; + +Handlebars.registerHelper('sanitize', function(html) { + // Strip the script tags from the html, and return it as a Handlebars.SafeString + html = html.replace(/)<[^<]*)*<\/script>/gi, ''); + return new Handlebars.SafeString(html); +}); this["Handlebars"]["templates"]["main"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression, buffer = "
" + escapeExpression(lambda(((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.title : stack1), depth0)) + "
\n
"; stack1 = lambda(((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.description : stack1), depth0); if (stack1 != null) { buffer += stack1; } - buffer += "
\n "; - stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.termsOfServiceUrl : stack1), {"name":"if","hash":{},"fn":this.program(2, data),"inverse":this.noop,"data":data}); + buffer += "\n"; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.externalDocs : depth0), {"name":"if","hash":{},"fn":this.program(2, data),"inverse":this.noop,"data":data}); + if (stack1 != null) { buffer += stack1; } + buffer += " "; + stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.termsOfServiceUrl : stack1), {"name":"if","hash":{},"fn":this.program(4, data),"inverse":this.noop,"data":data}); if (stack1 != null) { buffer += stack1; } buffer += "\n "; - stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.contact : stack1)) != null ? stack1.name : stack1), {"name":"if","hash":{},"fn":this.program(4, data),"inverse":this.noop,"data":data}); + stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.contact : stack1)) != null ? stack1.name : stack1), {"name":"if","hash":{},"fn":this.program(6, data),"inverse":this.noop,"data":data}); if (stack1 != null) { buffer += stack1; } buffer += "\n "; - stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.contact : stack1)) != null ? stack1.url : stack1), {"name":"if","hash":{},"fn":this.program(6, data),"inverse":this.noop,"data":data}); + stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.contact : stack1)) != null ? stack1.url : stack1), {"name":"if","hash":{},"fn":this.program(8, data),"inverse":this.noop,"data":data}); if (stack1 != null) { buffer += stack1; } buffer += "\n "; - stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.contact : stack1)) != null ? stack1.email : stack1), {"name":"if","hash":{},"fn":this.program(8, data),"inverse":this.noop,"data":data}); + stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.contact : stack1)) != null ? stack1.email : stack1), {"name":"if","hash":{},"fn":this.program(10, data),"inverse":this.noop,"data":data}); if (stack1 != null) { buffer += stack1; } buffer += "\n "; - stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.license : stack1), {"name":"if","hash":{},"fn":this.program(10, data),"inverse":this.noop,"data":data}); + stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.license : stack1), {"name":"if","hash":{},"fn":this.program(12, data),"inverse":this.noop,"data":data}); if (stack1 != null) { buffer += stack1; } return buffer + "\n"; },"2":function(depth0,helpers,partials,data) { + var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression; + return "
More documentations
\n

" + + escapeExpression(lambda(((stack1 = (depth0 != null ? depth0.externalDocs : depth0)) != null ? stack1.description : stack1), depth0)) + + "

\n " + + escapeExpression(lambda(((stack1 = (depth0 != null ? depth0.externalDocs : depth0)) != null ? stack1.url : stack1), depth0)) + + "\n"; +},"4":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression; return ""; -},"4":function(depth0,helpers,partials,data) { +},"6":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression; return "
Created by " + escapeExpression(lambda(((stack1 = ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.contact : stack1)) != null ? stack1.name : stack1), depth0)) + "
"; -},"6":function(depth0,helpers,partials,data) { +},"8":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression; return ""; -},"8":function(depth0,helpers,partials,data) { +},"10":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression; return ""; -},"10":function(depth0,helpers,partials,data) { +},"12":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression; return ""; -},"12":function(depth0,helpers,partials,data) { +},"14":function(depth0,helpers,partials,data) { var stack1, lambda=this.lambda, escapeExpression=this.escapeExpression; return " , api version: " + escapeExpression(lambda(((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.version : stack1), depth0)) + "\n "; -},"14":function(depth0,helpers,partials,data) { +},"16":function(depth0,helpers,partials,data) { var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; return " \n
\n
\n

[ base url: " + escapeExpression(((helper = (helper = helpers.basePath || (depth0 != null ? depth0.basePath : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"basePath","hash":{},"data":data}) : helper))) + "\n"; - stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.version : stack1), {"name":"if","hash":{},"fn":this.program(12, data),"inverse":this.noop,"data":data}); + stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 != null ? depth0.info : depth0)) != null ? stack1.version : stack1), {"name":"if","hash":{},"fn":this.program(14, data),"inverse":this.noop,"data":data}); if (stack1 != null) { buffer += stack1; } buffer += "]\n"; - stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.validatorUrl : depth0), {"name":"if","hash":{},"fn":this.program(14, data),"inverse":this.noop,"data":data}); + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.validatorUrl : depth0), {"name":"if","hash":{},"fn":this.program(16, data),"inverse":this.noop,"data":data}); if (stack1 != null) { buffer += stack1; } return buffer + "

\n \n\n"; },"useData":true}); -var BasicAuthButton, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - __hasProp = {}.hasOwnProperty; - -BasicAuthButton = (function(_super) { - __extends(BasicAuthButton, _super); - - function BasicAuthButton() { - return BasicAuthButton.__super__.constructor.apply(this, arguments); - } - - BasicAuthButton.prototype.initialize = function() {}; - - BasicAuthButton.prototype.render = function() { - var template; - template = this.template(); - $(this.el).html(template(this.model)); - return this; - }; - - BasicAuthButton.prototype.events = { - "click #basic_auth_button": "togglePasswordContainer", - "click #apply_basic_auth": "applyPassword" - }; - - BasicAuthButton.prototype.applyPassword = function() { - var elem, password, username; - username = $(".input_username").val(); - password = $(".input_password").val(); - window.authorizations.add(this.model.type, new PasswordAuthorization("basic", username, password)); - window.swaggerUi.load(); - return elem = $('#basic_auth_container').hide(); - }; - - BasicAuthButton.prototype.togglePasswordContainer = function() { - var elem; - if ($('#basic_auth_container').length > 0) { - elem = $('#basic_auth_container').show(); - if (elem.is(':visible')) { - return elem.slideUp(); - } else { - $('.auth_container').hide(); - return elem.show(); - } - } - }; - - BasicAuthButton.prototype.template = function() { - return Handlebars.templates.basic_auth_button_view; - }; - - return BasicAuthButton; - -})(Backbone.View); - this["Handlebars"]["templates"]["operation"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { return "deprecated"; },"3":function(depth0,helpers,partials,data) { return "

Warning: Deprecated

\n"; },"5":function(depth0,helpers,partials,data) { - var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, buffer = "

Implementation Notes

\n

"; + var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, buffer = "

Implementation Notes

\n
"; stack1 = ((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"description","hash":{},"data":data}) : helper)); if (stack1 != null) { buffer += stack1; } - return buffer + "

\n"; + return buffer + "
\n"; },"7":function(depth0,helpers,partials,data) { return "
\n "; },"9":function(depth0,helpers,partials,data) { @@ -648,7 +627,7 @@ this["Handlebars"]["templates"]["operation"] = Handlebars.template({"1":function },"18":function(depth0,helpers,partials,data) { return "

Parameters

\n \n \n \n \n \n \n \n \n \n \n \n\n \n
ParameterValueDescriptionParameter TypeData Type
\n"; },"20":function(depth0,helpers,partials,data) { - return "
\n

Response Messages

\n \n \n \n \n \n \n \n \n \n \n \n
HTTP Status CodeReasonResponse Model
\n"; + return "
\n

Response Messages

\n \n \n \n \n \n \n \n \n \n \n\n \n
HTTP Status CodeReasonResponse ModelHeaders
\n"; },"22":function(depth0,helpers,partials,data) { return ""; },"24":function(depth0,helpers,partials,data) { @@ -661,13 +640,13 @@ this["Handlebars"]["templates"]["operation"] = Handlebars.template({"1":function + "_" + escapeExpression(((helper = (helper = helpers.nickname || (depth0 != null ? depth0.nickname : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"nickname","hash":{},"data":data}) : helper))) + "'>\n
\n \n \n"; },"useData":true}); -var ContentTypeView, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - __hasProp = {}.hasOwnProperty; - -ContentTypeView = (function(_super) { - __extends(ContentTypeView, _super); - - function ContentTypeView() { - return ContentTypeView.__super__.constructor.apply(this, arguments); - } - - ContentTypeView.prototype.initialize = function() {}; - - ContentTypeView.prototype.render = function() { - var template; - template = this.template(); - $(this.el).html(template(this.model)); - $('label[for=contentType]', $(this.el)).text('Response Content Type'); - return this; - }; - - ContentTypeView.prototype.template = function() { - return Handlebars.templates.content_type; - }; - - return ContentTypeView; - -})(Backbone.View); - this["Handlebars"]["templates"]["param"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { var stack1, buffer = ""; stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isFile : depth0), {"name":"if","hash":{},"fn":this.program(2, data),"inverse":this.program(4, data),"data":data}); @@ -808,100 +758,40 @@ this["Handlebars"]["templates"]["param"] = Handlebars.template({"1":function(dep if (stack1 != null) { buffer += stack1; } return buffer + "\n\n \n\n"; },"useData":true}); -var HeaderView, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - __hasProp = {}.hasOwnProperty; - -HeaderView = (function(_super) { - __extends(HeaderView, _super); - - function HeaderView() { - return HeaderView.__super__.constructor.apply(this, arguments); - } - - HeaderView.prototype.events = { - 'click #show-pet-store-icon': 'showPetStore', - 'click #show-wordnik-dev-icon': 'showWordnikDev', - 'click #explore': 'showCustom', - 'keyup #input_baseUrl': 'showCustomOnKeyup', - 'keyup #input_apiKey': 'showCustomOnKeyup' - }; - - HeaderView.prototype.initialize = function() {}; - - HeaderView.prototype.showPetStore = function(e) { - return this.trigger('update-swagger-ui', { - url: "http://petstore.swagger.wordnik.com/api/api-docs" - }); - }; - - HeaderView.prototype.showWordnikDev = function(e) { - return this.trigger('update-swagger-ui', { - url: "http://api.wordnik.com/v4/resources.json" - }); - }; - - HeaderView.prototype.showCustomOnKeyup = function(e) { - if (e.keyCode === 13) { - return this.showCustom(); - } - }; - - HeaderView.prototype.showCustom = function(e) { - if (e != null) { - e.preventDefault(); - } - return this.trigger('update-swagger-ui', { - url: $('#input_baseUrl').val(), - apiKey: $('#input_apiKey').val() - }); - }; - - HeaderView.prototype.update = function(url, apiKey, trigger) { - if (trigger == null) { - trigger = false; - } - $('#input_baseUrl').val(url); - if (trigger) { - return this.trigger('update-swagger-ui', { - url: url - }); - } - }; - - return HeaderView; - -})(Backbone.View); - this["Handlebars"]["templates"]["param_list"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return "" + + escapeExpression(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"name","hash":{},"data":data}) : helper))) + + "\n"; +},"3":function(depth0,helpers,partials,data) { return " multiple='multiple'"; - },"3":function(depth0,helpers,partials,data) { + },"5":function(depth0,helpers,partials,data) { return ""; -},"5":function(depth0,helpers,partials,data) { +},"7":function(depth0,helpers,partials,data) { var stack1, buffer = ""; - stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0['default'] : depth0), {"name":"if","hash":{},"fn":this.program(3, data),"inverse":this.program(6, data),"data":data}); + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0['default'] : depth0), {"name":"if","hash":{},"fn":this.program(5, data),"inverse":this.program(8, data),"data":data}); if (stack1 != null) { buffer += stack1; } return buffer; -},"6":function(depth0,helpers,partials,data) { +},"8":function(depth0,helpers,partials,data) { var stack1, helperMissing=helpers.helperMissing, buffer = ""; - stack1 = ((helpers.isArray || (depth0 && depth0.isArray) || helperMissing).call(depth0, depth0, {"name":"isArray","hash":{},"fn":this.program(3, data),"inverse":this.program(7, data),"data":data})); + stack1 = ((helpers.isArray || (depth0 && depth0.isArray) || helperMissing).call(depth0, depth0, {"name":"isArray","hash":{},"fn":this.program(5, data),"inverse":this.program(9, data),"data":data})); if (stack1 != null) { buffer += stack1; } return buffer; -},"7":function(depth0,helpers,partials,data) { +},"9":function(depth0,helpers,partials,data) { return " \n"; - },"9":function(depth0,helpers,partials,data) { + },"11":function(depth0,helpers,partials,data) { var stack1, buffer = ""; - stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isDefault : depth0), {"name":"if","hash":{},"fn":this.program(10, data),"inverse":this.program(12, data),"data":data}); + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isDefault : depth0), {"name":"if","hash":{},"fn":this.program(12, data),"inverse":this.program(14, data),"data":data}); if (stack1 != null) { buffer += stack1; } return buffer; -},"10":function(depth0,helpers,partials,data) { +},"12":function(depth0,helpers,partials,data) { var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; return " \n"; -},"12":function(depth0,helpers,partials,data) { +},"14":function(depth0,helpers,partials,data) { var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; return "
\n"; +},"7":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n
\n
\n"; +},"9":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isFile : depth0), {"name":"if","hash":{},"fn":this.program(10, data),"inverse":this.program(12, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"10":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n"; +},"12":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0['default'] : depth0), {"name":"if","hash":{},"fn":this.program(13, data),"inverse":this.program(15, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"13":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n"; +},"15":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return " \n"; +},"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, buffer = "" + + escapeExpression(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"name","hash":{},"data":data}) : helper))) + + "\n\n"; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.isBody : depth0), {"name":"if","hash":{},"fn":this.program(1, data),"inverse":this.program(9, data),"data":data}); + if (stack1 != null) { buffer += stack1; } + buffer += "\n\n "; + stack1 = ((helper = (helper = helpers.description || (depth0 != null ? depth0.description : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"description","hash":{},"data":data}) : helper)); + if (stack1 != null) { buffer += stack1; } + buffer += "\n\n"; + stack1 = ((helper = (helper = helpers.paramType || (depth0 != null ? depth0.paramType : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"paramType","hash":{},"data":data}) : helper)); + if (stack1 != null) { buffer += stack1; } + return buffer + "\n\n"; +},"useData":true}); +this["Handlebars"]["templates"]["parameter_content_type"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers.each.call(depth0, (depth0 != null ? depth0.consumes : depth0), {"name":"each","hash":{},"fn":this.program(2, data),"inverse":this.noop,"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"2":function(depth0,helpers,partials,data) { + var stack1, lambda=this.lambda, buffer = " \n"; +},"4":function(depth0,helpers,partials,data) { + return " \n"; + },"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var stack1, buffer = "\n\n"; +},"useData":true}); +this["Handlebars"]["templates"]["resource"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { + return " : "; + },"3":function(depth0,helpers,partials,data) { + var helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression; + return "
  • \n Raw\n
  • \n"; +},"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var stack1, helper, options, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, blockHelperMissing=helpers.blockHelperMissing, buffer = "
    \n

    \n " + + escapeExpression(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"name","hash":{},"data":data}) : helper))) + + " "; + stack1 = ((helper = (helper = helpers.summary || (depth0 != null ? depth0.summary : depth0)) != null ? helper : helperMissing),(options={"name":"summary","hash":{},"fn":this.program(1, data),"inverse":this.noop,"data":data}),(typeof helper === functionType ? helper.call(depth0, options) : helper)); + if (!helpers.summary) { stack1 = blockHelperMissing.call(depth0, stack1, options); } + if (stack1 != null) { buffer += stack1; } + stack1 = ((helper = (helper = helpers.summary || (depth0 != null ? depth0.summary : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"summary","hash":{},"data":data}) : helper)); + if (stack1 != null) { buffer += stack1; } + buffer += "\n

    \n
      \n
    • \n Show/Hide\n
    • \n
    • \n \n List Operations\n \n
    • \n
    • \n \n Expand Operations\n \n
    • \n"; + stack1 = helpers['if'].call(depth0, (depth0 != null ? depth0.url : depth0), {"name":"if","hash":{},"fn":this.program(3, data),"inverse":this.noop,"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer + "
    \n
    \n\n"; +},"useData":true}); +this["Handlebars"]["templates"]["response_content_type"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { + var stack1, buffer = ""; + stack1 = helpers.each.call(depth0, (depth0 != null ? depth0.produces : depth0), {"name":"each","hash":{},"fn":this.program(2, data),"inverse":this.noop,"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer; +},"2":function(depth0,helpers,partials,data) { + var stack1, lambda=this.lambda, buffer = " \n"; +},"4":function(depth0,helpers,partials,data) { + return " \n"; + },"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var stack1, buffer = "\n\n"; +},"useData":true}); +this["Handlebars"]["templates"]["signature"] = Handlebars.template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, buffer = "
    \n\n
    \n\n
    \n
    \n "; + stack1 = ((helper = (helper = helpers.signature || (depth0 != null ? depth0.signature : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"signature","hash":{},"data":data}) : helper)); + if (stack1 != null) { buffer += stack1; } + return buffer + "\n
    \n\n
    \n
    "
    +    + escapeExpression(((helper = (helper = helpers.sampleJSON || (depth0 != null ? depth0.sampleJSON : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"sampleJSON","hash":{},"data":data}) : helper)))
    +    + "
    \n \n
    \n
    \n\n"; +},"useData":true}); +this["Handlebars"]["templates"]["status_code"] = Handlebars.template({"1":function(depth0,helpers,partials,data) { + var lambda=this.lambda, escapeExpression=this.escapeExpression; + return " \n " + + escapeExpression(lambda((data && data.key), depth0)) + + "\n " + + escapeExpression(lambda((depth0 != null ? depth0.description : depth0), depth0)) + + "\n " + + escapeExpression(lambda((depth0 != null ? depth0.type : depth0), depth0)) + + "\n \n"; +},"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) { + var stack1, helper, functionType="function", helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, buffer = "" + + escapeExpression(((helper = (helper = helpers.code || (depth0 != null ? depth0.code : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"code","hash":{},"data":data}) : helper))) + + "\n"; + stack1 = ((helper = (helper = helpers.message || (depth0 != null ? depth0.message : depth0)) != null ? helper : helperMissing),(typeof helper === functionType ? helper.call(depth0, {"name":"message","hash":{},"data":data}) : helper)); + if (stack1 != null) { buffer += stack1; } + buffer += "\n\n\n \n \n"; + stack1 = helpers.each.call(depth0, (depth0 != null ? depth0.headers : depth0), {"name":"each","hash":{},"fn":this.program(1, data),"inverse":this.noop,"data":data}); + if (stack1 != null) { buffer += stack1; } + return buffer + " \n
    \n"; +},"useData":true}); +/** + * swagger-client - swagger-client is a javascript client for use with swaggering APIs. + * @version v2.1.0 + * @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 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') { + 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 (name, username, password) { + this.name = name; + this.username = username; + this.password = password; +}; + +PasswordAuthorization.prototype.apply = function (obj) { + obj.headers.Authorization = 'Basic ' + btoa(this.username + ':' + this.password); + + return true; +}; + +},{"btoa":16,"cookiejar":17}],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'), + 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'); + +// 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 = [ + 'authorizationScheme', + 'authorizations', + 'basePath', + 'build', + 'buildFrom1_1Spec', + 'buildFrom1_2Spec', + 'buildFromSpec', + 'clientAuthorizations', + 'convertInfo', + 'debug', + 'defaultErrorCallback', + 'defaultSuccessCallback', + 'fail', + 'failure', + 'finish', + 'help', + 'idFromOp', + 'info', + 'initialize', + 'isBuilt', + 'isValid', + 'models', + 'modelsArray', + 'options', + 'parseUri', + 'progress', + 'resourceCount', + 'sampleModels', + 'selfReflect', + 'setConsolidatedModels', + 'spec', + 'supportedSubmitMethods', + 'swaggerRequestHeaders', + 'tagFromLabel', + '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.authorizationScheme = null; + this.authorizations = null; + this.basePath = null; + this.debug = false; + this.info = null; + this.isBuilt = false; + this.isValid = false; + this.modelsArray = []; + this.resourceCount = 0; + this.url = null; + this.useJQuery = false; + + if (typeof url !== 'undefined') { + return this.initialize(url, options); + } else { + return this; + } +}; + +SwaggerClient.prototype.initialize = function (url, options) { + this.models = {}; + this.sampleModels = {}; + + options = (options || {}); + + if (typeof url === 'string') { + this.url = url; + } else if (typeof url === 'object') { + options = url; + this.url = options.url; + } + + this.swaggerRequestHeaders = options.swaggerRequestHeaders || 'application/json;charset=utf-8,*/*'; + this.defaultSuccessCallback = options.defaultSuccessCallback || null; + this.defaultErrorCallback = options.defaultErrorCallback || null; + + if (typeof options.success === 'function') { + this.success = options.success; + } + + if (options.useJQuery) { + this.useJQuery = options.useJQuery; + } + + if (options.authorizations) { + this.clientAuthorizations = options.authorizations; + } else { + this.clientAuthorizations = new auth.SwaggerAuthorizations(); + } + + this.supportedSubmitMethods = options.supportedSubmitMethods || []; + this.failure = options.failure || function () {}; + this.progress = options.progress || function () {}; + this.spec = _.cloneDeep(options.spec); // Clone so we do not alter the provided document + this.options = options; + + if (typeof options.success === 'function') { + this.ready = true; + this.build(); + } +}; + +SwaggerClient.prototype.build = function (mock) { + if (this.isBuilt) { + return this; + } + + var self = this; + + this.progress('fetching resource list: ' + this.url); + + 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 || JSON.parse(resp.data); + self.swaggerVersion = responseObj.swaggerVersion; + + if (responseObj.swagger && parseInt(responseObj.swagger) === 2) { + self.swaggerVersion = responseObj.swagger; + + new Resolver().resolve(responseObj, self.buildFromSpec, self); + + self.isValid = true; + } else { + var converter = new SwaggerSpecConverter(); + converter.setDocumentationLocation(self.url); + converter.convert(responseObj, function(spec) { + new Resolver().resolve(spec, self.buildFromSpec, self); + self.isValid = true; + }); + } + } + } + }; + + if (this.spec) { + setTimeout(function () { + new Resolver().resolve(self.spec, self.buildFromSpec, self); + }, 10); + } else { + this.clientAuthorizations.apply(obj); + + if (mock) { + return obj; + } + + new SwaggerHttp().execute(obj); + } + + return 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.schemes === 'undefined' || this.schemes.length === 0) { + this.scheme = location.scheme || 'http'; + } else { + this.scheme = this.schemes[0]; + } + + if (typeof this.host === 'undefined' || this.host === '') { + this.host = location.host; + + if (location.port) { + this.host = this.host + ':' + location.port; + } + } + + this.definitions = response.definitions; + + var key; + + for (key in this.definitions) { + var model = new Model(key, this.definitions[key], this.models); + + 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)); + } + + // 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); + } + }); + }); + }); + + this.isBuilt = true; + + if (this.success) { + this.isValid = true; + this.isBuilt = true; + this.success(); + } + + return this; +}; + +SwaggerClient.prototype.parseUri = function (uri) { + var urlParseRE = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/; + var parts = urlParseRE.exec(uri); + + return { + scheme: parts[4].replace(':',''), + 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.fail = function (message) { + this.failure(message); + + throw message; +}; + +},{"./auth":2,"./helpers":4,"./http":5,"./resolver":6,"./spec-converter":7,"./types/model":8,"./types/operation":9,"./types/operationGroup":10,"lodash-compat/array/indexOf":19,"lodash-compat/collection/find":21,"lodash-compat/collection/forEach":22,"lodash-compat/function/bind":25,"lodash-compat/lang/cloneDeep":94,"lodash-compat/lang/isArray":96,"lodash-compat/lang/isFunction":97,"lodash-compat/lang/isPlainObject":100,"lodash-compat/lang/isUndefined":103}],4:[function(require,module,exports){ +(function (process){ +'use strict'; + +module.exports.__bind = function (fn, me) { + return function(){ + return fn.apply(me, arguments); + }; +}; + +var log = module.exports.log = function() { + log.history = log.history || []; + log.history.push(arguments); + + // 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); +}; + +module.exports.optionHtml = function (label, value) { + return '' + label + ':' + value + ''; +}; + +module.exports.typeFromJsonSchema = function (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; +}; + +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; + } +}; + +var getStringSignature = module.exports.getStringSignature = function (obj, baseComponent) { + var str = ''; + + if (typeof obj.$ref !== 'undefined') { + str += 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 += simpleRef(obj.$ref); + } else { + str += obj.type; + } + + return str; +}; + +}).call(this,require('_process')) + +},{"_process":15}],5:[function(require,module,exports){ +'use strict'; + +var helpers = require('./helpers'); +var jQuery = require('jquery'); +var request = require('superagent'); + +/* + * JQueryHttpClient is a light-weight, node or browser HTTP client + */ +var JQueryHttpClient = function () {}; + +/* + * SuperagentHttpClient is a light-weight, node or browser HTTP client + */ +var SuperagentHttpClient = function () {}; + +/** + * SwaggerHttp is a wrapper for executing requests + */ +var SwaggerHttp = module.exports = function () {}; + +SwaggerHttp.prototype.execute = function (obj, opts) { + if (obj && (typeof obj.useJQuery === 'boolean')) { + this.useJQuery = obj.useJQuery; + } else { + this.useJQuery = this.isIE8(); + } + + if (obj && typeof obj.body === 'object') { + // 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); + } + } + + if (this.useJQuery) { + return new JQueryHttpClient(opts).execute(obj); + } else { + return new SuperagentHttpClient(opts).execute(obj); + } +}; + +SwaggerHttp.prototype.isIE8 = 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 cb = obj.on; + var request = obj; + + 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 + }; + + var contentType = (headers['content-type'] || headers['Content-Type'] || null); + + if (contentType) { + if (contentType.indexOf('application/json') === 0 || contentType.indexOf('+json') > 0) { + try { + out.obj = response.responseJSON || JSON.parse(out.data) || {}; + } catch (ex) { + // do not set out.obj + helpers.log('unable to parse JSON content'); + } + } + } + + 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); + } + }; + + jQuery.support.cors = true; + + return jQuery.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.body) { + r.send(obj.body); + } + + 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.obj = err; + response.status = res ? res.status : 500; + response.statusText = res ? res.text : err.message; + cb = obj.on.error; + } else if (res && obj.on && obj.on.response) { + response.obj = (typeof res.body !== 'undefined') ? res.body : res.text; + response.status = res.status; + response.statusText = res.text; + cb = obj.on.response; + } + response.data = response.statusText; + + if (cb) { + cb(response); + } + }); +}; + +},{"./helpers":4,"jquery":18,"superagent":111}],6:[function(require,module,exports){ +'use strict'; + +var SwaggerHttp = require('./http'); + +/** + * Resolves a spec's remote references + */ +var Resolver = module.exports = function () {}; + +Resolver.prototype.resolve = function (spec, callback, scope) { + this.scope = (scope || this); + + var host, name, path, property, propertyName; + var processedCalls = 0, resolvedRefs = {}, unresolvedRefs = {}; + var resolutionTable = {}; // store objects for dereferencing + + // models + for (name in spec.definitions) { + var model = spec.definitions[name]; + + for (propertyName in model.properties) { + property = model.properties[propertyName]; + + this.resolveTo(property, resolutionTable); + } + } + + // operations + for (name in spec.paths) { + var method, operation, responseCode; + + path = spec.paths[name]; + + for (method in path) { + if(method === '$ref') { + this.resolveInline(spec, path, resolutionTable, unresolvedRefs); + } + else { + operation = path[method]; + + var i, parameters = operation.parameters; + + for (i in parameters) { + var parameter = parameters[i]; + + if (parameter.in === 'body' && parameter.schema) { + this.resolveTo(parameter.schema, resolutionTable); + } + + if (parameter.$ref) { + this.resolveInline(spec, parameter, resolutionTable, unresolvedRefs); + } + } + + for (responseCode in operation.responses) { + var response = operation.responses[responseCode]; + if(typeof response === 'object') { + if(response.$ref) { + this.resolveInline(spec, response, resolutionTable, unresolvedRefs); + } + } + if (response.schema) { + this.resolveTo(response.schema, resolutionTable); + } + } + } + } + } + + // get hosts + var opts = {}, expectedCalls = 0; + + for (name in resolutionTable) { + var parts = name.split('#'); + + if (parts.length === 2) { + host = parts[0]; path = parts[1]; + + if (!Array.isArray(opts[host])) { + opts[host] = []; + expectedCalls += 1; + } + + opts[host].push(path); + } + else { + if (!Array.isArray(opts[name])) { + opts[name] = []; + expectedCalls += 1; + } + + opts[name].push(null); + } + } + + for (name in opts) { + var self = this, opt = opts[name]; + + host = name; + + var obj = { + useJQuery: false, // TODO + url: host, + method: 'get', + headers: { + accept: this.scope.swaggerRequestHeaders || 'application/json' + }, + on: { + error: function () { + processedCalls += 1; + + var i; + + for (i = 0; i < opt.length; i++) { + // fail all of these + var resolved = host + '#' + opt[i]; + + unresolvedRefs[resolved] = null; + } + + if (processedCalls === expectedCalls) { + self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback); + } + }, // jshint ignore:line + response: function (response) { + + var i, j, swagger = response.obj; + + if(swagger === null || Object.keys(swagger).length === 0) { + try { + swagger = JSON.parse(response.data); + } + catch (e){ + swagger = {}; + } + } + + processedCalls += 1; + + for (i = 0; i < opt.length; i++) { + var path = opt[i]; + if(path == null) { + resolvedRefs[name] = { + name: name, + obj: swagger + }; + } + else { + var location = swagger, parts = path.split('/'); + for (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') { + break; + } + + if (segment.length > 0) { + location = location[segment]; + } + } + var resolved = host + '#' + path, resolvedName = parts[j-1]; + + if (typeof location !== 'undefined') { + resolvedRefs[resolved] = { + name: resolvedName, + obj: location + }; + } else { + unresolvedRefs[resolved] = null; + } + } + } + if (processedCalls === expectedCalls) { + self.finish(spec, resolutionTable, resolvedRefs, unresolvedRefs, callback); + } + } + } // jshint ignore:line + }; + + if (scope && scope.clientAuthorizations) { + scope.clientAuthorizations.apply(obj); + } + + new SwaggerHttp().execute(obj); + } + + if (Object.keys(opts).length === 0) { + callback.call(this.scope, spec, unresolvedRefs); + } +}; + +Resolver.prototype.finish = function (spec, resolutionTable, resolvedRefs, unresolvedRefs, callback) { + // walk resolution table and replace with resolved refs + var ref; + + for (ref in resolutionTable) { + var i, locations = resolutionTable[ref]; + + for (i = 0; i < locations.length; i++) { + var resolvedTo = resolvedRefs[locations[i].obj.$ref]; + + if (resolvedTo) { + if (!spec.definitions) { + spec.definitions = {}; + } + + if (locations[i].resolveAs === '$ref') { + spec.definitions[resolvedTo.name] = resolvedTo.obj; + locations[i].obj.$ref = '#/definitions/' + resolvedTo.name; + } else if (locations[i].resolveAs === 'inline') { + var targetObj = locations[i].obj; + var key; + + delete targetObj.$ref; + + for (key in resolvedTo.obj) { + targetObj[key] = resolvedTo.obj[key]; + } + } + } + } + } + + callback.call(this.scope, spec, unresolvedRefs); +}; + +/** + * immediately in-lines local refs, queues remote refs + * for inline resolution + */ +Resolver.prototype.resolveInline = function (spec, property, objs, unresolvedRefs) { + var ref = property.$ref; + + if (ref) { + if (ref.indexOf('http') === 0) { + if (Array.isArray(objs[ref])) { + objs[ref].push({obj: property, resolveAs: 'inline'}); + } else { + objs[ref] = [{obj: property, resolveAs: 'inline'}]; + } + } else if (ref.indexOf('#') === 0) { + // local resolve + var shortenedRef = ref.substring(1); + var i, parts = shortenedRef.split('/'), location = spec; + + for (i = 0; i < parts.length; i++) { + var part = parts[i]; + + if (part.length > 0) { + location = location[part]; + } + } + + if (location) { + delete property.$ref; + + var key; + + for (key in location) { + property[key] = location[key]; + } + } else { + unresolvedRefs[ref] = null; + } + } + } else if (property.type === 'array') { + this.resolveTo(property.items, objs); + } +}; + +Resolver.prototype.resolveTo = function (property, objs) { + var ref = property.$ref; + + if (ref) { + if (ref.indexOf('http') === 0) { + if (Array.isArray(objs[ref])) { + objs[ref].push({obj: property, resolveAs: '$ref'}); + } else { + objs[ref] = [{obj: property, resolveAs: '$ref'}]; + } + } + } else if (property.type === 'array') { + var items = property.items; + + this.resolveTo(items, objs); + } +}; + +},{"./http":5}],7:[function(require,module,exports){ +'use strict'; + +var SwaggerClient = require('./client'); +var SwaggerHttp = require('./http'); + +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, callback) { + // not a valid spec + if(!obj || !Array.isArray(obj.apis)) { + return this.finish(callback, null); + } + + // 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); + + // 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, callback); + } +}; + +SwaggerSpecConverter.prototype.declaration = function(obj, swagger) { + var name, i; + if(!obj.apis) { + return; + } + + var basePath = obj.basePath; + if(obj.basePath.indexOf('http://') === 0) { + var p = obj.basePath.substring('http://'.length); + var pos = p.indexOf('/'); + if(pos > 0) { + swagger.host = p.substring(0, pos); + swagger.basePath = p.substring(pos); + } + else{ + swagger.host = p; + swagger.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(typeof obj === 'object') { + 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(typeof obj !== 'object') { + return; + } + var name; + + swagger.definitions = swagger.definitions || {}; + for(name in obj) { + var existingModel = obj[name]; + var _enum = []; + 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) { + _enum.push(propertyName); + } + if(typeof existingProperty.required === 'string' && existingProperty.required === 'true') { + _enum.push(propertyName); + } + schema.properties[propertyName] = property; + } + if(_enum.length > 0) { + schema['enum'] = _enum; + } + 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(); + } + 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') { + 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); + } + var scopesObject = {}; + scopesObject[key] = securityScopes; + operation.security.push(scopesObject); + } + else { + var 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, swagger) { + if(typeof existingOperation !== 'object') { + return; + } + // build default response from the operation (1.x) + var defaultResponse = {}; + this.dataType(existingOperation, defaultResponse); + if(!defaultResponse.schema) { + 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; + } + operation.responses['' + existingResponse.code] = response; + // TODO: schema + } + } + + if(has200) { + operation.responses['default'] = defaultResponse; + } + else { + operation.responses['200'] = defaultResponse; + } +}; + +SwaggerSpecConverter.prototype.authorizations = function(obj, swagger) { + // TODO + if(typeof obj !== 'object') { + return; + } +}; + +SwaggerSpecConverter.prototype.parameters = function(operation, obj, swagger) { + 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.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); + } + + operation.parameters = operation.parameters || []; + operation.parameters.push(parameter); + } +}; + +SwaggerSpecConverter.prototype.dataType = function(source, target) { + if(typeof source !== 'object') { + return; + } + + if(source.minimum) { + target.minimum = source.minimum; + } + if(source.maximum) { + target.maximum = source.maximum; + } + if(source.defaultValue) { + 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 === '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: '#/definitions/' + this.modelMap[source.$ref] || source.$ref}; + } + else { + return {$ref: '#/definitions/' + this.modelMap[source.type] || source.type}; + } +}; + +SwaggerSpecConverter.prototype.resourceListing = function(obj, swagger, callback) { + var i, processedCount = 0; + var self = this; + var expectedCount = obj.apis.length; + var _swagger = swagger; + + 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' + }; + http.on.response = function(data) { + processedCount += 1; + if(data.obj) { + self.declaration(data.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); + } + }; + new SwaggerHttp().execute(http); + } +}; + +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 === '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; + } + 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; + } + } + } + } + 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); +}; +},{"./client":3,"./http":5}],8:[function(require,module,exports){ +'use strict'; + +var _ = { + forEach: require('lodash-compat/collection/forEach'), + indexOf: require('lodash-compat/array/indexOf'), + isArray: require('lodash-compat/lang/isArray'), + isPlainObject: require('lodash-compat/lang/isPlainObject'), + isString: require('lodash-compat/lang/isString'), + isUndefined: require('lodash-compat/lang/isUndefined'), + keys: require('lodash-compat/object/keys'), + map: require('lodash-compat/collection/map') +}; +var helpers = require('../helpers'); + + +/** + * allows override of the default value based on the parameter being + * supplied + **/ +var applyParameterMacro = function (operation, parameter) { + // TODO the reference to operation.api is not available + if (operation.api && operation.api.parameterMacro) { + return operation.api.parameterMacro(operation, parameter); + } else { + return parameter.defaultValue; + } +}; + +/** + * allows overriding the default value of an model property + **/ +var applyModelPropertyMacro = function (model, property) { + // TODO the reference to model.api is not available + if (model.api && model.api.modelPropertyMacro) { + return model.api.modelPropertyMacro(model, property); + } else { + return property.default; + } +}; + +var Model = module.exports = function (name, definition, models) { + this.definition = definition || {}; + this.isArray = definition.type === 'array'; + this.models = models || {}; + this.name = name || 'Inline Model'; + + return this; +}; + +var schemaToHTML = function (name, schema, models) { + var strongOpen = ''; + var strongClose = ''; + var references = {}; + var seenModels = []; + var inlineModels = 0; + var addReference = function (schema, name, skipRef) { + var modelName = name; + var model; + + if (schema.$ref) { + modelName = helpers.simpleRef(schema.$ref); + model = models[modelName]; + } else if (_.isUndefined(name)) { + modelName = 'Inline Model ' + (++inlineModels); + model = new Model(modelName, schema, models); + } + + if (skipRef !== true) { + references[modelName] = _.isUndefined(model) ? {} : model.definition; + } + + return modelName; + }; + var primitiveToHTML = function (schema) { + var html = ''; + 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 += ''; + + return html; + }; + var primitiveToOptionsHTML = function (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 (schema.default) { + options += helpers.optionHtml('Default', schema.default); + } + + switch (type) { + case 'string': + if (schema.minLength) { + options += helpers.optionHtml('Min. Length', schema.minLength); + } + + if (schema.maxLength) { + options += helpers.optionHtml('Max. Length', schema.maxLength); + } + + if (schema.pattern) { + options += helpers.optionHtml('Reg. Exp.', schema.pattern); + } + break; + case 'integer': + case 'number': + if (schema.minimum) { + options += helpers.optionHtml('Min. Value', schema.minimum); + } + + if (schema.exclusiveMinimum) { + options += helpers.optionHtml('Exclusive Min.', 'true'); + } + + if (schema.maximum) { + options += helpers.optionHtml('Max. Value', schema.maximum); + } + + if (schema.exclusiveMaximum) { + options += helpers.optionHtml('Exclusive Max.', 'true'); + } + + if (schema.multipleOf) { + options += helpers.optionHtml('Multiple Of', schema.multipleOf); + } + + break; + } + + if (isArray) { + if (schema.minItems) { + options += helpers.optionHtml('Min. Items', schema.minItems); + } + + if (schema.maxItems) { + options += helpers.optionHtml('Max. Items', schema.maxItems); + } + + if (schema.uniqueItems) { + options += helpers.optionHtml('Unique Items', 'true'); + } + + if (schema.collectionFormat) { + options += helpers.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 += helpers.optionHtml('Enum', enumString); + } + } + + if (options.length > 0) { + html = '' + html + '' + options + '
    ' + type + '
    '; + } + + return html; + }; + var processModel = function (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 += '
    ' + _.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(',
    '); + } 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 += '
    object
    '; + } else { + html += '
    ' + addReference(schema.items) + '
    '; + } + } else { + html += '
    ' + primitiveToOptionsHTML(schema.items, schema.items.type) + '
    '; + } + } else { + html += '
    ' + addReference(schema.items, helpers.simpleRef(schema.items.$ref)) + '
    '; + } + } else { + helpers.log('Array type\'s \'items\' property is not an array or an object, cannot process'); + html += '
    object
    '; + } + } else { + if (schema.$ref) { + html += '
    ' + addReference(schema, name) + '
    '; + } else if (type === 'object') { + html += '
    '; + + if (_.isPlainObject(schema.properties)) { + html += _.map(schema.properties, function (property, name) { + var required = _.indexOf(schema.required || [], name) > -1; + var html = '' + name + ' ('; + + html += primitiveToHTML(property); + + if (!required) { + html += ', optional'; + } + + html += ')'; + + if (!_.isUndefined(property.description)) { + html += ': ' + property.description; + } + + if (property.enum) { + html += ' = [\'' + property.enum.join('\' or \'') + '\']'; + } + + return primitiveToOptionsHTML(property, html); + }).join(',
    '); + } + + html += '
    '; + } else { + html = '
    ' + primitiveToOptionsHTML(schema, type) + '
    '; + } + } + + return html + strongOpen + (isArray ? ']' : '}') + strongClose; + }; + + + // Generate current HTML + var html = processModel(schema, name); + + // Generate references HTML + while (_.keys(references).length > 0) { + _.forEach(references, function (schema, name) { + var seenModel = _.indexOf(seenModels, name) > -1; + + delete references[name]; + + if (!seenModel) { + seenModels.push(name); + + html += '
    ' + processModel(schema, name); + } + }); + } + + return html; +}; + +var schemaToJSON = function (schema, models, modelsToIgnore) { + var type = schema.type || 'object'; + var model; + var output; + + if (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); + delete modelsToIgnore[model.name]; + } else { + if (model.type === 'array') { + output = []; + } else { + output = {}; + } + } + } + } else if (schema.default) { + output = schema.default; + } else if (type === 'date-time') { + output = new Date().toISOString(); + } else if (type === 'date') { + output = new Date().toISOString().split('T')[0]; + } else if (type === 'string') { + output = 'string'; + } else if (type === 'integer') { + output = 0; + } else if (type === 'long') { + output = 0; + } else if (type === 'float') { + output = 0.0; + } else if (type === 'double') { + output = 0.0; + } else if (type === 'boolean') { + output = true; + } else if (type === 'object') { + output = {}; + + _.forEach(schema.properties, function (property, name) { + output[name] = schemaToJSON(property, models, modelsToIgnore); + }); + } else if (type === 'array') { + output = []; + + if (_.isArray(schema.items)) { + _.forEach(schema.items, function (item) { + output.push(schemaToJSON(item, models, modelsToIgnore)); + }); + } else if (_.isPlainObject(schema.items)) { + output.push(schemaToJSON(schema.items, models, modelsToIgnore)); + } 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; +}; + +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 = JSON.parse(this.definition.example); + } + } else { + this.definition.example = this.examples; + } + + + return schemaToJSON(this.definition, this.models, modelsToIgnore); +}; + +Model.prototype.getMockSignature = function () { + return schemaToHTML(this.name, this.definition, this.models); +}; + +},{"../helpers":4,"lodash-compat/array/indexOf":19,"lodash-compat/collection/forEach":22,"lodash-compat/collection/map":23,"lodash-compat/lang/isArray":96,"lodash-compat/lang/isPlainObject":100,"lodash-compat/lang/isString":101,"lodash-compat/lang/isUndefined":103,"lodash-compat/object/keys":104}],9:[function(require,module,exports){ +'use strict'; + +var _ = { + isUndefined: require('lodash-compat/lang/isUndefined') +}; +var helpers = require('../helpers'); +var Model = require('./model'); +var SwaggerHttp = require('../http'); + +var Operation = module.exports = function (parent, scheme, operationId, httpMethod, path, args, definitions, models, clientAuthorizations) { + var errors = []; + + parent = parent || {}; + args = args || {}; + + this.authorizations = args.security; + this.basePath = parent.basePath || '/'; + this.clientAuthorizations = clientAuthorizations; + this.consumes = args.consumes; + 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.produces = args.produces; + this.responses = (args.responses || {}); + this.scheme = scheme || parent.scheme || 'http'; + this.schemes = parent.schemes; + this.security = args.security; + this.summary = args.summary || ''; + this.type = null; + this.useJQuery = parent.useJQuery; + + 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 this.definitions) { + model = new Model(key, definitions[key], this.models); + + if (model) { + this.models[key] = model; + } + } + } + for (i = 0; i < this.parameters.length; i++) { + var param = this.parameters[i]; + + if (param.type === 'array') { + param.isList = true; + param.allowMultiple = true; + } + + var innerType = this.getType(param); + + if (innerType && innerType.toString().toLowerCase() === 'boolean') { + param.allowableValues = {}; + param.isList = true; + param['enum'] = ['true', 'false']; + } + + 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) ? true : false; + + param.allowableValues.values.push(value); + 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.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); + } 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.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); + } + } + + if (param.$ref) { + str = 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 { + return this.getType(schema); + } + } + if (isArray) { + return [ str ]; + } else { + return str; + } +}; + +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); + } + } else if (schema.type === 'object' || _.isUndefined(schema.type)) { + return new Model(undefined, schema, this.models); + } + + 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]; + } else if (typeof type === 'undefined') { + type = 'undefined'; + } + + if (type === 'string') { + isPrimitive = true; + } else { + isPrimitive = (listType && definitions[listType]) || (definitions[type]) ? false : true; + } + + if (isPrimitive) { + if (listType) { + return 'Array[' + type + ']'; + } else { + return type.toString(); + } + } else { + if (listType) { + return 'Array[' + definitions[type].getMockSignature() + ']'; + } else { + return definitions[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 = {}, body, key, value; + + 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]; + } + } + } + + // handle form params + if (headers['Content-Type'] === 'application/x-www-form-urlencoded') { + 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 (headers['Content-Type'] && headers['Content-Type'].indexOf('multipart/form-data') >= 0) { + 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 isPrimitive, listType, sampleJson; + + listType = (type instanceof Array); + isPrimitive = models[type] ? false : true; + sampleJson = isPrimitive ? void 0 : models[type].createJSONSample(); + + if (sampleJson) { + sampleJson = listType ? [sampleJson] : sampleJson; + + if (typeof sampleJson === 'string') { + return sampleJson; + } else if (typeof sampleJson === 'object') { + var t = sampleJson; + + if (sampleJson instanceof Array && sampleJson.length > 0) { + t = sampleJson[0]; + } + + if (t.nodeName) { + 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; + + if (typeof arg2 === 'object') { + opts = arg2; + success = arg3; + error = arg4; + } + + if (typeof arg2 === 'function') { + success = arg2; + error = arg3; + } + + success = (success || helpers.log); + error = (error || helpers.log); + + if (opts.useJQuery) { + this.useJQuery = opts.useJQuery; + } + + var missingParams = this.getMissingParams(args); + + if (missingParams.length > 0) { + var message = 'missing required params: ' + missingParams; + + helpers.fail(message); + + 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(headers, 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, + useJQuery: this.useJQuery, + headers: headers, + on: { + response: function (response) { + return success(response, parent); + }, + error: function (response) { + return error(response, parent); + } + } + }; + + this.clientAuthorizations.apply(obj, this.operation.security); + if (opts.mock === true) { + return obj; + } else { + new SwaggerHttp().execute(obj, opts); + } +}; + +Operation.prototype.setContentTypes = function (args, opts) { + // default type + var accepts = 'application/json'; + var allDefinedParams = this.parameters; + var body; + var consumes = args.parameterContentType || 'application/json'; + 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 (body && (this.method === 'post' || this.method === 'put' || this.method === 'patch' || this.method === 'delete')) { + if (opts.requestContentType) { + consumes = opts.requestContentType; + } + } else { + // 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 if (this.type === 'DELETE') { + body = '{}'; + } else if (this.type !== 'DELETE') { + 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 (opts.responseContentType) { + accepts = opts.responseContentType; + } else { + accepts = 'application/json'; + } + + if (accepts && this.produces) { + if (this.produces.indexOf(accepts) === -1) { + 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; +}; + +Operation.prototype.asCurl = function (args) { + var obj = this.execute(args, {mock: true}); + + this.clientAuthorizations.apply(obj); + + var results = []; + + results.push('-X ' + this.method.toUpperCase()); + + if (obj.headers) { + var key; + + for (key in obj.headers) { + results.push('--header "' + key + ': ' + obj.headers[key] + '"'); + } + } + + if (obj.body) { + var body; + + if (typeof obj.body === 'object') { + body = JSON.stringify(obj.body); + } else { + body = obj.body; + } + + results.push('-d "' + body.replace(/"/g, '\\"') + '"'); + } + + 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) { + var encParts, parts, i, len; + + pathParam = pathParam.toString(); + + if (pathParam.indexOf('/') === -1) { + return encodeURIComponent(pathParam); + } else { + parts = pathParam.split('/'); + encParts = []; + + for (i = 0, len = parts.length; i < len; i++) { + encParts.push(encodeURIComponent(parts[i])); + } + + return encParts.join('/'); + } +}; + +},{"../helpers":4,"../http":5,"./model":8,"lodash-compat/lang/isUndefined":103}],10:[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 () { + +}; + + +},{}],11:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @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 kMaxLength = 0x3fffffff +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+. + * + * Note: + * + * - Implementation must support adding new properties to `Uint8Array` instances. + * Firefox 4-29 lacked support, fixed in Firefox 30+. + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - 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 will + * get the Object implementation, which is slower but will work correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = (function () { + try { + var buf = new ArrayBuffer(0) + var arr = new Uint8Array(buf) + arr.foo = function () { return 42 } + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +})() + +/** + * 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 (subject, encoding) { + var self = this + if (!(self instanceof Buffer)) return new Buffer(subject, encoding) + + var type = typeof subject + var length + + if (type === 'number') { + length = +subject + } else if (type === 'string') { + length = Buffer.byteLength(subject, encoding) + } else if (type === 'object' && subject !== null) { + // assume object is array-like + if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data + length = +subject.length + } else { + throw new TypeError('must start with number, buffer, array or string') + } + + if (length > kMaxLength) { + throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' + + kMaxLength.toString(16) + ' bytes') + } + + if (length < 0) length = 0 + else length >>>= 0 // coerce to uint32 + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Preferred: Return an augmented `Uint8Array` instance for best performance + self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this + } else { + // Fallback: Return THIS instance of Buffer (created by `new`) + self.length = length + self._isBuffer = true + } + + var i + if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { + // Speed optimization -- use set if we're copying from a typed array + self._set(subject) + } else if (isArrayish(subject)) { + // Treat array-ish objects as a byte array + if (Buffer.isBuffer(subject)) { + for (i = 0; i < length; i++) { + self[i] = subject.readUInt8(i) + } + } else { + for (i = 0; i < length; i++) { + self[i] = ((subject[i] % 256) + 256) % 256 + } + } + } else if (type === 'string') { + self.write(subject, 0, encoding) + } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT) { + for (i = 0; i < length; i++) { + self[i] = 0 + } + } + + if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent + + return self +} + +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 + for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; 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, totalLength) { + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } + + var i + if (totalLength === undefined) { + totalLength = 0 + for (i = 0; i < list.length; i++) { + totalLength += list[i].length + } + } + + var buf = new Buffer(totalLength) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +Buffer.byteLength = function byteLength (str, encoding) { + var ret + str = str + '' + switch (encoding || 'utf8') { + case 'ascii': + case 'binary': + case 'raw': + ret = str.length + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = str.length * 2 + break + case 'hex': + ret = str.length >>> 1 + break + case 'utf8': + case 'utf-8': + ret = utf8ToBytes(str).length + break + case 'base64': + ret = base64ToBytes(str).length + break + default: + ret = str.length + } + return ret +} + +// pre-set for values that may exist in the future +Buffer.prototype.length = undefined +Buffer.prototype.parent = undefined + +// toString(encoding, start=0, end=buffer.length) +Buffer.prototype.toString = function toString (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.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.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` will be removed in Node 0.13+ +Buffer.prototype.get = function get (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} + +// `set` will be removed in Node 0.13+ +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) { + var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + return charsWritten +} + +function asciiWrite (buf, string, offset, length) { + var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) + return charsWritten +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) + return charsWritten +} + +function utf16leWrite (buf, string, offset, length) { + var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + return charsWritten +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length + length = undefined + } + } else { // legacy + var swap = encoding + encoding = offset + offset = length + length = swap + } + + offset = Number(offset) || 0 + + if (length < 0 || offset < 0 || offset > this.length) { + throw new RangeError('attempt to write outside buffer bounds') + } + + var remaining = this.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + encoding = String(encoding || 'utf8').toLowerCase() + + var ret + switch (encoding) { + case 'hex': + ret = hexWrite(this, string, offset, length) + break + case 'utf8': + case 'utf-8': + ret = utf8Write(this, string, offset, length) + break + case 'ascii': + ret = asciiWrite(this, string, offset, length) + break + case 'binary': + ret = binaryWrite(this, string, offset, length) + break + case 'base64': + ret = base64Write(this, string, offset, length) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = utf16leWrite(this, string, offset, length) + break + default: + throw new TypeError('Unknown encoding: ' + encoding) + } + return ret +} + +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) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + if (buf[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) + tmp = '' + } else { + tmp += '%' + buf[i].toString(16) + } + } + + return res + decodeUtf8Char(tmp) +} + +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) >>> 0 & 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) >>> 0 & 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) { + checkInt( + this, value, offset, byteLength, + Math.pow(2, 8 * byteLength - 1) - 1, + -Math.pow(2, 8 * byteLength - 1) + ) + } + + 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) { + checkInt( + this, value, offset, byteLength, + Math.pow(2, 8 * byteLength - 1) - 1, + -Math.pow(2, 8 * byteLength - 1) + ) + } + + 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, target_start, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (target_start >= target.length) target_start = target.length + if (!target_start) target_start = 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 (target_start < 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 - target_start < end - start) { + end = target.length - target_start + start + } + + var len = end - start + + if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < len; i++) { + target[i + target_start] = this[i + start] + } + } else { + target._set(this.subarray(start, start + len), target_start) + } + + 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, will be removed in node 0.13+ + 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-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 isArrayish (subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number' +} + +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 = [] + var i = 0 + + for (; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (leadSurrogate) { + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } else { + // valid surrogate pair + codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 + leadSurrogate = null + } + } else { + // 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 + } else { + // valid lead + leadSurrogate = codePoint + continue + } + } + } 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 < 0x200000) { + 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 +} + +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char + } +} + +},{"base64-js":12,"ieee754":13,"is-array":14}],12:[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)) + +},{}],13:[function(require,module,exports){ +exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = isLE ? (nBytes - 1) : 0, + d = isLE ? -1 : 1, + 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, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = isLE ? 0 : (nBytes - 1), + d = isLE ? 1 : -1, + 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; +}; + +},{}],14:[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); +}; + +},{}],15:[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; }; + +},{}],16:[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) + +},{"buffer":11}],17:[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); + } + 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) { + if (this.path !== access_info.path) { + 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(Cookie); + for (i = 0; i < cookies.length; i += 1) { + cookie = cookies[i]; + if (this.setCookie(cookie, request_domain, request_path)) { + successful.push(cookie); + } + } + return successful; + }; +}()); + +},{}],18:[function(require,module,exports){ +/*! + * jQuery JavaScript Library v2.1.3 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-12-18T15:11Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Support: Firefox 18+ +// Can't be in strict mode, several libs including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// + +var arr = []; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + version = "2.1.3", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; + }, + + isPlainObject: function( obj ) { + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.constructor && + !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { + return false; + } + + // If the function hasn't returned already, we're confident that + // |obj| is a plain object, created by {} or constructed with new Object + return true; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + // Support: Android<4.0, iOS<6 (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call(obj) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + var script, + indirect = eval; + + code = jQuery.trim( code ); + + if ( code ) { + // If the code includes a valid, prologue position + // strict mode pragma, execute code by injecting a + // script tag into the document. + if ( code.indexOf("use strict") === 1 ) { + script = document.createElement("script"); + script.text = code; + document.head.appendChild( script ).parentNode.removeChild( script ); + } else { + // Otherwise, avoid the DOM node creation, insertion + // and removal by using an indirect global eval + indirect( code ); + } + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE9-11+ + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Support: Android<4.1 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.2.0-pre + * http://sizzlejs.com/ + * + * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-12-16 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // http://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + characterEncoding + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + nodeType = context.nodeType; + + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + if ( !seed && documentIsHTML ) { + + // Try to shortcut find operations when possible (e.g., not under DocumentFragment) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document (jQuery #6963) + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType !== 1 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, parent, + doc = node ? node.ownerDocument || node : preferredDoc; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + parent = doc.defaultView; + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent !== parent.top ) { + // IE11 does not have attachEvent, so all must suffer + if ( parent.addEventListener ) { + parent.addEventListener( "unload", unloadHandler, false ); + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", unloadHandler ); + } + } + + /* Support tests + ---------------------------------------------------------------------- */ + documentIsHTML = !isXML( doc ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + docElem.appendChild( div ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ + if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibing-combinator selector` fails + if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (oldCache = outerCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + outerCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context !== document && context; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is no seed and only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; + }); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + len = this.length, + ret = [], + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +}); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Support: Blackberry 4.6 + // gEBID returns nodes no longer in the document (#6963) + if ( elem && elem.parentNode ) { + // Inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof rootjQuery.ready !== "undefined" ? + rootjQuery.ready( selector ) : + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.extend({ + dir: function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; + }, + + sibling: function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; + } +}); + +jQuery.fn.extend({ + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter(function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.unique( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return elem.contentDocument || jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.unique( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +}); +var rnotwhite = (/\S+/g); + + + +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // Add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // If we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * The ready event handler and self cleanup method + */ +function completed() { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + jQuery.ready(); +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // We once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + } else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + } + } + return readyList.promise( obj ); +}; + +// Kick off the DOM ready check even if the user does not +jQuery.ready.promise(); + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + len ? fn( elems[0], key ) : emptyGet; +}; + + +/** + * Determines whether an object can have data + */ +jQuery.acceptData = function( owner ) { + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + /* jshint -W018 */ + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + +function Data() { + // Support: Android<4, + // Old WebKit does not have Object.preventExtensions/freeze method, + // return new empty object instead with no [[set]] accessor + Object.defineProperty( this.cache = {}, 0, { + get: function() { + return {}; + } + }); + + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; +Data.accepts = jQuery.acceptData; + +Data.prototype = { + key: function( owner ) { + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return the key for a frozen object. + if ( !Data.accepts( owner ) ) { + return 0; + } + + var descriptor = {}, + // Check if the owner object already has a cache key + unlock = owner[ this.expando ]; + + // If not, create one + if ( !unlock ) { + unlock = Data.uid++; + + // Secure it in a non-enumerable, non-writable property + try { + descriptor[ this.expando ] = { value: unlock }; + Object.defineProperties( owner, descriptor ); + + // Support: Android<4 + // Fallback to a less secure definition + } catch ( e ) { + descriptor[ this.expando ] = unlock; + jQuery.extend( owner, descriptor ); + } + } + + // Ensure the cache object + if ( !this.cache[ unlock ] ) { + this.cache[ unlock ] = {}; + } + + return unlock; + }, + set: function( owner, data, value ) { + var prop, + // There may be an unlock assigned to this node, + // if there is no entry for this "owner", create one inline + // and set the unlock as though an owner entry had always existed + unlock = this.key( owner ), + cache = this.cache[ unlock ]; + + // Handle: [ owner, key, value ] args + if ( typeof data === "string" ) { + cache[ data ] = value; + + // Handle: [ owner, { properties } ] args + } else { + // Fresh assignments by object are shallow copied + if ( jQuery.isEmptyObject( cache ) ) { + jQuery.extend( this.cache[ unlock ], data ); + // Otherwise, copy the properties one-by-one to the cache object + } else { + for ( prop in data ) { + cache[ prop ] = data[ prop ]; + } + } + } + return cache; + }, + get: function( owner, key ) { + // Either a valid cache is found, or will be created. + // New caches will be created and the unlock returned, + // allowing direct access to the newly created + // empty data object. A valid owner object must be provided. + var cache = this.cache[ this.key( owner ) ]; + + return key === undefined ? + cache : cache[ key ]; + }, + access: function( owner, key, value ) { + var stored; + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ((key && typeof key === "string") && value === undefined) ) { + + stored = this.get( owner, key ); + + return stored !== undefined ? + stored : this.get( owner, jQuery.camelCase(key) ); + } + + // [*]When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, name, camel, + unlock = this.key( owner ), + cache = this.cache[ unlock ]; + + if ( key === undefined ) { + this.cache[ unlock ] = {}; + + } else { + // Support array or space separated string of keys + if ( jQuery.isArray( key ) ) { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = key.concat( key.map( jQuery.camelCase ) ); + } else { + camel = jQuery.camelCase( key ); + // Try the string as a key before any manipulation + if ( key in cache ) { + name = [ key, camel ]; + } else { + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + name = camel; + name = name in cache ? + [ name ] : ( name.match( rnotwhite ) || [] ); + } + } + + i = name.length; + while ( i-- ) { + delete cache[ name[ i ] ]; + } + } + }, + hasData: function( owner ) { + return !jQuery.isEmptyObject( + this.cache[ owner[ this.expando ] ] || {} + ); + }, + discard: function( owner ) { + if ( owner[ this.expando ] ) { + delete this.cache[ owner[ this.expando ] ]; + } + } +}; +var data_priv = new Data(); + +var data_user = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + data_user.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend({ + hasData: function( elem ) { + return data_user.hasData( elem ) || data_priv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return data_user.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + data_user.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to data_priv methods, these can be deprecated. + _data: function( elem, name, data ) { + return data_priv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + data_priv.remove( elem, name ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = data_user.get( elem ); + + if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + data_priv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + data_user.set( this, key ); + }); + } + + return access( this, function( value ) { + var data, + camelKey = jQuery.camelCase( key ); + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + // Attempt to get data from the cache + // with the key as-is + data = data_user.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to get data from the cache + // with the key camelized + data = data_user.get( elem, camelKey ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, camelKey, undefined ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each(function() { + // First, attempt to store a copy or reference of any + // data that might've been store with a camelCased key. + var data = data_user.get( this, camelKey ); + + // For HTML5 data-* attribute interop, we have to + // store property names with dashes in a camelCase form. + // This might not apply to all properties...* + data_user.set( this, camelKey, value ); + + // *... In the case of properties that might _actually_ + // have dashes, we need to also store a copy of that + // unchanged property. + if ( key.indexOf("-") !== -1 && data !== undefined ) { + data_user.set( this, key, value ); + } + }); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each(function() { + data_user.remove( this, key ); + }); + } +}); + + +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = data_priv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = data_priv.access( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return data_priv.get( elem, key ) || data_priv.access( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + data_priv.remove( elem, [ type + "queue", key ] ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = data_priv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); + }; + +var rcheckableType = (/^(?:checkbox|radio)$/i); + + + +(function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Safari<=5.1 + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Safari<=5.1, Android<4.2 + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<=11+ + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +})(); +var strundefined = typeof undefined; + + + +support.focusinBubbles = "onfocusin" in window; + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = data_priv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = data_priv.hasData( elem ) && data_priv.get( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + data_priv.remove( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && jQuery.acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.disabled !== true || event.type !== "click" ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: Cordova 2.5 (WebKit) (#13255) + // All events should have a target; Cordova deviceready doesn't + if ( !event.target ) { + event.target = document; + } + + // Support: Safari 6.0+, Chrome<28 + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } +}; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + // Support: Android<4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && e.preventDefault ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && e.stopPropagation ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +// Support: Chrome 15+ +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// Support: Firefox, Chrome, Safari +// Create "bubbling" focus and blur events +if ( !support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = data_priv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = data_priv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + data_priv.remove( doc, fix ); + + } else { + data_priv.access( doc, fix, attaches ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); + + +var + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rhtml = /<|&#?\w+;/, + rnoInnerhtml = /<(?:script|style|link)/i, + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /^$|\/(?:java|ecma)script/i, + rscriptTypeMasked = /^true\/(.*)/, + rcleanScript = /^\s*\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + + // Support: IE9 + option: [ 1, "" ], + + thead: [ 1, "", "
    " ], + col: [ 2, "", "
    " ], + tr: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + + _default: [ 0, "", "" ] + }; + +// Support: IE9 +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: 1.x compatibility +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute("type"); + } + + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + data_priv.set( + elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) + ); + } +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( data_priv.hasData( src ) ) { + pdataOld = data_priv.access( src ); + pdataCur = data_priv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( data_user.hasData( src ) ) { + udataOld = data_user.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + data_user.set( dest, udataCur ); + } +} + +function getAll( context, tag ) { + var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : + context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : + []; + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], ret ) : + ret; +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + // Support: QtWebKit, PhantomJS + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: QtWebKit, PhantomJS + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; + }, + + cleanData: function( elems ) { + var data, elem, type, key, + special = jQuery.event.special, + i = 0; + + for ( ; (elem = elems[ i ]) !== undefined; i++ ) { + if ( jQuery.acceptData( elem ) ) { + key = elem[ data_priv.expando ]; + + if ( key && (data = data_priv.cache[ key ]) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + if ( data_priv.cache[ key ] ) { + // Discard any remaining `private` data + delete data_priv.cache[ key ]; + } + } + } + // Discard any remaining `user` data + delete data_user.cache[ elem[ data_user.expando ] ]; + } + } +}); + +jQuery.fn.extend({ + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each(function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + }); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + remove: function( selector, keepData /* Internal Use Only */ ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map(function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var arg = arguments[ 0 ]; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + arg = this.parentNode; + + jQuery.cleanData( getAll( this ) ); + + if ( arg ) { + arg.replaceChild( elem, this ); + } + }); + + // Force removal if there was no new content (e.g., from empty arguments) + return arg && (arg.length || arg.nodeType) ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + self.domManip( args, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + // Support: QtWebKit + // jQuery.merge because push.apply(_, arraylike) throws + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); + } + } + } + } + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: QtWebKit + // .get() because push.apply(_, arraylike) throws + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + + +var iframe, + elemdisplay = {}; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var style, + elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + // getDefaultComputedStyle might be reliably used only on attached element + display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? + + // Use of this method is a temporary fix (more like optimization) until something better comes along, + // since it was removed from specification and supported only in FF + style.display : jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = (iframe || jQuery( "