From 50ddc3e017fcbccb636762d048f28373343c3e77 Mon Sep 17 00:00:00 2001 From: huangjian Date: Tue, 27 Sep 2016 10:08:44 +0800 Subject: Update license header Change-Id: I9254691ebb7c05ebed80d2348e750db773ff0685 Issue-id: TOSCA-84 Signed-off-by: huangjian --- .../src/main/resources/api-doc/WEB-INF/web.xml | 2 +- .../src/main/resources/api-doc/css/reset.css | 280 +- .../src/main/resources/api-doc/css/screen.css | 2542 ++++---- .../src/main/resources/api-doc/css/typography.css | 82 +- .../src/main/resources/api-doc/index.html | 2 +- .../src/main/resources/api-doc/lib/backbone-min.js | 58 +- .../main/resources/api-doc/lib/handlebars-2.0.0.js | 84 +- .../resources/api-doc/lib/highlight.7.3.pack.js | 30 +- .../main/resources/api-doc/lib/jquery-1.8.0.min.js | 2 +- .../resources/api-doc/lib/jquery.ba-bbq.min.js | 48 +- .../resources/api-doc/lib/jquery.slideto.min.js | 32 +- .../resources/api-doc/lib/jquery.wiggle.min.js | 44 +- .../src/main/resources/api-doc/lib/marked.js | 2560 ++++---- .../src/main/resources/api-doc/lib/shred.bundle.js | 5558 ++++++++-------- .../main/resources/api-doc/lib/shred/content.js | 412 +- .../main/resources/api-doc/lib/swagger-client.js | 6616 ++++++++++---------- .../main/resources/api-doc/lib/swagger-oauth.js | 586 +- .../main/resources/api-doc/lib/underscore-min.js | 40 +- .../src/main/resources/api-doc/o2c.html | 72 +- .../src/main/resources/api-doc/swagger-ui.js | 2 +- .../src/main/resources/api-doc/swagger-ui.min.js | 32 +- .../catalog-mgr/src/main/resources/migrations.xml | 2 +- 22 files changed, 9543 insertions(+), 9543 deletions(-) (limited to 'catalog-core/catalog-mgr/src/main/resources') diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/WEB-INF/web.xml b/catalog-core/catalog-mgr/src/main/resources/api-doc/WEB-INF/web.xml index 2f57e7e8..2a5346c4 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/WEB-INF/web.xml +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/WEB-INF/web.xml @@ -1,7 +1,7 @@ ",r:10},{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"|$)",e:">",k:{title:"style"},c:[b],starts:{e:"",rE:true,sL:"css"}},{cN:"tag",b:"|$)",e:">",k:{title:"script"},c:[b],starts:{e:"<\/script>",rE:true,sL:"javascript"}},{b:"<%",e:"%>",sL:"vbscript"},{cN:"tag",b:"",c:[{cN:"title",b:"[^ />]+"},b]}]}}(hljs);hljs.LANGUAGES.json=function(a){var e={literal:"true false null"};var d=[a.QSM,a.CNM];var c={cN:"value",e:",",eW:true,eE:true,c:d,k:e};var b={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:true,eE:true,c:[a.BE],i:"\\n",starts:c}],i:"\\S"};var f={b:"\\[",e:"\\]",c:[a.inherit(c,{cN:null})],i:"\\S"};d.splice(d.length,0,b,f);return{c:d,k:e,i:"\\S"}}(hljs); \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery-1.8.0.min.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery-1.8.0.min.js index 4aee7fbc..fcdf2c43 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery-1.8.0.min.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery-1.8.0.min.js @@ -1,5 +1,5 @@ /* - * Copyright 2016 [ZTE] and others. + * Copyright 2016 ZTE Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.ba-bbq.min.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.ba-bbq.min.js index 64e37d56..a9756be3 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.ba-bbq.min.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.ba-bbq.min.js @@ -1,25 +1,25 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -(function($,p){var i,m=Array.prototype.slice,r=decodeURIComponent,a=$.param,c,l,v,b=$.bbq=$.bbq||{},q,u,j,e=$.event.special,d="hashchange",A="querystring",D="fragment",y="elemUrlAttr",g="location",k="href",t="src",x=/^.*\?|#.*$/g,w=/^.*\#/,h,C={};function E(F){return typeof F==="string"}function B(G){var F=m.call(arguments,1);return function(){return G.apply(this,F.concat(m.call(arguments)))}}function n(F){return F.replace(/^[^#]*#?(.*)$/,"$1")}function o(F){return F.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(H,M,F,I,G){var O,L,K,N,J;if(I!==i){K=F.match(H?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);J=K[3]||"";if(G===2&&E(I)){L=I.replace(H?w:x,"")}else{N=l(K[2]);I=E(I)?l[H?D:A](I):I;L=G===2?I:G===1?$.extend({},I,N):$.extend({},N,I);L=a(L);if(H){L=L.replace(h,r)}}O=K[1]+(H?"#":L||!K[1]?"?":"")+L+J}else{O=M(F!==i?F:p[g][k])}return O}a[A]=B(f,0,o);a[D]=c=B(f,1,n);c.noEscape=function(G){G=G||"";var F=$.map(G.split(""),encodeURIComponent);h=new RegExp(F.join("|"),"g")};c.noEscape(",/");$.deparam=l=function(I,F){var H={},G={"true":!0,"false":!1,"null":null};$.each(I.replace(/\+/g," ").split("&"),function(L,Q){var K=Q.split("="),P=r(K[0]),J,O=H,M=0,R=P.split("]["),N=R.length-1;if(/\[/.test(R[0])&&/\]$/.test(R[N])){R[N]=R[N].replace(/\]$/,"");R=R.shift().split("[").concat(R);N=R.length-1}else{N=0}if(K.length===2){J=r(K[1]);if(F){J=J&&!isNaN(J)?+J:J==="undefined"?i:G[J]!==i?G[J]:J}if(N){for(;M<=N;M++){P=R[M]===""?O.length:R[M];O=O[P]=M').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this); \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.slideto.min.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.slideto.min.js index e41e6d02..6c79a233 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.slideto.min.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.slideto.min.js @@ -1,16 +1,16 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -(function(b){b.fn.slideto=function(a){a=b.extend({slide_duration:"slow",highlight_duration:3E3,highlight:true,highlight_color:"#FFFF99"},a);return this.each(function(){obj=b(this);b("body").animate({scrollTop:obj.offset().top},a.slide_duration,function(){a.highlight&&b.ui.version&&obj.effect("highlight",{color:a.highlight_color},a.highlight_duration)})})}})(jQuery); +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +(function(b){b.fn.slideto=function(a){a=b.extend({slide_duration:"slow",highlight_duration:3E3,highlight:true,highlight_color:"#FFFF99"},a);return this.each(function(){obj=b(this);b("body").animate({scrollTop:obj.offset().top},a.slide_duration,function(){a.highlight&&b.ui.version&&obj.effect("highlight",{color:a.highlight_color},a.highlight_duration)})})}})(jQuery); diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.wiggle.min.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.wiggle.min.js index f63aa7ed..35e7be63 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.wiggle.min.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/jquery.wiggle.min.js @@ -1,23 +1,23 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* -jQuery Wiggle -Author: WonderGroup, Jordan Thomas -URL: http://labs.wondergroup.com/demos/mini-ui/index.html -License: MIT (http://en.wikipedia.org/wiki/MIT_License) -*/ -jQuery.fn.wiggle=function(o){var d={speed:50,wiggles:3,travel:5,callback:null};var o=jQuery.extend(d,o);return this.each(function(){var cache=this;var wrap=jQuery(this).wrap('
').css("position","relative");var calls=0;for(i=1;i<=o.wiggles;i++){jQuery(this).animate({left:"-="+o.travel},o.speed).animate({left:"+="+o.travel*2},o.speed*2).animate({left:"-="+o.travel},o.speed,function(){calls++;if(jQuery(cache).parent().hasClass('wiggle-wrap')){jQuery(cache).parent().replaceWith(cache);} +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* +jQuery Wiggle +Author: WonderGroup, Jordan Thomas +URL: http://labs.wondergroup.com/demos/mini-ui/index.html +License: MIT (http://en.wikipedia.org/wiki/MIT_License) +*/ +jQuery.fn.wiggle=function(o){var d={speed:50,wiggles:3,travel:5,callback:null};var o=jQuery.extend(d,o);return this.each(function(){var cache=this;var wrap=jQuery(this).wrap('
').css("position","relative");var calls=0;for(i=1;i<=o.wiggles;i++){jQuery(this).animate({left:"-="+o.travel},o.speed).animate({left:"+="+o.travel*2},o.speed*2).animate({left:"-="+o.travel},o.speed,function(){calls++;if(jQuery(cache).parent().hasClass('wiggle-wrap')){jQuery(cache).parent().replaceWith(cache);} if(calls==o.wiggles&&jQuery.isFunction(o.callback)){o.callback();}});}});}; \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/marked.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/marked.js index 88f91fde..7940c03c 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/marked.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/marked.js @@ -1,1281 +1,1281 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -;(function() { - -/** - * Block-Level Grammar - */ - -var block = { - newline: /^\n+/, - code: /^( {4}[^\n]+\n*)+/, - fences: noop, - hr: /^( *[-*_]){3,} *(?:\n+|$)/, - heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, - nptable: noop, - lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, - blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, - list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, - html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, - def: /^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, - table: noop, - paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, - text: /^[^\n]+/ -}; - -block.bullet = /(?:[*+-]|\d+\.)/; -block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; -block.item = replace(block.item, 'gm') - (/bull/g, block.bullet) - (); - -block.list = replace(block.list) - (/bull/g, block.bullet) - ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') - ('def', '\\n+(?=' + block.def.source + ')') - (); - -block.blockquote = replace(block.blockquote) - ('def', block.def) - (); - -block._tag = '(?!(?:' - + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' - + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' - + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; - -block.html = replace(block.html) - ('comment', //) - ('closed', /<(tag)[\s\S]+?<\/\1>/) - ('closing', /])*?>/) - (/tag/g, block._tag) - (); - -block.paragraph = replace(block.paragraph) - ('hr', block.hr) - ('heading', block.heading) - ('lheading', block.lheading) - ('blockquote', block.blockquote) - ('tag', '<' + block._tag) - ('def', block.def) - (); - -/** - * Normal Block Grammar - */ - -block.normal = merge({}, block); - -/** - * GFM Block Grammar - */ - -block.gfm = merge({}, block.normal, { - fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, - paragraph: /^/ -}); - -block.gfm.paragraph = replace(block.paragraph) - ('(?!', '(?!' - + block.gfm.fences.source.replace('\\1', '\\2') + '|' - + block.list.source.replace('\\1', '\\3') + '|') - (); - -/** - * GFM + Tables Block Grammar - */ - -block.tables = merge({}, block.gfm, { - nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, - table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ -}); - -/** - * Block Lexer - */ - -function Lexer(options) { - this.tokens = []; - this.tokens.links = {}; - this.options = options || marked.defaults; - this.rules = block.normal; - - if (this.options.gfm) { - if (this.options.tables) { - this.rules = block.tables; - } else { - this.rules = block.gfm; - } - } -} - -/** - * Expose Block Rules - */ - -Lexer.rules = block; - -/** - * Static Lex Method - */ - -Lexer.lex = function(src, options) { - var lexer = new Lexer(options); - return lexer.lex(src); -}; - -/** - * Preprocessing - */ - -Lexer.prototype.lex = function(src) { - src = src - .replace(/\r\n|\r/g, '\n') - .replace(/\t/g, ' ') - .replace(/\u00a0/g, ' ') - .replace(/\u2424/g, '\n'); - - return this.token(src, true); -}; - -/** - * Lexing - */ - -Lexer.prototype.token = function(src, top, bq) { - var src = src.replace(/^ +$/gm, '') - , next - , loose - , cap - , bull - , b - , item - , space - , i - , l; - - while (src) { - // newline - if (cap = this.rules.newline.exec(src)) { - src = src.substring(cap[0].length); - if (cap[0].length > 1) { - this.tokens.push({ - type: 'space' - }); - } - } - - // code - if (cap = this.rules.code.exec(src)) { - src = src.substring(cap[0].length); - cap = cap[0].replace(/^ {4}/gm, ''); - this.tokens.push({ - type: 'code', - text: !this.options.pedantic - ? cap.replace(/\n+$/, '') - : cap - }); - continue; - } - - // fences (gfm) - if (cap = this.rules.fences.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'code', - lang: cap[2], - text: cap[3] - }); - continue; - } - - // heading - if (cap = this.rules.heading.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'heading', - depth: cap[1].length, - text: cap[2] - }); - continue; - } - - // table no leading pipe (gfm) - if (top && (cap = this.rules.nptable.exec(src))) { - src = src.substring(cap[0].length); - - item = { - type: 'table', - header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), - align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), - cells: cap[3].replace(/\n$/, '').split('\n') - }; - - for (i = 0; i < item.align.length; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = 'right'; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = 'center'; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = 'left'; - } else { - item.align[i] = null; - } - } - - for (i = 0; i < item.cells.length; i++) { - item.cells[i] = item.cells[i].split(/ *\| */); - } - - this.tokens.push(item); - - continue; - } - - // lheading - if (cap = this.rules.lheading.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'heading', - depth: cap[2] === '=' ? 1 : 2, - text: cap[1] - }); - continue; - } - - // hr - if (cap = this.rules.hr.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'hr' - }); - continue; - } - - // blockquote - if (cap = this.rules.blockquote.exec(src)) { - src = src.substring(cap[0].length); - - this.tokens.push({ - type: 'blockquote_start' - }); - - cap = cap[0].replace(/^ *> ?/gm, ''); - - // Pass `top` to keep the current - // "toplevel" state. This is exactly - // how markdown.pl works. - this.token(cap, top, true); - - this.tokens.push({ - type: 'blockquote_end' - }); - - continue; - } - - // list - if (cap = this.rules.list.exec(src)) { - src = src.substring(cap[0].length); - bull = cap[2]; - - this.tokens.push({ - type: 'list_start', - ordered: bull.length > 1 - }); - - // Get each top-level item. - cap = cap[0].match(this.rules.item); - - next = false; - l = cap.length; - i = 0; - - for (; i < l; i++) { - item = cap[i]; - - // Remove the list item's bullet - // so it is seen as the next token. - space = item.length; - item = item.replace(/^ *([*+-]|\d+\.) +/, ''); - - // Outdent whatever the - // list item contains. Hacky. - if (~item.indexOf('\n ')) { - space -= item.length; - item = !this.options.pedantic - ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') - : item.replace(/^ {1,4}/gm, ''); - } - - // Determine whether the next list item belongs here. - // Backpedal if it does not belong in this list. - if (this.options.smartLists && i !== l - 1) { - b = block.bullet.exec(cap[i + 1])[0]; - if (bull !== b && !(bull.length > 1 && b.length > 1)) { - src = cap.slice(i + 1).join('\n') + src; - i = l - 1; - } - } - - // Determine whether item is loose or not. - // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ - // for discount behavior. - loose = next || /\n\n(?!\s*$)/.test(item); - if (i !== l - 1) { - next = item.charAt(item.length - 1) === '\n'; - if (!loose) loose = next; - } - - this.tokens.push({ - type: loose - ? 'loose_item_start' - : 'list_item_start' - }); - - // Recurse. - this.token(item, false, bq); - - this.tokens.push({ - type: 'list_item_end' - }); - } - - this.tokens.push({ - type: 'list_end' - }); - - continue; - } - - // html - if (cap = this.rules.html.exec(src)) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: this.options.sanitize - ? 'paragraph' - : 'html', - pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', - text: cap[0] - }); - continue; - } - - // def - if ((!bq && top) && (cap = this.rules.def.exec(src))) { - src = src.substring(cap[0].length); - this.tokens.links[cap[1].toLowerCase()] = { - href: cap[2], - title: cap[3] - }; - continue; - } - - // table (gfm) - if (top && (cap = this.rules.table.exec(src))) { - src = src.substring(cap[0].length); - - item = { - type: 'table', - header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), - align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), - cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') - }; - - for (i = 0; i < item.align.length; i++) { - if (/^ *-+: *$/.test(item.align[i])) { - item.align[i] = 'right'; - } else if (/^ *:-+: *$/.test(item.align[i])) { - item.align[i] = 'center'; - } else if (/^ *:-+ *$/.test(item.align[i])) { - item.align[i] = 'left'; - } else { - item.align[i] = null; - } - } - - for (i = 0; i < item.cells.length; i++) { - item.cells[i] = item.cells[i] - .replace(/^ *\| *| *\| *$/g, '') - .split(/ *\| */); - } - - this.tokens.push(item); - - continue; - } - - // top-level paragraph - if (top && (cap = this.rules.paragraph.exec(src))) { - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'paragraph', - text: cap[1].charAt(cap[1].length - 1) === '\n' - ? cap[1].slice(0, -1) - : cap[1] - }); - continue; - } - - // text - if (cap = this.rules.text.exec(src)) { - // Top-level should never reach here. - src = src.substring(cap[0].length); - this.tokens.push({ - type: 'text', - text: cap[0] - }); - continue; - } - - if (src) { - throw new - Error('Infinite loop on byte: ' + src.charCodeAt(0)); - } - } - - return this.tokens; -}; - -/** - * Inline-Level Grammar - */ - -var inline = { - escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, - autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, - url: noop, - tag: /^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, - link: /^!?\[(inside)\]\(href\)/, - reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, - nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, - strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, - em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, - code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, - br: /^ {2,}\n(?!\s*$)/, - del: noop, - text: /^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/; - -inline.link = replace(inline.link) - ('inside', inline._inside) - ('href', inline._href) - (); - -inline.reflink = replace(inline.reflink) - ('inside', inline._inside) - (); - -/** - * Normal Inline Grammar - */ - -inline.normal = merge({}, inline); - -/** - * Pedantic Inline Grammar - */ - -inline.pedantic = merge({}, inline.normal, { - strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, - em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ -}); - -/** - * GFM Inline Grammar - */ - -inline.gfm = merge({}, inline.normal, { - escape: replace(inline.escape)('])', '~|])')(), - url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, - del: /^~~(?=\S)([\s\S]*?\S)~~/, - text: replace(inline.text) - (']|', '~]|') - ('|', '|https?://|') - () -}); - -/** - * GFM + Line Breaks Inline Grammar - */ - -inline.breaks = merge({}, inline.gfm, { - br: replace(inline.br)('{2,}', '*')(), - text: replace(inline.gfm.text)('{2,}', '*')() -}); - -/** - * Inline Lexer & Compiler - */ - -function InlineLexer(links, options) { - this.options = options || marked.defaults; - this.links = links; - this.rules = inline.normal; - this.renderer = this.options.renderer || new Renderer; - this.renderer.options = this.options; - - if (!this.links) { - throw new - Error('Tokens array requires a `links` property.'); - } - - if (this.options.gfm) { - if (this.options.breaks) { - this.rules = inline.breaks; - } else { - this.rules = inline.gfm; - } - } else if (this.options.pedantic) { - this.rules = inline.pedantic; - } -} - -/** - * Expose Inline Rules - */ - -InlineLexer.rules = inline; - -/** - * Static Lexing/Compiling Method - */ - -InlineLexer.output = function(src, links, options) { - var inline = new InlineLexer(links, options); - return inline.output(src); -}; - -/** - * Lexing/Compiling - */ - -InlineLexer.prototype.output = function(src) { - var out = '' - , link - , text - , href - , cap; - - while (src) { - // escape - if (cap = this.rules.escape.exec(src)) { - src = src.substring(cap[0].length); - out += cap[1]; - continue; - } - - // autolink - if (cap = this.rules.autolink.exec(src)) { - src = src.substring(cap[0].length); - if (cap[2] === '@') { - text = cap[1].charAt(6) === ':' - ? this.mangle(cap[1].substring(7)) - : this.mangle(cap[1]); - href = this.mangle('mailto:') + text; - } else { - text = escape(cap[1]); - href = text; - } - out += this.renderer.link(href, null, text); - continue; - } - - // url (gfm) - if (!this.inLink && (cap = this.rules.url.exec(src))) { - src = src.substring(cap[0].length); - text = escape(cap[1]); - href = text; - out += this.renderer.link(href, null, text); - continue; - } - - // tag - if (cap = this.rules.tag.exec(src)) { - if (!this.inLink && /^/i.test(cap[0])) { - this.inLink = false; - } - src = src.substring(cap[0].length); - out += this.options.sanitize - ? escape(cap[0]) - : cap[0]; - continue; - } - - // link - if (cap = this.rules.link.exec(src)) { - src = src.substring(cap[0].length); - this.inLink = true; - out += this.outputLink(cap, { - href: cap[2], - title: cap[3] - }); - this.inLink = false; - continue; - } - - // reflink, nolink - if ((cap = this.rules.reflink.exec(src)) - || (cap = this.rules.nolink.exec(src))) { - src = src.substring(cap[0].length); - link = (cap[2] || cap[1]).replace(/\s+/g, ' '); - link = this.links[link.toLowerCase()]; - if (!link || !link.href) { - out += cap[0].charAt(0); - src = cap[0].substring(1) + src; - continue; - } - this.inLink = true; - out += this.outputLink(cap, link); - this.inLink = false; - continue; - } - - // strong - if (cap = this.rules.strong.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.strong(this.output(cap[2] || cap[1])); - continue; - } - - // em - if (cap = this.rules.em.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.em(this.output(cap[2] || cap[1])); - continue; - } - - // code - if (cap = this.rules.code.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.codespan(escape(cap[2], true)); - continue; - } - - // br - if (cap = this.rules.br.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.br(); - continue; - } - - // del (gfm) - if (cap = this.rules.del.exec(src)) { - src = src.substring(cap[0].length); - out += this.renderer.del(this.output(cap[1])); - continue; - } - - // text - if (cap = this.rules.text.exec(src)) { - src = src.substring(cap[0].length); - out += escape(this.smartypants(cap[0])); - continue; - } - - if (src) { - throw new - Error('Infinite loop on byte: ' + src.charCodeAt(0)); - } - } - - return out; -}; - -/** - * Compile Link - */ - -InlineLexer.prototype.outputLink = function(cap, link) { - var href = escape(link.href) - , title = link.title ? escape(link.title) : null; - - return cap[0].charAt(0) !== '!' - ? this.renderer.link(href, title, this.output(cap[1])) - : this.renderer.image(href, title, escape(cap[1])); -}; - -/** - * Smartypants Transformations - */ - -InlineLexer.prototype.smartypants = function(text) { - if (!this.options.smartypants) return text; - return text - // em-dashes - .replace(/--/g, '\u2014') - // opening singles - .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') - // closing singles & apostrophes - .replace(/'/g, '\u2019') - // opening doubles - .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') - // closing doubles - .replace(/"/g, '\u201d') - // ellipses - .replace(/\.{3}/g, '\u2026'); -}; - -/** - * Mangle Links - */ - -InlineLexer.prototype.mangle = function(text) { - var out = '' - , l = text.length - , i = 0 - , ch; - - for (; i < l; i++) { - ch = text.charCodeAt(i); - if (Math.random() > 0.5) { - ch = 'x' + ch.toString(16); - } - out += '&#' + ch + ';'; - } - - return out; -}; - -/** - * Renderer - */ - -function Renderer(options) { - this.options = options || {}; -} - -Renderer.prototype.code = function(code, lang, escaped) { - if (this.options.highlight) { - var out = this.options.highlight(code, lang); - if (out != null && out !== code) { - escaped = true; - code = out; - } - } - - if (!lang) { - return '
'
-      + (escaped ? code : escape(code, true))
-      + '\n
'; - } - - return '
'
-    + (escaped ? code : escape(code, true))
-    + '\n
\n'; -}; - -Renderer.prototype.blockquote = function(quote) { - return '
\n' + quote + '
\n'; -}; - -Renderer.prototype.html = function(html) { - return html; -}; - -Renderer.prototype.heading = function(text, level, raw) { - return '' - + text - + '\n'; -}; - -Renderer.prototype.hr = function() { - return this.options.xhtml ? '
\n' : '
\n'; -}; - -Renderer.prototype.list = function(body, ordered) { - var type = ordered ? 'ol' : 'ul'; - return '<' + type + '>\n' + body + '\n'; -}; - -Renderer.prototype.listitem = function(text) { - return '
  • ' + text + '
  • \n'; -}; - -Renderer.prototype.paragraph = function(text) { - return '

    ' + text + '

    \n'; -}; - -Renderer.prototype.table = function(header, body) { - return '\n' - + '\n' - + header - + '\n' - + '\n' - + body - + '\n' - + '
    \n'; -}; - -Renderer.prototype.tablerow = function(content) { - return '\n' + content + '\n'; -}; - -Renderer.prototype.tablecell = function(content, flags) { - var type = flags.header ? 'th' : 'td'; - var tag = flags.align - ? '<' + type + ' style="text-align:' + flags.align + '">' - : '<' + type + '>'; - return tag + content + '\n'; -}; - -// span level renderer -Renderer.prototype.strong = function(text) { - return '' + text + ''; -}; - -Renderer.prototype.em = function(text) { - return '' + text + ''; -}; - -Renderer.prototype.codespan = function(text) { - return '' + text + ''; -}; - -Renderer.prototype.br = function() { - return this.options.xhtml ? '
    ' : '
    '; -}; - -Renderer.prototype.del = function(text) { - return '' + text + ''; -}; - -Renderer.prototype.link = function(href, title, text) { - if (this.options.sanitize) { - try { - var prot = decodeURIComponent(unescape(href)) - .replace(/[^\w:]/g, '') - .toLowerCase(); - } catch (e) { - return ''; - } - if (prot.indexOf('javascript:') === 0) { - return ''; - } - } - var out = '
    '; - return out; -}; - -Renderer.prototype.image = function(href, title, text) { - var out = '' + text + '' : '>'; - return out; -}; - -/** - * Parsing & Compiling - */ - -function Parser(options) { - this.tokens = []; - this.token = null; - this.options = options || marked.defaults; - this.options.renderer = this.options.renderer || new Renderer; - this.renderer = this.options.renderer; - this.renderer.options = this.options; -} - -/** - * Static Parse Method - */ - -Parser.parse = function(src, options, renderer) { - var parser = new Parser(options, renderer); - return parser.parse(src); -}; - -/** - * Parse Loop - */ - -Parser.prototype.parse = function(src) { - this.inline = new InlineLexer(src.links, this.options, this.renderer); - this.tokens = src.reverse(); - - var out = ''; - while (this.next()) { - out += this.tok(); - } - - return out; -}; - -/** - * Next Token - */ - -Parser.prototype.next = function() { - return this.token = this.tokens.pop(); -}; - -/** - * Preview Next Token - */ - -Parser.prototype.peek = function() { - return this.tokens[this.tokens.length - 1] || 0; -}; - -/** - * Parse Text Tokens - */ - -Parser.prototype.parseText = function() { - var body = this.token.text; - - while (this.peek().type === 'text') { - body += '\n' + this.next().text; - } - - return this.inline.output(body); -}; - -/** - * Parse Current Token - */ - -Parser.prototype.tok = function() { - switch (this.token.type) { - case 'space': { - return ''; - } - case 'hr': { - return this.renderer.hr(); - } - case 'heading': { - return this.renderer.heading( - this.inline.output(this.token.text), - this.token.depth, - this.token.text); - } - case 'code': { - return this.renderer.code(this.token.text, - this.token.lang, - this.token.escaped); - } - case 'table': { - var header = '' - , body = '' - , i - , row - , cell - , flags - , j; - - // header - cell = ''; - for (i = 0; i < this.token.header.length; i++) { - flags = { header: true, align: this.token.align[i] }; - cell += this.renderer.tablecell( - this.inline.output(this.token.header[i]), - { header: true, align: this.token.align[i] } - ); - } - header += this.renderer.tablerow(cell); - - for (i = 0; i < this.token.cells.length; i++) { - row = this.token.cells[i]; - - cell = ''; - for (j = 0; j < row.length; j++) { - cell += this.renderer.tablecell( - this.inline.output(row[j]), - { header: false, align: this.token.align[j] } - ); - } - - body += this.renderer.tablerow(cell); - } - return this.renderer.table(header, body); - } - case 'blockquote_start': { - var body = ''; - - while (this.next().type !== 'blockquote_end') { - body += this.tok(); - } - - return this.renderer.blockquote(body); - } - case 'list_start': { - var body = '' - , ordered = this.token.ordered; - - while (this.next().type !== 'list_end') { - body += this.tok(); - } - - return this.renderer.list(body, ordered); - } - case 'list_item_start': { - var body = ''; - - while (this.next().type !== 'list_item_end') { - body += this.token.type === 'text' - ? this.parseText() - : this.tok(); - } - - return this.renderer.listitem(body); - } - case 'loose_item_start': { - var body = ''; - - while (this.next().type !== 'list_item_end') { - body += this.tok(); - } - - return this.renderer.listitem(body); - } - case 'html': { - var html = !this.token.pre && !this.options.pedantic - ? this.inline.output(this.token.text) - : this.token.text; - return this.renderer.html(html); - } - case 'paragraph': { - return this.renderer.paragraph(this.inline.output(this.token.text)); - } - case 'text': { - return this.renderer.paragraph(this.parseText()); - } - } -}; - -/** - * Helpers - */ - -function escape(html, encode) { - return html - .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} - -function unescape(html) { - return html.replace(/&([#\w]+);/g, function(_, n) { - n = n.toLowerCase(); - if (n === 'colon') return ':'; - if (n.charAt(0) === '#') { - return n.charAt(1) === 'x' - ? String.fromCharCode(parseInt(n.substring(2), 16)) - : String.fromCharCode(+n.substring(1)); - } - return ''; - }); -} - -function replace(regex, opt) { - regex = regex.source; - opt = opt || ''; - return function self(name, val) { - if (!name) return new RegExp(regex, opt); - val = val.source || val; - val = val.replace(/(^|[^\[])\^/g, '$1'); - regex = regex.replace(name, val); - return self; - }; -} - -function noop() {} -noop.exec = noop; - -function merge(obj) { - var i = 1 - , target - , key; - - for (; i < arguments.length; i++) { - target = arguments[i]; - for (key in target) { - if (Object.prototype.hasOwnProperty.call(target, key)) { - obj[key] = target[key]; - } - } - } - - return obj; -} - - -/** - * Marked - */ - -function marked(src, opt, callback) { - if (callback || typeof opt === 'function') { - if (!callback) { - callback = opt; - opt = null; - } - - opt = merge({}, marked.defaults, opt || {}); - - var highlight = opt.highlight - , tokens - , pending - , i = 0; - - try { - tokens = Lexer.lex(src, opt) - } catch (e) { - return callback(e); - } - - pending = tokens.length; - - var done = function(err) { - if (err) { - opt.highlight = highlight; - return callback(err); - } - - var out; - - try { - out = Parser.parse(tokens, opt); - } catch (e) { - err = e; - } - - opt.highlight = highlight; - - return err - ? callback(err) - : callback(null, out); - }; - - if (!highlight || highlight.length < 3) { - return done(); - } - - delete opt.highlight; - - if (!pending) return done(); - - for (; i < tokens.length; i++) { - (function(token) { - if (token.type !== 'code') { - return --pending || done(); - } - return highlight(token.text, token.lang, function(err, code) { - if (err) return done(err); - if (code == null || code === token.text) { - return --pending || done(); - } - token.text = code; - token.escaped = true; - --pending || done(); - }); - })(tokens[i]); - } - - return; - } - try { - if (opt) opt = merge({}, marked.defaults, opt); - return Parser.parse(Lexer.lex(src, opt), opt); - } catch (e) { - e.message += '\nPlease report this to https://github.com/chjj/marked.'; - if ((opt || marked.defaults).silent) { - return '

    An error occured:

    '
    -        + escape(e.message + '', true)
    -        + '
    '; - } - throw e; - } -} - -/** - * Options - */ - -marked.options = -marked.setOptions = function(opt) { - merge(marked.defaults, opt); - return marked; -}; - -marked.defaults = { - gfm: true, - tables: true, - breaks: false, - pedantic: false, - sanitize: false, - smartLists: false, - silent: false, - highlight: null, - langPrefix: 'lang-', - smartypants: false, - headerPrefix: '', - renderer: new Renderer, - xhtml: false -}; - -/** - * Expose - */ - -marked.Parser = Parser; -marked.parser = Parser.parse; - -marked.Renderer = Renderer; - -marked.Lexer = Lexer; -marked.lexer = Lexer.lex; - -marked.InlineLexer = InlineLexer; -marked.inlineLexer = InlineLexer.output; - -marked.parse = marked; - -if (typeof module !== 'undefined' && typeof exports === 'object') { - module.exports = marked; -} else if (typeof define === 'function' && define.amd) { - define(function() { return marked; }); -} else { - this.marked = marked; -} - -}).call(function() { - return this || (typeof window !== 'undefined' ? window : global); +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +;(function() { + +/** + * Block-Level Grammar + */ + +var block = { + newline: /^\n+/, + code: /^( {4}[^\n]+\n*)+/, + fences: noop, + hr: /^( *[-*_]){3,} *(?:\n+|$)/, + heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, + nptable: noop, + lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, + blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, + list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, + html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, + def: /^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, + table: noop, + paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, + text: /^[^\n]+/ +}; + +block.bullet = /(?:[*+-]|\d+\.)/; +block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; +block.item = replace(block.item, 'gm') + (/bull/g, block.bullet) + (); + +block.list = replace(block.list) + (/bull/g, block.bullet) + ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') + ('def', '\\n+(?=' + block.def.source + ')') + (); + +block.blockquote = replace(block.blockquote) + ('def', block.def) + (); + +block._tag = '(?!(?:' + + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; + +block.html = replace(block.html) + ('comment', //) + ('closed', /<(tag)[\s\S]+?<\/\1>/) + ('closing', /])*?>/) + (/tag/g, block._tag) + (); + +block.paragraph = replace(block.paragraph) + ('hr', block.hr) + ('heading', block.heading) + ('lheading', block.lheading) + ('blockquote', block.blockquote) + ('tag', '<' + block._tag) + ('def', block.def) + (); + +/** + * Normal Block Grammar + */ + +block.normal = merge({}, block); + +/** + * GFM Block Grammar + */ + +block.gfm = merge({}, block.normal, { + fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/, + paragraph: /^/ +}); + +block.gfm.paragraph = replace(block.paragraph) + ('(?!', '(?!' + + block.gfm.fences.source.replace('\\1', '\\2') + '|' + + block.list.source.replace('\\1', '\\3') + '|') + (); + +/** + * GFM + Tables Block Grammar + */ + +block.tables = merge({}, block.gfm, { + nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, + table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ +}); + +/** + * Block Lexer + */ + +function Lexer(options) { + this.tokens = []; + this.tokens.links = {}; + this.options = options || marked.defaults; + this.rules = block.normal; + + if (this.options.gfm) { + if (this.options.tables) { + this.rules = block.tables; + } else { + this.rules = block.gfm; + } + } +} + +/** + * Expose Block Rules + */ + +Lexer.rules = block; + +/** + * Static Lex Method + */ + +Lexer.lex = function(src, options) { + var lexer = new Lexer(options); + return lexer.lex(src); +}; + +/** + * Preprocessing + */ + +Lexer.prototype.lex = function(src) { + src = src + .replace(/\r\n|\r/g, '\n') + .replace(/\t/g, ' ') + .replace(/\u00a0/g, ' ') + .replace(/\u2424/g, '\n'); + + return this.token(src, true); +}; + +/** + * Lexing + */ + +Lexer.prototype.token = function(src, top, bq) { + var src = src.replace(/^ +$/gm, '') + , next + , loose + , cap + , bull + , b + , item + , space + , i + , l; + + while (src) { + // newline + if (cap = this.rules.newline.exec(src)) { + src = src.substring(cap[0].length); + if (cap[0].length > 1) { + this.tokens.push({ + type: 'space' + }); + } + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + cap = cap[0].replace(/^ {4}/gm, ''); + this.tokens.push({ + type: 'code', + text: !this.options.pedantic + ? cap.replace(/\n+$/, '') + : cap + }); + continue; + } + + // fences (gfm) + if (cap = this.rules.fences.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'code', + lang: cap[2], + text: cap[3] + }); + continue; + } + + // heading + if (cap = this.rules.heading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[1].length, + text: cap[2] + }); + continue; + } + + // table no leading pipe (gfm) + if (top && (cap = this.rules.nptable.exec(src))) { + src = src.substring(cap[0].length); + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/\n$/, '').split('\n') + }; + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i].split(/ *\| */); + } + + this.tokens.push(item); + + continue; + } + + // lheading + if (cap = this.rules.lheading.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'heading', + depth: cap[2] === '=' ? 1 : 2, + text: cap[1] + }); + continue; + } + + // hr + if (cap = this.rules.hr.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'hr' + }); + continue; + } + + // blockquote + if (cap = this.rules.blockquote.exec(src)) { + src = src.substring(cap[0].length); + + this.tokens.push({ + type: 'blockquote_start' + }); + + cap = cap[0].replace(/^ *> ?/gm, ''); + + // Pass `top` to keep the current + // "toplevel" state. This is exactly + // how markdown.pl works. + this.token(cap, top, true); + + this.tokens.push({ + type: 'blockquote_end' + }); + + continue; + } + + // list + if (cap = this.rules.list.exec(src)) { + src = src.substring(cap[0].length); + bull = cap[2]; + + this.tokens.push({ + type: 'list_start', + ordered: bull.length > 1 + }); + + // Get each top-level item. + cap = cap[0].match(this.rules.item); + + next = false; + l = cap.length; + i = 0; + + for (; i < l; i++) { + item = cap[i]; + + // Remove the list item's bullet + // so it is seen as the next token. + space = item.length; + item = item.replace(/^ *([*+-]|\d+\.) +/, ''); + + // Outdent whatever the + // list item contains. Hacky. + if (~item.indexOf('\n ')) { + space -= item.length; + item = !this.options.pedantic + ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') + : item.replace(/^ {1,4}/gm, ''); + } + + // Determine whether the next list item belongs here. + // Backpedal if it does not belong in this list. + if (this.options.smartLists && i !== l - 1) { + b = block.bullet.exec(cap[i + 1])[0]; + if (bull !== b && !(bull.length > 1 && b.length > 1)) { + src = cap.slice(i + 1).join('\n') + src; + i = l - 1; + } + } + + // Determine whether item is loose or not. + // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ + // for discount behavior. + loose = next || /\n\n(?!\s*$)/.test(item); + if (i !== l - 1) { + next = item.charAt(item.length - 1) === '\n'; + if (!loose) loose = next; + } + + this.tokens.push({ + type: loose + ? 'loose_item_start' + : 'list_item_start' + }); + + // Recurse. + this.token(item, false, bq); + + this.tokens.push({ + type: 'list_item_end' + }); + } + + this.tokens.push({ + type: 'list_end' + }); + + continue; + } + + // html + if (cap = this.rules.html.exec(src)) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: this.options.sanitize + ? 'paragraph' + : 'html', + pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style', + text: cap[0] + }); + continue; + } + + // def + if ((!bq && top) && (cap = this.rules.def.exec(src))) { + src = src.substring(cap[0].length); + this.tokens.links[cap[1].toLowerCase()] = { + href: cap[2], + title: cap[3] + }; + continue; + } + + // table (gfm) + if (top && (cap = this.rules.table.exec(src))) { + src = src.substring(cap[0].length); + + item = { + type: 'table', + header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), + align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), + cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') + }; + + for (i = 0; i < item.align.length; i++) { + if (/^ *-+: *$/.test(item.align[i])) { + item.align[i] = 'right'; + } else if (/^ *:-+: *$/.test(item.align[i])) { + item.align[i] = 'center'; + } else if (/^ *:-+ *$/.test(item.align[i])) { + item.align[i] = 'left'; + } else { + item.align[i] = null; + } + } + + for (i = 0; i < item.cells.length; i++) { + item.cells[i] = item.cells[i] + .replace(/^ *\| *| *\| *$/g, '') + .split(/ *\| */); + } + + this.tokens.push(item); + + continue; + } + + // top-level paragraph + if (top && (cap = this.rules.paragraph.exec(src))) { + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'paragraph', + text: cap[1].charAt(cap[1].length - 1) === '\n' + ? cap[1].slice(0, -1) + : cap[1] + }); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + // Top-level should never reach here. + src = src.substring(cap[0].length); + this.tokens.push({ + type: 'text', + text: cap[0] + }); + continue; + } + + if (src) { + throw new + Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return this.tokens; +}; + +/** + * Inline-Level Grammar + */ + +var inline = { + escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, + autolink: /^<([^ >]+(@|:\/)[^ >]+)>/, + url: noop, + tag: /^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/, + link: /^!?\[(inside)\]\(href\)/, + reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, + nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, + strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, + em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, + code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/, + br: /^ {2,}\n(?!\s*$)/, + del: noop, + text: /^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/; + +inline.link = replace(inline.link) + ('inside', inline._inside) + ('href', inline._href) + (); + +inline.reflink = replace(inline.reflink) + ('inside', inline._inside) + (); + +/** + * Normal Inline Grammar + */ + +inline.normal = merge({}, inline); + +/** + * Pedantic Inline Grammar + */ + +inline.pedantic = merge({}, inline.normal, { + strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, + em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ +}); + +/** + * GFM Inline Grammar + */ + +inline.gfm = merge({}, inline.normal, { + escape: replace(inline.escape)('])', '~|])')(), + url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, + del: /^~~(?=\S)([\s\S]*?\S)~~/, + text: replace(inline.text) + (']|', '~]|') + ('|', '|https?://|') + () +}); + +/** + * GFM + Line Breaks Inline Grammar + */ + +inline.breaks = merge({}, inline.gfm, { + br: replace(inline.br)('{2,}', '*')(), + text: replace(inline.gfm.text)('{2,}', '*')() +}); + +/** + * Inline Lexer & Compiler + */ + +function InlineLexer(links, options) { + this.options = options || marked.defaults; + this.links = links; + this.rules = inline.normal; + this.renderer = this.options.renderer || new Renderer; + this.renderer.options = this.options; + + if (!this.links) { + throw new + Error('Tokens array requires a `links` property.'); + } + + if (this.options.gfm) { + if (this.options.breaks) { + this.rules = inline.breaks; + } else { + this.rules = inline.gfm; + } + } else if (this.options.pedantic) { + this.rules = inline.pedantic; + } +} + +/** + * Expose Inline Rules + */ + +InlineLexer.rules = inline; + +/** + * Static Lexing/Compiling Method + */ + +InlineLexer.output = function(src, links, options) { + var inline = new InlineLexer(links, options); + return inline.output(src); +}; + +/** + * Lexing/Compiling + */ + +InlineLexer.prototype.output = function(src) { + var out = '' + , link + , text + , href + , cap; + + while (src) { + // escape + if (cap = this.rules.escape.exec(src)) { + src = src.substring(cap[0].length); + out += cap[1]; + continue; + } + + // autolink + if (cap = this.rules.autolink.exec(src)) { + src = src.substring(cap[0].length); + if (cap[2] === '@') { + text = cap[1].charAt(6) === ':' + ? this.mangle(cap[1].substring(7)) + : this.mangle(cap[1]); + href = this.mangle('mailto:') + text; + } else { + text = escape(cap[1]); + href = text; + } + out += this.renderer.link(href, null, text); + continue; + } + + // url (gfm) + if (!this.inLink && (cap = this.rules.url.exec(src))) { + src = src.substring(cap[0].length); + text = escape(cap[1]); + href = text; + out += this.renderer.link(href, null, text); + continue; + } + + // tag + if (cap = this.rules.tag.exec(src)) { + if (!this.inLink && /^
    /i.test(cap[0])) { + this.inLink = false; + } + src = src.substring(cap[0].length); + out += this.options.sanitize + ? escape(cap[0]) + : cap[0]; + continue; + } + + // link + if (cap = this.rules.link.exec(src)) { + src = src.substring(cap[0].length); + this.inLink = true; + out += this.outputLink(cap, { + href: cap[2], + title: cap[3] + }); + this.inLink = false; + continue; + } + + // reflink, nolink + if ((cap = this.rules.reflink.exec(src)) + || (cap = this.rules.nolink.exec(src))) { + src = src.substring(cap[0].length); + link = (cap[2] || cap[1]).replace(/\s+/g, ' '); + link = this.links[link.toLowerCase()]; + if (!link || !link.href) { + out += cap[0].charAt(0); + src = cap[0].substring(1) + src; + continue; + } + this.inLink = true; + out += this.outputLink(cap, link); + this.inLink = false; + continue; + } + + // strong + if (cap = this.rules.strong.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.strong(this.output(cap[2] || cap[1])); + continue; + } + + // em + if (cap = this.rules.em.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.em(this.output(cap[2] || cap[1])); + continue; + } + + // code + if (cap = this.rules.code.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.codespan(escape(cap[2], true)); + continue; + } + + // br + if (cap = this.rules.br.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.br(); + continue; + } + + // del (gfm) + if (cap = this.rules.del.exec(src)) { + src = src.substring(cap[0].length); + out += this.renderer.del(this.output(cap[1])); + continue; + } + + // text + if (cap = this.rules.text.exec(src)) { + src = src.substring(cap[0].length); + out += escape(this.smartypants(cap[0])); + continue; + } + + if (src) { + throw new + Error('Infinite loop on byte: ' + src.charCodeAt(0)); + } + } + + return out; +}; + +/** + * Compile Link + */ + +InlineLexer.prototype.outputLink = function(cap, link) { + var href = escape(link.href) + , title = link.title ? escape(link.title) : null; + + return cap[0].charAt(0) !== '!' + ? this.renderer.link(href, title, this.output(cap[1])) + : this.renderer.image(href, title, escape(cap[1])); +}; + +/** + * Smartypants Transformations + */ + +InlineLexer.prototype.smartypants = function(text) { + if (!this.options.smartypants) return text; + return text + // em-dashes + .replace(/--/g, '\u2014') + // opening singles + .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') + // closing singles & apostrophes + .replace(/'/g, '\u2019') + // opening doubles + .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') + // closing doubles + .replace(/"/g, '\u201d') + // ellipses + .replace(/\.{3}/g, '\u2026'); +}; + +/** + * Mangle Links + */ + +InlineLexer.prototype.mangle = function(text) { + var out = '' + , l = text.length + , i = 0 + , ch; + + for (; i < l; i++) { + ch = text.charCodeAt(i); + if (Math.random() > 0.5) { + ch = 'x' + ch.toString(16); + } + out += '&#' + ch + ';'; + } + + return out; +}; + +/** + * Renderer + */ + +function Renderer(options) { + this.options = options || {}; +} + +Renderer.prototype.code = function(code, lang, escaped) { + if (this.options.highlight) { + var out = this.options.highlight(code, lang); + if (out != null && out !== code) { + escaped = true; + code = out; + } + } + + if (!lang) { + return '
    '
    +      + (escaped ? code : escape(code, true))
    +      + '\n
    '; + } + + return '
    '
    +    + (escaped ? code : escape(code, true))
    +    + '\n
    \n'; +}; + +Renderer.prototype.blockquote = function(quote) { + return '
    \n' + quote + '
    \n'; +}; + +Renderer.prototype.html = function(html) { + return html; +}; + +Renderer.prototype.heading = function(text, level, raw) { + return '' + + text + + '\n'; +}; + +Renderer.prototype.hr = function() { + return this.options.xhtml ? '
    \n' : '
    \n'; +}; + +Renderer.prototype.list = function(body, ordered) { + var type = ordered ? 'ol' : 'ul'; + return '<' + type + '>\n' + body + '\n'; +}; + +Renderer.prototype.listitem = function(text) { + return '
  • ' + text + '
  • \n'; +}; + +Renderer.prototype.paragraph = function(text) { + return '

    ' + text + '

    \n'; +}; + +Renderer.prototype.table = function(header, body) { + return '\n' + + '\n' + + header + + '\n' + + '\n' + + body + + '\n' + + '
    \n'; +}; + +Renderer.prototype.tablerow = function(content) { + return '\n' + content + '\n'; +}; + +Renderer.prototype.tablecell = function(content, flags) { + var type = flags.header ? 'th' : 'td'; + var tag = flags.align + ? '<' + type + ' style="text-align:' + flags.align + '">' + : '<' + type + '>'; + return tag + content + '\n'; +}; + +// span level renderer +Renderer.prototype.strong = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.em = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.codespan = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.br = function() { + return this.options.xhtml ? '
    ' : '
    '; +}; + +Renderer.prototype.del = function(text) { + return '' + text + ''; +}; + +Renderer.prototype.link = function(href, title, text) { + if (this.options.sanitize) { + try { + var prot = decodeURIComponent(unescape(href)) + .replace(/[^\w:]/g, '') + .toLowerCase(); + } catch (e) { + return ''; + } + if (prot.indexOf('javascript:') === 0) { + return ''; + } + } + var out = '
    '; + return out; +}; + +Renderer.prototype.image = function(href, title, text) { + var out = '' + text + '' : '>'; + return out; +}; + +/** + * Parsing & Compiling + */ + +function Parser(options) { + this.tokens = []; + this.token = null; + this.options = options || marked.defaults; + this.options.renderer = this.options.renderer || new Renderer; + this.renderer = this.options.renderer; + this.renderer.options = this.options; +} + +/** + * Static Parse Method + */ + +Parser.parse = function(src, options, renderer) { + var parser = new Parser(options, renderer); + return parser.parse(src); +}; + +/** + * Parse Loop + */ + +Parser.prototype.parse = function(src) { + this.inline = new InlineLexer(src.links, this.options, this.renderer); + this.tokens = src.reverse(); + + var out = ''; + while (this.next()) { + out += this.tok(); + } + + return out; +}; + +/** + * Next Token + */ + +Parser.prototype.next = function() { + return this.token = this.tokens.pop(); +}; + +/** + * Preview Next Token + */ + +Parser.prototype.peek = function() { + return this.tokens[this.tokens.length - 1] || 0; +}; + +/** + * Parse Text Tokens + */ + +Parser.prototype.parseText = function() { + var body = this.token.text; + + while (this.peek().type === 'text') { + body += '\n' + this.next().text; + } + + return this.inline.output(body); +}; + +/** + * Parse Current Token + */ + +Parser.prototype.tok = function() { + switch (this.token.type) { + case 'space': { + return ''; + } + case 'hr': { + return this.renderer.hr(); + } + case 'heading': { + return this.renderer.heading( + this.inline.output(this.token.text), + this.token.depth, + this.token.text); + } + case 'code': { + return this.renderer.code(this.token.text, + this.token.lang, + this.token.escaped); + } + case 'table': { + var header = '' + , body = '' + , i + , row + , cell + , flags + , j; + + // header + cell = ''; + for (i = 0; i < this.token.header.length; i++) { + flags = { header: true, align: this.token.align[i] }; + cell += this.renderer.tablecell( + this.inline.output(this.token.header[i]), + { header: true, align: this.token.align[i] } + ); + } + header += this.renderer.tablerow(cell); + + for (i = 0; i < this.token.cells.length; i++) { + row = this.token.cells[i]; + + cell = ''; + for (j = 0; j < row.length; j++) { + cell += this.renderer.tablecell( + this.inline.output(row[j]), + { header: false, align: this.token.align[j] } + ); + } + + body += this.renderer.tablerow(cell); + } + return this.renderer.table(header, body); + } + case 'blockquote_start': { + var body = ''; + + while (this.next().type !== 'blockquote_end') { + body += this.tok(); + } + + return this.renderer.blockquote(body); + } + case 'list_start': { + var body = '' + , ordered = this.token.ordered; + + while (this.next().type !== 'list_end') { + body += this.tok(); + } + + return this.renderer.list(body, ordered); + } + case 'list_item_start': { + var body = ''; + + while (this.next().type !== 'list_item_end') { + body += this.token.type === 'text' + ? this.parseText() + : this.tok(); + } + + return this.renderer.listitem(body); + } + case 'loose_item_start': { + var body = ''; + + while (this.next().type !== 'list_item_end') { + body += this.tok(); + } + + return this.renderer.listitem(body); + } + case 'html': { + var html = !this.token.pre && !this.options.pedantic + ? this.inline.output(this.token.text) + : this.token.text; + return this.renderer.html(html); + } + case 'paragraph': { + return this.renderer.paragraph(this.inline.output(this.token.text)); + } + case 'text': { + return this.renderer.paragraph(this.parseText()); + } + } +}; + +/** + * Helpers + */ + +function escape(html, encode) { + return html + .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function unescape(html) { + return html.replace(/&([#\w]+);/g, function(_, n) { + n = n.toLowerCase(); + if (n === 'colon') return ':'; + if (n.charAt(0) === '#') { + return n.charAt(1) === 'x' + ? String.fromCharCode(parseInt(n.substring(2), 16)) + : String.fromCharCode(+n.substring(1)); + } + return ''; + }); +} + +function replace(regex, opt) { + regex = regex.source; + opt = opt || ''; + return function self(name, val) { + if (!name) return new RegExp(regex, opt); + val = val.source || val; + val = val.replace(/(^|[^\[])\^/g, '$1'); + regex = regex.replace(name, val); + return self; + }; +} + +function noop() {} +noop.exec = noop; + +function merge(obj) { + var i = 1 + , target + , key; + + for (; i < arguments.length; i++) { + target = arguments[i]; + for (key in target) { + if (Object.prototype.hasOwnProperty.call(target, key)) { + obj[key] = target[key]; + } + } + } + + return obj; +} + + +/** + * Marked + */ + +function marked(src, opt, callback) { + if (callback || typeof opt === 'function') { + if (!callback) { + callback = opt; + opt = null; + } + + opt = merge({}, marked.defaults, opt || {}); + + var highlight = opt.highlight + , tokens + , pending + , i = 0; + + try { + tokens = Lexer.lex(src, opt) + } catch (e) { + return callback(e); + } + + pending = tokens.length; + + var done = function(err) { + if (err) { + opt.highlight = highlight; + return callback(err); + } + + var out; + + try { + out = Parser.parse(tokens, opt); + } catch (e) { + err = e; + } + + opt.highlight = highlight; + + return err + ? callback(err) + : callback(null, out); + }; + + if (!highlight || highlight.length < 3) { + return done(); + } + + delete opt.highlight; + + if (!pending) return done(); + + for (; i < tokens.length; i++) { + (function(token) { + if (token.type !== 'code') { + return --pending || done(); + } + return highlight(token.text, token.lang, function(err, code) { + if (err) return done(err); + if (code == null || code === token.text) { + return --pending || done(); + } + token.text = code; + token.escaped = true; + --pending || done(); + }); + })(tokens[i]); + } + + return; + } + try { + if (opt) opt = merge({}, marked.defaults, opt); + return Parser.parse(Lexer.lex(src, opt), opt); + } catch (e) { + e.message += '\nPlease report this to https://github.com/chjj/marked.'; + if ((opt || marked.defaults).silent) { + return '

    An error occured:

    '
    +        + escape(e.message + '', true)
    +        + '
    '; + } + throw e; + } +} + +/** + * Options + */ + +marked.options = +marked.setOptions = function(opt) { + merge(marked.defaults, opt); + return marked; +}; + +marked.defaults = { + gfm: true, + tables: true, + breaks: false, + pedantic: false, + sanitize: false, + smartLists: false, + silent: false, + highlight: null, + langPrefix: 'lang-', + smartypants: false, + headerPrefix: '', + renderer: new Renderer, + xhtml: false +}; + +/** + * Expose + */ + +marked.Parser = Parser; +marked.parser = Parser.parse; + +marked.Renderer = Renderer; + +marked.Lexer = Lexer; +marked.lexer = Lexer.lex; + +marked.InlineLexer = InlineLexer; +marked.inlineLexer = InlineLexer.output; + +marked.parse = marked; + +if (typeof module !== 'undefined' && typeof exports === 'object') { + module.exports = marked; +} else if (typeof define === 'function' && define.amd) { + define(function() { return marked; }); +} else { + this.marked = marked; +} + +}).call(function() { + return this || (typeof window !== 'undefined' ? window : global); }()); \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred.bundle.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred.bundle.js index 8e77b680..4bbad0f5 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred.bundle.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred.bundle.js @@ -1,2780 +1,2780 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -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"); - +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +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/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred/content.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred/content.js index f4e1b09f..465b3ceb 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred/content.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/shred/content.js @@ -1,207 +1,207 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// 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."); - } -} +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// 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/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-client.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-client.js index 08c88e98..510464ce 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-client.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-client.js @@ -1,3309 +1,3309 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * 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; +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * 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/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-oauth.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-oauth.js index 4027bd4b..26d99d5e 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-oauth.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/swagger-oauth.js @@ -1,294 +1,294 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var appName; -var popupMask; -var popupDialog; -var clientId; -var realm; -var oauth2KeyName; -var redirect_uri; - -function handleLogin() { - var scopes = []; - - var auths = window.swaggerUi.api.authSchemes || window.swaggerUi.api.securityDefinitions; - if(auths) { - var key; - var defs = auths; - for(key in defs) { - var auth = defs[key]; - if(auth.type === 'oauth2' && auth.scopes) { - oauth2KeyName = key; - var scope; - if(Array.isArray(auth.scopes)) { - // 1.2 support - var i; - for(i = 0; i < auth.scopes.length; i++) { - scopes.push(auth.scopes[i]); - } - } - else { - // 2.0 support - for(scope in auth.scopes) { - scopes.push({scope: scope, description: auth.scopes[scope]}); - } - } - } - } - } - - if(window.swaggerUi.api - && window.swaggerUi.api.info) { - appName = window.swaggerUi.api.info.title; - } - - popupDialog = $( - [ - '
    ', - '
    Select OAuth2.0 Scopes
    ', - '
    ', - '

    Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.', - 'Learn how to use', - '

    ', - '

    ' + appName + ' API requires the following scopes. Select which ones you want to grant to Swagger UI.

    ', - '
      ', - '
    ', - '

    ', - '
    ', - '
    ', - '
    '].join('')); - $(document.body).append(popupDialog); - - popup = popupDialog.find('ul.api-popup-scopes').empty(); - for (i = 0; i < scopes.length; i ++) { - scope = scopes[i]; - str = '
  • ' + '
  • '; - popup.append(str); - } - - var $win = $(window), - dw = $win.width(), - dh = $win.height(), - st = $win.scrollTop(), - dlgWd = popupDialog.outerWidth(), - dlgHt = popupDialog.outerHeight(), - top = (dh -dlgHt)/2 + st, - left = (dw - dlgWd)/2; - - popupDialog.css({ - top: (top < 0? 0 : top) + 'px', - left: (left < 0? 0 : left) + 'px' - }); - - popupDialog.find('button.api-popup-cancel').click(function() { - popupMask.hide(); - popupDialog.hide(); - popupDialog.empty(); - popupDialog = []; - }); - - $('button.api-popup-authbtn').unbind(); - popupDialog.find('button.api-popup-authbtn').click(function() { - popupMask.hide(); - popupDialog.hide(); - - 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 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); - } - else if(authSchemes[key].grantTypes) { - // 1.2 support - var o = authSchemes[key].grantTypes; - for(var t in o) { - if(o.hasOwnProperty(t) && t === 'implicit') { - var dets = o[t]; - var ep = dets.loginEndpoint.url; - url = dets.loginEndpoint.url + '?response_type=token'; - window.swaggerUi.tokenName = dets.tokenName; - } - else if (o.hasOwnProperty(t) && t === 'accessCode') { - var dets = o[t]; - var ep = dets.tokenRequestEndpoint.url; - url = dets.tokenRequestEndpoint.url + '?response_type=code'; - window.swaggerUi.tokenName = dets.tokenName; - } - } - } - } - } - var scopes = [] - var o = $('.api-popup-scopes').find('input:checked'); - - for(k =0; k < o.length; k++) { - var scope = $(o[k]).attr('scope'); - - if (scopes.indexOf(scope) === -1) - scopes.push(scope); - } - - window.enabledScopes=scopes; - - redirect_uri = redirectUrl; - - url += '&redirect_uri=' + encodeURIComponent(redirectUrl); - url += '&realm=' + encodeURIComponent(realm); - url += '&client_id=' + encodeURIComponent(clientId); - url += '&scope=' + encodeURIComponent(scopes); - - window.open(url); - }); - - popupMask.show(); - popupDialog.show(); - return; -} - - -function handleLogout() { - for(key in window.authorizations.authz){ - window.authorizations.remove(key) - } - window.enabledScopes = null; - $('.api-ic.ic-on').addClass('ic-off'); - $('.api-ic.ic-on').removeClass('ic-on'); - - // set the info box - $('.api-ic.ic-warning').addClass('ic-error'); - $('.api-ic.ic-warning').removeClass('ic-warning'); -} - -function initOAuth(opts) { - var o = (opts||{}); - var errors = []; - - appName = (o.appName||errors.push('missing appName')); - popupMask = (o.popupMask||$('#api-common-mask')); - popupDialog = (o.popupDialog||$('.api-popup-dialog')); - clientId = (o.clientId||errors.push('missing client id')); - realm = (o.realm||errors.push('missing realm')); - - if(errors.length > 0){ - log('auth unable initialize oauth: ' + errors); - return; - } - - $('pre code').each(function(i, e) {hljs.highlightBlock(e)}); - $('.api-ic').unbind(); - $('.api-ic').click(function(s) { - if($(s.target).hasClass('ic-off')) - handleLogin(); - else { - handleLogout(); - } - false; - }); -} - -function processOAuthCode(data) { - var params = { - 'client_id': clientId, - 'code': data.code, - 'grant_type': 'authorization_code', - 'redirect_uri': redirect_uri - } - $.ajax( - { - url : window.swaggerUi.tokenUrl, - type: "POST", - data: params, - success:function(data, textStatus, jqXHR) - { - onOAuthComplete(data); - }, - error: function(jqXHR, textStatus, errorThrown) - { - onOAuthComplete(""); - } - }); -} - -function onOAuthComplete(token) { - if(token) { - if(token.error) { - var checkbox = $('input[type=checkbox],.secured') - checkbox.each(function(pos){ - checkbox[pos].checked = false; - }); - alert(token.error); - } - else { - var b = token[window.swaggerUi.tokenName]; - if(b){ - // if all roles are satisfied - var o = null; - $.each($('.auth #api_information_panel'), function(k, v) { - var children = v; - if(children && children.childNodes) { - var requiredScopes = []; - $.each((children.childNodes), function (k1, v1){ - var inner = v1.innerHTML; - if(inner) - requiredScopes.push(inner); - }); - var diff = []; - for(var i=0; i < requiredScopes.length; i++) { - var s = requiredScopes[i]; - if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) { - diff.push(s); - } - } - if(diff.length > 0){ - o = v.parentNode; - $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off'); - $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on'); - - // sorry, not all scopes are satisfied - $(o).find('.api-ic').addClass('ic-warning'); - $(o).find('.api-ic').removeClass('ic-error'); - } - else { - o = v.parentNode; - $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on'); - $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off'); - - // 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'); - } - } - }); - window.authorizations.add(oauth2KeyName, new ApiKeyAuthorization('Authorization', 'Bearer ' + b, 'header')); - } - } - } +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var appName; +var popupMask; +var popupDialog; +var clientId; +var realm; +var oauth2KeyName; +var redirect_uri; + +function handleLogin() { + var scopes = []; + + var auths = window.swaggerUi.api.authSchemes || window.swaggerUi.api.securityDefinitions; + if(auths) { + var key; + var defs = auths; + for(key in defs) { + var auth = defs[key]; + if(auth.type === 'oauth2' && auth.scopes) { + oauth2KeyName = key; + var scope; + if(Array.isArray(auth.scopes)) { + // 1.2 support + var i; + for(i = 0; i < auth.scopes.length; i++) { + scopes.push(auth.scopes[i]); + } + } + else { + // 2.0 support + for(scope in auth.scopes) { + scopes.push({scope: scope, description: auth.scopes[scope]}); + } + } + } + } + } + + if(window.swaggerUi.api + && window.swaggerUi.api.info) { + appName = window.swaggerUi.api.info.title; + } + + popupDialog = $( + [ + '
    ', + '
    Select OAuth2.0 Scopes
    ', + '
    ', + '

    Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes.', + 'Learn how to use', + '

    ', + '

    ' + appName + ' API requires the following scopes. Select which ones you want to grant to Swagger UI.

    ', + '
      ', + '
    ', + '

    ', + '
    ', + '
    ', + '
    '].join('')); + $(document.body).append(popupDialog); + + popup = popupDialog.find('ul.api-popup-scopes').empty(); + for (i = 0; i < scopes.length; i ++) { + scope = scopes[i]; + str = '
  • ' + '
  • '; + popup.append(str); + } + + var $win = $(window), + dw = $win.width(), + dh = $win.height(), + st = $win.scrollTop(), + dlgWd = popupDialog.outerWidth(), + dlgHt = popupDialog.outerHeight(), + top = (dh -dlgHt)/2 + st, + left = (dw - dlgWd)/2; + + popupDialog.css({ + top: (top < 0? 0 : top) + 'px', + left: (left < 0? 0 : left) + 'px' + }); + + popupDialog.find('button.api-popup-cancel').click(function() { + popupMask.hide(); + popupDialog.hide(); + popupDialog.empty(); + popupDialog = []; + }); + + $('button.api-popup-authbtn').unbind(); + popupDialog.find('button.api-popup-authbtn').click(function() { + popupMask.hide(); + popupDialog.hide(); + + 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 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); + } + else if(authSchemes[key].grantTypes) { + // 1.2 support + var o = authSchemes[key].grantTypes; + for(var t in o) { + if(o.hasOwnProperty(t) && t === 'implicit') { + var dets = o[t]; + var ep = dets.loginEndpoint.url; + url = dets.loginEndpoint.url + '?response_type=token'; + window.swaggerUi.tokenName = dets.tokenName; + } + else if (o.hasOwnProperty(t) && t === 'accessCode') { + var dets = o[t]; + var ep = dets.tokenRequestEndpoint.url; + url = dets.tokenRequestEndpoint.url + '?response_type=code'; + window.swaggerUi.tokenName = dets.tokenName; + } + } + } + } + } + var scopes = [] + var o = $('.api-popup-scopes').find('input:checked'); + + for(k =0; k < o.length; k++) { + var scope = $(o[k]).attr('scope'); + + if (scopes.indexOf(scope) === -1) + scopes.push(scope); + } + + window.enabledScopes=scopes; + + redirect_uri = redirectUrl; + + url += '&redirect_uri=' + encodeURIComponent(redirectUrl); + url += '&realm=' + encodeURIComponent(realm); + url += '&client_id=' + encodeURIComponent(clientId); + url += '&scope=' + encodeURIComponent(scopes); + + window.open(url); + }); + + popupMask.show(); + popupDialog.show(); + return; +} + + +function handleLogout() { + for(key in window.authorizations.authz){ + window.authorizations.remove(key) + } + window.enabledScopes = null; + $('.api-ic.ic-on').addClass('ic-off'); + $('.api-ic.ic-on').removeClass('ic-on'); + + // set the info box + $('.api-ic.ic-warning').addClass('ic-error'); + $('.api-ic.ic-warning').removeClass('ic-warning'); +} + +function initOAuth(opts) { + var o = (opts||{}); + var errors = []; + + appName = (o.appName||errors.push('missing appName')); + popupMask = (o.popupMask||$('#api-common-mask')); + popupDialog = (o.popupDialog||$('.api-popup-dialog')); + clientId = (o.clientId||errors.push('missing client id')); + realm = (o.realm||errors.push('missing realm')); + + if(errors.length > 0){ + log('auth unable initialize oauth: ' + errors); + return; + } + + $('pre code').each(function(i, e) {hljs.highlightBlock(e)}); + $('.api-ic').unbind(); + $('.api-ic').click(function(s) { + if($(s.target).hasClass('ic-off')) + handleLogin(); + else { + handleLogout(); + } + false; + }); +} + +function processOAuthCode(data) { + var params = { + 'client_id': clientId, + 'code': data.code, + 'grant_type': 'authorization_code', + 'redirect_uri': redirect_uri + } + $.ajax( + { + url : window.swaggerUi.tokenUrl, + type: "POST", + data: params, + success:function(data, textStatus, jqXHR) + { + onOAuthComplete(data); + }, + error: function(jqXHR, textStatus, errorThrown) + { + onOAuthComplete(""); + } + }); +} + +function onOAuthComplete(token) { + if(token) { + if(token.error) { + var checkbox = $('input[type=checkbox],.secured') + checkbox.each(function(pos){ + checkbox[pos].checked = false; + }); + alert(token.error); + } + else { + var b = token[window.swaggerUi.tokenName]; + if(b){ + // if all roles are satisfied + var o = null; + $.each($('.auth #api_information_panel'), function(k, v) { + var children = v; + if(children && children.childNodes) { + var requiredScopes = []; + $.each((children.childNodes), function (k1, v1){ + var inner = v1.innerHTML; + if(inner) + requiredScopes.push(inner); + }); + var diff = []; + for(var i=0; i < requiredScopes.length; i++) { + var s = requiredScopes[i]; + if(window.enabledScopes && window.enabledScopes.indexOf(s) == -1) { + diff.push(s); + } + } + if(diff.length > 0){ + o = v.parentNode; + $(o.parentNode).find('.api-ic.ic-on').addClass('ic-off'); + $(o.parentNode).find('.api-ic.ic-on').removeClass('ic-on'); + + // sorry, not all scopes are satisfied + $(o).find('.api-ic').addClass('ic-warning'); + $(o).find('.api-ic').removeClass('ic-error'); + } + else { + o = v.parentNode; + $(o.parentNode).find('.api-ic.ic-off').addClass('ic-on'); + $(o.parentNode).find('.api-ic.ic-off').removeClass('ic-off'); + + // 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'); + } + } + }); + window.authorizations.add(oauth2KeyName, new ApiKeyAuthorization('Authorization', 'Bearer ' + b, 'header')); + } + } + } } \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/underscore-min.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/underscore-min.js index a71ff084..d39231c5 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/underscore-min.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/lib/underscore-min.js @@ -1,21 +1,21 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Underscore.js 1.7.0 -// http://underscorejs.org -// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors -// Underscore may be freely distributed under the MIT license. -(function(){var n=this,t=n._,r=Array.prototype,e=Object.prototype,u=Function.prototype,i=r.push,a=r.slice,o=r.concat,l=e.toString,c=e.hasOwnProperty,f=Array.isArray,s=Object.keys,p=u.bind,h=function(n){return n instanceof h?n:this instanceof h?void(this._wrapped=n):new h(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=h),exports._=h):n._=h,h.VERSION="1.7.0";var g=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}};h.iteratee=function(n,t,r){return null==n?h.identity:h.isFunction(n)?g(n,t,r):h.isObject(n)?h.matches(n):h.property(n)},h.each=h.forEach=function(n,t,r){if(null==n)return n;t=g(t,r);var e,u=n.length;if(u===+u)for(e=0;u>e;e++)t(n[e],e,n);else{var i=h.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},h.map=h.collect=function(n,t,r){if(null==n)return[];t=h.iteratee(t,r);for(var e,u=n.length!==+n.length&&h.keys(n),i=(u||n).length,a=Array(i),o=0;i>o;o++)e=u?u[o]:o,a[o]=t(n[e],e,n);return a};var v="Reduce of empty array with no initial value";h.reduce=h.foldl=h.inject=function(n,t,r,e){null==n&&(n=[]),t=g(t,e,4);var u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length,o=0;if(arguments.length<3){if(!a)throw new TypeError(v);r=n[i?i[o++]:o++]}for(;a>o;o++)u=i?i[o]:o,r=t(r,n[u],u,n);return r},h.reduceRight=h.foldr=function(n,t,r,e){null==n&&(n=[]),t=g(t,e,4);var u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;if(arguments.length<3){if(!a)throw new TypeError(v);r=n[i?i[--a]:--a]}for(;a--;)u=i?i[a]:a,r=t(r,n[u],u,n);return r},h.find=h.detect=function(n,t,r){var e;return t=h.iteratee(t,r),h.some(n,function(n,r,u){return t(n,r,u)?(e=n,!0):void 0}),e},h.filter=h.select=function(n,t,r){var e=[];return null==n?e:(t=h.iteratee(t,r),h.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e)},h.reject=function(n,t,r){return h.filter(n,h.negate(h.iteratee(t)),r)},h.every=h.all=function(n,t,r){if(null==n)return!0;t=h.iteratee(t,r);var e,u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;for(e=0;a>e;e++)if(u=i?i[e]:e,!t(n[u],u,n))return!1;return!0},h.some=h.any=function(n,t,r){if(null==n)return!1;t=h.iteratee(t,r);var e,u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;for(e=0;a>e;e++)if(u=i?i[e]:e,t(n[u],u,n))return!0;return!1},h.contains=h.include=function(n,t){return null==n?!1:(n.length!==+n.length&&(n=h.values(n)),h.indexOf(n,t)>=0)},h.invoke=function(n,t){var r=a.call(arguments,2),e=h.isFunction(t);return h.map(n,function(n){return(e?t:n[t]).apply(n,r)})},h.pluck=function(n,t){return h.map(n,h.property(t))},h.where=function(n,t){return h.filter(n,h.matches(t))},h.findWhere=function(n,t){return h.find(n,h.matches(t))},h.max=function(n,t,r){var e,u,i=-1/0,a=-1/0;if(null==t&&null!=n){n=n.length===+n.length?n:h.values(n);for(var o=0,l=n.length;l>o;o++)e=n[o],e>i&&(i=e)}else t=h.iteratee(t,r),h.each(n,function(n,r,e){u=t(n,r,e),(u>a||u===-1/0&&i===-1/0)&&(i=n,a=u)});return i},h.min=function(n,t,r){var e,u,i=1/0,a=1/0;if(null==t&&null!=n){n=n.length===+n.length?n:h.values(n);for(var o=0,l=n.length;l>o;o++)e=n[o],i>e&&(i=e)}else t=h.iteratee(t,r),h.each(n,function(n,r,e){u=t(n,r,e),(a>u||1/0===u&&1/0===i)&&(i=n,a=u)});return i},h.shuffle=function(n){for(var t,r=n&&n.length===+n.length?n:h.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=h.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},h.sample=function(n,t,r){return null==t||r?(n.length!==+n.length&&(n=h.values(n)),n[h.random(n.length-1)]):h.shuffle(n).slice(0,Math.max(0,t))},h.sortBy=function(n,t,r){return t=h.iteratee(t,r),h.pluck(h.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var m=function(n){return function(t,r,e){var u={};return r=h.iteratee(r,e),h.each(t,function(e,i){var a=r(e,i,t);n(u,e,a)}),u}};h.groupBy=m(function(n,t,r){h.has(n,r)?n[r].push(t):n[r]=[t]}),h.indexBy=m(function(n,t,r){n[r]=t}),h.countBy=m(function(n,t,r){h.has(n,r)?n[r]++:n[r]=1}),h.sortedIndex=function(n,t,r,e){r=h.iteratee(r,e,1);for(var u=r(t),i=0,a=n.length;a>i;){var o=i+a>>>1;r(n[o])t?[]:a.call(n,0,t)},h.initial=function(n,t,r){return a.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},h.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:a.call(n,Math.max(n.length-t,0))},h.rest=h.tail=h.drop=function(n,t,r){return a.call(n,null==t||r?1:t)},h.compact=function(n){return h.filter(n,h.identity)};var y=function(n,t,r,e){if(t&&h.every(n,h.isArray))return o.apply(e,n);for(var u=0,a=n.length;a>u;u++){var l=n[u];h.isArray(l)||h.isArguments(l)?t?i.apply(e,l):y(l,t,r,e):r||e.push(l)}return e};h.flatten=function(n,t){return y(n,t,!1,[])},h.without=function(n){return h.difference(n,a.call(arguments,1))},h.uniq=h.unique=function(n,t,r,e){if(null==n)return[];h.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=h.iteratee(r,e));for(var u=[],i=[],a=0,o=n.length;o>a;a++){var l=n[a];if(t)a&&i===l||u.push(l),i=l;else if(r){var c=r(l,a,n);h.indexOf(i,c)<0&&(i.push(c),u.push(l))}else h.indexOf(u,l)<0&&u.push(l)}return u},h.union=function(){return h.uniq(y(arguments,!0,!0,[]))},h.intersection=function(n){if(null==n)return[];for(var t=[],r=arguments.length,e=0,u=n.length;u>e;e++){var i=n[e];if(!h.contains(t,i)){for(var a=1;r>a&&h.contains(arguments[a],i);a++);a===r&&t.push(i)}}return t},h.difference=function(n){var t=y(a.call(arguments,1),!0,!0,[]);return h.filter(n,function(n){return!h.contains(t,n)})},h.zip=function(n){if(null==n)return[];for(var t=h.max(arguments,"length").length,r=Array(t),e=0;t>e;e++)r[e]=h.pluck(arguments,e);return r},h.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},h.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=h.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}for(;u>e;e++)if(n[e]===t)return e;return-1},h.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=n.length;for("number"==typeof r&&(e=0>r?e+r+1:Math.min(e,r+1));--e>=0;)if(n[e]===t)return e;return-1},h.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var d=function(){};h.bind=function(n,t){var r,e;if(p&&n.bind===p)return p.apply(n,a.call(arguments,1));if(!h.isFunction(n))throw new TypeError("Bind must be called on a function");return r=a.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(a.call(arguments)));d.prototype=n.prototype;var u=new d;d.prototype=null;var i=n.apply(u,r.concat(a.call(arguments)));return h.isObject(i)?i:u}},h.partial=function(n){var t=a.call(arguments,1);return function(){for(var r=0,e=t.slice(),u=0,i=e.length;i>u;u++)e[u]===h&&(e[u]=arguments[r++]);for(;r=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=h.bind(n[r],n);return n},h.memoize=function(n,t){var r=function(e){var u=r.cache,i=t?t.apply(this,arguments):e;return h.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},h.delay=function(n,t){var r=a.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},h.defer=function(n){return h.delay.apply(h,[n,1].concat(a.call(arguments,1)))},h.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var l=function(){o=r.leading===!1?0:h.now(),a=null,i=n.apply(e,u),a||(e=u=null)};return function(){var c=h.now();o||r.leading!==!1||(o=c);var f=t-(c-o);return e=this,u=arguments,0>=f||f>t?(clearTimeout(a),a=null,o=c,i=n.apply(e,u),a||(e=u=null)):a||r.trailing===!1||(a=setTimeout(l,f)),i}},h.debounce=function(n,t,r){var e,u,i,a,o,l=function(){var c=h.now()-a;t>c&&c>0?e=setTimeout(l,t-c):(e=null,r||(o=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,a=h.now();var c=r&&!e;return e||(e=setTimeout(l,t)),c&&(o=n.apply(i,u),i=u=null),o}},h.wrap=function(n,t){return h.partial(t,n)},h.negate=function(n){return function(){return!n.apply(this,arguments)}},h.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},h.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},h.before=function(n,t){var r;return function(){return--n>0?r=t.apply(this,arguments):t=null,r}},h.once=h.partial(h.before,2),h.keys=function(n){if(!h.isObject(n))return[];if(s)return s(n);var t=[];for(var r in n)h.has(n,r)&&t.push(r);return t},h.values=function(n){for(var t=h.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},h.pairs=function(n){for(var t=h.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},h.invert=function(n){for(var t={},r=h.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},h.functions=h.methods=function(n){var t=[];for(var r in n)h.isFunction(n[r])&&t.push(r);return t.sort()},h.extend=function(n){if(!h.isObject(n))return n;for(var t,r,e=1,u=arguments.length;u>e;e++){t=arguments[e];for(r in t)c.call(t,r)&&(n[r]=t[r])}return n},h.pick=function(n,t,r){var e,u={};if(null==n)return u;if(h.isFunction(t)){t=g(t,r);for(e in n){var i=n[e];t(i,e,n)&&(u[e]=i)}}else{var l=o.apply([],a.call(arguments,1));n=new Object(n);for(var c=0,f=l.length;f>c;c++)e=l[c],e in n&&(u[e]=n[e])}return u},h.omit=function(n,t,r){if(h.isFunction(t))t=h.negate(t);else{var e=h.map(o.apply([],a.call(arguments,1)),String);t=function(n,t){return!h.contains(e,t)}}return h.pick(n,t,r)},h.defaults=function(n){if(!h.isObject(n))return n;for(var t=1,r=arguments.length;r>t;t++){var e=arguments[t];for(var u in e)n[u]===void 0&&(n[u]=e[u])}return n},h.clone=function(n){return h.isObject(n)?h.isArray(n)?n.slice():h.extend({},n):n},h.tap=function(n,t){return t(n),n};var b=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof h&&(n=n._wrapped),t instanceof h&&(t=t._wrapped);var u=l.call(n);if(u!==l.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]===n)return e[i]===t;var a=n.constructor,o=t.constructor;if(a!==o&&"constructor"in n&&"constructor"in t&&!(h.isFunction(a)&&a instanceof a&&h.isFunction(o)&&o instanceof o))return!1;r.push(n),e.push(t);var c,f;if("[object Array]"===u){if(c=n.length,f=c===t.length)for(;c--&&(f=b(n[c],t[c],r,e)););}else{var s,p=h.keys(n);if(c=p.length,f=h.keys(t).length===c)for(;c--&&(s=p[c],f=h.has(t,s)&&b(n[s],t[s],r,e)););}return r.pop(),e.pop(),f};h.isEqual=function(n,t){return b(n,t,[],[])},h.isEmpty=function(n){if(null==n)return!0;if(h.isArray(n)||h.isString(n)||h.isArguments(n))return 0===n.length;for(var t in n)if(h.has(n,t))return!1;return!0},h.isElement=function(n){return!(!n||1!==n.nodeType)},h.isArray=f||function(n){return"[object Array]"===l.call(n)},h.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},h.each(["Arguments","Function","String","Number","Date","RegExp"],function(n){h["is"+n]=function(t){return l.call(t)==="[object "+n+"]"}}),h.isArguments(arguments)||(h.isArguments=function(n){return h.has(n,"callee")}),"function"!=typeof/./&&(h.isFunction=function(n){return"function"==typeof n||!1}),h.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},h.isNaN=function(n){return h.isNumber(n)&&n!==+n},h.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===l.call(n)},h.isNull=function(n){return null===n},h.isUndefined=function(n){return n===void 0},h.has=function(n,t){return null!=n&&c.call(n,t)},h.noConflict=function(){return n._=t,this},h.identity=function(n){return n},h.constant=function(n){return function(){return n}},h.noop=function(){},h.property=function(n){return function(t){return t[n]}},h.matches=function(n){var t=h.pairs(n),r=t.length;return function(n){if(null==n)return!r;n=new Object(n);for(var e=0;r>e;e++){var u=t[e],i=u[0];if(u[1]!==n[i]||!(i in n))return!1}return!0}},h.times=function(n,t,r){var e=Array(Math.max(0,n));t=g(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},h.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},h.now=Date.now||function(){return(new Date).getTime()};var _={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},w=h.invert(_),j=function(n){var t=function(t){return n[t]},r="(?:"+h.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};h.escape=j(_),h.unescape=j(w),h.result=function(n,t){if(null==n)return void 0;var r=n[t];return h.isFunction(r)?n[t]():r};var x=0;h.uniqueId=function(n){var t=++x+"";return n?n+t:t},h.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var A=/(.)^/,k={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},O=/\\|'|\r|\n|\u2028|\u2029/g,F=function(n){return"\\"+k[n]};h.template=function(n,t,r){!t&&r&&(t=r),t=h.defaults({},t,h.templateSettings);var e=RegExp([(t.escape||A).source,(t.interpolate||A).source,(t.evaluate||A).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,a,o){return i+=n.slice(u,o).replace(O,F),u=o+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":a&&(i+="';\n"+a+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var a=new Function(t.variable||"obj","_",i)}catch(o){throw o.source=i,o}var l=function(n){return a.call(this,n,h)},c=t.variable||"obj";return l.source="function("+c+"){\n"+i+"}",l},h.chain=function(n){var t=h(n);return t._chain=!0,t};var E=function(n){return this._chain?h(n).chain():n};h.mixin=function(n){h.each(h.functions(n),function(t){var r=h[t]=n[t];h.prototype[t]=function(){var n=[this._wrapped];return i.apply(n,arguments),E.call(this,r.apply(h,n))}})},h.mixin(h),h.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=r[n];h.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],E.call(this,r)}}),h.each(["concat","join","slice"],function(n){var t=r[n];h.prototype[n]=function(){return E.call(this,t.apply(this._wrapped,arguments))}}),h.prototype.value=function(){return this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return h})}).call(this); +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Underscore.js 1.7.0 +// http://underscorejs.org +// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. +(function(){var n=this,t=n._,r=Array.prototype,e=Object.prototype,u=Function.prototype,i=r.push,a=r.slice,o=r.concat,l=e.toString,c=e.hasOwnProperty,f=Array.isArray,s=Object.keys,p=u.bind,h=function(n){return n instanceof h?n:this instanceof h?void(this._wrapped=n):new h(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=h),exports._=h):n._=h,h.VERSION="1.7.0";var g=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}};h.iteratee=function(n,t,r){return null==n?h.identity:h.isFunction(n)?g(n,t,r):h.isObject(n)?h.matches(n):h.property(n)},h.each=h.forEach=function(n,t,r){if(null==n)return n;t=g(t,r);var e,u=n.length;if(u===+u)for(e=0;u>e;e++)t(n[e],e,n);else{var i=h.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},h.map=h.collect=function(n,t,r){if(null==n)return[];t=h.iteratee(t,r);for(var e,u=n.length!==+n.length&&h.keys(n),i=(u||n).length,a=Array(i),o=0;i>o;o++)e=u?u[o]:o,a[o]=t(n[e],e,n);return a};var v="Reduce of empty array with no initial value";h.reduce=h.foldl=h.inject=function(n,t,r,e){null==n&&(n=[]),t=g(t,e,4);var u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length,o=0;if(arguments.length<3){if(!a)throw new TypeError(v);r=n[i?i[o++]:o++]}for(;a>o;o++)u=i?i[o]:o,r=t(r,n[u],u,n);return r},h.reduceRight=h.foldr=function(n,t,r,e){null==n&&(n=[]),t=g(t,e,4);var u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;if(arguments.length<3){if(!a)throw new TypeError(v);r=n[i?i[--a]:--a]}for(;a--;)u=i?i[a]:a,r=t(r,n[u],u,n);return r},h.find=h.detect=function(n,t,r){var e;return t=h.iteratee(t,r),h.some(n,function(n,r,u){return t(n,r,u)?(e=n,!0):void 0}),e},h.filter=h.select=function(n,t,r){var e=[];return null==n?e:(t=h.iteratee(t,r),h.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e)},h.reject=function(n,t,r){return h.filter(n,h.negate(h.iteratee(t)),r)},h.every=h.all=function(n,t,r){if(null==n)return!0;t=h.iteratee(t,r);var e,u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;for(e=0;a>e;e++)if(u=i?i[e]:e,!t(n[u],u,n))return!1;return!0},h.some=h.any=function(n,t,r){if(null==n)return!1;t=h.iteratee(t,r);var e,u,i=n.length!==+n.length&&h.keys(n),a=(i||n).length;for(e=0;a>e;e++)if(u=i?i[e]:e,t(n[u],u,n))return!0;return!1},h.contains=h.include=function(n,t){return null==n?!1:(n.length!==+n.length&&(n=h.values(n)),h.indexOf(n,t)>=0)},h.invoke=function(n,t){var r=a.call(arguments,2),e=h.isFunction(t);return h.map(n,function(n){return(e?t:n[t]).apply(n,r)})},h.pluck=function(n,t){return h.map(n,h.property(t))},h.where=function(n,t){return h.filter(n,h.matches(t))},h.findWhere=function(n,t){return h.find(n,h.matches(t))},h.max=function(n,t,r){var e,u,i=-1/0,a=-1/0;if(null==t&&null!=n){n=n.length===+n.length?n:h.values(n);for(var o=0,l=n.length;l>o;o++)e=n[o],e>i&&(i=e)}else t=h.iteratee(t,r),h.each(n,function(n,r,e){u=t(n,r,e),(u>a||u===-1/0&&i===-1/0)&&(i=n,a=u)});return i},h.min=function(n,t,r){var e,u,i=1/0,a=1/0;if(null==t&&null!=n){n=n.length===+n.length?n:h.values(n);for(var o=0,l=n.length;l>o;o++)e=n[o],i>e&&(i=e)}else t=h.iteratee(t,r),h.each(n,function(n,r,e){u=t(n,r,e),(a>u||1/0===u&&1/0===i)&&(i=n,a=u)});return i},h.shuffle=function(n){for(var t,r=n&&n.length===+n.length?n:h.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=h.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},h.sample=function(n,t,r){return null==t||r?(n.length!==+n.length&&(n=h.values(n)),n[h.random(n.length-1)]):h.shuffle(n).slice(0,Math.max(0,t))},h.sortBy=function(n,t,r){return t=h.iteratee(t,r),h.pluck(h.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var m=function(n){return function(t,r,e){var u={};return r=h.iteratee(r,e),h.each(t,function(e,i){var a=r(e,i,t);n(u,e,a)}),u}};h.groupBy=m(function(n,t,r){h.has(n,r)?n[r].push(t):n[r]=[t]}),h.indexBy=m(function(n,t,r){n[r]=t}),h.countBy=m(function(n,t,r){h.has(n,r)?n[r]++:n[r]=1}),h.sortedIndex=function(n,t,r,e){r=h.iteratee(r,e,1);for(var u=r(t),i=0,a=n.length;a>i;){var o=i+a>>>1;r(n[o])t?[]:a.call(n,0,t)},h.initial=function(n,t,r){return a.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},h.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:a.call(n,Math.max(n.length-t,0))},h.rest=h.tail=h.drop=function(n,t,r){return a.call(n,null==t||r?1:t)},h.compact=function(n){return h.filter(n,h.identity)};var y=function(n,t,r,e){if(t&&h.every(n,h.isArray))return o.apply(e,n);for(var u=0,a=n.length;a>u;u++){var l=n[u];h.isArray(l)||h.isArguments(l)?t?i.apply(e,l):y(l,t,r,e):r||e.push(l)}return e};h.flatten=function(n,t){return y(n,t,!1,[])},h.without=function(n){return h.difference(n,a.call(arguments,1))},h.uniq=h.unique=function(n,t,r,e){if(null==n)return[];h.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=h.iteratee(r,e));for(var u=[],i=[],a=0,o=n.length;o>a;a++){var l=n[a];if(t)a&&i===l||u.push(l),i=l;else if(r){var c=r(l,a,n);h.indexOf(i,c)<0&&(i.push(c),u.push(l))}else h.indexOf(u,l)<0&&u.push(l)}return u},h.union=function(){return h.uniq(y(arguments,!0,!0,[]))},h.intersection=function(n){if(null==n)return[];for(var t=[],r=arguments.length,e=0,u=n.length;u>e;e++){var i=n[e];if(!h.contains(t,i)){for(var a=1;r>a&&h.contains(arguments[a],i);a++);a===r&&t.push(i)}}return t},h.difference=function(n){var t=y(a.call(arguments,1),!0,!0,[]);return h.filter(n,function(n){return!h.contains(t,n)})},h.zip=function(n){if(null==n)return[];for(var t=h.max(arguments,"length").length,r=Array(t),e=0;t>e;e++)r[e]=h.pluck(arguments,e);return r},h.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},h.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=h.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}for(;u>e;e++)if(n[e]===t)return e;return-1},h.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=n.length;for("number"==typeof r&&(e=0>r?e+r+1:Math.min(e,r+1));--e>=0;)if(n[e]===t)return e;return-1},h.range=function(n,t,r){arguments.length<=1&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var d=function(){};h.bind=function(n,t){var r,e;if(p&&n.bind===p)return p.apply(n,a.call(arguments,1));if(!h.isFunction(n))throw new TypeError("Bind must be called on a function");return r=a.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(a.call(arguments)));d.prototype=n.prototype;var u=new d;d.prototype=null;var i=n.apply(u,r.concat(a.call(arguments)));return h.isObject(i)?i:u}},h.partial=function(n){var t=a.call(arguments,1);return function(){for(var r=0,e=t.slice(),u=0,i=e.length;i>u;u++)e[u]===h&&(e[u]=arguments[r++]);for(;r=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=h.bind(n[r],n);return n},h.memoize=function(n,t){var r=function(e){var u=r.cache,i=t?t.apply(this,arguments):e;return h.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},h.delay=function(n,t){var r=a.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},h.defer=function(n){return h.delay.apply(h,[n,1].concat(a.call(arguments,1)))},h.throttle=function(n,t,r){var e,u,i,a=null,o=0;r||(r={});var l=function(){o=r.leading===!1?0:h.now(),a=null,i=n.apply(e,u),a||(e=u=null)};return function(){var c=h.now();o||r.leading!==!1||(o=c);var f=t-(c-o);return e=this,u=arguments,0>=f||f>t?(clearTimeout(a),a=null,o=c,i=n.apply(e,u),a||(e=u=null)):a||r.trailing===!1||(a=setTimeout(l,f)),i}},h.debounce=function(n,t,r){var e,u,i,a,o,l=function(){var c=h.now()-a;t>c&&c>0?e=setTimeout(l,t-c):(e=null,r||(o=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,a=h.now();var c=r&&!e;return e||(e=setTimeout(l,t)),c&&(o=n.apply(i,u),i=u=null),o}},h.wrap=function(n,t){return h.partial(t,n)},h.negate=function(n){return function(){return!n.apply(this,arguments)}},h.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},h.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},h.before=function(n,t){var r;return function(){return--n>0?r=t.apply(this,arguments):t=null,r}},h.once=h.partial(h.before,2),h.keys=function(n){if(!h.isObject(n))return[];if(s)return s(n);var t=[];for(var r in n)h.has(n,r)&&t.push(r);return t},h.values=function(n){for(var t=h.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},h.pairs=function(n){for(var t=h.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},h.invert=function(n){for(var t={},r=h.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},h.functions=h.methods=function(n){var t=[];for(var r in n)h.isFunction(n[r])&&t.push(r);return t.sort()},h.extend=function(n){if(!h.isObject(n))return n;for(var t,r,e=1,u=arguments.length;u>e;e++){t=arguments[e];for(r in t)c.call(t,r)&&(n[r]=t[r])}return n},h.pick=function(n,t,r){var e,u={};if(null==n)return u;if(h.isFunction(t)){t=g(t,r);for(e in n){var i=n[e];t(i,e,n)&&(u[e]=i)}}else{var l=o.apply([],a.call(arguments,1));n=new Object(n);for(var c=0,f=l.length;f>c;c++)e=l[c],e in n&&(u[e]=n[e])}return u},h.omit=function(n,t,r){if(h.isFunction(t))t=h.negate(t);else{var e=h.map(o.apply([],a.call(arguments,1)),String);t=function(n,t){return!h.contains(e,t)}}return h.pick(n,t,r)},h.defaults=function(n){if(!h.isObject(n))return n;for(var t=1,r=arguments.length;r>t;t++){var e=arguments[t];for(var u in e)n[u]===void 0&&(n[u]=e[u])}return n},h.clone=function(n){return h.isObject(n)?h.isArray(n)?n.slice():h.extend({},n):n},h.tap=function(n,t){return t(n),n};var b=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof h&&(n=n._wrapped),t instanceof h&&(t=t._wrapped);var u=l.call(n);if(u!==l.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]===n)return e[i]===t;var a=n.constructor,o=t.constructor;if(a!==o&&"constructor"in n&&"constructor"in t&&!(h.isFunction(a)&&a instanceof a&&h.isFunction(o)&&o instanceof o))return!1;r.push(n),e.push(t);var c,f;if("[object Array]"===u){if(c=n.length,f=c===t.length)for(;c--&&(f=b(n[c],t[c],r,e)););}else{var s,p=h.keys(n);if(c=p.length,f=h.keys(t).length===c)for(;c--&&(s=p[c],f=h.has(t,s)&&b(n[s],t[s],r,e)););}return r.pop(),e.pop(),f};h.isEqual=function(n,t){return b(n,t,[],[])},h.isEmpty=function(n){if(null==n)return!0;if(h.isArray(n)||h.isString(n)||h.isArguments(n))return 0===n.length;for(var t in n)if(h.has(n,t))return!1;return!0},h.isElement=function(n){return!(!n||1!==n.nodeType)},h.isArray=f||function(n){return"[object Array]"===l.call(n)},h.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},h.each(["Arguments","Function","String","Number","Date","RegExp"],function(n){h["is"+n]=function(t){return l.call(t)==="[object "+n+"]"}}),h.isArguments(arguments)||(h.isArguments=function(n){return h.has(n,"callee")}),"function"!=typeof/./&&(h.isFunction=function(n){return"function"==typeof n||!1}),h.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},h.isNaN=function(n){return h.isNumber(n)&&n!==+n},h.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===l.call(n)},h.isNull=function(n){return null===n},h.isUndefined=function(n){return n===void 0},h.has=function(n,t){return null!=n&&c.call(n,t)},h.noConflict=function(){return n._=t,this},h.identity=function(n){return n},h.constant=function(n){return function(){return n}},h.noop=function(){},h.property=function(n){return function(t){return t[n]}},h.matches=function(n){var t=h.pairs(n),r=t.length;return function(n){if(null==n)return!r;n=new Object(n);for(var e=0;r>e;e++){var u=t[e],i=u[0];if(u[1]!==n[i]||!(i in n))return!1}return!0}},h.times=function(n,t,r){var e=Array(Math.max(0,n));t=g(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},h.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},h.now=Date.now||function(){return(new Date).getTime()};var _={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},w=h.invert(_),j=function(n){var t=function(t){return n[t]},r="(?:"+h.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};h.escape=j(_),h.unescape=j(w),h.result=function(n,t){if(null==n)return void 0;var r=n[t];return h.isFunction(r)?n[t]():r};var x=0;h.uniqueId=function(n){var t=++x+"";return n?n+t:t},h.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var A=/(.)^/,k={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},O=/\\|'|\r|\n|\u2028|\u2029/g,F=function(n){return"\\"+k[n]};h.template=function(n,t,r){!t&&r&&(t=r),t=h.defaults({},t,h.templateSettings);var e=RegExp([(t.escape||A).source,(t.interpolate||A).source,(t.evaluate||A).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,a,o){return i+=n.slice(u,o).replace(O,F),u=o+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":a&&(i+="';\n"+a+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var a=new Function(t.variable||"obj","_",i)}catch(o){throw o.source=i,o}var l=function(n){return a.call(this,n,h)},c=t.variable||"obj";return l.source="function("+c+"){\n"+i+"}",l},h.chain=function(n){var t=h(n);return t._chain=!0,t};var E=function(n){return this._chain?h(n).chain():n};h.mixin=function(n){h.each(h.functions(n),function(t){var r=h[t]=n[t];h.prototype[t]=function(){var n=[this._wrapped];return i.apply(n,arguments),E.call(this,r.apply(h,n))}})},h.mixin(h),h.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=r[n];h.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],E.call(this,r)}}),h.each(["concat","join","slice"],function(n){var t=r[n];h.prototype[n]=function(){return E.call(this,t.apply(this._wrapped,arguments))}}),h.prototype.value=function(){return this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return h})}).call(this); //# sourceMappingURL=underscore-min.map \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/o2c.html b/catalog-core/catalog-mgr/src/main/resources/api-doc/o2c.html index 99561bc6..a2336bdf 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/o2c.html +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/o2c.html @@ -1,37 +1,37 @@ - - \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.js index 53ae58a5..d650a030 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.js @@ -1,5 +1,5 @@ /* - * Copyright 2016 [ZTE] and others. + * Copyright 2016 ZTE Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.min.js b/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.min.js index aab5ec40..3eabe583 100644 --- a/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.min.js +++ b/catalog-core/catalog-mgr/src/main/resources/api-doc/swagger-ui.min.js @@ -1,17 +1,17 @@ -/* - * Copyright 2016 [ZTE] and others. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function clippyCopiedCallback(){$("#api_key_copied").fadeIn().delay(1e3).fadeOut()}$(function(){$.fn.vAlign=function(){return this.each(function(){var e=$(this).height(),t=$(this).parent().height(),n=(t-e)/2;$(this).css("margin-top",n)})},$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(){var e=$(this).closest("form").innerWidth(),t=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10),n=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",e-t-n)})},$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent(),$("ul.downplayed li div.content p").vAlign(),$("form.sandbox").submit(function(){var e=!0;return $(this).find("input.required").each(function(){$(this).removeClass("error"),""==$(this).val()&&($(this).addClass("error"),$(this).wiggle(),e=!1)}),e})}),log=function(){log.history=log.history||[],log.history.push(arguments),this.console&&console.log(Array.prototype.slice.call(arguments)[0])},Function.prototype.bind&&console&&"object"==typeof console.log&&["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(e){console[e]=this.bind(console[e],console)},Function.prototype.call);var Docs={shebang:function(){var e=$.param.fragment().split("/");switch(e.shift(),e.length){case 1:var t="resource_"+e[0];Docs.expandEndpointListForResource(e[0]),$("#"+t).slideto({highlight:!1});break;case 2:Docs.expandEndpointListForResource(e[0]),$("#"+t).slideto({highlight:!1});var n=e.join("_"),a=n+"_content";Docs.expandOperation($("#"+a)),$("#"+n).slideto({highlight:!1})}},toggleEndpointListForResource:function(e){var t=$("li#resource_"+Docs.escapeResourceName(e)+" ul.endpoints");t.is(":visible")?Docs.collapseEndpointListForResource(e):Docs.expandEndpointListForResource(e)},expandEndpointListForResource:function(e){var e=Docs.escapeResourceName(e);if(""==e)return void $(".resource ul.endpoints").slideDown();$("li#resource_"+e).addClass("active");var t=$("li#resource_"+e+" ul.endpoints");t.slideDown()},collapseEndpointListForResource:function(e){var e=Docs.escapeResourceName(e);if(""==e)return void $(".resource ul.endpoints").slideUp();$("li#resource_"+e).removeClass("active");var t=$("li#resource_"+e+" ul.endpoints");t.slideUp()},expandOperationsForResource:function(e){return Docs.expandEndpointListForResource(e),""==e?void $(".resource ul.endpoints li.operation div.content").slideDown():void $("li#resource_"+Docs.escapeResourceName(e)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(e){return Docs.expandEndpointListForResource(e),""==e?void $(".resource ul.endpoints li.operation div.content").slideUp():void $("li#resource_"+Docs.escapeResourceName(e)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(e){return e.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(e){e.slideDown()},collapseOperation:function(e){e.slideUp()}};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(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return"\n
    \n
    \n
    "+l((s=null!=(s=t.keyName||(null!=e?e.keyName:e))?s:r,typeof s===i?s.call(e,{name:"keyName",hash:{},data:a}):s))+'
    \n \n \n
    \n
    \n\n'},useData:!0});var SwaggerUi,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;SwaggerUi=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.dom_id="swagger_ui",t.prototype.options=null,t.prototype.api=null,t.prototype.headerView=null,t.prototype.mainView=null,t.prototype.initialize=function(e){return null==e&&(e={}),null!=e.dom_id&&(this.dom_id=e.dom_id,delete e.dom_id),null==e.supportedSubmitMethods&&(e.supportedSubmitMethods=["get","put","post","delete","head","options","patch"]),null==$("#"+this.dom_id)&&$("body").append('
    '),this.options=e,this.options.success=function(e){return function(){return e.render()}}(this),this.options.progress=function(e){return function(t){return e.showMessage(t)}}(this),this.options.failure=function(e){return function(t){return e.onLoadFailure(t)}}(this),this.headerView=new HeaderView({el:$("#header")}),this.headerView.on("update-swagger-ui",function(e){return function(t){return e.updateSwaggerUi(t)}}(this))},t.prototype.setOption=function(e,t){return this.options[e]=t},t.prototype.getOption=function(e){return this.options[e]},t.prototype.updateSwaggerUi=function(e){return this.options.url=e.url,this.load()},t.prototype.load=function(){var e,t;return null!=(t=this.mainView)&&t.clear(),e=this.options.url,e&&0!==e.indexOf("http")&&(e=this.buildUrl(window.location.href.toString(),e)),this.options.url=e,this.headerView.update(e),this.api=new SwaggerClient(this.options)},t.prototype.collapseAll=function(){return Docs.collapseEndpointListForResource("")},t.prototype.listAll=function(){return Docs.collapseOperationsForResource("")},t.prototype.expandAll=function(){return Docs.expandOperationsForResource("")},t.prototype.render=function(){switch(this.showMessage("Finished Loading Resource Information. Rendering Swagger UI..."),this.mainView=new MainView({model:this.api,el:$("#"+this.dom_id),swaggerOptions:this.options}).render(),this.showMessage(),this.options.docExpansion){case"full":this.expandAll();break;case"list":this.listAll()}return this.renderGFM(),this.options.onComplete&&this.options.onComplete(this.api,this),setTimeout(function(){return function(){return Docs.shebang()}}(this),100)},t.prototype.buildUrl=function(e,t){var n,a;return 0===t.indexOf("/")?(a=e.split("/"),e=a[0]+"//"+a[2],e+t):(n=e.length,e.indexOf("?")>-1&&(n=Math.min(n,e.indexOf("?"))),e.indexOf("#")>-1&&(n=Math.min(n,e.indexOf("#"))),e=e.substring(0,n),-1!==e.indexOf("/",e.length-1)?e+t:e+"/"+t)},t.prototype.showMessage=function(e){return null==e&&(e=""),$("#message-bar").removeClass("message-fail"),$("#message-bar").addClass("message-success"),$("#message-bar").html(e)},t.prototype.onLoadFailure=function(e){var t;return null==e&&(e=""),$("#message-bar").removeClass("message-success"),$("#message-bar").addClass("message-fail"),t=$("#message-bar").html(e),null!=this.options.onFailure&&this.options.onFailure(e),t},t.prototype.renderGFM=function(e){return null==e&&(e=""),$(".markdown").each(function(){return $(this).html(marked($(this).html()))})},t}(Backbone.Router),window.SwaggerUi=SwaggerUi,this.Handlebars.templates.basic_auth_button_view=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(){return'
    \n
    \n
    \n
    Username
    \n \n
    Password
    \n \n \n
    \n
    \n\n'},useData:!0}),Handlebars.registerHelper("sanitize",function(e){return e=e.replace(/)<[^<]*)*<\/script>/gi,""),new Handlebars.SafeString(e)}),this.Handlebars.templates.content_type=Handlebars.template({1:function(e,t,n,a){var s,i="";return s=t.each.call(e,null!=e?e.produces:e,{name:"each",hash:{},fn:this.program(2,a),inverse:this.noop,data:a}),null!=s&&(i+=s),i},2:function(e){var t,n=this.lambda,a=' \n"},4:function(){return' \n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i='\n\n"},useData:!0});var ApiKeyButton,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ApiKeyButton=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),this},t.prototype.events={"click #apikey_button":"toggleApiKeyContainer","click #apply_api_key":"applyApiKey"},t.prototype.applyApiKey=function(){var e;return window.authorizations.add(this.model.name,new ApiKeyAuthorization(this.model.name,$("#input_apiKey_entry").val(),this.model["in"])),window.swaggerUi.load(),e=$("#apikey_container").show()},t.prototype.toggleApiKeyContainer=function(){var e;return $("#apikey_container").length>0?(e=$("#apikey_container").first(),e.is(":visible")?e.hide():($(".auth_container").hide(),e.show())):void 0},t.prototype.template=function(){return Handlebars.templates.apikey_button_view},t}(Backbone.View),this.Handlebars.templates.main=Handlebars.template({1:function(e,t,n,a){var s,i=this.lambda,r=this.escapeExpression,l='
    '+r(i(null!=(s=null!=e?e.info:e)?s.title:s,e))+'
    \n
    ';return s=i(null!=(s=null!=e?e.info:e)?s.description:s,e),null!=s&&(l+=s),l+="
    \n ",s=t["if"].call(e,null!=(s=null!=e?e.info:e)?s.termsOfServiceUrl:s,{name:"if",hash:{},fn:this.program(2,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=(s=null!=e?e.info:e)?s.contact:s)?s.name:s,{name:"if",hash:{},fn:this.program(4,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=(s=null!=e?e.info:e)?s.contact:s)?s.url:s,{name:"if",hash:{},fn:this.program(6,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=(s=null!=e?e.info:e)?s.contact:s)?s.email:s,{name:"if",hash:{},fn:this.program(8,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=e?e.info:e)?s.license:s,{name:"if",hash:{},fn:this.program(10,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+"\n"},2:function(e){var t,n=this.lambda,a=this.escapeExpression;return''},4:function(e){var t,n=this.lambda,a=this.escapeExpression;return"
    Created by "+a(n(null!=(t=null!=(t=null!=e?e.info:e)?t.contact:t)?t.name:t,e))+"
    "},6:function(e){var t,n=this.lambda,a=this.escapeExpression;return""},8:function(e){var t,n=this.lambda,a=this.escapeExpression;return"'},10:function(e){var t,n=this.lambda,a=this.escapeExpression;return""},12:function(e){var t,n=this.lambda,a=this.escapeExpression;return' , api version: '+a(n(null!=(t=null!=e?e.info:e)?t.version:t,e))+"\n "},14:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return' \n \n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p="
    \n";return s=t["if"].call(e,null!=e?e.info:e,{name:"if",hash:{},fn:this.program(1,a),inverse:this.noop,data:a}),null!=s&&(p+=s),p+="
    \n
    \n
      \n\n
      \n
      \n
      \n

      [ base url: "+o((i=null!=(i=t.basePath||(null!=e?e.basePath:e))?i:l,typeof i===r?i.call(e,{name:"basePath",hash:{},data:a}):i))+"\n",s=t["if"].call(e,null!=(s=null!=e?e.info:e)?s.version:s,{name:"if",hash:{},fn:this.program(12,a),inverse:this.noop,data:a}),null!=s&&(p+=s),p+="]\n",s=t["if"].call(e,null!=e?e.validatorUrl:e,{name:"if",hash:{},fn:this.program(14,a),inverse:this.noop,data:a}),null!=s&&(p+=s),p+"

      \n
      \n
      \n"},useData:!0});var BasicAuthButton,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;BasicAuthButton=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),this},t.prototype.events={"click #basic_auth_button":"togglePasswordContainer","click #apply_basic_auth":"applyPassword"},t.prototype.applyPassword=function(){var e,t,n;return n=$(".input_username").val(),t=$(".input_password").val(),window.authorizations.add(this.model.type,new PasswordAuthorization("basic",n,t)),window.swaggerUi.load(),e=$("#basic_auth_container").hide()},t.prototype.togglePasswordContainer=function(){var e;return $("#basic_auth_container").length>0?(e=$("#basic_auth_container").show(),e.is(":visible")?e.slideUp():($(".auth_container").hide(),e.show())):void 0},t.prototype.template=function(){return Handlebars.templates.basic_auth_button_view},t}(Backbone.View),this.Handlebars.templates.operation=Handlebars.template({1:function(){return"deprecated"},3:function(){return"

      Warning: Deprecated

      \n"},5:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o='

      Implementation Notes

      \n

      ';return i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(o+=s),o+"

      \n"},7:function(){return'
      \n '},9:function(e,t,n,a){var s,i=' \n"},10:function(e){var t,n=this.lambda,a=this.escapeExpression,s="
      "+a(n(null!=e?e.scope:e,e))+"
      \n"},12:function(){return"
      "},14:function(){return'
      \n \n
      \n'},16:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return"

      Response Class (Status "+l((s=null!=(s=t.successCode||(null!=e?e.successCode:e))?s:r,typeof s===i?s.call(e,{name:"successCode",hash:{},data:a}):s))+')

      \n

      \n
      \n
      \n'},18:function(){return'

      Parameters

      \n \n \n \n \n \n \n \n \n \n \n \n\n \n
      ParameterValueDescriptionParameter TypeData Type
      \n'},20:function(){return"
      \n

      Response Messages

      \n \n \n \n \n \n \n \n \n \n \n \n
      HTTP Status CodeReasonResponse Model
      \n"},22:function(){return""},24:function(){return"
      \n \n \n \n
      \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r,l="function",o=t.helperMissing,p=this.escapeExpression,u=t.blockHelperMissing,h="\n
        \n
      • \n \n \n
      • \n
      \n"},useData:!0});var ContentTypeView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ContentTypeView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),$("label[for=contentType]",$(this.el)).text("Response Content Type"),this},t.prototype.template=function(){return Handlebars.templates.content_type},t}(Backbone.View),this.Handlebars.templates.param=Handlebars.template({1:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,a),inverse:this.program(4,a),data:a}),null!=s&&(i+=s),i},2:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return' \n
      \n'},4:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(5,a),inverse:this.program(7,a),data:a}),null!=s&&(i+=s),i},5:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n
      \n
      \n'},7:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n
      \n
      \n'},9:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,a),inverse:this.program(10,a),data:a}),null!=s&&(i+=s),i},10:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(11,a),inverse:this.program(13,a),data:a}),null!=s&&(i+=s),i},11:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},13:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.name||(null!=e?e.name:e))?i:l,typeof i===r?i.call(e,{name:"name",hash:{},data:a}):i))+"\n\n\n";return s=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,a),inverse:this.program(9,a),data:a}),null!=s&&(p+=s),p+='\n\n',i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(p+=s),p+="\n",i=null!=(i=t.paramType||(null!=e?e.paramType:e))?i:l,s=typeof i===r?i.call(e,{name:"paramType",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n\n \n\n'},useData:!0});var HeaderView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;HeaderView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.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"},t.prototype.initialize=function(){},t.prototype.showPetStore=function(){return this.trigger("update-swagger-ui",{url:"http://petstore.swagger.wordnik.com/api/api-docs"})},t.prototype.showWordnikDev=function(){return this.trigger("update-swagger-ui",{url:"http://api.wordnik.com/v4/resources.json"})},t.prototype.showCustomOnKeyup=function(e){return 13===e.keyCode?this.showCustom():void 0},t.prototype.showCustom=function(e){return null!=e&&e.preventDefault(),this.trigger("update-swagger-ui",{url:$("#input_baseUrl").val(),apiKey:$("#input_apiKey").val()})},t.prototype.update=function(e,t,n){return null==n&&(n=!1),$("#input_baseUrl").val(e),n?this.trigger("update-swagger-ui",{url:e}):void 0},t}(Backbone.View),this.Handlebars.templates.param_list=Handlebars.template({1:function(){return" multiple='multiple'"},3:function(){return""},5:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(3,a),inverse:this.program(6,a),data:a}),null!=s&&(i+=s),i},6:function(e,t,n,a){var s,i=t.helperMissing,r="";return s=(t.isArray||e&&e.isArray||i).call(e,e,{name:"isArray",hash:{},fn:this.program(3,a),inverse:this.program(7,a),data:a}),null!=s&&(r+=s),r},7:function(){return" \n"},9:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isDefault:e,{name:"if",hash:{},fn:this.program(10,a),inverse:this.program(12,a),data:a}),null!=s&&(i+=s),i},10:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return' \n"},12:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.name||(null!=e?e.name:e))?i:l,typeof i===r?i.call(e,{name:"name",hash:{},data:a}):i))+"\n\n \n\n',i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(p+=s),p+="\n",i=null!=(i=t.paramType||(null!=e?e.paramType:e))?i:l,s=typeof i===r?i.call(e,{name:"paramType",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n'},useData:!0});var MainView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;MainView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}var n;return __extends(t,e),n={alpha:function(e,t){return e.path.localeCompare(t.path)},method:function(e,t){return e.method.localeCompare(t.method)}},t.prototype.initialize=function(e){var t,n,a,s;null==e&&(e={}),this.model.auths=[],s=this.model.securityDefinitions;for(n in s)a=s[n],t={name:n,type:a.type,value:a},this.model.auths.push(t);return"2.0"===this.model.swaggerVersion?this.model.validatorUrl="validatorUrl"in e.swaggerOptions?e.swaggerOptions.validatorUrl:this.model.url.indexOf("localhost")>0?null:"http://online.swagger.io/validator":void 0},t.prototype.render=function(){var e,t,n,a,s,i,r,l,o,p;if(this.model.securityDefinitions)for(s in this.model.securityDefinitions)e=this.model.securityDefinitions[s],"apiKey"===e.type&&0===$("#apikey_button").length&&(t=new ApiKeyButton({model:e}).render().el,$(".auth_main_container").append(t)),"basicAuth"===e.type&&0===$("#basic_auth_button").length&&(t=new BasicAuthButton({model:e}).render().el,$(".auth_main_container").append(t));for($(this.el).html(Handlebars.templates.main(this.model)),r={},n=0,p=this.model.apisArray,l=0,o=p.length;o>l;l++){for(i=p[l],a=i.name;"undefined"!=typeof r[a];)a=a+"_"+n,n+=1; +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function clippyCopiedCallback(){$("#api_key_copied").fadeIn().delay(1e3).fadeOut()}$(function(){$.fn.vAlign=function(){return this.each(function(){var e=$(this).height(),t=$(this).parent().height(),n=(t-e)/2;$(this).css("margin-top",n)})},$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(){var e=$(this).closest("form").innerWidth(),t=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10),n=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",e-t-n)})},$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent(),$("ul.downplayed li div.content p").vAlign(),$("form.sandbox").submit(function(){var e=!0;return $(this).find("input.required").each(function(){$(this).removeClass("error"),""==$(this).val()&&($(this).addClass("error"),$(this).wiggle(),e=!1)}),e})}),log=function(){log.history=log.history||[],log.history.push(arguments),this.console&&console.log(Array.prototype.slice.call(arguments)[0])},Function.prototype.bind&&console&&"object"==typeof console.log&&["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(e){console[e]=this.bind(console[e],console)},Function.prototype.call);var Docs={shebang:function(){var e=$.param.fragment().split("/");switch(e.shift(),e.length){case 1:var t="resource_"+e[0];Docs.expandEndpointListForResource(e[0]),$("#"+t).slideto({highlight:!1});break;case 2:Docs.expandEndpointListForResource(e[0]),$("#"+t).slideto({highlight:!1});var n=e.join("_"),a=n+"_content";Docs.expandOperation($("#"+a)),$("#"+n).slideto({highlight:!1})}},toggleEndpointListForResource:function(e){var t=$("li#resource_"+Docs.escapeResourceName(e)+" ul.endpoints");t.is(":visible")?Docs.collapseEndpointListForResource(e):Docs.expandEndpointListForResource(e)},expandEndpointListForResource:function(e){var e=Docs.escapeResourceName(e);if(""==e)return void $(".resource ul.endpoints").slideDown();$("li#resource_"+e).addClass("active");var t=$("li#resource_"+e+" ul.endpoints");t.slideDown()},collapseEndpointListForResource:function(e){var e=Docs.escapeResourceName(e);if(""==e)return void $(".resource ul.endpoints").slideUp();$("li#resource_"+e).removeClass("active");var t=$("li#resource_"+e+" ul.endpoints");t.slideUp()},expandOperationsForResource:function(e){return Docs.expandEndpointListForResource(e),""==e?void $(".resource ul.endpoints li.operation div.content").slideDown():void $("li#resource_"+Docs.escapeResourceName(e)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(e){return Docs.expandEndpointListForResource(e),""==e?void $(".resource ul.endpoints li.operation div.content").slideUp():void $("li#resource_"+Docs.escapeResourceName(e)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(e){return e.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(e){e.slideDown()},collapseOperation:function(e){e.slideUp()}};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(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return"\n
      \n
      \n
      "+l((s=null!=(s=t.keyName||(null!=e?e.keyName:e))?s:r,typeof s===i?s.call(e,{name:"keyName",hash:{},data:a}):s))+'
      \n \n \n
      \n
      \n\n'},useData:!0});var SwaggerUi,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;SwaggerUi=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.dom_id="swagger_ui",t.prototype.options=null,t.prototype.api=null,t.prototype.headerView=null,t.prototype.mainView=null,t.prototype.initialize=function(e){return null==e&&(e={}),null!=e.dom_id&&(this.dom_id=e.dom_id,delete e.dom_id),null==e.supportedSubmitMethods&&(e.supportedSubmitMethods=["get","put","post","delete","head","options","patch"]),null==$("#"+this.dom_id)&&$("body").append('
      '),this.options=e,this.options.success=function(e){return function(){return e.render()}}(this),this.options.progress=function(e){return function(t){return e.showMessage(t)}}(this),this.options.failure=function(e){return function(t){return e.onLoadFailure(t)}}(this),this.headerView=new HeaderView({el:$("#header")}),this.headerView.on("update-swagger-ui",function(e){return function(t){return e.updateSwaggerUi(t)}}(this))},t.prototype.setOption=function(e,t){return this.options[e]=t},t.prototype.getOption=function(e){return this.options[e]},t.prototype.updateSwaggerUi=function(e){return this.options.url=e.url,this.load()},t.prototype.load=function(){var e,t;return null!=(t=this.mainView)&&t.clear(),e=this.options.url,e&&0!==e.indexOf("http")&&(e=this.buildUrl(window.location.href.toString(),e)),this.options.url=e,this.headerView.update(e),this.api=new SwaggerClient(this.options)},t.prototype.collapseAll=function(){return Docs.collapseEndpointListForResource("")},t.prototype.listAll=function(){return Docs.collapseOperationsForResource("")},t.prototype.expandAll=function(){return Docs.expandOperationsForResource("")},t.prototype.render=function(){switch(this.showMessage("Finished Loading Resource Information. Rendering Swagger UI..."),this.mainView=new MainView({model:this.api,el:$("#"+this.dom_id),swaggerOptions:this.options}).render(),this.showMessage(),this.options.docExpansion){case"full":this.expandAll();break;case"list":this.listAll()}return this.renderGFM(),this.options.onComplete&&this.options.onComplete(this.api,this),setTimeout(function(){return function(){return Docs.shebang()}}(this),100)},t.prototype.buildUrl=function(e,t){var n,a;return 0===t.indexOf("/")?(a=e.split("/"),e=a[0]+"//"+a[2],e+t):(n=e.length,e.indexOf("?")>-1&&(n=Math.min(n,e.indexOf("?"))),e.indexOf("#")>-1&&(n=Math.min(n,e.indexOf("#"))),e=e.substring(0,n),-1!==e.indexOf("/",e.length-1)?e+t:e+"/"+t)},t.prototype.showMessage=function(e){return null==e&&(e=""),$("#message-bar").removeClass("message-fail"),$("#message-bar").addClass("message-success"),$("#message-bar").html(e)},t.prototype.onLoadFailure=function(e){var t;return null==e&&(e=""),$("#message-bar").removeClass("message-success"),$("#message-bar").addClass("message-fail"),t=$("#message-bar").html(e),null!=this.options.onFailure&&this.options.onFailure(e),t},t.prototype.renderGFM=function(e){return null==e&&(e=""),$(".markdown").each(function(){return $(this).html(marked($(this).html()))})},t}(Backbone.Router),window.SwaggerUi=SwaggerUi,this.Handlebars.templates.basic_auth_button_view=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(){return'
      \n
      \n
      \n
      Username
      \n \n
      Password
      \n \n \n
      \n
      \n\n'},useData:!0}),Handlebars.registerHelper("sanitize",function(e){return e=e.replace(/)<[^<]*)*<\/script>/gi,""),new Handlebars.SafeString(e)}),this.Handlebars.templates.content_type=Handlebars.template({1:function(e,t,n,a){var s,i="";return s=t.each.call(e,null!=e?e.produces:e,{name:"each",hash:{},fn:this.program(2,a),inverse:this.noop,data:a}),null!=s&&(i+=s),i},2:function(e){var t,n=this.lambda,a=' \n"},4:function(){return' \n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i='\n\n"},useData:!0});var ApiKeyButton,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ApiKeyButton=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),this},t.prototype.events={"click #apikey_button":"toggleApiKeyContainer","click #apply_api_key":"applyApiKey"},t.prototype.applyApiKey=function(){var e;return window.authorizations.add(this.model.name,new ApiKeyAuthorization(this.model.name,$("#input_apiKey_entry").val(),this.model["in"])),window.swaggerUi.load(),e=$("#apikey_container").show()},t.prototype.toggleApiKeyContainer=function(){var e;return $("#apikey_container").length>0?(e=$("#apikey_container").first(),e.is(":visible")?e.hide():($(".auth_container").hide(),e.show())):void 0},t.prototype.template=function(){return Handlebars.templates.apikey_button_view},t}(Backbone.View),this.Handlebars.templates.main=Handlebars.template({1:function(e,t,n,a){var s,i=this.lambda,r=this.escapeExpression,l='
      '+r(i(null!=(s=null!=e?e.info:e)?s.title:s,e))+'
      \n
      ';return s=i(null!=(s=null!=e?e.info:e)?s.description:s,e),null!=s&&(l+=s),l+="
      \n ",s=t["if"].call(e,null!=(s=null!=e?e.info:e)?s.termsOfServiceUrl:s,{name:"if",hash:{},fn:this.program(2,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=(s=null!=e?e.info:e)?s.contact:s)?s.name:s,{name:"if",hash:{},fn:this.program(4,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=(s=null!=e?e.info:e)?s.contact:s)?s.url:s,{name:"if",hash:{},fn:this.program(6,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=(s=null!=e?e.info:e)?s.contact:s)?s.email:s,{name:"if",hash:{},fn:this.program(8,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+="\n ",s=t["if"].call(e,null!=(s=null!=e?e.info:e)?s.license:s,{name:"if",hash:{},fn:this.program(10,a),inverse:this.noop,data:a}),null!=s&&(l+=s),l+"\n"},2:function(e){var t,n=this.lambda,a=this.escapeExpression;return''},4:function(e){var t,n=this.lambda,a=this.escapeExpression;return"
      Created by "+a(n(null!=(t=null!=(t=null!=e?e.info:e)?t.contact:t)?t.name:t,e))+"
      "},6:function(e){var t,n=this.lambda,a=this.escapeExpression;return""},8:function(e){var t,n=this.lambda,a=this.escapeExpression;return"'},10:function(e){var t,n=this.lambda,a=this.escapeExpression;return""},12:function(e){var t,n=this.lambda,a=this.escapeExpression;return' , api version: '+a(n(null!=(t=null!=e?e.info:e)?t.version:t,e))+"\n "},14:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return' \n \n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p="
      \n";return s=t["if"].call(e,null!=e?e.info:e,{name:"if",hash:{},fn:this.program(1,a),inverse:this.noop,data:a}),null!=s&&(p+=s),p+="
      \n
      \n
        \n\n
        \n
        \n
        \n

        [ base url: "+o((i=null!=(i=t.basePath||(null!=e?e.basePath:e))?i:l,typeof i===r?i.call(e,{name:"basePath",hash:{},data:a}):i))+"\n",s=t["if"].call(e,null!=(s=null!=e?e.info:e)?s.version:s,{name:"if",hash:{},fn:this.program(12,a),inverse:this.noop,data:a}),null!=s&&(p+=s),p+="]\n",s=t["if"].call(e,null!=e?e.validatorUrl:e,{name:"if",hash:{},fn:this.program(14,a),inverse:this.noop,data:a}),null!=s&&(p+=s),p+"

        \n
        \n
        \n"},useData:!0});var BasicAuthButton,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;BasicAuthButton=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),this},t.prototype.events={"click #basic_auth_button":"togglePasswordContainer","click #apply_basic_auth":"applyPassword"},t.prototype.applyPassword=function(){var e,t,n;return n=$(".input_username").val(),t=$(".input_password").val(),window.authorizations.add(this.model.type,new PasswordAuthorization("basic",n,t)),window.swaggerUi.load(),e=$("#basic_auth_container").hide()},t.prototype.togglePasswordContainer=function(){var e;return $("#basic_auth_container").length>0?(e=$("#basic_auth_container").show(),e.is(":visible")?e.slideUp():($(".auth_container").hide(),e.show())):void 0},t.prototype.template=function(){return Handlebars.templates.basic_auth_button_view},t}(Backbone.View),this.Handlebars.templates.operation=Handlebars.template({1:function(){return"deprecated"},3:function(){return"

        Warning: Deprecated

        \n"},5:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o='

        Implementation Notes

        \n

        ';return i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(o+=s),o+"

        \n"},7:function(){return'
        \n '},9:function(e,t,n,a){var s,i=' \n"},10:function(e){var t,n=this.lambda,a=this.escapeExpression,s="
        "+a(n(null!=e?e.scope:e,e))+"
        \n"},12:function(){return"
        "},14:function(){return'
        \n \n
        \n'},16:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return"

        Response Class (Status "+l((s=null!=(s=t.successCode||(null!=e?e.successCode:e))?s:r,typeof s===i?s.call(e,{name:"successCode",hash:{},data:a}):s))+')

        \n

        \n
        \n
        \n'},18:function(){return'

        Parameters

        \n \n \n \n \n \n \n \n \n \n \n \n\n \n
        ParameterValueDescriptionParameter TypeData Type
        \n'},20:function(){return"
        \n

        Response Messages

        \n \n \n \n \n \n \n \n \n \n \n \n
        HTTP Status CodeReasonResponse Model
        \n"},22:function(){return""},24:function(){return"
        \n \n \n \n
        \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r,l="function",o=t.helperMissing,p=this.escapeExpression,u=t.blockHelperMissing,h="\n
          \n
        • \n \n \n
        • \n
        \n"},useData:!0});var ContentTypeView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ContentTypeView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),$("label[for=contentType]",$(this.el)).text("Response Content Type"),this},t.prototype.template=function(){return Handlebars.templates.content_type},t}(Backbone.View),this.Handlebars.templates.param=Handlebars.template({1:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,a),inverse:this.program(4,a),data:a}),null!=s&&(i+=s),i},2:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return' \n
        \n'},4:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(5,a),inverse:this.program(7,a),data:a}),null!=s&&(i+=s),i},5:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n
        \n
        \n'},7:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n
        \n
        \n'},9:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,a),inverse:this.program(10,a),data:a}),null!=s&&(i+=s),i},10:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(11,a),inverse:this.program(13,a),data:a}),null!=s&&(i+=s),i},11:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},13:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.name||(null!=e?e.name:e))?i:l,typeof i===r?i.call(e,{name:"name",hash:{},data:a}):i))+"\n\n\n";return s=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,a),inverse:this.program(9,a),data:a}),null!=s&&(p+=s),p+='\n\n',i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(p+=s),p+="\n",i=null!=(i=t.paramType||(null!=e?e.paramType:e))?i:l,s=typeof i===r?i.call(e,{name:"paramType",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n\n \n\n'},useData:!0});var HeaderView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;HeaderView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.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"},t.prototype.initialize=function(){},t.prototype.showPetStore=function(){return this.trigger("update-swagger-ui",{url:"http://petstore.swagger.wordnik.com/api/api-docs"})},t.prototype.showWordnikDev=function(){return this.trigger("update-swagger-ui",{url:"http://api.wordnik.com/v4/resources.json"})},t.prototype.showCustomOnKeyup=function(e){return 13===e.keyCode?this.showCustom():void 0},t.prototype.showCustom=function(e){return null!=e&&e.preventDefault(),this.trigger("update-swagger-ui",{url:$("#input_baseUrl").val(),apiKey:$("#input_apiKey").val()})},t.prototype.update=function(e,t,n){return null==n&&(n=!1),$("#input_baseUrl").val(e),n?this.trigger("update-swagger-ui",{url:e}):void 0},t}(Backbone.View),this.Handlebars.templates.param_list=Handlebars.template({1:function(){return" multiple='multiple'"},3:function(){return""},5:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(3,a),inverse:this.program(6,a),data:a}),null!=s&&(i+=s),i},6:function(e,t,n,a){var s,i=t.helperMissing,r="";return s=(t.isArray||e&&e.isArray||i).call(e,e,{name:"isArray",hash:{},fn:this.program(3,a),inverse:this.program(7,a),data:a}),null!=s&&(r+=s),r},7:function(){return" \n"},9:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isDefault:e,{name:"if",hash:{},fn:this.program(10,a),inverse:this.program(12,a),data:a}),null!=s&&(i+=s),i},10:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return' \n"},12:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.name||(null!=e?e.name:e))?i:l,typeof i===r?i.call(e,{name:"name",hash:{},data:a}):i))+"\n\n \n\n',i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(p+=s),p+="\n",i=null!=(i=t.paramType||(null!=e?e.paramType:e))?i:l,s=typeof i===r?i.call(e,{name:"paramType",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n'},useData:!0});var MainView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;MainView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}var n;return __extends(t,e),n={alpha:function(e,t){return e.path.localeCompare(t.path)},method:function(e,t){return e.method.localeCompare(t.method)}},t.prototype.initialize=function(e){var t,n,a,s;null==e&&(e={}),this.model.auths=[],s=this.model.securityDefinitions;for(n in s)a=s[n],t={name:n,type:a.type,value:a},this.model.auths.push(t);return"2.0"===this.model.swaggerVersion?this.model.validatorUrl="validatorUrl"in e.swaggerOptions?e.swaggerOptions.validatorUrl:this.model.url.indexOf("localhost")>0?null:"http://online.swagger.io/validator":void 0},t.prototype.render=function(){var e,t,n,a,s,i,r,l,o,p;if(this.model.securityDefinitions)for(s in this.model.securityDefinitions)e=this.model.securityDefinitions[s],"apiKey"===e.type&&0===$("#apikey_button").length&&(t=new ApiKeyButton({model:e}).render().el,$(".auth_main_container").append(t)),"basicAuth"===e.type&&0===$("#basic_auth_button").length&&(t=new BasicAuthButton({model:e}).render().el,$(".auth_main_container").append(t));for($(this.el).html(Handlebars.templates.main(this.model)),r={},n=0,p=this.model.apisArray,l=0,o=p.length;o>l;l++){for(i=p[l],a=i.name;"undefined"!=typeof r[a];)a=a+"_"+n,n+=1; i.id=a,r[a]=i,this.addResource(i,this.model.auths)}return $(".propWrap").hover(function(){return $(".optionsWrapper",$(this)).show()},function(){return $(".optionsWrapper",$(this)).hide()}),this},t.prototype.addResource=function(e,t){var n;return e.id=e.id.replace(/\s/g,"_"),n=new ResourceView({model:e,tagName:"li",id:"resource_"+e.id,className:"resource",auths:t,swaggerOptions:this.options.swaggerOptions}),$("#resources").append(n.render().el)},t.prototype.clear=function(){return $(this.el).html("")},t}(Backbone.View),this.Handlebars.templates.param_readonly=Handlebars.template({1:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},3:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(4,a),inverse:this.program(6,a),data:a}),null!=s&&(i+=s),i},4:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" "+l((s=null!=(s=t["default"]||(null!=e?e["default"]:e))?s:r,typeof s===i?s.call(e,{name:"default",hash:{},data:a}):s))+"\n"},6:function(){return" (empty)\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.name||(null!=e?e.name:e))?i:l,typeof i===r?i.call(e,{name:"name",hash:{},data:a}):i))+"\n\n";return s=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,a),inverse:this.program(3,a),data:a}),null!=s&&(p+=s),p+='\n',i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(p+=s),p+="\n",i=null!=(i=t.paramType||(null!=e?e.paramType:e))?i:l,s=typeof i===r?i.call(e,{name:"paramType",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n\n'},useData:!0}),this.Handlebars.templates.param_readonly_required=Handlebars.template({1:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},3:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(4,a),inverse:this.program(6,a),data:a}),null!=s&&(i+=s),i},4:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" "+l((s=null!=(s=t["default"]||(null!=e?e["default"]:e))?s:r,typeof s===i?s.call(e,{name:"default",hash:{},data:a}):s))+"\n"},6:function(){return" (empty)\n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.name||(null!=e?e.name:e))?i:l,typeof i===r?i.call(e,{name:"name",hash:{},data:a}):i))+"\n\n";return s=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,a),inverse:this.program(3,a),data:a}),null!=s&&(p+=s),p+='\n',i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(p+=s),p+="\n",i=null!=(i=t.paramType||(null!=e?e.paramType:e))?i:l,s=typeof i===r?i.call(e,{name:"paramType",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n\n'},useData:!0});var OperationView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;OperationView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.invocationUrl=null,t.prototype.events={"submit .sandbox":"submitOperation","click .submit":"submitOperation","click .response_hider":"hideResponse","click .toggleOperation":"toggleOperationContent","mouseenter .api-ic":"mouseEnter","mouseout .api-ic":"mouseExit"},t.prototype.initialize=function(e){return null==e&&(e={}),this.auths=e.auths,this.parentId=this.model.parentId,this.nickname=this.model.nickname,this},t.prototype.mouseEnter=function(e){var t,n,a,s,i,r,l,o,p,u;return t=$(this.el).find(".content"),p=e.pageX,u=e.pageY,r=$(window).scrollLeft(),l=$(window).scrollTop(),s=r+$(window).width(),i=l+$(window).height(),o=t.width(),n=t.height(),p+o>s&&(p=s-o),r>p&&(p=r),u+n>i&&(u=i-n),l>u&&(u=l),a={},a.top=u,a.left=p,t.css(a),$(e.currentTarget.parentNode).find("#api_information_panel").show()},t.prototype.mouseExit=function(e){return $(e.currentTarget.parentNode).find("#api_information_panel").hide()},t.prototype.render=function(){var e,t,n,a,s,i,r,l,o,p,u,h,c,d,m,f,y,g,v,_,w,b,x,k,O,C,S,P,T,D,H,M,E,R,V,N,U,A;if(i=jQuery.inArray(this.model.method,this.model.supportedSubmitMethods())>=0,i||(this.model.isReadOnly=!0),this.model.description=this.model.description||this.model.notes,this.model.description&&(this.model.description=this.model.description.replace(/(?:\r\n|\r|\n)/g,"
        ")),this.model.oauth=null,o=this.model.authorizations||this.model.security)if(Array.isArray(o))for(k=0,P=o.length;P>k;k++){n=o[k];for(l in n){t=n[l];for(e in this.auths)if(t=this.auths[e],"oauth2"===t.type){this.model.oauth={},this.model.oauth.scopes=[],R=t.value.scopes;for(r in R)b=R[r],y=n[l].indexOf(r),y>=0&&(p={scope:r,description:b},this.model.oauth.scopes.push(p))}}}else for(r in o)if(b=o[r],"oauth2"===r)for(null===this.model.oauth&&(this.model.oauth={}),void 0===this.model.oauth.scopes&&(this.model.oauth.scopes=[]),O=0,T=b.length;T>O;O++)p=b[O],this.model.oauth.scopes.push(p);if("undefined"!=typeof this.model.responses){this.model.responseMessages=[],V=this.model.responses;for(a in V)x=V[a],m=null,f=this.model.responses[a].schema,f&&f.$ref&&(m=f.$ref,0===m.indexOf("#/definitions/")&&(m=m.substring("#/definitions/".length))),this.model.responseMessages.push({code:a,message:x.description,responseModel:m})}if("undefined"==typeof this.model.responseMessages&&(this.model.responseMessages=[]),g=null,this.model.successResponse){_=this.model.successResponse;for(l in _)x=_[l],this.model.successCode=l,"object"==typeof x&&"function"==typeof x.createJSONSample&&(g={sampleJSON:JSON.stringify(x.createJSONSample(),void 0,2),isParam:!1,signature:x.getMockSignature()})}else this.model.responseClassSignature&&"string"!==this.model.responseClassSignature&&(g={sampleJSON:this.model.responseSampleJSON,isParam:!1,signature:this.model.responseClassSignature});for($(this.el).html(Handlebars.templates.operation(this.model)),g?(d=new SignatureView({model:g,tagName:"div"}),$(".model-signature",$(this.el)).append(d.render().el)):(this.model.responseClassSignature="string",$(".model-signature",$(this.el)).html(this.model.type)),s={isParam:!1},s.consumes=this.model.consumes,s.produces=this.model.produces,N=this.model.parameters,C=0,D=N.length;D>C;C++)u=N[C],w=u.type||u.dataType||"","undefined"==typeof w&&(m=u.schema,m&&m.$ref&&(h=m.$ref,w=0===h.indexOf("#/definitions/")?h.substring("#/definitions/".length):h)),w&&"file"===w.toLowerCase()&&(s.consumes||(s.consumes="multipart/form-data")),u.type=w;for(c=new ResponseContentTypeView({model:s}),$(".response-content-type",$(this.el)).append(c.render().el),U=this.model.parameters,S=0,H=U.length;H>S;S++)u=U[S],this.addParameter(u,s.consumes);for(A=this.model.responseMessages,E=0,M=A.length;M>E;E++)v=A[E],this.addStatusCode(v);return this},t.prototype.addParameter=function(e,t){var n;return e.consumes=t,n=new ParameterView({model:e,tagName:"tr",readOnly:this.model.isReadOnly}),$(".operation-params",$(this.el)).append(n.render().el)},t.prototype.addStatusCode=function(e){var t;return t=new StatusCodeView({model:e,tagName:"tr"}),$(".operation-status",$(this.el)).append(t.render().el)},t.prototype.submitOperation=function(e){var t,n,a,s,i,r,l,o,p,u,h,c,d,m,f,y;if(null!=e&&e.preventDefault(),n=$(".sandbox",$(this.el)),t=!0,n.find("input.required").each(function(){return $(this).removeClass("error"),""===jQuery.trim($(this).val())?($(this).addClass("error"),$(this).wiggle({callback:function(e){return function(){return $(e).focus()}}(this)}),t=!1):void 0}),n.find("textarea.required").each(function(){return $(this).removeClass("error"),""===jQuery.trim($(this).val())?($(this).addClass("error"),$(this).wiggle({callback:function(e){return function(){return $(e).focus()}}(this)}),t=!1):void 0}),t){for(s={},r={parent:this},a=!1,m=n.find("input"),o=0,h=m.length;h>o;o++)i=m[o],null!=i.value&&jQuery.trim(i.value).length>0&&(s[i.name]=i.value),"file"===i.type&&(s[i.name]=i.files[0],a=!0);for(f=n.find("textarea"),p=0,c=f.length;c>p;p++)i=f[p],null!=i.value&&jQuery.trim(i.value).length>0&&(s[i.name]=i.value);for(y=n.find("select"),u=0,d=y.length;d>u;u++)i=y[u],l=this.getSelectedValue(i),null!=l&&jQuery.trim(l).length>0&&(s[i.name]=l);return r.responseContentType=$("div select[name=responseContentType]",$(this.el)).val(),r.requestContentType=$("div select[name=parameterContentType]",$(this.el)).val(),$(".response_throbber",$(this.el)).show(),a?this.handleFileUpload(s,n):this.model["do"](s,r,this.showCompleteStatus,this.showErrorStatus,this)}},t.prototype.success=function(e,t){return t.showCompleteStatus(e)},t.prototype.handleFileUpload=function(e,t){var n,a,s,i,r,l,o,p,u,h,c,d,m,f,y,g,v,_,w;for(g=t.serializeArray(),p=0,d=g.length;d>p;p++)i=g[p],null!=i.value&&jQuery.trim(i.value).length>0&&(e[i.name]=i.value);for(n=new FormData,o=0,v=this.model.parameters,u=0,m=v.length;m>u;u++)l=v[u],("form"===l.paramType||"formData"===l["in"])&&"file"!==l.type.toLowerCase()&&void 0!==e[l.name]&&n.append(l.name,e[l.name]);for(s={},_=this.model.parameters,h=0,f=_.length;f>h;h++)l=_[h],"header"===l.paramType&&(s[l.name]=e[l.name]);for(w=t.find('input[type~="file"]'),c=0,y=w.length;y>c;c++)a=w[c],"undefined"!=typeof a.files[0]&&(n.append($(a).attr("name"),a.files[0]),o+=1);return this.invocationUrl=this.model.supportHeaderParams()?(s=this.model.getHeaderParams(e),delete s["Content-Type"],this.model.urlify(e,!1)):this.model.urlify(e,!0),$(".request_url",$(this.el)).html("
        "),$(".request_url pre",$(this.el)).text(this.invocationUrl),r={type:this.model.method,url:this.invocationUrl,headers:s,data:n,dataType:"json",contentType:!1,processData:!1,error:function(e){return function(t){return e.showErrorStatus(e.wrap(t),e)}}(this),success:function(e){return function(t){return e.showResponse(t,e)}}(this),complete:function(e){return function(t){return e.showCompleteStatus(e.wrap(t),e)}}(this)},window.authorizations&&window.authorizations.apply(r),0===o&&r.data.append("fake","true"),jQuery.ajax(r),!1},t.prototype.wrap=function(e){var t,n,a,s,i,r,l;for(a={},n=e.getAllResponseHeaders().split("\r"),r=0,l=n.length;l>r;r++)s=n[r],t=s.match(/^([^:]*?):(.*)$/),t||(t=[]),t.shift(),void 0!==t[0]&&void 0!==t[1]&&(a[t[0].trim()]=t[1].trim());return i={},i.content={},i.content.data=e.responseText,i.headers=a,i.request={},i.request.url=this.invocationUrl,i.status=e.status,i},t.prototype.getSelectedValue=function(e){var t,n,a,s,i;if(e.multiple){for(n=[],i=e.options,a=0,s=i.length;s>a;a++)t=i[a],t.selected&&n.push(t.value);return n.length>0?n:null}return e.value},t.prototype.hideResponse=function(e){return null!=e&&e.preventDefault(),$(".response",$(this.el)).slideUp(),$(".response_hider",$(this.el)).fadeOut()},t.prototype.showResponse=function(e){var t;return t=JSON.stringify(e,null,"	").replace(/\n/g,"
        "),$(".response_body",$(this.el)).html(escape(t))},t.prototype.showErrorStatus=function(e,t){return t.showStatus(e)},t.prototype.showCompleteStatus=function(e,t){return t.showStatus(e)},t.prototype.formatXml=function(e){var t,n,a,s,i,r,l,o,p,u,h,c,d;for(o=/(>)(<)(\/*)/g,u=/[ ]*(.*)[ ]+\n/g,t=/(<.+>)(.+\n)/g,e=e.replace(o,"$1\n$2$3").replace(u,"$1\n").replace(t,"$1\n$2"),l=0,n="",i=e.split("\n"),a=0,s="other",p={"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},h=function(e){var t,i,r,l,o,u,h;return u={single:Boolean(e.match(/<.+\/>/)),closing:Boolean(e.match(/<\/.+>/)),opening:Boolean(e.match(/<[^!?].*>/))},o=function(){var e;e=[];for(r in u)h=u[r],h&&e.push(r);return e}()[0],o=void 0===o?"other":o,t=s+"->"+o,s=o,l="",a+=p[t],l=function(){var e,t,n;for(n=[],i=e=0,t=a;t>=0?t>e:e>t;i=t>=0?++e:--e)n.push(" ");return n}().join(""),"opening->closing"===t?n=n.substr(0,n.length-1)+e+"\n":n+=l+e+"\n"},c=0,d=i.length;d>c;c++)r=i[c],h(r);return n},t.prototype.showStatus=function(e){var t,n,a,s,i,r,l,o,p,u,h;if(void 0===e.content?(n=e.data,h=e.url):(n=e.content.data,h=e.request.url),i=e.headers,a=null,i&&(a=i["Content-Type"]||i["content-type"],a&&(a=a.split(";")[0].trim())),$(".response_body",$(this.el)).removeClass("json"),$(".response_body",$(this.el)).removeClass("xml"),n)if("application/json"===a||/\+json$/.test(a)){r=null;try{r=JSON.stringify(JSON.parse(n),null," ")}catch(c){s=c,r="can't parse JSON. Raw result:\n\n"+n}t=$("").text(r),o=$('
        ').append(t)}else"application/xml"===a||/\+xml$/.test(a)?(t=$("").text(this.formatXml(n)),o=$('
        ').append(t)):"text/html"===a?(t=$("").html(_.escape(n)),o=$('
        ').append(t)):/^image\//.test(a)?o=$("").attr("src",h):(t=$("").text(n),o=$('
        ').append(t));else t=$("").text("no content"),o=$('
        ').append(t);return p=o,$(".request_url",$(this.el)).html("
        "),$(".request_url pre",$(this.el)).text(h),$(".response_code",$(this.el)).html("
        "+e.status+"
        "),$(".response_body",$(this.el)).html(p),$(".response_headers",$(this.el)).html("
        "+_.escape(JSON.stringify(e.headers,null,"  ")).replace(/\n/g,"
        ")+"
        "),$(".response",$(this.el)).slideDown(),$(".response_hider",$(this.el)).show(),$(".response_throbber",$(this.el)).hide(),u=$(".response_body",$(this.el))[0],l=this.options.swaggerOptions,l.highlightSizeThreshold&&e.data.length>l.highlightSizeThreshold?u:hljs.highlightBlock(u)},t.prototype.toggleOperationContent=function(){var e;return e=$("#"+Docs.escapeResourceName(this.parentId+"_"+this.nickname+"_content")),e.is(":visible")?Docs.collapseOperation(e):Docs.expandOperation(e)},t}(Backbone.View);var ParameterContentTypeView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ParameterContentTypeView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:"),this},t.prototype.template=function(){return Handlebars.templates.parameter_content_type},t}(Backbone.View),this.Handlebars.templates.param_required=Handlebars.template({1:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(2,a),inverse:this.program(4,a),data:a}),null!=s&&(i+=s),i},2:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return' \n"},4:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(5,a),inverse:this.program(7,a),data:a}),null!=s&&(i+=s),i},5:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n
        \n
        \n'},7:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n
        \n
        \n'},9:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e.isFile:e,{name:"if",hash:{},fn:this.program(10,a),inverse:this.program(12,a),data:a}),null!=s&&(i+=s),i},10:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},12:function(e,t,n,a){var s,i="";return s=t["if"].call(e,null!=e?e["default"]:e,{name:"if",hash:{},fn:this.program(13,a),inverse:this.program(15,a),data:a}),null!=s&&(i+=s),i},13:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},15:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return" \n"},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.name||(null!=e?e.name:e))?i:l,typeof i===r?i.call(e,{name:"name",hash:{},data:a}):i))+"\n\n";return s=t["if"].call(e,null!=e?e.isBody:e,{name:"if",hash:{},fn:this.program(1,a),inverse:this.program(9,a),data:a}),null!=s&&(p+=s),p+='\n\n ',i=null!=(i=t.description||(null!=e?e.description:e))?i:l,s=typeof i===r?i.call(e,{name:"description",hash:{},data:a}):i,null!=s&&(p+=s),p+="\n\n",i=null!=(i=t.paramType||(null!=e?e.paramType:e))?i:l,s=typeof i===r?i.call(e,{name:"paramType",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n\n'},useData:!0}),this.Handlebars.templates.parameter_content_type=Handlebars.template({1:function(e,t,n,a){var s,i="";return s=t.each.call(e,null!=e?e.consumes:e,{name:"each",hash:{},fn:this.program(2,a),inverse:this.noop,data:a}),null!=s&&(i+=s),i},2:function(e){var t,n=this.lambda,a=' \n"},4:function(){return' \n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i='\n\n"},useData:!0});var ParameterView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ParameterView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){return Handlebars.registerHelper("isArray",function(e,t){return"array"===e.type.toLowerCase()||e.allowMultiple?t.fn(this):t.inverse(this)})},t.prototype.render=function(){var e,t,n,a,s,i,r,l,o,p;return p=this.model.type||this.model.dataType,"undefined"==typeof p&&(i=this.model.schema,i&&i.$ref&&(a=i.$ref,p=0===a.indexOf("#/definitions/")?a.substring("#/definitions/".length):a)),this.model.type=p,this.model.paramType=this.model["in"]||this.model.paramType,("body"===this.model.paramType||"body"===this.model["in"])&&(this.model.isBody=!0),p&&"file"===p.toLowerCase()&&(this.model.isFile=!0),this.model["default"]=this.model["default"]||this.model.defaultValue,this.model.allowableValues&&(this.model.isList=!0),o=this.template(),$(this.el).html(o(this.model)),r={sampleJSON:this.model.sampleJSON,isParam:!0,signature:this.model.signature},this.model.sampleJSON?(l=new SignatureView({model:r,tagName:"div"}),$(".model-signature",$(this.el)).append(l.render().el)):$(".model-signature",$(this.el)).html(this.model.signature),t=!1,this.model.isBody&&(t=!0),e={isParam:t},e.consumes=this.model.consumes,t?(n=new ParameterContentTypeView({model:e}),$(".parameter-content-type",$(this.el)).append(n.render().el)):(s=new ResponseContentTypeView({model:e}),$(".response-content-type",$(this.el)).append(s.render().el)),this},t.prototype.template=function(){return this.model.isList?Handlebars.templates.param_list:this.options.readOnly?this.model.required?Handlebars.templates.param_readonly_required:Handlebars.templates.param_readonly:this.model.required?Handlebars.templates.param_required:Handlebars.templates.param},t}(Backbone.View);var ResourceView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ResourceView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(e){return null==e&&(e={}),this.auths=e.auths,""===this.model.description&&(this.model.description=null),null!=this.model.description?this.model.summary=this.model.description:void 0},t.prototype.render=function(){var e,t,n,a,s,i,r;for(n={},$(this.el).html(Handlebars.templates.resource(this.model)),r=this.model.operationsArray,s=0,i=r.length;i>s;s++){for(a=r[s],e=0,t=a.nickname;"undefined"!=typeof n[t];)t=t+"_"+e,e+=1;n[t]=a,a.nickname=t,a.parentId=this.model.id,this.addOperation(a)}return $(".toggleEndpointList",this.el).click(this.callDocs.bind(this,"toggleEndpointListForResource")),$(".collapseResource",this.el).click(this.callDocs.bind(this,"collapseOperationsForResource")),$(".expandResource",this.el).click(this.callDocs.bind(this,"expandOperationsForResource")),this},t.prototype.addOperation=function(e){var t;return e.number=this.number,t=new OperationView({model:e,tagName:"li",className:"endpoint",swaggerOptions:this.options.swaggerOptions,auths:this.auths}),$(".endpoints",$(this.el)).append(t.render().el),this.number++},t.prototype.callDocs=function(e,t){return t.preventDefault(),Docs[e](t.currentTarget.getAttribute("data-id"))},t}(Backbone.View),this.Handlebars.templates.resource=Handlebars.template({1:function(){return" : "},3:function(e,t,n,a){var s,i="function",r=t.helperMissing,l=this.escapeExpression;return"
      • \n Raw\n
      • "},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r,l="function",o=t.helperMissing,p=this.escapeExpression,u=t.blockHelperMissing,h="
        \n

        \n '+p((i=null!=(i=t.name||(null!=e?e.name:e))?i:o,typeof i===l?i.call(e,{name:"name",hash:{},data:a}):i))+" ";return i=null!=(i=t.summary||(null!=e?e.summary:e))?i:o,r={name:"summary",hash:{},fn:this.program(1,a),inverse:this.noop,data:a},s=typeof i===l?i.call(e,r):i,t.summary||(s=u.call(e,s,r)),null!=s&&(h+=s),i=null!=(i=t.summary||(null!=e?e.summary:e))?i:o,s=typeof i===l?i.call(e,{name:"summary",hash:{},data:a}):i,null!=s&&(h+=s),h+="\n

        \n
          \n
        • \n Show/Hide\n
        • \n
        • \n \n List Operations\n \n
        • \n
        • \n \n Expand Operations\n \n
        • \n ',i=null!=(i=t.url||(null!=e?e.url:e))?i:o,r={name:"url",hash:{},fn:this.program(3,a),inverse:this.noop,data:a},s=typeof i===l?i.call(e,r):i,t.url||(s=u.call(e,s,r)),null!=s&&(h+=s),h+"\n
        \n
        \n\n"},useData:!0});var ResponseContentTypeView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;ResponseContentTypeView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),$("label[for=responseContentType]",$(this.el)).text("Response Content Type"),this},t.prototype.template=function(){return Handlebars.templates.response_content_type},t}(Backbone.View),this.Handlebars.templates.response_content_type=Handlebars.template({1:function(e,t,n,a){var s,i="";return s=t.each.call(e,null!=e?e.produces:e,{name:"each",hash:{},fn:this.program(2,a),inverse:this.noop,data:a}),null!=s&&(i+=s),i},2:function(e){var t,n=this.lambda,a=' \n"},4:function(){return' \n'},compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i='\n\n"},useData:!0});var SignatureView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;SignatureView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.events={"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"},t.prototype.initialize=function(){},t.prototype.render=function(){var e;return e=this.template(),$(this.el).html(e(this.model)),this.switchToSnippet(),this.isParam=this.model.isParam,this.isParam&&$(".notice",$(this.el)).text("Click to set as parameter value"),this},t.prototype.template=function(){return Handlebars.templates.signature},t.prototype.switchToDescription=function(e){return null!=e&&e.preventDefault(),$(".snippet",$(this.el)).hide(),$(".description",$(this.el)).show(),$(".description-link",$(this.el)).addClass("selected"),$(".snippet-link",$(this.el)).removeClass("selected")},t.prototype.switchToSnippet=function(e){return null!=e&&e.preventDefault(),$(".description",$(this.el)).hide(),$(".snippet",$(this.el)).show(),$(".snippet-link",$(this.el)).addClass("selected"),$(".description-link",$(this.el)).removeClass("selected")},t.prototype.snippetToTextArea=function(e){var t;return this.isParam&&(null!=e&&e.preventDefault(),t=$("textarea",$(this.el.parentNode.parentNode.parentNode)),""===$.trim(t.val()))?t.val(this.model.sampleJSON):void 0},t}(Backbone.View),this.Handlebars.templates.signature=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p='
        \n\n
        \n\n
        \n
        \n ';return i=null!=(i=t.signature||(null!=e?e.signature:e))?i:l,s=typeof i===r?i.call(e,{name:"signature",hash:{},data:a}):i,null!=s&&(p+=s),p+'\n
        \n\n
        \n
        '+o((i=null!=(i=t.sampleJSON||(null!=e?e.sampleJSON:e))?i:l,typeof i===r?i.call(e,{name:"sampleJSON",hash:{},data:a}):i))+'
        \n \n
        \n
        \n\n'},useData:!0});var StatusCodeView,__extends=function(e,t){function n(){this.constructor=e}for(var a in t)__hasProp.call(t,a)&&(e[a]=t[a]);return n.prototype=t.prototype,e.prototype=new n,e.__super__=t.prototype,e},__hasProp={}.hasOwnProperty;StatusCodeView=function(e){function t(){return t.__super__.constructor.apply(this,arguments)}return __extends(t,e),t.prototype.initialize=function(){},t.prototype.render=function(){var e,t,n;return n=this.template(),$(this.el).html(n(this.model)),swaggerUi.api.models.hasOwnProperty(this.model.responseModel)?(e={sampleJSON:JSON.stringify(swaggerUi.api.models[this.model.responseModel].createJSONSample(),null,2),isParam:!1,signature:swaggerUi.api.models[this.model.responseModel].getMockSignature()},t=new SignatureView({model:e,tagName:"div"}),$(".model-signature",this.$el).append(t.render().el)):$(".model-signature",this.$el).html(""),this},t.prototype.template=function(){return Handlebars.templates.status_code},t}(Backbone.View),this.Handlebars.templates.status_code=Handlebars.template({compiler:[6,">= 2.0.0-beta.1"],main:function(e,t,n,a){var s,i,r="function",l=t.helperMissing,o=this.escapeExpression,p=""+o((i=null!=(i=t.code||(null!=e?e.code:e))?i:l,typeof i===r?i.call(e,{name:"code",hash:{},data:a}):i))+"\n";return i=null!=(i=t.message||(null!=e?e.message:e))?i:l,s=typeof i===r?i.call(e,{name:"message",hash:{},data:a}):i,null!=s&&(p+=s),p+"\n"},useData:!0}); \ No newline at end of file diff --git a/catalog-core/catalog-mgr/src/main/resources/migrations.xml b/catalog-core/catalog-mgr/src/main/resources/migrations.xml index 41231d6e..84181c62 100644 --- a/catalog-core/catalog-mgr/src/main/resources/migrations.xml +++ b/catalog-core/catalog-mgr/src/main/resources/migrations.xml @@ -1,7 +1,7 @@