diff --git a/build-browser-diags.json b/build-browser-diags.json index d4e1f82..3092bb8 100644 --- a/build-browser-diags.json +++ b/build-browser-diags.json @@ -1,7 +1,9 @@ { - "source": "src/diags", - "output": "lib/standard", - "lint": {}, - "uglify": {}, - "extensions": { "uglify": "min" } + "source" : "src/diags", + "output" : "lib/standard", + "lint" : {}, + "uglify" : {}, + "extensions" : { + "uglify" : "min" + } } \ No newline at end of file diff --git a/build-browser.json b/build-browser.json index 5d0105c..45b8f50 100644 --- a/build-browser.json +++ b/build-browser.json @@ -1,10 +1,12 @@ { - "source": "src/main", - "output": "lib/standard", - "lint": {}, - "uglify": {}, - "extensions": { "uglify": "min" }, - "hosts": { + "source" : "src/main", + "output" : "lib/standard", + "lint" : {}, + "uglify" : {}, + "extensions" : { + "uglify" : "min" + }, + "hosts" : { "/" : "./" }, "port" : 8080 diff --git a/example/amd/index.html b/example/amd/index.html index 26bb8a4..33c3e8c 100644 --- a/example/amd/index.html +++ b/example/amd/index.html @@ -1,50 +1,50 @@ + "http://www.w3.org/TR/html4/loose.dtd"> - Postal Examples (AMD/require.js Lib Format) - - + Postal Examples (AMD/require.js Lib Format) + + -
- Example 1 - The World's Simplest Subscription -
-
+
+ Example 1 - The World's Simplest Subscription +
+
-
- Example 2 - Subscribing with the "#" wildcard character - -
+
+ Example 2 - Subscribing with the "#" wildcard character + +
-
- Example 3 - Subscribing with the "*" wildcard character - -
+
+ Example 3 - Subscribing with the "*" wildcard character + +
-
- Example 4 - using ignoreDuplicates() - -
+
+ Example 4 - using ignoreDuplicates() + +
-
- Example 5 - using disposeAfter(X) - -
+
+ Example 5 - using disposeAfter(X) + +
-
- Example 6 - using withConstraint() to apply a predicate to subscription callback - -
+
+ Example 6 - using withConstraint() to apply a predicate to subscription callback + +
-
- Example 7 - using withContext to set the "this" context - -
+
+ Example 7 - using withContext to set the "this" context + +
-
- Example 8 - using withDelay to delay evaluation of subscription - -
+
+ Example 8 - using withDelay to delay evaluation of subscription + +
\ No newline at end of file diff --git a/example/amd/js/examples.js b/example/amd/js/examples.js index f333a02..d6884e9 100644 --- a/example/amd/js/examples.js +++ b/example/amd/js/examples.js @@ -1,11 +1,13 @@ -define(['postal', 'postaldiags'], function(postal, diags){ +define( ['postal', 'postaldiags'], function ( postal, diags ) { // The world's simplest subscription - var channel = postal.channel("Name.Changed"); + var channel = postal.channel( "Name.Changed" ); // subscribe - var subscription = channel.subscribe(function(data) { $("#example1").html("Name: " + data.name); }); + var subscription = channel.subscribe( function ( data ) { + $( "#example1" ).html( "Name: " + data.name ); + } ); // And someone publishes a first name change: - channel.publish({ name: "Dr. Who" }); + channel.publish( { name : "Dr. Who" } ); subscription.unsubscribe(); @@ -13,14 +15,14 @@ define(['postal', 'postaldiags'], function(postal, diags){ // The # symbol represents "one word" in a topic (i.e - the text between two periods of a topic). // By subscribing to "#.Changed", the binding will match // Name.Changed & Location.Changed but *not* for Changed.Companion - var hashChannel = postal.channel("#.Changed"), - chgSubscription = hashChannel.subscribe(function(data) { - $('
  • ' + data.type + " Changed: " + data.value + '
  • ').appendTo("#example2"); - }); - postal.channel("Name.Changed") - .publish({ type: "Name", value:"John Smith" }); - postal.channel("Location.Changed") - .publish({ type: "Location", value: "Early 20th Century England" }); + var hashChannel = postal.channel( "#.Changed" ), + chgSubscription = hashChannel.subscribe( function ( data ) { + $( '
  • ' + data.type + " Changed: " + data.value + '
  • ' ).appendTo( "#example2" ); + } ); + postal.channel( "Name.Changed" ) + .publish( { type : "Name", value : "John Smith" } ); + postal.channel( "Location.Changed" ) + .publish( { type : "Location", value : "Early 20th Century England" } ); chgSubscription.unsubscribe(); @@ -28,94 +30,101 @@ define(['postal', 'postaldiags'], function(postal, diags){ // The * symbol represents any number of characters/words in a topic string. // By subscribing to "DrWho.*.Changed", the binding will match // DrWho.NinthDoctor.Companion.Changed & DrWho.Location.Changed but *not* Changed - var starChannel = postal.channel("DrWho.*.Changed"), - starSubscription = starChannel.subscribe(function(data) { - $('
  • ' + data.type + " Changed: " + data.value + '
  • ').appendTo("#example3"); - }); - postal.channel("DrWho.NinthDoctor.Companion.Changed") - .publish({ type: "Companion Name", value:"Rose" }); - postal.channel("DrWho.TenthDoctor.Companion.Changed") - .publish({ type: "Companion Name", value:"Martha" }); - postal.channel("DrWho.Eleventh.Companion.Changed") - .publish({ type: "Companion Name", value:"Amy" }); - postal.channel("DrWho.Location.Changed") - .publish({ type: "Location", value: "The Library" }); - postal.channel("TheMaster.DrumBeat.Changed") - .publish({ type: "DrumBeat", value: "This won't trigger any subscriptions" }); - postal.channel("Changed") - .publish({ type: "Useless", value: "This won't trigger any subscriptions either" }); + var starChannel = postal.channel( "DrWho.*.Changed" ), + starSubscription = starChannel.subscribe( function ( data ) { + $( '
  • ' + data.type + " Changed: " + data.value + '
  • ' ).appendTo( "#example3" ); + } ); + postal.channel( "DrWho.NinthDoctor.Companion.Changed" ) + .publish( { type : "Companion Name", value : "Rose" } ); + postal.channel( "DrWho.TenthDoctor.Companion.Changed" ) + .publish( { type : "Companion Name", value : "Martha" } ); + postal.channel( "DrWho.Eleventh.Companion.Changed" ) + .publish( { type : "Companion Name", value : "Amy" } ); + postal.channel( "DrWho.Location.Changed" ) + .publish( { type : "Location", value : "The Library" } ); + postal.channel( "TheMaster.DrumBeat.Changed" ) + .publish( { type : "DrumBeat", value : "This won't trigger any subscriptions" } ); + postal.channel( "Changed" ) + .publish( { type : "Useless", value : "This won't trigger any subscriptions either" } ); starSubscription.unsubscribe(); // Applying ignoreDuplicates to a subscription - var dupChannel = postal.channel("WeepingAngel.*"), - dupSubscription = dupChannel.subscribe(function(data) { - $('
  • ' + data.value + '
  • ').appendTo("#example4"); - }).ignoreDuplicates(); - postal.channel("WeepingAngel.DontBlink") - .publish({ value:"Don't Blink" }); - postal.channel("WeepingAngel.DontBlink") - .publish({ value:"Don't Blink" }); - postal.channel("WeepingAngel.DontEvenBlink") - .publish({ value:"Don't Even Blink" }); - postal.channel("WeepingAngel.DontBlink") - .publish({ value:"Don't Close Your Eyes" }); + var dupChannel = postal.channel( "WeepingAngel.*" ), + dupSubscription = dupChannel.subscribe( + function ( data ) { + $( '
  • ' + data.value + '
  • ' ).appendTo( "#example4" ); + } ).ignoreDuplicates(); + postal.channel( "WeepingAngel.DontBlink" ) + .publish( { value : "Don't Blink" } ); + postal.channel( "WeepingAngel.DontBlink" ) + .publish( { value : "Don't Blink" } ); + postal.channel( "WeepingAngel.DontEvenBlink" ) + .publish( { value : "Don't Even Blink" } ); + postal.channel( "WeepingAngel.DontBlink" ) + .publish( { value : "Don't Close Your Eyes" } ); dupSubscription.unsubscribe(); // Using disposeAfter(X) to remove subscription automagically after X number of receives - var daChannel = postal.channel("Donna.Noble.*"), - daSubscription = daChannel.subscribe(function(data) { - $('
  • ' + data.value + '
  • ').appendTo("#example5"); - }).disposeAfter(2); - postal.channel("Donna.Noble.ScreamingAgain") - .publish({ value:"Donna Noble has left the library." }); - postal.channel("Donna.Noble.ScreamingAgain") - .publish({ value:"Donna Noble has left the library." }); - postal.channel("Donna.Noble.ScreamingAgain") - .publish({ value:"Donna Noble has left the library." }); - postal.channel("Donna.Noble.ScreamingAgain") - .publish({ value:"Donna Noble has left the library." }); - postal.channel("Donna.Noble.ScreamingAgain") - .publish({ value:"Donna Noble has left the library." }); + var daChannel = postal.channel( "Donna.Noble.*" ), + daSubscription = daChannel.subscribe( + function ( data ) { + $( '
  • ' + data.value + '
  • ' ).appendTo( "#example5" ); + } ).disposeAfter( 2 ); + postal.channel( "Donna.Noble.ScreamingAgain" ) + .publish( { value : "Donna Noble has left the library." } ); + postal.channel( "Donna.Noble.ScreamingAgain" ) + .publish( { value : "Donna Noble has left the library." } ); + postal.channel( "Donna.Noble.ScreamingAgain" ) + .publish( { value : "Donna Noble has left the library." } ); + postal.channel( "Donna.Noble.ScreamingAgain" ) + .publish( { value : "Donna Noble has left the library." } ); + postal.channel( "Donna.Noble.ScreamingAgain" ) + .publish( { value : "Donna Noble has left the library." } ); daSubscription.unsubscribe(); // Using withConstraint to apply a predicate to the subscription var drIsInTheTardis = false, - wcChannel = postal.channel("Tardis.Depart"), - wcSubscription = wcChannel.subscribe(function(data) { - $('
  • ' + data.value + '
  • ').appendTo("#example6"); - }).withConstraint(function() { return drIsInTheTardis; } ); - postal.channel("Tardis.Depart") - .publish({ value:"Time for time travel....fantastic!" }); - postal.channel("Tardis.Depart") - .publish({ value:"Time for time travel....fantastic!" }); + wcChannel = postal.channel( "Tardis.Depart" ), + wcSubscription = wcChannel.subscribe( + function ( data ) { + $( '
  • ' + data.value + '
  • ' ).appendTo( "#example6" ); + } ).withConstraint( function () { + return drIsInTheTardis; + } ); + postal.channel( "Tardis.Depart" ) + .publish( { value : "Time for time travel....fantastic!" } ); + postal.channel( "Tardis.Depart" ) + .publish( { value : "Time for time travel....fantastic!" } ); drIsInTheTardis = true; - postal.channel("Tardis.Depart") - .publish({ value:"Time for time travel....fantastic!" }); + postal.channel( "Tardis.Depart" ) + .publish( { value : "Time for time travel....fantastic!" } ); wcSubscription.unsubscribe(); // Using withContext to set the "this" context - var ctxChannel = postal.channel("Dalek.Meet.CyberMen"), - ctxSubscription = ctxChannel.subscribe(function(data) { - $('
  • ' + data.value + '
  • ').appendTo(this); - }).withContext($("#example7")); - postal.channel("Dalek.Meet.CyberMen") - .publish({ value:"Exterminate!" }); - postal.channel("Dalek.Meet.CyberMen") - .publish({ value:"Delete!" }); + var ctxChannel = postal.channel( "Dalek.Meet.CyberMen" ), + ctxSubscription = ctxChannel.subscribe( + function ( data ) { + $( '
  • ' + data.value + '
  • ' ).appendTo( this ); + } ).withContext( $( "#example7" ) ); + postal.channel( "Dalek.Meet.CyberMen" ) + .publish( { value : "Exterminate!" } ); + postal.channel( "Dalek.Meet.CyberMen" ) + .publish( { value : "Delete!" } ); ctxSubscription.unsubscribe(); // Using withDelay() to delay the subscription evaluation - var wdChannel = postal.channel("He.Will.Knock.Four.Times"), - wdSubscription = wdChannel.subscribe(function(data) { - $('
  • ' + data.value + '
  • ').appendTo($("#example8")); - }).withDelay(5000); - postal.channel("He.Will.Knock.Four.Times") - .publish({ value:"Knock!" }); - postal.channel("He.Will.Knock.Four.Times") - .publish({ value:"Knock!" }); - postal.channel("He.Will.Knock.Four.Times") - .publish({ value:"Knock!" }); - postal.channel("He.Will.Knock.Four.Times") - .publish({ value:"Knock!" }); + var wdChannel = postal.channel( "He.Will.Knock.Four.Times" ), + wdSubscription = wdChannel.subscribe( + function ( data ) { + $( '
  • ' + data.value + '
  • ' ).appendTo( $( "#example8" ) ); + } ).withDelay( 5000 ); + postal.channel( "He.Will.Knock.Four.Times" ) + .publish( { value : "Knock!" } ); + postal.channel( "He.Will.Knock.Four.Times" ) + .publish( { value : "Knock!" } ); + postal.channel( "He.Will.Knock.Four.Times" ) + .publish( { value : "Knock!" } ); + postal.channel( "He.Will.Knock.Four.Times" ) + .publish( { value : "Knock!" } ); wdSubscription.unsubscribe(); -}); \ No newline at end of file +} ); \ No newline at end of file diff --git a/example/amd/js/libs/jquery/jquery-min.js b/example/amd/js/libs/jquery/jquery-min.js index 198b3ff..c80ae49 100644 --- a/example/amd/js/libs/jquery/jquery-min.js +++ b/example/amd/js/libs/jquery/jquery-min.js @@ -1,4 +1,3320 @@ /*! jQuery v1.7.1 jquery.com | jquery.org/license */ -(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"":"")+""),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g0){if(c!=="border")for(;g=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c
    a",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="
    "+""+"
    ",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="
    t
    ",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="
    ",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; -f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;le&&i.push({elem:this,matches:d.slice(e)});for(j=0;j0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return bc[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="

    ";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="
    ";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h0)for(h=g;h=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/",""],legend:[1,"
    ","
    "],thead:[1,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],col:[2,"","
    "],area:[1,"",""],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div
    ","
    "]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() -{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1>");try{for(var c=0,d=this.length;c1&&l0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]===""&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("
    ").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); \ No newline at end of file +(function ( a, b ) { + function cy( a ) { + return f.isWindow( a ) ? a : a.nodeType === 9 ? a.defaultView || a.parentWindow : !1 + } + + function cv( a ) { + if ( !ck[a] ) { + var b = c.body, d = f( "<" + a + ">" ).appendTo( b ), e = d.css( "display" ); + d.remove(); + if ( e === "none" || e === "" ) { + cl || (cl = c.createElement( "iframe" ), cl.frameBorder = cl.width = cl.height = 0), b.appendChild( cl ); + if ( !cm || !cl.createElement ) { + cm = (cl.contentWindow || cl.contentDocument).document, cm.write( (c.compatMode === "CSS1Compat" ? "" : "") + "" ), cm.close(); + } + d = cm.createElement( a ), cm.body.appendChild( d ), e = f.css( d, "display" ), b.removeChild( cl ) + } + ck[a] = e + } + return ck[a] + } + + function cu( a, b ) { + var c = {}; + f.each( cq.concat.apply( [], cq.slice( 0, b ) ), function () { + c[this] = a + } ); + return c + } + + function ct() { + cr = b + } + + function cs() { + setTimeout( ct, 0 ); + return cr = f.now() + } + + function cj() { + try { + return new a.ActiveXObject( "Microsoft.XMLHTTP" ) + } catch ( b ) { + } + } + + function ci() { + try { + return new a.XMLHttpRequest + } catch ( b ) { + } + } + + function cc( a, c ) { + a.dataFilter && (c = a.dataFilter( c, a.dataType )); + var d = a.dataTypes, e = {}, g, h, i = d.length, j, k = d[0], l, m, n, o, p; + for ( g = 1; g < i; g++ ) { + if ( g === 1 ) { + for ( h in a.converters ) { + typeof h == "string" && (e[h.toLowerCase()] = a.converters[h]); + } + } + l = k, k = d[g]; + if ( k === "*" ) { + k = l; + } else if ( l !== "*" && l !== k ) { + m = l + " " + k, n = e[m] || e["* " + k]; + if ( !n ) { + p = b; + for ( o in e ) { + j = o.split( " " ); + if ( j[0] === l || j[0] === "*" ) { + p = e[j[1] + " " + k]; + if ( p ) { + o = e[o], o === !0 ? n = p : p === !0 && (n = o); + break + } + } + } + } + !n && !p && f.error( "No conversion from " + m.replace( " ", " to " ) ), n !== !0 && (c = n ? n( c ) : p( o( c ) )) + } + } + return c + } + + function cb( a, c, d ) { + var e = a.contents, f = a.dataTypes, g = a.responseFields, h, i, j, k; + for ( i in g ) { + i in d && (c[g[i]] = d[i]); + } + while ( f[0] === "*" ) { + f.shift(), h === b && (h = a.mimeType || c.getResponseHeader( "content-type" )); + } + if ( h ) { + for ( i in e ) { + if ( e[i] && e[i].test( h ) ) { + f.unshift( i ); + break + } + } + } + if ( f[0]in d ) { + j = f[0]; + } else { + for ( i in d ) { + if ( !f[0] || a.converters[i + " " + f[0]] ) { + j = i; + break + } + k || (k = i) + } + j = j || k + } + if ( j ) { + j !== f[0] && f.unshift( j ); + return d[j] + } + } + + function ca( a, b, c, d ) { + if ( f.isArray( b ) ) { + f.each( b, function ( b, e ) { + c || bE.test( a ) ? d( a, e ) : ca( a + "[" + (typeof e == "object" || f.isArray( e ) ? b : "") + "]", e, c, d ) + } ); + } else if ( !c && b != null && typeof b == "object" ) { + for ( var e in b ) { + ca( a + "[" + e + "]", b[e], c, d ); + } + } else { + d( a, b ) + } + } + + function b_( a, c ) { + var d, e, g = f.ajaxSettings.flatOptions || {}; + for ( d in c ) { + c[d] !== b && ((g[d] ? a : e || (e = {}))[d] = c[d]); + } + e && f.extend( !0, a, e ) + } + + function b$( a, c, d, e, f, g ) { + f = f || c.dataTypes[0], g = g || {}, g[f] = !0; + var h = a[f], i = 0, j = h ? h.length : 0, k = a === bT, l; + for ( ; i < j && (k || !l); i++ ) { + l = h[i]( c, d, e ), typeof l == "string" && (!k || g[l] ? l = b : (c.dataTypes.unshift( l ), l = b$( a, c, d, e, l, g ))); + } + (k || !l) && !g["*"] && (l = b$( a, c, d, e, "*", g )); + return l + } + + function bZ( a ) { + return function ( b, c ) { + typeof b != "string" && (c = b, b = "*"); + if ( f.isFunction( c ) ) { + var d = b.toLowerCase().split( bP ), e = 0, g = d.length, h, i, j; + for ( ; e < g; e++ ) { + h = d[e], j = /^\+/.test( h ), j && (h = h.substr( 1 ) || "*"), i = a[h] = a[h] || [], i[j ? "unshift" : "push"]( c ) + } + } + } + } + + function bC( a, b, c ) { + var d = b === "width" ? a.offsetWidth : a.offsetHeight, e = b === "width" ? bx : by, g = 0, h = e.length; + if ( d > 0 ) { + if ( c !== "border" ) { + for ( ; g < h; g++ ) { + c || (d -= parseFloat( f.css( a, "padding" + e[g] ) ) || 0), c === "margin" ? d += parseFloat( f.css( a, c + e[g] ) ) || 0 : d -= parseFloat( f.css( a, "border" + e[g] + "Width" ) ) || 0; + } + } + return d + "px" + } + d = bz( a, b, b ); + if ( d < 0 || d == null ) { + d = a.style[b] || 0; + } + d = parseFloat( d ) || 0; + if ( c ) { + for ( ; g < h; g++ ) { + d += parseFloat( f.css( a, "padding" + e[g] ) ) || 0, c !== "padding" && (d += parseFloat( f.css( a, "border" + e[g] + "Width" ) ) || 0), c === "margin" && (d += parseFloat( f.css( a, c + e[g] ) ) || 0); + } + } + return d + "px" + } + + function bp( a, b ) { + b.src ? f.ajax( {url : b.src, async : !1, dataType : "script"} ) : f.globalEval( (b.text || b.textContent || b.innerHTML || "").replace( bf, "/*$0*/" ) ), b.parentNode && b.parentNode.removeChild( b ) + } + + function bo( a ) { + var b = c.createElement( "div" ); + bh.appendChild( b ), b.innerHTML = a.outerHTML; + return b.firstChild + } + + function bn( a ) { + var b = (a.nodeName || "").toLowerCase(); + b === "input" ? bm( a ) : b !== "script" && typeof a.getElementsByTagName != "undefined" && f.grep( a.getElementsByTagName( "input" ), bm ) + } + + function bm( a ) { + if ( a.type === "checkbox" || a.type === "radio" ) { + a.defaultChecked = a.checked + } + } + + function bl( a ) { + return typeof a.getElementsByTagName != "undefined" ? a.getElementsByTagName( "*" ) : typeof a.querySelectorAll != "undefined" ? a.querySelectorAll( "*" ) : [] + } + + function bk( a, b ) { + var c; + if ( b.nodeType === 1 ) { + b.clearAttributes && b.clearAttributes(), b.mergeAttributes && b.mergeAttributes( a ), c = b.nodeName.toLowerCase(); + if ( c === "object" ) { + b.outerHTML = a.outerHTML; + } else if ( c !== "input" || a.type !== "checkbox" && a.type !== "radio" ) { + if ( c === "option" ) { + b.selected = a.defaultSelected; + } else if ( c === "input" || c === "textarea" ) { + b.defaultValue = a.defaultValue + } + } else { + a.checked && (b.defaultChecked = b.checked = a.checked), b.value !== a.value && (b.value = a.value); + } + b.removeAttribute( f.expando ) + } + } + + function bj( a, b ) { + if ( b.nodeType === 1 && !!f.hasData( a ) ) { + var c, d, e, g = f._data( a ), h = f._data( b, g ), i = g.events; + if ( i ) { + delete h.handle, h.events = {}; + for ( c in i ) { + for ( d = 0, e = i[c].length; d < e; d++ ) { + f.event.add( b, c + (i[c][d].namespace ? "." : "") + i[c][d].namespace, i[c][d], i[c][d].data ) + } + } + } + h.data && (h.data = f.extend( {}, h.data )) + } + } + + function bi( a, b ) { + return f.nodeName( a, "table" ) ? a.getElementsByTagName( "tbody" )[0] || a.appendChild( a.ownerDocument.createElement( "tbody" ) ) : a + } + + function U( a ) { + var b = V.split( "|" ), c = a.createDocumentFragment(); + if ( c.createElement ) { + while ( b.length ) { + c.createElement( b.pop() ); + } + } + return c + } + + function T( a, b, c ) { + b = b || 0; + if ( f.isFunction( b ) ) { + return f.grep( a, function ( a, d ) { + var e = !!b.call( a, d, a ); + return e === c + } ); + } + if ( b.nodeType ) { + return f.grep( a, function ( a, d ) { + return a === b === c + } ); + } + if ( typeof b == "string" ) { + var d = f.grep( a, function ( a ) { + return a.nodeType === 1 + } ); + if ( O.test( b ) ) { + return f.filter( b, d, !c ); + } + b = f.filter( b, d ) + } + return f.grep( a, function ( a, d ) { + return f.inArray( a, b ) >= 0 === c + } ) + } + + function S( a ) { + return!a || !a.parentNode || a.parentNode.nodeType === 11 + } + + function K() { + return!0 + } + + function J() { + return!1 + } + + function n( a, b, c ) { + var d = b + "defer", e = b + "queue", g = b + "mark", h = f._data( a, d ); + h && (c === "queue" || !f._data( a, e )) && (c === "mark" || !f._data( a, g )) && setTimeout( function () { + !f._data( a, e ) && !f._data( a, g ) && (f.removeData( a, d, !0 ), h.fire()) + }, 0 ) + } + + function m( a ) { + for ( var b in a ) { + if ( b === "data" && f.isEmptyObject( a[b] ) ) { + continue; + } + if ( b !== "toJSON" ) { + return!1 + } + } + return!0 + } + + function l( a, c, d ) { + if ( d === b && a.nodeType === 1 ) { + var e = "data-" + c.replace( k, "-$1" ).toLowerCase(); + d = a.getAttribute( e ); + if ( typeof d == "string" ) { + try { + d = d === "true" ? !0 : d === "false" ? !1 : d === "null" ? null : f.isNumeric( d ) ? parseFloat( d ) : j.test( d ) ? f.parseJSON( d ) : d + } catch ( g ) { + } + f.data( a, c, d ) + } else { + d = b + } + } + return d + } + + function h( a ) { + var b = g[a] = {}, c, d; + a = a.split( /\s+/ ); + for ( c = 0, d = a.length; c < d; c++ ) { + b[a[c]] = !0; + } + return b + } + + var c = a.document, d = a.navigator, e = a.location, f = function () { + function J() { + if ( !e.isReady ) { + try { + c.documentElement.doScroll( "left" ) + } catch ( a ) { + setTimeout( J, 1 ); + return + } + e.ready() + } + } + + var e = function ( a, b ) { + return new e.fn.init( a, b, h ) + }, f = a.jQuery, g = a.$, h, i = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, j = /\S/, k = /^\s+/, l = /\s+$/, m = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, n = /^[\],:{}\s]*$/, o = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, p = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, q = /(?:^|:|,)(?:\s*\[)+/g, r = /(webkit)[ \/]([\w.]+)/, s = /(opera)(?:.*version)?[ \/]([\w.]+)/, t = /(msie) ([\w.]+)/, u = /(mozilla)(?:.*? rv:([\w.]+))?/, v = /-([a-z]|[0-9])/ig, w = /^-ms-/, x = function ( a, b ) { + return(b + "").toUpperCase() + }, y = d.userAgent, z, A, B, C = Object.prototype.toString, D = Object.prototype.hasOwnProperty, E = Array.prototype.push, F = Array.prototype.slice, G = String.prototype.trim, H = Array.prototype.indexOf, I = {}; + e.fn = e.prototype = {constructor : e, init : function ( a, d, f ) { + var g, h, j, k; + if ( !a ) { + return this; + } + if ( a.nodeType ) { + this.context = this[0] = a, this.length = 1; + return this + } + if ( a === "body" && !d && c.body ) { + this.context = c, this[0] = c.body, this.selector = a, this.length = 1; + return this + } + if ( typeof a == "string" ) { + a.charAt( 0 ) !== "<" || a.charAt( a.length - 1 ) !== ">" || a.length < 3 ? g = i.exec( a ) : g = [null, a, null]; + if ( g && (g[1] || !d) ) { + if ( g[1] ) { + d = d instanceof e ? d[0] : d, k = d ? d.ownerDocument || d : c, j = m.exec( a ), j ? e.isPlainObject( d ) ? (a = [c.createElement( j[1] )], e.fn.attr.call( a, d, !0 )) : a = [k.createElement( j[1] )] : (j = e.buildFragment( [g[1]], [k] ), a = (j.cacheable ? e.clone( j.fragment ) : j.fragment).childNodes); + return e.merge( this, a ) + } + h = c.getElementById( g[2] ); + if ( h && h.parentNode ) { + if ( h.id !== g[2] ) { + return f.find( a ); + } + this.length = 1, this[0] = h + } + this.context = c, this.selector = a; + return this + } + return!d || d.jquery ? (d || f).find( a ) : this.constructor( d ).find( a ) + } + if ( e.isFunction( a ) ) { + return f.ready( a ); + } + a.selector !== b && (this.selector = a.selector, this.context = a.context); + return e.makeArray( a, this ) + }, selector : "", jquery : "1.7.1", length : 0, size : function () { + return this.length + }, toArray : function () { + return F.call( this, 0 ) + }, get : function ( a ) { + return a == null ? this.toArray() : a < 0 ? this[this.length + a] : this[a] + }, pushStack : function ( a, b, c ) { + var d = this.constructor(); + e.isArray( a ) ? E.apply( d, a ) : e.merge( d, a ), d.prevObject = this, d.context = this.context, b === "find" ? d.selector = this.selector + (this.selector ? " " : "") + c : b && (d.selector = this.selector + "." + b + "(" + c + ")"); + return d + }, each : function ( a, b ) { + return e.each( this, a, b ) + }, ready : function ( a ) { + e.bindReady(), A.add( a ); + return this + }, eq : function ( a ) { + a = +a; + return a === -1 ? this.slice( a ) : this.slice( a, a + 1 ) + }, first : function () { + return this.eq( 0 ) + }, last : function () { + return this.eq( -1 ) + }, slice : function () { + return this.pushStack( F.apply( this, arguments ), "slice", F.call( arguments ).join( "," ) ) + }, map : function ( a ) { + return this.pushStack( e.map( this, function ( b, c ) { + return a.call( b, c, b ) + } ) ) + }, end : function () { + return this.prevObject || this.constructor( null ) + }, push : E, sort : [].sort, splice : [].splice}, e.fn.init.prototype = e.fn, e.extend = e.fn.extend = function () { + var a, c, d, f, g, h, i = arguments[0] || {}, j = 1, k = arguments.length, l = !1; + typeof i == "boolean" && (l = i, i = arguments[1] || {}, j = 2), typeof i != "object" && !e.isFunction( i ) && (i = {}), k === j && (i = this, --j); + for ( ; j < k; j++ ) { + if ( (a = arguments[j]) != null ) { + for ( c in a ) { + d = i[c], f = a[c]; + if ( i === f ) { + continue; + } + l && f && (e.isPlainObject( f ) || (g = e.isArray( f ))) ? (g ? (g = !1, h = d && e.isArray( d ) ? d : []) : h = d && e.isPlainObject( d ) ? d : {}, i[c] = e.extend( l, h, f )) : f !== b && (i[c] = f) + } + } + } + return i + }, e.extend( {noConflict : function ( b ) { + a.$ === e && (a.$ = g), b && a.jQuery === e && (a.jQuery = f); + return e + }, isReady : !1, readyWait : 1, holdReady : function ( a ) { + a ? e.readyWait++ : e.ready( !0 ) + }, ready : function ( a ) { + if ( a === !0 && !--e.readyWait || a !== !0 && !e.isReady ) { + if ( !c.body ) { + return setTimeout( e.ready, 1 ); + } + e.isReady = !0; + if ( a !== !0 && --e.readyWait > 0 ) { + return; + } + A.fireWith( c, [e] ), e.fn.trigger && e( c ).trigger( "ready" ).off( "ready" ) + } + }, bindReady : function () { + if ( !A ) { + A = e.Callbacks( "once memory" ); + if ( c.readyState === "complete" ) { + return setTimeout( e.ready, 1 ); + } + if ( c.addEventListener ) { + c.addEventListener( "DOMContentLoaded", B, !1 ), a.addEventListener( "load", e.ready, !1 ); + } else if ( c.attachEvent ) { + c.attachEvent( "onreadystatechange", B ), a.attachEvent( "onload", e.ready ); + var b = !1; + try { + b = a.frameElement == null + } catch ( d ) { + } + c.documentElement.doScroll && b && J() + } + } + }, isFunction : function ( a ) { + return e.type( a ) === "function" + }, isArray : Array.isArray || function ( a ) { + return e.type( a ) === "array" + }, isWindow : function ( a ) { + return a && typeof a == "object" && "setInterval"in a + }, isNumeric : function ( a ) { + return!isNaN( parseFloat( a ) ) && isFinite( a ) + }, type : function ( a ) { + return a == null ? String( a ) : I[C.call( a )] || "object" + }, isPlainObject : function ( a ) { + if ( !a || e.type( a ) !== "object" || a.nodeType || e.isWindow( a ) ) { + return!1; + } + try { + if ( a.constructor && !D.call( a, "constructor" ) && !D.call( a.constructor.prototype, "isPrototypeOf" ) ) { + return!1 + } + } catch ( c ) { + return!1 + } + var d; + for ( d in a ) { + ; + } + return d === b || D.call( a, d ) + }, isEmptyObject : function ( a ) { + for ( var b in a ) { + return!1; + } + return!0 + }, error : function ( a ) { + throw new Error( a ) + }, parseJSON : function ( b ) { + if ( typeof b != "string" || !b ) { + return null; + } + b = e.trim( b ); + if ( a.JSON && a.JSON.parse ) { + return a.JSON.parse( b ); + } + if ( n.test( b.replace( o, "@" ).replace( p, "]" ).replace( q, "" ) ) ) { + return(new Function( "return " + b ))(); + } + e.error( "Invalid JSON: " + b ) + }, parseXML : function ( c ) { + var d, f; + try { + a.DOMParser ? (f = new DOMParser, d = f.parseFromString( c, "text/xml" )) : (d = new ActiveXObject( "Microsoft.XMLDOM" ), d.async = "false", d.loadXML( c )) + } catch ( g ) { + d = b + } + (!d || !d.documentElement || d.getElementsByTagName( "parsererror" ).length) && e.error( "Invalid XML: " + c ); + return d + }, noop : function () { + }, globalEval : function ( b ) { + b && j.test( b ) && (a.execScript || function ( b ) { + a.eval.call( a, b ) + })( b ) + }, camelCase : function ( a ) { + return a.replace( w, "ms-" ).replace( v, x ) + }, nodeName : function ( a, b ) { + return a.nodeName && a.nodeName.toUpperCase() === b.toUpperCase() + }, each : function ( a, c, d ) { + var f, g = 0, h = a.length, i = h === b || e.isFunction( a ); + if ( d ) { + if ( i ) { + for ( f in a ) { + if ( c.apply( a[f], d ) === !1 ) { + break + } + } + } else { + for ( ; g < h; ) { + if ( c.apply( a[g++], d ) === !1 ) { + break + } + } + } + } else if ( i ) { + for ( f in a ) { + if ( c.call( a[f], f, a[f] ) === !1 ) { + break + } + } + } else { + for ( ; g < h; ) { + if ( c.call( a[g], g, a[g++] ) === !1 ) { + break; + } + } + } + return a + }, trim : G ? function ( a ) { + return a == null ? "" : G.call( a ) + } : function ( a ) { + return a == null ? "" : (a + "").replace( k, "" ).replace( l, "" ) + }, makeArray : function ( a, b ) { + var c = b || []; + if ( a != null ) { + var d = e.type( a ); + a.length == null || d === "string" || d === "function" || d === "regexp" || e.isWindow( a ) ? E.call( c, a ) : e.merge( c, a ) + } + return c + }, inArray : function ( a, b, c ) { + var d; + if ( b ) { + if ( H ) { + return H.call( b, a, c ); + } + d = b.length, c = c ? c < 0 ? Math.max( 0, d + c ) : c : 0; + for ( ; c < d; c++ ) { + if ( c in b && b[c] === a ) { + return c + } + } + } + return-1 + }, merge : function ( a, c ) { + var d = a.length, e = 0; + if ( typeof c.length == "number" ) { + for ( var f = c.length; e < f; e++ ) { + a[d++] = c[e]; + } + } else { + while ( c[e] !== b ) { + a[d++] = c[e++]; + } + } + a.length = d; + return a + }, grep : function ( a, b, c ) { + var d = [], e; + c = !!c; + for ( var f = 0, g = a.length; f < g; f++ ) { + e = !!b( a[f], f ), c !== e && d.push( a[f] ); + } + return d + }, map : function ( a, c, d ) { + var f, g, h = [], i = 0, j = a.length, k = a instanceof e || j !== b && typeof j == "number" && (j > 0 && a[0] && a[j - 1] || j === 0 || e.isArray( a )); + if ( k ) { + for ( ; i < j; i++ ) { + f = c( a[i], i, d ), f != null && (h[h.length] = f); + } + } else { + for ( g in a ) { + f = c( a[g], g, d ), f != null && (h[h.length] = f); + } + } + return h.concat.apply( [], h ) + }, guid : 1, proxy : function ( a, c ) { + if ( typeof c == "string" ) { + var d = a[c]; + c = a, a = d + } + if ( !e.isFunction( a ) ) { + return b; + } + var f = F.call( arguments, 2 ), g = function () { + return a.apply( c, f.concat( F.call( arguments ) ) ) + }; + g.guid = a.guid = a.guid || g.guid || e.guid++; + return g + }, access : function ( a, c, d, f, g, h ) { + var i = a.length; + if ( typeof c == "object" ) { + for ( var j in c ) { + e.access( a, j, c[j], f, g, d ); + } + return a + } + if ( d !== b ) { + f = !h && f && e.isFunction( d ); + for ( var k = 0; k < i; k++ ) { + g( a[k], c, f ? d.call( a[k], k, g( a[k], c ) ) : d, h ); + } + return a + } + return i ? g( a[0], c ) : b + }, now : function () { + return(new Date).getTime() + }, uaMatch : function ( a ) { + a = a.toLowerCase(); + var b = r.exec( a ) || s.exec( a ) || t.exec( a ) || a.indexOf( "compatible" ) < 0 && u.exec( a ) || []; + return{browser : b[1] || "", version : b[2] || "0"} + }, sub : function () { + function a( b, c ) { + return new a.fn.init( b, c ) + } + + e.extend( !0, a, this ), a.superclass = this, a.fn = a.prototype = this(), a.fn.constructor = a, a.sub = this.sub, a.fn.init = function ( d, f ) { + f && f instanceof e && !(f instanceof a) && (f = a( f )); + return e.fn.init.call( this, d, f, b ) + }, a.fn.init.prototype = a.fn; + var b = a( c ); + return a + }, browser : {}} ), e.each( "Boolean Number String Function Array Date RegExp Object".split( " " ), function ( a, b ) { + I["[object " + b + "]"] = b.toLowerCase() + } ), z = e.uaMatch( y ), z.browser && (e.browser[z.browser] = !0, e.browser.version = z.version), e.browser.webkit && (e.browser.safari = !0), j.test( " " ) && (k = /^[\s\xA0]+/, l = /[\s\xA0]+$/), h = e( c ), c.addEventListener ? B = function () { + c.removeEventListener( "DOMContentLoaded", B, !1 ), e.ready() + } : c.attachEvent && (B = function () { + c.readyState === "complete" && (c.detachEvent( "onreadystatechange", B ), e.ready()) + }); + return e + }(), g = {}; + f.Callbacks = function ( a ) { + a = a ? g[a] || h( a ) : {}; + var c = [], d = [], e, i, j, k, l, m = function ( b ) { + var d, e, g, h, i; + for ( d = 0, e = b.length; d < e; d++ ) { + g = b[d], h = f.type( g ), h === "array" ? m( g ) : h === "function" && (!a.unique || !o.has( g )) && c.push( g ) + } + }, n = function ( b, f ) { + f = f || [], e = !a.memory || [b, f], i = !0, l = j || 0, j = 0, k = c.length; + for ( ; c && l < k; l++ ) { + if ( c[l].apply( b, f ) === !1 && a.stopOnFalse ) { + e = !0; + break + } + } + i = !1, c && (a.once ? e === !0 ? o.disable() : c = [] : d && d.length && (e = d.shift(), o.fireWith( e[0], e[1] ))) + }, o = {add : function () { + if ( c ) { + var a = c.length; + m( arguments ), i ? k = c.length : e && e !== !0 && (j = a, n( e[0], e[1] )) + } + return this + }, remove : function () { + if ( c ) { + var b = arguments, d = 0, e = b.length; + for ( ; d < e; d++ ) { + for ( var f = 0; f < c.length; f++ ) { + if ( b[d] === c[f] ) { + i && f <= k && (k--, f <= l && l--), c.splice( f--, 1 ); + if ( a.unique ) { + break + } + } + } + } + } + return this + }, has : function ( a ) { + if ( c ) { + var b = 0, d = c.length; + for ( ; b < d; b++ ) { + if ( a === c[b] ) { + return!0 + } + } + } + return!1 + }, empty : function () { + c = []; + return this + }, disable : function () { + c = d = e = b; + return this + }, disabled : function () { + return!c + }, lock : function () { + d = b, (!e || e === !0) && o.disable(); + return this + }, locked : function () { + return!d + }, fireWith : function ( b, c ) { + d && (i ? a.once || d.push( [b, c] ) : (!a.once || !e) && n( b, c )); + return this + }, fire : function () { + o.fireWith( this, arguments ); + return this + }, fired : function () { + return!!e + }}; + return o + }; + var i = [].slice; + f.extend( {Deferred : function ( a ) { + var b = f.Callbacks( "once memory" ), c = f.Callbacks( "once memory" ), d = f.Callbacks( "memory" ), e = "pending", g = {resolve : b, reject : c, notify : d}, h = {done : b.add, fail : c.add, progress : d.add, state : function () { + return e + }, isResolved : b.fired, isRejected : c.fired, then : function ( a, b, c ) { + i.done( a ).fail( b ).progress( c ); + return this + }, always : function () { + i.done.apply( i, arguments ).fail.apply( i, arguments ); + return this + }, pipe : function ( a, b, c ) { + return f.Deferred( + function ( d ) { + f.each( {done : [a, "resolve"], fail : [b, "reject"], progress : [c, "notify"]}, function ( a, b ) { + var c = b[0], e = b[1], g; + f.isFunction( c ) ? i[a]( function () { + g = c.apply( this, arguments ), g && f.isFunction( g.promise ) ? g.promise().then( d.resolve, d.reject, d.notify ) : d[e + "With"]( this === i ? d : this, [g] ) + } ) : i[a]( d[e] ) + } ) + } ).promise() + }, promise : function ( a ) { + if ( a == null ) { + a = h; + } else { + for ( var b in h ) { + a[b] = h[b]; + } + } + return a + }}, i = h.promise( {} ), j; + for ( j in g ) { + i[j] = g[j].fire, i[j + "With"] = g[j].fireWith; + } + i.done( + function () { + e = "resolved" + }, c.disable, d.lock ).fail( function () { + e = "rejected" + }, b.disable, d.lock ), a && a.call( i, i ); + return i + }, when : function ( a ) { + function m( a ) { + return function ( b ) { + e[a] = arguments.length > 1 ? i.call( arguments, 0 ) : b, j.notifyWith( k, e ) + } + } + + function l( a ) { + return function ( c ) { + b[a] = arguments.length > 1 ? i.call( arguments, 0 ) : c, --g || j.resolveWith( j, b ) + } + } + + var b = i.call( arguments, 0 ), c = 0, d = b.length, e = Array( d ), g = d, h = d, j = d <= 1 && a && f.isFunction( a.promise ) ? a : f.Deferred(), k = j.promise(); + if ( d > 1 ) { + for ( ; c < d; c++ ) { + b[c] && b[c].promise && f.isFunction( b[c].promise ) ? b[c].promise().then( l( c ), j.reject, m( c ) ) : --g; + } + g || j.resolveWith( j, b ) + } else { + j !== a && j.resolveWith( j, d ? [a] : [] ); + } + return k + }} ), f.support = function () { + var b, d, e, g, h, i, j, k, l, m, n, o, p, q = c.createElement( "div" ), r = c.documentElement; + q.setAttribute( "className", "t" ), q.innerHTML = "
    a", d = q.getElementsByTagName( "*" ), e = q.getElementsByTagName( "a" )[0]; + if ( !d || !d.length || !e ) { + return{}; + } + g = c.createElement( "select" ), h = g.appendChild( c.createElement( "option" ) ), i = q.getElementsByTagName( "input" )[0], b = {leadingWhitespace : q.firstChild.nodeType === 3, tbody : !q.getElementsByTagName( "tbody" ).length, htmlSerialize : !!q.getElementsByTagName( "link" ).length, style : /top/.test( e.getAttribute( "style" ) ), hrefNormalized : e.getAttribute( "href" ) === "/a", opacity : /^0.55/.test( e.style.opacity ), cssFloat : !!e.style.cssFloat, checkOn : i.value === "on", optSelected : h.selected, getSetAttribute : q.className !== "t", enctype : !!c.createElement( "form" ).enctype, html5Clone : c.createElement( "nav" ).cloneNode( !0 ).outerHTML !== "<:nav>", submitBubbles : !0, changeBubbles : !0, focusinBubbles : !1, deleteExpando : !0, noCloneEvent : !0, inlineBlockNeedsLayout : !1, shrinkWrapBlocks : !1, reliableMarginRight : !0}, i.checked = !0, b.noCloneChecked = i.cloneNode( !0 ).checked, g.disabled = !0, b.optDisabled = !h.disabled; + try { + delete q.test + } catch ( s ) { + b.deleteExpando = !1 + } + !q.addEventListener && q.attachEvent && q.fireEvent && (q.attachEvent( "onclick", function () { + b.noCloneEvent = !1 + } ), q.cloneNode( !0 ).fireEvent( "onclick" )), i = c.createElement( "input" ), i.value = "t", i.setAttribute( "type", "radio" ), b.radioValue = i.value === "t", i.setAttribute( "checked", "checked" ), q.appendChild( i ), k = c.createDocumentFragment(), k.appendChild( q.lastChild ), b.checkClone = k.cloneNode( !0 ).cloneNode( !0 ).lastChild.checked, b.appendChecked = i.checked, k.removeChild( i ), k.appendChild( q ), q.innerHTML = "", a.getComputedStyle && (j = c.createElement( "div" ), j.style.width = "0", j.style.marginRight = "0", q.style.width = "2px", q.appendChild( j ), b.reliableMarginRight = (parseInt( (a.getComputedStyle( j, null ) || {marginRight : 0}).marginRight, 10 ) || 0) === 0); + if ( q.attachEvent ) { + for ( o in{submit : 1, change : 1, focusin : 1} ) { + n = "on" + o, p = n in q, p || (q.setAttribute( n, "return;" ), p = typeof q[n] == "function"), b[o + "Bubbles"] = p; + } + } + k.removeChild( q ), k = g = h = j = q = i = null, f( function () { + var a, d, e, g, h, i, j, k, m, n, o, r = c.getElementsByTagName( "body" )[0]; + !r || (j = 1, k = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;", m = "visibility:hidden;border:0;", n = "style='" + k + "border:5px solid #000;padding:0;'", o = "
    " + "" + "
    ", a = c.createElement( "div" ), a.style.cssText = m + "width:0;height:0;position:static;top:0;margin-top:" + j + "px", r.insertBefore( a, r.firstChild ), q = c.createElement( "div" ), a.appendChild( q ), q.innerHTML = "
    t
    ", l = q.getElementsByTagName( "td" ), p = l[0].offsetHeight === 0, l[0].style.display = "", l[1].style.display = "none", b.reliableHiddenOffsets = p && l[0].offsetHeight === 0, q.innerHTML = "", q.style.width = q.style.paddingLeft = "1px", f.boxModel = b.boxModel = q.offsetWidth === 2, typeof q.style.zoom != "undefined" && (q.style.display = "inline", q.style.zoom = 1, b.inlineBlockNeedsLayout = q.offsetWidth === 2, q.style.display = "", q.innerHTML = "
    ", b.shrinkWrapBlocks = q.offsetWidth !== 2), q.style.cssText = k + m, q.innerHTML = o, d = q.firstChild, e = d.firstChild, h = d.nextSibling.firstChild.firstChild, i = {doesNotAddBorder : e.offsetTop !== 5, doesAddBorderForTableAndCells : h.offsetTop === 5}, e.style.position = "fixed", e.style.top = "20px", i.fixedPosition = e.offsetTop === 20 || e.offsetTop === 15, e.style.position = e.style.top = "", d.style.overflow = "hidden", d.style.position = "relative", i.subtractsBorderForOverflowNotVisible = e.offsetTop === -5, i.doesNotIncludeMarginInBodyOffset = r.offsetTop !== j, r.removeChild( a ), q = a = null, f.extend( b, i )) + } ); + return b + }(); + var j = /^(?:\{.*\}|\[.*\])$/, k = /([A-Z])/g; + f.extend( {cache : {}, uuid : 0, expando : "jQuery" + (f.fn.jquery + Math.random()).replace( /\D/g, "" ), noData : {embed : !0, object : "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", applet : !0}, hasData : function ( a ) { + a = a.nodeType ? f.cache[a[f.expando]] : a[f.expando]; + return!!a && !m( a ) + }, data : function ( a, c, d, e ) { + if ( !!f.acceptData( a ) ) { + var g, h, i, j = f.expando, k = typeof c == "string", l = a.nodeType, m = l ? f.cache : a, n = l ? a[j] : a[j] && j, o = c === "events"; + if ( (!n || !m[n] || !o && !e && !m[n].data) && k && d === b ) { + return; + } + n || (l ? a[j] = n = ++f.uuid : n = j), m[n] || (m[n] = {}, l || (m[n].toJSON = f.noop)); + if ( typeof c == "object" || typeof c == "function" ) { + e ? m[n] = f.extend( m[n], c ) : m[n].data = f.extend( m[n].data, c ); + } + g = h = m[n], e || (h.data || (h.data = {}), h = h.data), d !== b && (h[f.camelCase( c )] = d); + if ( o && !h[c] ) { + return g.events; + } + k ? (i = h[c], i == null && (i = h[f.camelCase( c )])) : i = h; + return i + } + }, removeData : function ( a, b, c ) { + if ( !!f.acceptData( a ) ) { + var d, e, g, h = f.expando, i = a.nodeType, j = i ? f.cache : a, k = i ? a[h] : h; + if ( !j[k] ) { + return; + } + if ( b ) { + d = c ? j[k] : j[k].data; + if ( d ) { + f.isArray( b ) || (b in d ? b = [b] : (b = f.camelCase( b ), b in d ? b = [b] : b = b.split( " " ))); + for ( e = 0, g = b.length; e < g; e++ ) { + delete d[b[e]]; + } + if ( !(c ? m : f.isEmptyObject)( d ) ) { + return + } + } + } + if ( !c ) { + delete j[k].data; + if ( !m( j[k] ) ) { + return + } + } + f.support.deleteExpando || !j.setInterval ? delete j[k] : j[k] = null, i && (f.support.deleteExpando ? delete a[h] : a.removeAttribute ? a.removeAttribute( h ) : a[h] = null) + } + }, _data : function ( a, b, c ) { + return f.data( a, b, c, !0 ) + }, acceptData : function ( a ) { + if ( a.nodeName ) { + var b = f.noData[a.nodeName.toLowerCase()]; + if ( b ) { + return b !== !0 && a.getAttribute( "classid" ) === b + } + } + return!0 + }} ), f.fn.extend( {data : function ( a, c ) { + var d, e, g, h = null; + if ( typeof a == "undefined" ) { + if ( this.length ) { + h = f.data( this[0] ); + if ( this[0].nodeType === 1 && !f._data( this[0], "parsedAttrs" ) ) { + e = this[0].attributes; + for ( var i = 0, j = e.length; i < j; i++ ) { + g = e[i].name, g.indexOf( "data-" ) === 0 && (g = f.camelCase( g.substring( 5 ) ), l( this[0], g, h[g] )); + } + f._data( this[0], "parsedAttrs", !0 ) + } + } + return h + } + if ( typeof a == "object" ) { + return this.each( function () { + f.data( this, a ) + } ); + } + d = a.split( "." ), d[1] = d[1] ? "." + d[1] : ""; + if ( c === b ) { + h = this.triggerHandler( "getData" + d[1] + "!", [d[0]] ), h === b && this.length && (h = f.data( this[0], a ), h = l( this[0], a, h )); + return h === b && d[1] ? this.data( d[0] ) : h + } + return this.each( function () { + var b = f( this ), e = [d[0], c]; + b.triggerHandler( "setData" + d[1] + "!", e ), f.data( this, a, c ), b.triggerHandler( "changeData" + d[1] + "!", e ) + } ) + }, removeData : function ( a ) { + return this.each( function () { + f.removeData( this, a ) + } ) + }} ), f.extend( {_mark : function ( a, b ) { + a && (b = (b || "fx") + "mark", f._data( a, b, (f._data( a, b ) || 0) + 1 )) + }, _unmark : function ( a, b, c ) { + a !== !0 && (c = b, b = a, a = !1); + if ( b ) { + c = c || "fx"; + var d = c + "mark", e = a ? 0 : (f._data( b, d ) || 1) - 1; + e ? f._data( b, d, e ) : (f.removeData( b, d, !0 ), n( b, c, "mark" )) + } + }, queue : function ( a, b, c ) { + var d; + if ( a ) { + b = (b || "fx") + "queue", d = f._data( a, b ), c && (!d || f.isArray( c ) ? d = f._data( a, b, f.makeArray( c ) ) : d.push( c )); + return d || [] + } + }, dequeue : function ( a, b ) { + b = b || "fx"; + var c = f.queue( a, b ), d = c.shift(), e = {}; + d === "inprogress" && (d = c.shift()), d && (b === "fx" && c.unshift( "inprogress" ), f._data( a, b + ".run", e ), d.call( a, function () { + f.dequeue( a, b ) + }, e )), c.length || (f.removeData( a, b + "queue " + b + ".run", !0 ), n( a, b, "queue" )) + }} ), f.fn.extend( {queue : function ( a, c ) { + typeof a != "string" && (c = a, a = "fx"); + if ( c === b ) { + return f.queue( this[0], a ); + } + return this.each( function () { + var b = f.queue( this, a, c ); + a === "fx" && b[0] !== "inprogress" && f.dequeue( this, a ) + } ) + }, dequeue : function ( a ) { + return this.each( function () { + f.dequeue( this, a ) + } ) + }, delay : function ( a, b ) { + a = f.fx ? f.fx.speeds[a] || a : a, b = b || "fx"; + return this.queue( b, function ( b, c ) { + var d = setTimeout( b, a ); + c.stop = function () { + clearTimeout( d ) + } + } ) + }, clearQueue : function ( a ) { + return this.queue( a || "fx", [] ) + }, promise : function ( a, c ) { + function m() { + --h || d.resolveWith( e, [e] ) + } + + typeof a != "string" && (c = a, a = b), a = a || "fx"; + var d = f.Deferred(), e = this, g = e.length, h = 1, i = a + "defer", j = a + "queue", k = a + "mark", l; + while ( g-- ) { + if ( l = f.data( e[g], i, b, !0 ) || (f.data( e[g], j, b, !0 ) || f.data( e[g], k, b, !0 )) && f.data( e[g], i, f.Callbacks( "once memory" ), !0 ) ) { + h++, l.add( m ); + } + } + m(); + return d.promise() + }} ); + var o = /[\n\t\r]/g, p = /\s+/, q = /\r/g, r = /^(?:button|input)$/i, s = /^(?:button|input|object|select|textarea)$/i, t = /^a(?:rea)?$/i, u = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, v = f.support.getSetAttribute, w, x, y; + f.fn.extend( {attr : function ( a, b ) { + return f.access( this, a, b, !0, f.attr ) + }, removeAttr : function ( a ) { + return this.each( function () { + f.removeAttr( this, a ) + } ) + }, prop : function ( a, b ) { + return f.access( this, a, b, !0, f.prop ) + }, removeProp : function ( a ) { + a = f.propFix[a] || a; + return this.each( function () { + try { + this[a] = b, delete this[a] + } catch ( c ) { + } + } ) + }, addClass : function ( a ) { + var b, c, d, e, g, h, i; + if ( f.isFunction( a ) ) { + return this.each( function ( b ) { + f( this ).addClass( a.call( this, b, this.className ) ) + } ); + } + if ( a && typeof a == "string" ) { + b = a.split( p ); + for ( c = 0, d = this.length; c < d; c++ ) { + e = this[c]; + if ( e.nodeType === 1 ) { + if ( !e.className && b.length === 1 ) { + e.className = a; + } else { + g = " " + e.className + " "; + for ( h = 0, i = b.length; h < i; h++ ) { + ~g.indexOf( " " + b[h] + " " ) || (g += b[h] + " "); + } + e.className = f.trim( g ) + } + } + } + } + return this + }, removeClass : function ( a ) { + var c, d, e, g, h, i, j; + if ( f.isFunction( a ) ) { + return this.each( function ( b ) { + f( this ).removeClass( a.call( this, b, this.className ) ) + } ); + } + if ( a && typeof a == "string" || a === b ) { + c = (a || "").split( p ); + for ( d = 0, e = this.length; d < e; d++ ) { + g = this[d]; + if ( g.nodeType === 1 && g.className ) { + if ( a ) { + h = (" " + g.className + " ").replace( o, " " ); + for ( i = 0, j = c.length; i < j; i++ ) { + h = h.replace( " " + c[i] + " ", " " ); + } + g.className = f.trim( h ) + } else { + g.className = "" + } + } + } + } + return this + }, toggleClass : function ( a, b ) { + var c = typeof a, d = typeof b == "boolean"; + if ( f.isFunction( a ) ) { + return this.each( function ( c ) { + f( this ).toggleClass( a.call( this, c, this.className, b ), b ) + } ); + } + return this.each( function () { + if ( c === "string" ) { + var e, g = 0, h = f( this ), i = b, j = a.split( p ); + while ( e = j[g++] ) { + i = d ? i : !h.hasClass( e ), h[i ? "addClass" : "removeClass"]( e ) + } + } else if ( c === "undefined" || c === "boolean" ) { + this.className && f._data( this, "__className__", this.className ), this.className = this.className || a === !1 ? "" : f._data( this, "__className__" ) || "" + } + } ) + }, hasClass : function ( a ) { + var b = " " + a + " ", c = 0, d = this.length; + for ( ; c < d; c++ ) { + if ( this[c].nodeType === 1 && (" " + this[c].className + " ").replace( o, " " ).indexOf( b ) > -1 ) { + return!0; + } + } + return!1 + }, val : function ( a ) { + var c, d, e, g = this[0]; + { + if ( !!arguments.length ) { + e = f.isFunction( a ); + return this.each( function ( d ) { + var g = f( this ), h; + if ( this.nodeType === 1 ) { + e ? h = a.call( this, d, g.val() ) : h = a, h == null ? h = "" : typeof h == "number" ? h += "" : f.isArray( h ) && (h = f.map( h, function ( a ) { + return a == null ? "" : a + "" + } )), c = f.valHooks[this.nodeName.toLowerCase()] || f.valHooks[this.type]; + if ( !c || !("set"in c) || c.set( this, h, "value" ) === b ) { + this.value = h + } + } + } ) + } + if ( g ) { + c = f.valHooks[g.nodeName.toLowerCase()] || f.valHooks[g.type]; + if ( c && "get"in c && (d = c.get( g, "value" )) !== b ) { + return d; + } + d = g.value; + return typeof d == "string" ? d.replace( q, "" ) : d == null ? "" : d + } + } + }} ), f.extend( {valHooks : {option : {get : function ( a ) { + var b = a.attributes.value; + return!b || b.specified ? a.value : a.text + }}, select : {get : function ( a ) { + var b, c, d, e, g = a.selectedIndex, h = [], i = a.options, j = a.type === "select-one"; + if ( g < 0 ) { + return null; + } + c = j ? g : 0, d = j ? g + 1 : i.length; + for ( ; c < d; c++ ) { + e = i[c]; + if ( e.selected && (f.support.optDisabled ? !e.disabled : e.getAttribute( "disabled" ) === null) && (!e.parentNode.disabled || !f.nodeName( e.parentNode, "optgroup" )) ) { + b = f( e ).val(); + if ( j ) { + return b; + } + h.push( b ) + } + } + if ( j && !h.length && i.length ) { + return f( i[g] ).val(); + } + return h + }, set : function ( a, b ) { + var c = f.makeArray( b ); + f( a ).find( "option" ).each( function () { + this.selected = f.inArray( f( this ).val(), c ) >= 0 + } ), c.length || (a.selectedIndex = -1); + return c + }}}, attrFn : {val : !0, css : !0, html : !0, text : !0, data : !0, width : !0, height : !0, offset : !0}, attr : function ( a, c, d, e ) { + var g, h, i, j = a.nodeType; + if ( !!a && j !== 3 && j !== 8 && j !== 2 ) { + if ( e && c in f.attrFn ) { + return f( a )[c]( d ); + } + if ( typeof a.getAttribute == "undefined" ) { + return f.prop( a, c, d ); + } + i = j !== 1 || !f.isXMLDoc( a ), i && (c = c.toLowerCase(), h = f.attrHooks[c] || (u.test( c ) ? x : w)); + if ( d !== b ) { + if ( d === null ) { + f.removeAttr( a, c ); + return + } + if ( h && "set"in h && i && (g = h.set( a, d, c )) !== b ) { + return g; + } + a.setAttribute( c, "" + d ); + return d + } + if ( h && "get"in h && i && (g = h.get( a, c )) !== null ) { + return g; + } + g = a.getAttribute( c ); + return g === null ? b : g + } + }, removeAttr : function ( a, b ) { + var c, d, e, g, h = 0; + if ( b && a.nodeType === 1 ) { + d = b.toLowerCase().split( p ), g = d.length; + for ( ; h < g; h++ ) { + e = d[h], e && (c = f.propFix[e] || e, f.attr( a, e, "" ), a.removeAttribute( v ? e : c ), u.test( e ) && c in a && (a[c] = !1)) + } + } + }, attrHooks : {type : {set : function ( a, b ) { + if ( r.test( a.nodeName ) && a.parentNode ) { + f.error( "type property can't be changed" ); + } else if ( !f.support.radioValue && b === "radio" && f.nodeName( a, "input" ) ) { + var c = a.value; + a.setAttribute( "type", b ), c && (a.value = c); + return b + } + }}, value : {get : function ( a, b ) { + if ( w && f.nodeName( a, "button" ) ) { + return w.get( a, b ); + } + return b in a ? a.value : null + }, set : function ( a, b, c ) { + if ( w && f.nodeName( a, "button" ) ) { + return w.set( a, b, c ); + } + a.value = b + }}}, propFix : {tabindex : "tabIndex", readonly : "readOnly", "for" : "htmlFor", "class" : "className", maxlength : "maxLength", cellspacing : "cellSpacing", cellpadding : "cellPadding", rowspan : "rowSpan", colspan : "colSpan", usemap : "useMap", frameborder : "frameBorder", contenteditable : "contentEditable"}, prop : function ( a, c, d ) { + var e, g, h, i = a.nodeType; + if ( !!a && i !== 3 && i !== 8 && i !== 2 ) { + h = i !== 1 || !f.isXMLDoc( a ), h && (c = f.propFix[c] || c, g = f.propHooks[c]); + return d !== b ? g && "set"in g && (e = g.set( a, d, c )) !== b ? e : a[c] = d : g && "get"in g && (e = g.get( a, c )) !== null ? e : a[c] + } + }, propHooks : {tabIndex : {get : function ( a ) { + var c = a.getAttributeNode( "tabindex" ); + return c && c.specified ? parseInt( c.value, 10 ) : s.test( a.nodeName ) || t.test( a.nodeName ) && a.href ? 0 : b + }}}} ), f.attrHooks.tabindex = f.propHooks.tabIndex, x = {get : function ( a, c ) { + var d, e = f.prop( a, c ); + return e === !0 || typeof e != "boolean" && (d = a.getAttributeNode( c )) && d.nodeValue !== !1 ? c.toLowerCase() : b + }, set : function ( a, b, c ) { + var d; + b === !1 ? f.removeAttr( a, c ) : (d = f.propFix[c] || c, d in a && (a[d] = !0), a.setAttribute( c, c.toLowerCase() )); + return c + }}, v || (y = {name : !0, id : !0}, w = f.valHooks.button = {get : function ( a, c ) { + var d; + d = a.getAttributeNode( c ); + return d && (y[c] ? d.nodeValue !== "" : d.specified) ? d.nodeValue : b + }, set : function ( a, b, d ) { + var e = a.getAttributeNode( d ); + e || (e = c.createAttribute( d ), a.setAttributeNode( e )); + return e.nodeValue = b + "" + }}, f.attrHooks.tabindex.set = w.set, f.each( ["width", "height"], function ( a, b ) { + f.attrHooks[b] = f.extend( f.attrHooks[b], {set : function ( a, c ) { + if ( c === "" ) { + a.setAttribute( b, "auto" ); + return c + } + }} ) + } ), f.attrHooks.contenteditable = {get : w.get, set : function ( a, b, c ) { + b === "" && (b = "false"), w.set( a, b, c ) + }}), f.support.hrefNormalized || f.each( ["href", "src", "width", "height"], function ( a, c ) { + f.attrHooks[c] = f.extend( f.attrHooks[c], {get : function ( a ) { + var d = a.getAttribute( c, 2 ); + return d === null ? b : d + }} ) + } ), f.support.style || (f.attrHooks.style = {get : function ( a ) { + return a.style.cssText.toLowerCase() || b + }, set : function ( a, b ) { + return a.style.cssText = "" + b + }}), f.support.optSelected || (f.propHooks.selected = f.extend( f.propHooks.selected, {get : function ( a ) { + var b = a.parentNode; + b && (b.selectedIndex, b.parentNode && b.parentNode.selectedIndex); + return null + }} )), f.support.enctype || (f.propFix.enctype = "encoding"), f.support.checkOn || f.each( ["radio", "checkbox"], function () { + f.valHooks[this] = {get : function ( a ) { + return a.getAttribute( "value" ) === null ? "on" : a.value + }} + } ), f.each( ["radio", "checkbox"], function () { + f.valHooks[this] = f.extend( f.valHooks[this], {set : function ( a, b ) { + if ( f.isArray( b ) ) { + return a.checked = f.inArray( f( a ).val(), b ) >= 0 + } + }} ) + } ); + var z = /^(?:textarea|input|select)$/i, A = /^([^\.]*)?(?:\.(.+))?$/, B = /\bhover(\.\S+)?\b/, C = /^key/, D = /^(?:mouse|contextmenu)|click/, E = /^(?:focusinfocus|focusoutblur)$/, F = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, G = function ( a ) { + var b = F.exec( a ); + b && (b[1] = (b[1] || "").toLowerCase(), b[3] = b[3] && new RegExp( "(?:^|\\s)" + b[3] + "(?:\\s|$)" )); + return b + }, H = function ( a, b ) { + var c = a.attributes || {}; + return(!b[1] || a.nodeName.toLowerCase() === b[1]) && (!b[2] || (c.id || {}).value === b[2]) && (!b[3] || b[3].test( (c["class"] || {}).value )) + }, I = function ( a ) { + return f.event.special.hover ? a : a.replace( B, "mouseenter$1 mouseleave$1" ) + }; + f.event = {add : function ( a, c, d, e, g ) { + var h, i, j, k, l, m, n, o, p, q, r, s; + if ( !(a.nodeType === 3 || a.nodeType === 8 || !c || !d || !(h = f._data( a ))) ) { + d.handler && (p = d, d = p.handler), d.guid || (d.guid = f.guid++), j = h.events, j || (h.events = j = {}), i = h.handle, i || (h.handle = i = function ( a ) { + return typeof f != "undefined" && (!a || f.event.triggered !== a.type) ? f.event.dispatch.apply( i.elem, arguments ) : b + }, i.elem = a), c = f.trim( I( c ) ).split( " " ); + for ( k = 0; k < c.length; k++ ) { + l = A.exec( c[k] ) || [], m = l[1], n = (l[2] || "").split( "." ).sort(), s = f.event.special[m] || {}, m = (g ? s.delegateType : s.bindType) || m, s = f.event.special[m] || {}, o = f.extend( {type : m, origType : l[1], data : e, handler : d, guid : d.guid, selector : g, quick : G( g ), namespace : n.join( "." )}, p ), r = j[m]; + if ( !r ) { + r = j[m] = [], r.delegateCount = 0; + if ( !s.setup || s.setup.call( a, e, n, i ) === !1 ) { + a.addEventListener ? a.addEventListener( m, i, !1 ) : a.attachEvent && a.attachEvent( "on" + m, i ) + } + } + s.add && (s.add.call( a, o ), o.handler.guid || (o.handler.guid = d.guid)), g ? r.splice( r.delegateCount++, 0, o ) : r.push( o ), f.event.global[m] = !0 + } + a = null + } + }, global : {}, remove : function ( a, b, c, d, e ) { + var g = f.hasData( a ) && f._data( a ), h, i, j, k, l, m, n, o, p, q, r, s; + if ( !!g && !!(o = g.events) ) { + b = f.trim( I( b || "" ) ).split( " " ); + for ( h = 0; h < b.length; h++ ) { + i = A.exec( b[h] ) || [], j = k = i[1], l = i[2]; + if ( !j ) { + for ( j in o ) { + f.event.remove( a, j + b[h], c, d, !0 ); + } + continue + } + p = f.event.special[j] || {}, j = (d ? p.delegateType : p.bindType) || j, r = o[j] || [], m = r.length, l = l ? new RegExp( "(^|\\.)" + l.split( "." ).sort().join( "\\.(?:.*\\.)?" ) + "(\\.|$)" ) : null; + for ( n = 0; n < r.length; n++ ) { + s = r[n], (e || k === s.origType) && (!c || c.guid === s.guid) && (!l || l.test( s.namespace )) && (!d || d === s.selector || d === "**" && s.selector) && (r.splice( n--, 1 ), s.selector && r.delegateCount--, p.remove && p.remove.call( a, s )); + } + r.length === 0 && m !== r.length && ((!p.teardown || p.teardown.call( a, l ) === !1) && f.removeEvent( a, j, g.handle ), delete o[j]) + } + f.isEmptyObject( o ) && (q = g.handle, q && (q.elem = null), f.removeData( a, ["events", "handle"], !0 )) + } + }, customEvent : {getData : !0, setData : !0, changeData : !0}, trigger : function ( c, d, e, g ) { + if ( !e || e.nodeType !== 3 && e.nodeType !== 8 ) { + var h = c.type || c, i = [], j, k, l, m, n, o, p, q, r, s; + if ( E.test( h + f.event.triggered ) ) { + return; + } + h.indexOf( "!" ) >= 0 && (h = h.slice( 0, -1 ), k = !0), h.indexOf( "." ) >= 0 && (i = h.split( "." ), h = i.shift(), i.sort()); + if ( (!e || f.event.customEvent[h]) && !f.event.global[h] ) { + return; + } + c = typeof c == "object" ? c[f.expando] ? c : new f.Event( h, c ) : new f.Event( h ), c.type = h, c.isTrigger = !0, c.exclusive = k, c.namespace = i.join( "." ), c.namespace_re = c.namespace ? new RegExp( "(^|\\.)" + i.join( "\\.(?:.*\\.)?" ) + "(\\.|$)" ) : null, o = h.indexOf( ":" ) < 0 ? "on" + h : ""; + if ( !e ) { + j = f.cache; + for ( l in j ) { + j[l].events && j[l].events[h] && f.event.trigger( c, d, j[l].handle.elem, !0 ); + } + return + } + c.result = b, c.target || (c.target = e), d = d != null ? f.makeArray( d ) : [], d.unshift( c ), p = f.event.special[h] || {}; + if ( p.trigger && p.trigger.apply( e, d ) === !1 ) { + return; + } + r = [ + [e, p.bindType || h] + ]; + if ( !g && !p.noBubble && !f.isWindow( e ) ) { + s = p.delegateType || h, m = E.test( s + h ) ? e : e.parentNode, n = null; + for ( ; m; m = m.parentNode ) { + r.push( [m, s] ), n = m; + } + n && n === e.ownerDocument && r.push( [n.defaultView || n.parentWindow || a, s] ) + } + for ( l = 0; l < r.length && !c.isPropagationStopped(); l++ ) { + m = r[l][0], c.type = r[l][1], q = (f._data( m, "events" ) || {})[c.type] && f._data( m, "handle" ), q && q.apply( m, d ), q = o && m[o], q && f.acceptData( m ) && q.apply( m, d ) === !1 && c.preventDefault(); + } + c.type = h, !g && !c.isDefaultPrevented() && (!p._default || p._default.apply( e.ownerDocument, d ) === !1) && (h !== "click" || !f.nodeName( e, "a" )) && f.acceptData( e ) && o && e[h] && (h !== "focus" && h !== "blur" || c.target.offsetWidth !== 0) && !f.isWindow( e ) && (n = e[o], n && (e[o] = null), f.event.triggered = h, e[h](), f.event.triggered = b, n && (e[o] = n)); + return c.result + } + }, dispatch : function ( c ) { + c = f.event.fix( c || a.event ); + var d = (f._data( this, "events" ) || {})[c.type] || [], e = d.delegateCount, g = [].slice.call( arguments, 0 ), h = !c.exclusive && !c.namespace, i = [], j, k, l, m, n, o, p, q, r, s, t; + g[0] = c, c.delegateTarget = this; + if ( e && !c.target.disabled && (!c.button || c.type !== "click") ) { + m = f( this ), m.context = this.ownerDocument || this; + for ( l = c.target; l != this; l = l.parentNode || this ) { + o = {}, q = [], m[0] = l; + for ( j = 0; j < e; j++ ) { + r = d[j], s = r.selector, o[s] === b && (o[s] = r.quick ? H( l, r.quick ) : m.is( s )), o[s] && q.push( r ); + } + q.length && i.push( {elem : l, matches : q} ) + } + } + d.length > e && i.push( {elem : this, matches : d.slice( e )} ); + for ( j = 0; j < i.length && !c.isPropagationStopped(); j++ ) { + p = i[j], c.currentTarget = p.elem; + for ( k = 0; k < p.matches.length && !c.isImmediatePropagationStopped(); k++ ) { + r = p.matches[k]; + if ( h || !c.namespace && !r.namespace || c.namespace_re && c.namespace_re.test( r.namespace ) ) { + c.data = r.data, c.handleObj = r, n = ((f.event.special[r.origType] || {}).handle || r.handler).apply( p.elem, g ), n !== b && (c.result = n, n === !1 && (c.preventDefault(), c.stopPropagation())) + } + } + } + return c.result + }, props : "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split( " " ), fixHooks : {}, keyHooks : {props : "char charCode key keyCode".split( " " ), filter : function ( a, b ) { + a.which == null && (a.which = b.charCode != null ? b.charCode : b.keyCode); + return a + }}, mouseHooks : {props : "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split( " " ), filter : function ( a, d ) { + var e, f, g, h = d.button, i = d.fromElement; + a.pageX == null && d.clientX != null && (e = a.target.ownerDocument || c, f = e.documentElement, g = e.body, a.pageX = d.clientX + (f && f.scrollLeft || g && g.scrollLeft || 0) - (f && f.clientLeft || g && g.clientLeft || 0), a.pageY = d.clientY + (f && f.scrollTop || g && g.scrollTop || 0) - (f && f.clientTop || g && g.clientTop || 0)), !a.relatedTarget && i && (a.relatedTarget = i === a.target ? d.toElement : i), !a.which && h !== b && (a.which = h & 1 ? 1 : h & 2 ? 3 : h & 4 ? 2 : 0); + return a + }}, fix : function ( a ) { + if ( a[f.expando] ) { + return a; + } + var d, e, g = a, h = f.event.fixHooks[a.type] || {}, i = h.props ? this.props.concat( h.props ) : this.props; + a = f.Event( g ); + for ( d = i.length; d; ) { + e = i[--d], a[e] = g[e]; + } + a.target || (a.target = g.srcElement || c), a.target.nodeType === 3 && (a.target = a.target.parentNode), a.metaKey === b && (a.metaKey = a.ctrlKey); + return h.filter ? h.filter( a, g ) : a + }, special : {ready : {setup : f.bindReady}, load : {noBubble : !0}, focus : {delegateType : "focusin"}, blur : {delegateType : "focusout"}, beforeunload : {setup : function ( a, b, c ) { + f.isWindow( this ) && (this.onbeforeunload = c) + }, teardown : function ( a, b ) { + this.onbeforeunload === b && (this.onbeforeunload = null) + }}}, simulate : function ( a, b, c, d ) { + var e = f.extend( new f.Event, c, {type : a, isSimulated : !0, originalEvent : {}} ); + d ? f.event.trigger( e, null, b ) : f.event.dispatch.call( b, e ), e.isDefaultPrevented() && c.preventDefault() + }}, f.event.handle = f.event.dispatch, f.removeEvent = c.removeEventListener ? function ( a, b, c ) { + a.removeEventListener && a.removeEventListener( b, c, !1 ) + } : function ( a, b, c ) { + a.detachEvent && a.detachEvent( "on" + b, c ) + }, f.Event = function ( a, b ) { + if ( !(this instanceof f.Event) ) { + return new f.Event( a, b ); + } + a && a.type ? (this.originalEvent = a, this.type = a.type, this.isDefaultPrevented = a.defaultPrevented || a.returnValue === !1 || a.getPreventDefault && a.getPreventDefault() ? K : J) : this.type = a, b && f.extend( this, b ), this.timeStamp = a && a.timeStamp || f.now(), this[f.expando] = !0 + }, f.Event.prototype = {preventDefault : function () { + this.isDefaultPrevented = K; + var a = this.originalEvent; + !a || (a.preventDefault ? a.preventDefault() : a.returnValue = !1) + }, stopPropagation : function () { + this.isPropagationStopped = K; + var a = this.originalEvent; + !a || (a.stopPropagation && a.stopPropagation(), a.cancelBubble = !0) + }, stopImmediatePropagation : function () { + this.isImmediatePropagationStopped = K, this.stopPropagation() + }, isDefaultPrevented : J, isPropagationStopped : J, isImmediatePropagationStopped : J}, f.each( {mouseenter : "mouseover", mouseleave : "mouseout"}, function ( a, b ) { + f.event.special[a] = {delegateType : b, bindType : b, handle : function ( a ) { + var c = this, d = a.relatedTarget, e = a.handleObj, g = e.selector, h; + if ( !d || d !== c && !f.contains( c, d ) ) { + a.type = e.origType, h = e.handler.apply( this, arguments ), a.type = b; + } + return h + }} + } ), f.support.submitBubbles || (f.event.special.submit = {setup : function () { + if ( f.nodeName( this, "form" ) ) { + return!1; + } + f.event.add( this, "click._submit keypress._submit", function ( a ) { + var c = a.target, d = f.nodeName( c, "input" ) || f.nodeName( c, "button" ) ? c.form : b; + d && !d._submit_attached && (f.event.add( d, "submit._submit", function ( a ) { + this.parentNode && !a.isTrigger && f.event.simulate( "submit", this.parentNode, a, !0 ) + } ), d._submit_attached = !0) + } ) + }, teardown : function () { + if ( f.nodeName( this, "form" ) ) { + return!1; + } + f.event.remove( this, "._submit" ) + }}), f.support.changeBubbles || (f.event.special.change = {setup : function () { + if ( z.test( this.nodeName ) ) { + if ( this.type === "checkbox" || this.type === "radio" ) { + f.event.add( this, "propertychange._change", function ( a ) { + a.originalEvent.propertyName === "checked" && (this._just_changed = !0) + } ), f.event.add( this, "click._change", function ( a ) { + this._just_changed && !a.isTrigger && (this._just_changed = !1, f.event.simulate( "change", this, a, !0 )) + } ); + } + return!1 + } + f.event.add( this, "beforeactivate._change", function ( a ) { + var b = a.target; + z.test( b.nodeName ) && !b._change_attached && (f.event.add( b, "change._change", function ( a ) { + this.parentNode && !a.isSimulated && !a.isTrigger && f.event.simulate( "change", this.parentNode, a, !0 ) + } ), b._change_attached = !0) + } ) + }, handle : function ( a ) { + var b = a.target; + if ( this !== b || a.isSimulated || a.isTrigger || b.type !== "radio" && b.type !== "checkbox" ) { + return a.handleObj.handler.apply( this, arguments ) + } + }, teardown : function () { + f.event.remove( this, "._change" ); + return z.test( this.nodeName ) + }}), f.support.focusinBubbles || f.each( {focus : "focusin", blur : "focusout"}, function ( a, b ) { + var d = 0, e = function ( a ) { + f.event.simulate( b, a.target, f.event.fix( a ), !0 ) + }; + f.event.special[b] = {setup : function () { + d++ === 0 && c.addEventListener( a, e, !0 ) + }, teardown : function () { + --d === 0 && c.removeEventListener( a, e, !0 ) + }} + } ), f.fn.extend( {on : function ( a, c, d, e, g ) { + var h, i; + if ( typeof a == "object" ) { + typeof c != "string" && (d = c, c = b); + for ( i in a ) { + this.on( i, c, d, a[i], g ); + } + return this + } + d == null && e == null ? (e = c, d = c = b) : e == null && (typeof c == "string" ? (e = d, d = b) : (e = d, d = c, c = b)); + if ( e === !1 ) { + e = J; + } else if ( !e ) { + return this; + } + g === 1 && (h = e, e = function ( a ) { + f().off( a ); + return h.apply( this, arguments ) + }, e.guid = h.guid || (h.guid = f.guid++)); + return this.each( function () { + f.event.add( this, a, e, d, c ) + } ) + }, one : function ( a, b, c, d ) { + return this.on.call( this, a, b, c, d, 1 ) + }, off : function ( a, c, d ) { + if ( a && a.preventDefault && a.handleObj ) { + var e = a.handleObj; + f( a.delegateTarget ).off( e.namespace ? e.type + "." + e.namespace : e.type, e.selector, e.handler ); + return this + } + if ( typeof a == "object" ) { + for ( var g in a ) { + this.off( g, c, a[g] ); + } + return this + } + if ( c === !1 || typeof c == "function" ) { + d = c, c = b; + } + d === !1 && (d = J); + return this.each( function () { + f.event.remove( this, a, d, c ) + } ) + }, bind : function ( a, b, c ) { + return this.on( a, null, b, c ) + }, unbind : function ( a, b ) { + return this.off( a, null, b ) + }, live : function ( a, b, c ) { + f( this.context ).on( a, this.selector, b, c ); + return this + }, die : function ( a, b ) { + f( this.context ).off( a, this.selector || "**", b ); + return this + }, delegate : function ( a, b, c, d ) { + return this.on( b, a, c, d ) + }, undelegate : function ( a, b, c ) { + return arguments.length == 1 ? this.off( a, "**" ) : this.off( b, a, c ) + }, trigger : function ( a, b ) { + return this.each( function () { + f.event.trigger( a, b, this ) + } ) + }, triggerHandler : function ( a, b ) { + if ( this[0] ) { + return f.event.trigger( a, b, this[0], !0 ) + } + }, toggle : function ( a ) { + var b = arguments, c = a.guid || f.guid++, d = 0, e = function ( c ) { + var e = (f._data( this, "lastToggle" + a.guid ) || 0) % d; + f._data( this, "lastToggle" + a.guid, e + 1 ), c.preventDefault(); + return b[e].apply( this, arguments ) || !1 + }; + e.guid = c; + while ( d < b.length ) { + b[d++].guid = c; + } + return this.click( e ) + }, hover : function ( a, b ) { + return this.mouseenter( a ).mouseleave( b || a ) + }} ), f.each( "blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split( " " ), function ( a, b ) { + f.fn[b] = function ( a, c ) { + c == null && (c = a, a = null); + return arguments.length > 0 ? this.on( b, null, a, c ) : this.trigger( b ) + }, f.attrFn && (f.attrFn[b] = !0), C.test( b ) && (f.event.fixHooks[b] = f.event.keyHooks), D.test( b ) && (f.event.fixHooks[b] = f.event.mouseHooks) + } ), function () { + function x( a, b, c, e, f, g ) { + for ( var h = 0, i = e.length; h < i; h++ ) { + var j = e[h]; + if ( j ) { + var k = !1; + j = j[a]; + while ( j ) { + if ( j[d] === c ) { + k = e[j.sizset]; + break + } + if ( j.nodeType === 1 ) { + g || (j[d] = c, j.sizset = h); + if ( typeof b != "string" ) { + if ( j === b ) { + k = !0; + break + } + } else if ( m.filter( b, [j] ).length > 0 ) { + k = j; + break + } + } + j = j[a] + } + e[h] = k + } + } + } + + function w( a, b, c, e, f, g ) { + for ( var h = 0, i = e.length; h < i; h++ ) { + var j = e[h]; + if ( j ) { + var k = !1; + j = j[a]; + while ( j ) { + if ( j[d] === c ) { + k = e[j.sizset]; + break + } + j.nodeType === 1 && !g && (j[d] = c, j.sizset = h); + if ( j.nodeName.toLowerCase() === b ) { + k = j; + break + } + j = j[a] + } + e[h] = k + } + } + } + + var a = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, d = "sizcache" + (Math.random() + "").replace( ".", "" ), e = 0, g = Object.prototype.toString, h = !1, i = !0, j = /\\/g, k = /\r\n/g, l = /\W/; + [0, 0].sort( function () { + i = !1; + return 0 + } ); + var m = function ( b, d, e, f ) { + e = e || [], d = d || c; + var h = d; + if ( d.nodeType !== 1 && d.nodeType !== 9 ) { + return[]; + } + if ( !b || typeof b != "string" ) { + return e; + } + var i, j, k, l, n, q, r, t, u = !0, v = m.isXML( d ), w = [], x = b; + do { + a.exec( "" ), i = a.exec( x ); + if ( i ) { + x = i[3], w.push( i[1] ); + if ( i[2] ) { + l = i[3]; + break + } + } + } while ( i ); + if ( w.length > 1 && p.exec( b ) ) { + if ( w.length === 2 && o.relative[w[0]] ) { + j = y( w[0] + w[1], d, f ); + } else { + j = o.relative[w[0]] ? [d] : m( w.shift(), d ); + while ( w.length ) { + b = w.shift(), o.relative[b] && (b += w.shift()), j = y( b, j, f ) + } + } + } else { + !f && w.length > 1 && d.nodeType === 9 && !v && o.match.ID.test( w[0] ) && !o.match.ID.test( w[w.length - 1] ) && (n = m.find( w.shift(), d, v ), d = n.expr ? m.filter( n.expr, n.set )[0] : n.set[0]); + if ( d ) { + n = f ? {expr : w.pop(), set : s( f )} : m.find( w.pop(), w.length === 1 && (w[0] === "~" || w[0] === "+") && d.parentNode ? d.parentNode : d, v ), j = n.expr ? m.filter( n.expr, n.set ) : n.set, w.length > 0 ? k = s( j ) : u = !1; + while ( w.length ) { + q = w.pop(), r = q, o.relative[q] ? r = w.pop() : q = "", r == null && (r = d), o.relative[q]( k, r, v ) + } + } else { + k = w = [] + } + } + k || (k = j), k || m.error( q || b ); + if ( g.call( k ) === "[object Array]" ) { + if ( !u ) { + e.push.apply( e, k ); + } else if ( d && d.nodeType === 1 ) { + for ( t = 0; k[t] != null; t++ ) { + k[t] && (k[t] === !0 || k[t].nodeType === 1 && m.contains( d, k[t] )) && e.push( j[t] ); + } + } else { + for ( t = 0; k[t] != null; t++ ) { + k[t] && k[t].nodeType === 1 && e.push( j[t] ); + } + } + } else { + s( k, e ); + } + l && (m( l, h, e, f ), m.uniqueSort( e )); + return e + }; + m.uniqueSort = function ( a ) { + if ( u ) { + h = i, a.sort( u ); + if ( h ) { + for ( var b = 1; b < a.length; b++ ) { + a[b] === a[b - 1] && a.splice( b--, 1 ) + } + } + } + return a + }, m.matches = function ( a, b ) { + return m( a, null, null, b ) + }, m.matchesSelector = function ( a, b ) { + return m( b, null, null, [a] ).length > 0 + }, m.find = function ( a, b, c ) { + var d, e, f, g, h, i; + if ( !a ) { + return[]; + } + for ( e = 0, f = o.order.length; e < f; e++ ) { + h = o.order[e]; + if ( g = o.leftMatch[h].exec( a ) ) { + i = g[1], g.splice( 1, 1 ); + if ( i.substr( i.length - 1 ) !== "\\" ) { + g[1] = (g[1] || "").replace( j, "" ), d = o.find[h]( g, b, c ); + if ( d != null ) { + a = a.replace( o.match[h], "" ); + break + } + } + } + } + d || (d = typeof b.getElementsByTagName != "undefined" ? b.getElementsByTagName( "*" ) : []); + return{set : d, expr : a} + }, m.filter = function ( a, c, d, e ) { + var f, g, h, i, j, k, l, n, p, q = a, r = [], s = c, t = c && c[0] && m.isXML( c[0] ); + while ( a && c.length ) { + for ( h in o.filter ) { + if ( (f = o.leftMatch[h].exec( a )) != null && f[2] ) { + k = o.filter[h], l = f[1], g = !1, f.splice( 1, 1 ); + if ( l.substr( l.length - 1 ) === "\\" ) { + continue; + } + s === r && (r = []); + if ( o.preFilter[h] ) { + f = o.preFilter[h]( f, s, d, r, e, t ); + if ( !f ) { + g = i = !0; + } else if ( f === !0 ) { + continue + } + } + if ( f ) { + for ( n = 0; (j = s[n]) != null; n++ ) { + j && (i = k( j, f, n, s ), p = e ^ i, d && i != null ? p ? g = !0 : s[n] = !1 : p && (r.push( j ), g = !0)); + } + } + if ( i !== b ) { + d || (s = r), a = a.replace( o.match[h], "" ); + if ( !g ) { + return[]; + } + break + } + } + } + if ( a === q ) { + if ( g == null ) { + m.error( a ); + } else { + break; + } + } + q = a + } + return s + }, m.error = function ( a ) { + throw new Error( "Syntax error, unrecognized expression: " + a ) + }; + var n = m.getText = function ( a ) { + var b, c, d = a.nodeType, e = ""; + if ( d ) { + if ( d === 1 || d === 9 ) { + if ( typeof a.textContent == "string" ) { + return a.textContent; + } + if ( typeof a.innerText == "string" ) { + return a.innerText.replace( k, "" ); + } + for ( a = a.firstChild; a; a = a.nextSibling ) { + e += n( a ) + } + } else if ( d === 3 || d === 4 ) { + return a.nodeValue + } + } else { + for ( b = 0; c = a[b]; b++ ) { + c.nodeType !== 8 && (e += n( c )); + } + } + return e + }, o = m.selectors = {order : ["ID", "NAME", "TAG"], match : {ID : /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS : /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME : /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR : /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG : /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD : /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS : /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO : /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/}, leftMatch : {}, attrMap : {"class" : "className", "for" : "htmlFor"}, attrHandle : {href : function ( a ) { + return a.getAttribute( "href" ) + }, type : function ( a ) { + return a.getAttribute( "type" ) + }}, relative : {"+" : function ( a, b ) { + var c = typeof b == "string", d = c && !l.test( b ), e = c && !d; + d && (b = b.toLowerCase()); + for ( var f = 0, g = a.length, h; f < g; f++ ) { + if ( h = a[f] ) { + while ( (h = h.previousSibling) && h.nodeType !== 1 ) { + ; + } + a[f] = e || h && h.nodeName.toLowerCase() === b ? h || !1 : h === b + } + } + e && m.filter( b, a, !0 ) + }, ">" : function ( a, b ) { + var c, d = typeof b == "string", e = 0, f = a.length; + if ( d && !l.test( b ) ) { + b = b.toLowerCase(); + for ( ; e < f; e++ ) { + c = a[e]; + if ( c ) { + var g = c.parentNode; + a[e] = g.nodeName.toLowerCase() === b ? g : !1 + } + } + } else { + for ( ; e < f; e++ ) { + c = a[e], c && (a[e] = d ? c.parentNode : c.parentNode === b); + } + d && m.filter( b, a, !0 ) + } + }, "" : function ( a, b, c ) { + var d, f = e++, g = x; + typeof b == "string" && !l.test( b ) && (b = b.toLowerCase(), d = b, g = w), g( "parentNode", b, f, a, d, c ) + }, "~" : function ( a, b, c ) { + var d, f = e++, g = x; + typeof b == "string" && !l.test( b ) && (b = b.toLowerCase(), d = b, g = w), g( "previousSibling", b, f, a, d, c ) + }}, find : {ID : function ( a, b, c ) { + if ( typeof b.getElementById != "undefined" && !c ) { + var d = b.getElementById( a[1] ); + return d && d.parentNode ? [d] : [] + } + }, NAME : function ( a, b ) { + if ( typeof b.getElementsByName != "undefined" ) { + var c = [], d = b.getElementsByName( a[1] ); + for ( var e = 0, f = d.length; e < f; e++ ) { + d[e].getAttribute( "name" ) === a[1] && c.push( d[e] ); + } + return c.length === 0 ? null : c + } + }, TAG : function ( a, b ) { + if ( typeof b.getElementsByTagName != "undefined" ) { + return b.getElementsByTagName( a[1] ) + } + }}, preFilter : {CLASS : function ( a, b, c, d, e, f ) { + a = " " + a[1].replace( j, "" ) + " "; + if ( f ) { + return a; + } + for ( var g = 0, h; (h = b[g]) != null; g++ ) { + h && (e ^ (h.className && (" " + h.className + " ").replace( /[\t\n\r]/g, " " ).indexOf( a ) >= 0) ? c || d.push( h ) : c && (b[g] = !1)); + } + return!1 + }, ID : function ( a ) { + return a[1].replace( j, "" ) + }, TAG : function ( a, b ) { + return a[1].replace( j, "" ).toLowerCase() + }, CHILD : function ( a ) { + if ( a[1] === "nth" ) { + a[2] || m.error( a[0] ), a[2] = a[2].replace( /^\+|\s*/g, "" ); + var b = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( a[2] === "even" && "2n" || a[2] === "odd" && "2n+1" || !/\D/.test( a[2] ) && "0n+" + a[2] || a[2] ); + a[2] = b[1] + (b[2] || 1) - 0, a[3] = b[3] - 0 + } else { + a[2] && m.error( a[0] ); + } + a[0] = e++; + return a + }, ATTR : function ( a, b, c, d, e, f ) { + var g = a[1] = a[1].replace( j, "" ); + !f && o.attrMap[g] && (a[1] = o.attrMap[g]), a[4] = (a[4] || a[5] || "").replace( j, "" ), a[2] === "~=" && (a[4] = " " + a[4] + " "); + return a + }, PSEUDO : function ( b, c, d, e, f ) { + if ( b[1] === "not" ) { + if ( (a.exec( b[3] ) || "").length > 1 || /^\w/.test( b[3] ) ) { + b[3] = m( b[3], null, null, c ); + } else { + var g = m.filter( b[3], c, d, !0 ^ f ); + d || e.push.apply( e, g ); + return!1 + } + } else if ( o.match.POS.test( b[0] ) || o.match.CHILD.test( b[0] ) ) { + return!0; + } + return b + }, POS : function ( a ) { + a.unshift( !0 ); + return a + }}, filters : {enabled : function ( a ) { + return a.disabled === !1 && a.type !== "hidden" + }, disabled : function ( a ) { + return a.disabled === !0 + }, checked : function ( a ) { + return a.checked === !0 + }, selected : function ( a ) { + a.parentNode && a.parentNode.selectedIndex; + return a.selected === !0 + }, parent : function ( a ) { + return!!a.firstChild + }, empty : function ( a ) { + return!a.firstChild + }, has : function ( a, b, c ) { + return!!m( c[3], a ).length + }, header : function ( a ) { + return/h\d/i.test( a.nodeName ) + }, text : function ( a ) { + var b = a.getAttribute( "type" ), c = a.type; + return a.nodeName.toLowerCase() === "input" && "text" === c && (b === c || b === null) + }, radio : function ( a ) { + return a.nodeName.toLowerCase() === "input" && "radio" === a.type + }, checkbox : function ( a ) { + return a.nodeName.toLowerCase() === "input" && "checkbox" === a.type + }, file : function ( a ) { + return a.nodeName.toLowerCase() === "input" && "file" === a.type + }, password : function ( a ) { + return a.nodeName.toLowerCase() === "input" && "password" === a.type + }, submit : function ( a ) { + var b = a.nodeName.toLowerCase(); + return(b === "input" || b === "button") && "submit" === a.type + }, image : function ( a ) { + return a.nodeName.toLowerCase() === "input" && "image" === a.type + }, reset : function ( a ) { + var b = a.nodeName.toLowerCase(); + return(b === "input" || b === "button") && "reset" === a.type + }, button : function ( a ) { + var b = a.nodeName.toLowerCase(); + return b === "input" && "button" === a.type || b === "button" + }, input : function ( a ) { + return/input|select|textarea|button/i.test( a.nodeName ) + }, focus : function ( a ) { + return a === a.ownerDocument.activeElement + }}, setFilters : {first : function ( a, b ) { + return b === 0 + }, last : function ( a, b, c, d ) { + return b === d.length - 1 + }, even : function ( a, b ) { + return b % 2 === 0 + }, odd : function ( a, b ) { + return b % 2 === 1 + }, lt : function ( a, b, c ) { + return b < c[3] - 0 + }, gt : function ( a, b, c ) { + return b > c[3] - 0 + }, nth : function ( a, b, c ) { + return c[3] - 0 === b + }, eq : function ( a, b, c ) { + return c[3] - 0 === b + }}, filter : {PSEUDO : function ( a, b, c, d ) { + var e = b[1], f = o.filters[e]; + if ( f ) { + return f( a, c, b, d ); + } + if ( e === "contains" ) { + return(a.textContent || a.innerText || n( [a] ) || "").indexOf( b[3] ) >= 0; + } + if ( e === "not" ) { + var g = b[3]; + for ( var h = 0, i = g.length; h < i; h++ ) { + if ( g[h] === a ) { + return!1; + } + } + return!0 + } + m.error( e ) + }, CHILD : function ( a, b ) { + var c, e, f, g, h, i, j, k = b[1], l = a; + switch ( k ) { + case"only": + case"first": + while ( l = l.previousSibling ) { + if ( l.nodeType === 1 ) { + return!1; + } + } + if ( k === "first" ) { + return!0; + } + l = a; + case"last": + while ( l = l.nextSibling ) { + if ( l.nodeType === 1 ) { + return!1; + } + } + return!0; + case"nth": + c = b[2], e = b[3]; + if ( c === 1 && e === 0 ) { + return!0; + } + f = b[0], g = a.parentNode; + if ( g && (g[d] !== f || !a.nodeIndex) ) { + i = 0; + for ( l = g.firstChild; l; l = l.nextSibling ) { + l.nodeType === 1 && (l.nodeIndex = ++i); + } + g[d] = f + } + j = a.nodeIndex - e; + return c === 0 ? j === 0 : j % c === 0 && j / c >= 0 + } + }, ID : function ( a, b ) { + return a.nodeType === 1 && a.getAttribute( "id" ) === b + }, TAG : function ( a, b ) { + return b === "*" && a.nodeType === 1 || !!a.nodeName && a.nodeName.toLowerCase() === b + }, CLASS : function ( a, b ) { + return(" " + (a.className || a.getAttribute( "class" )) + " ").indexOf( b ) > -1 + }, ATTR : function ( a, b ) { + var c = b[1], d = m.attr ? m.attr( a, c ) : o.attrHandle[c] ? o.attrHandle[c]( a ) : a[c] != null ? a[c] : a.getAttribute( c ), e = d + "", f = b[2], g = b[4]; + return d == null ? f === "!=" : !f && m.attr ? d != null : f === "=" ? e === g : f === "*=" ? e.indexOf( g ) >= 0 : f === "~=" ? (" " + e + " ").indexOf( g ) >= 0 : g ? f === "!=" ? e !== g : f === "^=" ? e.indexOf( g ) === 0 : f === "$=" ? e.substr( e.length - g.length ) === g : f === "|=" ? e === g || e.substr( 0, g.length + 1 ) === g + "-" : !1 : e && d !== !1 + }, POS : function ( a, b, c, d ) { + var e = b[2], f = o.setFilters[e]; + if ( f ) { + return f( a, c, b, d ) + } + }}}, p = o.match.POS, q = function ( a, b ) { + return"\\" + (b - 0 + 1) + }; + for ( var r in o.match ) { + o.match[r] = new RegExp( o.match[r].source + /(?![^\[]*\])(?![^\(]*\))/.source ), o.leftMatch[r] = new RegExp( /(^(?:.|\r|\n)*?)/.source + o.match[r].source.replace( /\\(\d+)/g, q ) ); + } + var s = function ( a, b ) { + a = Array.prototype.slice.call( a, 0 ); + if ( b ) { + b.push.apply( b, a ); + return b + } + return a + }; + try { + Array.prototype.slice.call( c.documentElement.childNodes, 0 )[0].nodeType + } catch ( t ) { + s = function ( a, b ) { + var c = 0, d = b || []; + if ( g.call( a ) === "[object Array]" ) { + Array.prototype.push.apply( d, a ); + } else if ( typeof a.length == "number" ) { + for ( var e = a.length; c < e; c++ ) { + d.push( a[c] ); + } + } else { + for ( ; a[c]; c++ ) { + d.push( a[c] ); + } + } + return d + } + } + var u, v; + c.documentElement.compareDocumentPosition ? u = function ( a, b ) { + if ( a === b ) { + h = !0; + return 0 + } + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + return a.compareDocumentPosition( b ) & 4 ? -1 : 1 + } : (u = function ( a, b ) { + if ( a === b ) { + h = !0; + return 0 + } + if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + var c, d, e = [], f = [], g = a.parentNode, i = b.parentNode, j = g; + if ( g === i ) { + return v( a, b ); + } + if ( !g ) { + return-1; + } + if ( !i ) { + return 1; + } + while ( j ) { + e.unshift( j ), j = j.parentNode; + } + j = i; + while ( j ) { + f.unshift( j ), j = j.parentNode; + } + c = e.length, d = f.length; + for ( var k = 0; k < c && k < d; k++ ) { + if ( e[k] !== f[k] ) { + return v( e[k], f[k] ); + } + } + return k === c ? v( a, f[k], -1 ) : v( e[k], b, 1 ) + }, v = function ( a, b, c ) { + if ( a === b ) { + return c; + } + var d = a.nextSibling; + while ( d ) { + if ( d === b ) { + return-1; + } + d = d.nextSibling + } + return 1 + }), function () { + var a = c.createElement( "div" ), d = "script" + (new Date).getTime(), e = c.documentElement; + a.innerHTML = "", e.insertBefore( a, e.firstChild ), c.getElementById( d ) && (o.find.ID = function ( a, c, d ) { + if ( typeof c.getElementById != "undefined" && !d ) { + var e = c.getElementById( a[1] ); + return e ? e.id === a[1] || typeof e.getAttributeNode != "undefined" && e.getAttributeNode( "id" ).nodeValue === a[1] ? [e] : b : [] + } + }, o.filter.ID = function ( a, b ) { + var c = typeof a.getAttributeNode != "undefined" && a.getAttributeNode( "id" ); + return a.nodeType === 1 && c && c.nodeValue === b + }), e.removeChild( a ), e = a = null + }(), function () { + var a = c.createElement( "div" ); + a.appendChild( c.createComment( "" ) ), a.getElementsByTagName( "*" ).length > 0 && (o.find.TAG = function ( a, b ) { + var c = b.getElementsByTagName( a[1] ); + if ( a[1] === "*" ) { + var d = []; + for ( var e = 0; c[e]; e++ ) { + c[e].nodeType === 1 && d.push( c[e] ); + } + c = d + } + return c + }), a.innerHTML = "", a.firstChild && typeof a.firstChild.getAttribute != "undefined" && a.firstChild.getAttribute( "href" ) !== "#" && (o.attrHandle.href = function ( a ) { + return a.getAttribute( "href", 2 ) + }), a = null + }(), c.querySelectorAll && function () { + var a = m, b = c.createElement( "div" ), d = "__sizzle__"; + b.innerHTML = "

    "; + if ( !b.querySelectorAll || b.querySelectorAll( ".TEST" ).length !== 0 ) { + m = function ( b, e, f, g ) { + e = e || c; + if ( !g && !m.isXML( e ) ) { + var h = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( b ); + if ( h && (e.nodeType === 1 || e.nodeType === 9) ) { + if ( h[1] ) { + return s( e.getElementsByTagName( b ), f ); + } + if ( h[2] && o.find.CLASS && e.getElementsByClassName ) { + return s( e.getElementsByClassName( h[2] ), f ) + } + } + if ( e.nodeType === 9 ) { + if ( b === "body" && e.body ) { + return s( [e.body], f ); + } + if ( h && h[3] ) { + var i = e.getElementById( h[3] ); + if ( !i || !i.parentNode ) { + return s( [], f ); + } + if ( i.id === h[3] ) { + return s( [i], f ) + } + } + try { + return s( e.querySelectorAll( b ), f ) + } catch ( j ) { + } + } else if ( e.nodeType === 1 && e.nodeName.toLowerCase() !== "object" ) { + var k = e, l = e.getAttribute( "id" ), n = l || d, p = e.parentNode, q = /^\s*[+~]/.test( b ); + l ? n = n.replace( /'/g, "\\$&" ) : e.setAttribute( "id", n ), q && p && (e = e.parentNode); + try { + if ( !q || p ) { + return s( e.querySelectorAll( "[id='" + n + "'] " + b ), f ) + } + } catch ( r ) { + } finally { + l || k.removeAttribute( "id" ) + } + } + } + return a( b, e, f, g ) + }; + for ( var e in a ) { + m[e] = a[e]; + } + b = null + } + }(), function () { + var a = c.documentElement, b = a.matchesSelector || a.mozMatchesSelector || a.webkitMatchesSelector || a.msMatchesSelector; + if ( b ) { + var d = !b.call( c.createElement( "div" ), "div" ), e = !1; + try { + b.call( c.documentElement, "[test!='']:sizzle" ) + } catch ( f ) { + e = !0 + } + m.matchesSelector = function ( a, c ) { + c = c.replace( /\=\s*([^'"\]]*)\s*\]/g, "='$1']" ); + if ( !m.isXML( a ) ) { + try { + if ( e || !o.match.PSEUDO.test( c ) && !/!=/.test( c ) ) { + var f = b.call( a, c ); + if ( f || !d || a.document && a.document.nodeType !== 11 ) { + return f + } + } + } catch ( g ) { + } + } + return m( c, null, null, [a] ).length > 0 + } + } + }(), function () { + var a = c.createElement( "div" ); + a.innerHTML = "
    "; + if ( !!a.getElementsByClassName && a.getElementsByClassName( "e" ).length !== 0 ) { + a.lastChild.className = "e"; + if ( a.getElementsByClassName( "e" ).length === 1 ) { + return; + } + o.order.splice( 1, 0, "CLASS" ), o.find.CLASS = function ( a, b, c ) { + if ( typeof b.getElementsByClassName != "undefined" && !c ) { + return b.getElementsByClassName( a[1] ) + } + }, a = null + } + }(), c.documentElement.contains ? m.contains = function ( a, b ) { + return a !== b && (a.contains ? a.contains( b ) : !0) + } : c.documentElement.compareDocumentPosition ? m.contains = function ( a, b ) { + return!!(a.compareDocumentPosition( b ) & 16) + } : m.contains = function () { + return!1 + }, m.isXML = function ( a ) { + var b = (a ? a.ownerDocument || a : 0).documentElement; + return b ? b.nodeName !== "HTML" : !1 + }; + var y = function ( a, b, c ) { + var d, e = [], f = "", g = b.nodeType ? [b] : b; + while ( d = o.match.PSEUDO.exec( a ) ) { + f += d[0], a = a.replace( o.match.PSEUDO, "" ); + } + a = o.relative[a] ? a + "*" : a; + for ( var h = 0, i = g.length; h < i; h++ ) { + m( a, g[h], e, c ); + } + return m.filter( f, e ) + }; + m.attr = f.attr, m.selectors.attrMap = {}, f.find = m, f.expr = m.selectors, f.expr[":"] = f.expr.filters, f.unique = m.uniqueSort, f.text = m.getText, f.isXMLDoc = m.isXML, f.contains = m.contains + }(); + var L = /Until$/, M = /^(?:parents|prevUntil|prevAll)/, N = /,/, O = /^.[^:#\[\.,]*$/, P = Array.prototype.slice, Q = f.expr.match.POS, R = {children : !0, contents : !0, next : !0, prev : !0}; + f.fn.extend( {find : function ( a ) { + var b = this, c, d; + if ( typeof a != "string" ) { + return f( a ).filter( function () { + for ( c = 0, d = b.length; c < d; c++ ) { + if ( f.contains( b[c], this ) ) { + return!0 + } + } + } ); + } + var e = this.pushStack( "", "find", a ), g, h, i; + for ( c = 0, d = this.length; c < d; c++ ) { + g = e.length, f.find( a, this[c], e ); + if ( c > 0 ) { + for ( h = g; h < e.length; h++ ) { + for ( i = 0; i < g; i++ ) { + if ( e[i] === e[h] ) { + e.splice( h--, 1 ); + break + } + } + } + } + } + return e + }, has : function ( a ) { + var b = f( a ); + return this.filter( function () { + for ( var a = 0, c = b.length; a < c; a++ ) { + if ( f.contains( this, b[a] ) ) { + return!0 + } + } + } ) + }, not : function ( a ) { + return this.pushStack( T( this, a, !1 ), "not", a ) + }, filter : function ( a ) { + return this.pushStack( T( this, a, !0 ), "filter", a ) + }, is : function ( a ) { + return!!a && (typeof a == "string" ? Q.test( a ) ? f( a, this.context ).index( this[0] ) >= 0 : f.filter( a, this ).length > 0 : this.filter( a ).length > 0) + }, closest : function ( a, b ) { + var c = [], d, e, g = this[0]; + if ( f.isArray( a ) ) { + var h = 1; + while ( g && g.ownerDocument && g !== b ) { + for ( d = 0; d < a.length; d++ ) { + f( g ).is( a[d] ) && c.push( {selector : a[d], elem : g, level : h} ); + } + g = g.parentNode, h++ + } + return c + } + var i = Q.test( a ) || typeof a != "string" ? f( a, b || this.context ) : 0; + for ( d = 0, e = this.length; d < e; d++ ) { + g = this[d]; + while ( g ) { + if ( i ? i.index( g ) > -1 : f.find.matchesSelector( g, a ) ) { + c.push( g ); + break + } + g = g.parentNode; + if ( !g || !g.ownerDocument || g === b || g.nodeType === 11 ) { + break + } + } + } + c = c.length > 1 ? f.unique( c ) : c; + return this.pushStack( c, "closest", a ) + }, index : function ( a ) { + if ( !a ) { + return this[0] && this[0].parentNode ? this.prevAll().length : -1; + } + if ( typeof a == "string" ) { + return f.inArray( this[0], f( a ) ); + } + return f.inArray( a.jquery ? a[0] : a, this ) + }, add : function ( a, b ) { + var c = typeof a == "string" ? f( a, b ) : f.makeArray( a && a.nodeType ? [a] : a ), d = f.merge( this.get(), c ); + return this.pushStack( S( c[0] ) || S( d[0] ) ? d : f.unique( d ) ) + }, andSelf : function () { + return this.add( this.prevObject ) + }} ), f.each( {parent : function ( a ) { + var b = a.parentNode; + return b && b.nodeType !== 11 ? b : null + }, parents : function ( a ) { + return f.dir( a, "parentNode" ) + }, parentsUntil : function ( a, b, c ) { + return f.dir( a, "parentNode", c ) + }, next : function ( a ) { + return f.nth( a, 2, "nextSibling" ) + }, prev : function ( a ) { + return f.nth( a, 2, "previousSibling" ) + }, nextAll : function ( a ) { + return f.dir( a, "nextSibling" ) + }, prevAll : function ( a ) { + return f.dir( a, "previousSibling" ) + }, nextUntil : function ( a, b, c ) { + return f.dir( a, "nextSibling", c ) + }, prevUntil : function ( a, b, c ) { + return f.dir( a, "previousSibling", c ) + }, siblings : function ( a ) { + return f.sibling( a.parentNode.firstChild, a ) + }, children : function ( a ) { + return f.sibling( a.firstChild ) + }, contents : function ( a ) { + return f.nodeName( a, "iframe" ) ? a.contentDocument || a.contentWindow.document : f.makeArray( a.childNodes ) + }}, function ( a, b ) { + f.fn[a] = function ( c, d ) { + var e = f.map( this, b, c ); + L.test( a ) || (d = c), d && typeof d == "string" && (e = f.filter( d, e )), e = this.length > 1 && !R[a] ? f.unique( e ) : e, (this.length > 1 || N.test( d )) && M.test( a ) && (e = e.reverse()); + return this.pushStack( e, a, P.call( arguments ).join( "," ) ) + } + } ), f.extend( {filter : function ( a, b, c ) { + c && (a = ":not(" + a + ")"); + return b.length === 1 ? f.find.matchesSelector( b[0], a ) ? [b[0]] : [] : f.find.matches( a, b ) + }, dir : function ( a, c, d ) { + var e = [], g = a[c]; + while ( g && g.nodeType !== 9 && (d === b || g.nodeType !== 1 || !f( g ).is( d )) ) { + g.nodeType === 1 && e.push( g ), g = g[c]; + } + return e + }, nth : function ( a, b, c, d ) { + b = b || 1; + var e = 0; + for ( ; a; a = a[c] ) { + if ( a.nodeType === 1 && ++e === b ) { + break; + } + } + return a + }, sibling : function ( a, b ) { + var c = []; + for ( ; a; a = a.nextSibling ) { + a.nodeType === 1 && a !== b && c.push( a ); + } + return c + }} ); + var V = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", W = / jQuery\d+="(?:\d+|null)"/g, X = /^\s+/, Y = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, Z = /<([\w:]+)/, $ = /", ""], legend : [1, "
    ", "
    "], thead : [1, "", "
    "], tr : [2, "", "
    "], td : [3, "", "
    "], col : [2, "", "
    "], area : [1, "", ""], _default : [0, "", ""]}, bh = U( c ); + bg.optgroup = bg.option, bg.tbody = bg.tfoot = bg.colgroup = bg.caption = bg.thead, bg.th = bg.td, f.support.htmlSerialize || (bg._default = [1, "div
    ", "
    "]), f.fn.extend( {text : function ( a ) { + if ( f.isFunction( a ) ) { + return this.each( function ( b ) { + var c = f( this ); + c.text( a.call( this, b, c.text() ) ) + } ); + } + if ( typeof a != "object" && a !== b ) { + return this.empty().append( (this[0] && this[0].ownerDocument || c).createTextNode( a ) ); + } + return f.text( this ) + }, wrapAll : function ( a ) { + if ( f.isFunction( a ) ) { + return this.each( function ( b ) { + f( this ).wrapAll( a.call( this, b ) ) + } ); + } + if ( this[0] ) { + var b = f( a, this[0].ownerDocument ).eq( 0 ).clone( !0 ); + this[0].parentNode && b.insertBefore( this[0] ), b.map( + function () { + var a = this; + while ( a.firstChild && a.firstChild.nodeType === 1 ) { + a = a.firstChild; + } + return a + } ).append( this ) + } + return this + }, wrapInner : function ( a ) { + if ( f.isFunction( a ) ) { + return this.each( function ( b ) { + f( this ).wrapInner( a.call( this, b ) ) + } ); + } + return this.each( function () { + var b = f( this ), c = b.contents(); + c.length ? c.wrapAll( a ) : b.append( a ) + } ) + }, wrap : function ( a ) { + var b = f.isFunction( a ); + return this.each( function ( c ) { + f( this ).wrapAll( b ? a.call( this, c ) : a ) + } ) + }, unwrap : function () { + return this.parent().each( + function () { + f.nodeName( this, "body" ) || f( this ).replaceWith( this.childNodes ) + } ).end() + }, append : function () { + return this.domManip( arguments, !0, function ( a ) { + this.nodeType === 1 && this.appendChild( a ) + } ) + }, prepend : function () { + return this.domManip( arguments, !0, function ( a ) { + this.nodeType === 1 && this.insertBefore( a, this.firstChild ) + } ) + }, before : function () { + if ( this[0] && this[0].parentNode ) { + return this.domManip( arguments, !1, function ( a ) { + this.parentNode.insertBefore( a, this ) + } ); + } + if ( arguments.length ) { + var a = f.clean( arguments ); + a.push.apply( a, this.toArray() ); + return this.pushStack( a, "before", arguments ) + } + }, after : function () { + if ( this[0] && this[0].parentNode ) { + return this.domManip( arguments, !1, function ( a ) { + this.parentNode.insertBefore( a, this.nextSibling ) + } ); + } + if ( arguments.length ) { + var a = this.pushStack( this, "after", arguments ); + a.push.apply( a, f.clean( arguments ) ); + return a + } + }, remove : function ( a, b ) { + for ( var c = 0, d; (d = this[c]) != null; c++ ) { + if ( !a || f.filter( a, [d] ).length ) { + !b && d.nodeType === 1 && (f.cleanData( d.getElementsByTagName( "*" ) ), f.cleanData( [d] )), d.parentNode && d.parentNode.removeChild( d ); + } + } + return this + }, empty : function () { + for ( var a = 0, b; (b = this[a]) != null; a++ ) { + b.nodeType === 1 && f.cleanData( b.getElementsByTagName( "*" ) ); + while ( b.firstChild ) { + b.removeChild( b.firstChild ) + } + } + return this + }, clone : function ( a, b ) { + a = a == null ? !1 : a, b = b == null ? a : b; + return this.map( function () { + return f.clone( this, a, b ) + } ) + }, html : function ( a ) { + if ( a === b ) { + return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace( W, "" ) : null; + } + if ( typeof a == "string" && !ba.test( a ) && (f.support.leadingWhitespace || !X.test( a )) && !bg[(Z.exec( a ) || ["", ""])[1].toLowerCase()] ) { + a = a.replace( Y, "<$1>" ); + try { + for ( var c = 0, d = this.length; c < d; c++ ) { + this[c].nodeType === 1 && (f.cleanData( this[c].getElementsByTagName( "*" ) ), this[c].innerHTML = a) + } + } catch ( e ) { + this.empty().append( a ) + } + } else { + f.isFunction( a ) ? this.each( function ( b ) { + var c = f( this ); + c.html( a.call( this, b, c.html() ) ) + } ) : this.empty().append( a ); + } + return this + }, replaceWith : function ( a ) { + if ( this[0] && this[0].parentNode ) { + if ( f.isFunction( a ) ) { + return this.each( function ( b ) { + var c = f( this ), d = c.html(); + c.replaceWith( a.call( this, b, d ) ) + } ); + } + typeof a != "string" && (a = f( a ).detach()); + return this.each( function () { + var b = this.nextSibling, c = this.parentNode; + f( this ).remove(), b ? f( b ).before( a ) : f( c ).append( a ) + } ) + } + return this.length ? this.pushStack( f( f.isFunction( a ) ? a() : a ), "replaceWith", a ) : this + }, detach : function ( a ) { + return this.remove( a, !0 ) + }, domManip : function ( a, c, d ) { + var e, g, h, i, j = a[0], k = []; + if ( !f.support.checkClone && arguments.length === 3 && typeof j == "string" && bd.test( j ) ) { + return this.each( function () { + f( this ).domManip( a, c, d, !0 ) + } ); + } + if ( f.isFunction( j ) ) { + return this.each( function ( e ) { + var g = f( this ); + a[0] = j.call( this, e, c ? g.html() : b ), g.domManip( a, c, d ) + } ); + } + if ( this[0] ) { + i = j && j.parentNode, f.support.parentNode && i && i.nodeType === 11 && i.childNodes.length === this.length ? e = {fragment : i} : e = f.buildFragment( a, this, k ), h = e.fragment, h.childNodes.length === 1 ? g = h = h.firstChild : g = h.firstChild; + if ( g ) { + c = c && f.nodeName( g, "tr" ); + for ( var l = 0, m = this.length, n = m - 1; l < m; l++ ) { + d.call( c ? bi( this[l], g ) : this[l], e.cacheable || m > 1 && l < n ? f.clone( h, !0, !0 ) : h ) + } + } + k.length && f.each( k, bp ) + } + return this + }} ), f.buildFragment = function ( a, b, d ) { + var e, g, h, i, j = a[0]; + b && b[0] && (i = b[0].ownerDocument || b[0]), i.createDocumentFragment || (i = c), a.length === 1 && typeof j == "string" && j.length < 512 && i === c && j.charAt( 0 ) === "<" && !bb.test( j ) && (f.support.checkClone || !bd.test( j )) && (f.support.html5Clone || !bc.test( j )) && (g = !0, h = f.fragments[j], h && h !== 1 && (e = h)), e || (e = i.createDocumentFragment(), f.clean( a, i, e, d )), g && (f.fragments[j] = h ? e : 1); + return{fragment : e, cacheable : g} + }, f.fragments = {}, f.each( {appendTo : "append", prependTo : "prepend", insertBefore : "before", insertAfter : "after", replaceAll : "replaceWith"}, function ( a, b ) { + f.fn[a] = function ( c ) { + var d = [], e = f( c ), g = this.length === 1 && this[0].parentNode; + if ( g && g.nodeType === 11 && g.childNodes.length === 1 && e.length === 1 ) { + e[b]( this[0] ); + return this + } + for ( var h = 0, i = e.length; h < i; h++ ) { + var j = (h > 0 ? this.clone( !0 ) : this).get(); + f( e[h] )[b]( j ), d = d.concat( j ) + } + return this.pushStack( d, a, e.selector ) + } + } ), f.extend( {clone : function ( a, b, c ) { + var d, e, g, h = f.support.html5Clone || !bc.test( "<" + a.nodeName ) ? a.cloneNode( !0 ) : bo( a ); + if ( (!f.support.noCloneEvent || !f.support.noCloneChecked) && (a.nodeType === 1 || a.nodeType === 11) && !f.isXMLDoc( a ) ) { + bk( a, h ), d = bl( a ), e = bl( h ); + for ( g = 0; d[g]; ++g ) { + e[g] && bk( d[g], e[g] ) + } + } + if ( b ) { + bj( a, h ); + if ( c ) { + d = bl( a ), e = bl( h ); + for ( g = 0; d[g]; ++g ) { + bj( d[g], e[g] ) + } + } + } + d = e = null; + return h + }, clean : function ( a, b, d, e ) { + var g; + b = b || c, typeof b.createElement == "undefined" && (b = b.ownerDocument || b[0] && b[0].ownerDocument || c); + var h = [], i; + for ( var j = 0, k; (k = a[j]) != null; j++ ) { + typeof k == "number" && (k += ""); + if ( !k ) { + continue; + } + if ( typeof k == "string" ) { + if ( !_.test( k ) ) { + k = b.createTextNode( k ); + } else { + k = k.replace( Y, "<$1>" ); + var l = (Z.exec( k ) || ["", ""])[1].toLowerCase(), m = bg[l] || bg._default, n = m[0], o = b.createElement( "div" ); + b === c ? bh.appendChild( o ) : U( b ).appendChild( o ), o.innerHTML = m[1] + k + m[2]; + while ( n-- ) { + o = o.lastChild; + } + if ( !f.support.tbody ) { + var p = $.test( k ), q = l === "table" && !p ? o.firstChild && o.firstChild.childNodes : m[1] === "" && !p ? o.childNodes : []; + for ( i = q.length - 1; i >= 0; --i ) { + f.nodeName( q[i], "tbody" ) && !q[i].childNodes.length && q[i].parentNode.removeChild( q[i] ) + } + } + !f.support.leadingWhitespace && X.test( k ) && o.insertBefore( b.createTextNode( X.exec( k )[0] ), o.firstChild ), k = o.childNodes + } + } + var r; + if ( !f.support.appendChecked ) { + if ( k[0] && typeof (r = k.length) == "number" ) { + for ( i = 0; i < r; i++ ) { + bn( k[i] ); + } + } else { + bn( k ); + } + } + k.nodeType ? h.push( k ) : h = f.merge( h, k ) + } + if ( d ) { + g = function ( a ) { + return!a.type || be.test( a.type ) + }; + for ( j = 0; h[j]; j++ ) { + if ( e && f.nodeName( h[j], "script" ) && (!h[j].type || h[j].type.toLowerCase() === "text/javascript") ) { + e.push( h[j].parentNode ? h[j].parentNode.removeChild( h[j] ) : h[j] ); + } else { + if ( h[j].nodeType === 1 ) { + var s = f.grep( h[j].getElementsByTagName( "script" ), g ); + h.splice.apply( h, [j + 1, 0].concat( s ) ) + } + d.appendChild( h[j] ) + } + } + } + return h + }, cleanData : function ( a ) { + var b, c, d = f.cache, e = f.event.special, g = f.support.deleteExpando; + for ( var h = 0, i; (i = a[h]) != null; h++ ) { + if ( i.nodeName && f.noData[i.nodeName.toLowerCase()] ) { + continue; + } + c = i[f.expando]; + if ( c ) { + b = d[c]; + if ( b && b.events ) { + for ( var j in b.events ) { + e[j] ? f.event.remove( i, j ) : f.removeEvent( i, j, b.handle ); + } + b.handle && (b.handle.elem = null) + } + g ? delete i[f.expando] : i.removeAttribute && i.removeAttribute( f.expando ), delete d[c] + } + } + }} ); + var bq = /alpha\([^)]*\)/i, br = /opacity=([^)]*)/, bs = /([A-Z]|^ms)/g, bt = /^-?\d+(?:px)?$/i, bu = /^-?\d/, bv = /^([\-+])=([\-+.\de]+)/, bw = {position : "absolute", visibility : "hidden", display : "block"}, bx = ["Left", "Right"], by = ["Top", "Bottom"], bz, bA, bB; + f.fn.css = function ( a, c ) { + if ( arguments.length === 2 && c === b ) { + return this; + } + return f.access( this, a, c, !0, function ( a, c, d ) { + return d !== b ? f.style( a, c, d ) : f.css( a, c ) + } ) + }, f.extend( {cssHooks : {opacity : {get : function ( a, b ) { + if ( b ) { + var c = bz( a, "opacity", "opacity" ); + return c === "" ? "1" : c + } + return a.style.opacity + }}}, cssNumber : {fillOpacity : !0, fontWeight : !0, lineHeight : !0, opacity : !0, orphans : !0, widows : !0, zIndex : !0, zoom : !0}, cssProps : {"float" : f.support.cssFloat ? "cssFloat" : "styleFloat"}, style : function ( a, c, d, e ) { + if ( !!a && a.nodeType !== 3 && a.nodeType !== 8 && !!a.style ) { + var g, h, i = f.camelCase( c ), j = a.style, k = f.cssHooks[i]; + c = f.cssProps[i] || i; + if ( d === b ) { + if ( k && "get"in k && (g = k.get( a, !1, e )) !== b ) { + return g; + } + return j[c] + } + h = typeof d, h === "string" && (g = bv.exec( d )) && (d = +(g[1] + 1) * +g[2] + parseFloat( f.css( a, c ) ), h = "number"); + if ( d == null || h === "number" && isNaN( d ) ) { + return; + } + h === "number" && !f.cssNumber[i] && (d += "px"); + if ( !k || !("set"in k) || (d = k.set( a, d )) !== b ) { + try { + j[c] = d + } catch ( l ) { + } + } + } + }, css : function ( a, c, d ) { + var e, g; + c = f.camelCase( c ), g = f.cssHooks[c], c = f.cssProps[c] || c, c === "cssFloat" && (c = "float"); + if ( g && "get"in g && (e = g.get( a, !0, d )) !== b ) { + return e; + } + if ( bz ) { + return bz( a, c ) + } + }, swap : function ( a, b, c ) { + var d = {}; + for ( var e in b ) { + d[e] = a.style[e], a.style[e] = b[e]; + } + c.call( a ); + for ( e in b ) { + a.style[e] = d[e] + } + }} ), f.curCSS = f.css, f.each( ["height", "width"], function ( a, b ) { + f.cssHooks[b] = {get : function ( a, c, d ) { + var e; + if ( c ) { + if ( a.offsetWidth !== 0 ) { + return bC( a, b, d ); + } + f.swap( a, bw, function () { + e = bC( a, b, d ) + } ); + return e + } + }, set : function ( a, b ) { + if ( !bt.test( b ) ) { + return b; + } + b = parseFloat( b ); + if ( b >= 0 ) { + return b + "px" + } + }} + } ), f.support.opacity || (f.cssHooks.opacity = {get : function ( a, b ) { + return br.test( (b && a.currentStyle ? a.currentStyle.filter : a.style.filter) || "" ) ? parseFloat( RegExp.$1 ) / 100 + "" : b ? "1" : "" + }, set : function ( a, b ) { + var c = a.style, d = a.currentStyle, e = f.isNumeric( b ) ? "alpha(opacity=" + b * 100 + ")" : "", g = d && d.filter || c.filter || ""; + c.zoom = 1; + if ( b >= 1 && f.trim( g.replace( bq, "" ) ) === "" ) { + c.removeAttribute( "filter" ); + if ( d && !d.filter ) { + return + } + } + c.filter = bq.test( g ) ? g.replace( bq, e ) : g + " " + e + }}), f( function () { + f.support.reliableMarginRight || (f.cssHooks.marginRight = {get : function ( a, b ) { + var c; + f.swap( a, {display : "inline-block"}, function () { + b ? c = bz( a, "margin-right", "marginRight" ) : c = a.style.marginRight + } ); + return c + }}) + } ), c.defaultView && c.defaultView.getComputedStyle && (bA = function ( a, b ) { + var c, d, e; + b = b.replace( bs, "-$1" ).toLowerCase(), (d = a.ownerDocument.defaultView) && (e = d.getComputedStyle( a, null )) && (c = e.getPropertyValue( b ), c === "" && !f.contains( a.ownerDocument.documentElement, a ) && (c = f.style( a, b ))); + return c + }), c.documentElement.currentStyle && (bB = function ( a, b ) { + var c, d, e, f = a.currentStyle && a.currentStyle[b], g = a.style; + f === null && g && (e = g[b]) && (f = e), !bt.test( f ) && bu.test( f ) && (c = g.left, d = a.runtimeStyle && a.runtimeStyle.left, d && (a.runtimeStyle.left = a.currentStyle.left), g.left = b === "fontSize" ? "1em" : f || 0, f = g.pixelLeft + "px", g.left = c, d && (a.runtimeStyle.left = d)); + return f === "" ? "auto" : f + }), bz = bA || bB, f.expr && f.expr.filters && (f.expr.filters.hidden = function ( a ) { + var b = a.offsetWidth, c = a.offsetHeight; + return b === 0 && c === 0 || !f.support.reliableHiddenOffsets && (a.style && a.style.display || f.css( a, "display" )) === "none" + }, f.expr.filters.visible = function ( a ) { + return!f.expr.filters.hidden( a ) + }); + var bD = /%20/g, bE = /\[\]$/, bF = /\r?\n/g, bG = /#.*$/, bH = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, bI = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, bJ = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, bK = /^(?:GET|HEAD)$/, bL = /^\/\//, bM = /\?/, bN = /)<[^<]*)*<\/script>/gi, bO = /^(?:select|textarea)/i, bP = /\s+/, bQ = /([?&])_=[^&]*/, bR = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, bS = f.fn.load, bT = {}, bU = {}, bV, bW, bX = ["*/"] + ["*"]; + try { + bV = e.href + } catch ( bY ) { + bV = c.createElement( "a" ), bV.href = "", bV = bV.href + } + bW = bR.exec( bV.toLowerCase() ) || [], f.fn.extend( {load : function ( a, c, d ) { + if ( typeof a != "string" && bS ) { + return bS.apply( this, arguments ); + } + if ( !this.length ) { + return this; + } + var e = a.indexOf( " " ); + if ( e >= 0 ) { + var g = a.slice( e, a.length ); + a = a.slice( 0, e ) + } + var h = "GET"; + c && (f.isFunction( c ) ? (d = c, c = b) : typeof c == "object" && (c = f.param( c, f.ajaxSettings.traditional ), h = "POST")); + var i = this; + f.ajax( {url : a, type : h, dataType : "html", data : c, complete : function ( a, b, c ) { + c = a.responseText, a.isResolved() && (a.done( function ( a ) { + c = a + } ), i.html( g ? f( "
    " ).append( c.replace( bN, "" ) ).find( g ) : c )), d && i.each( d, [c, b, a] ) + }} ); + return this + }, serialize : function () { + return f.param( this.serializeArray() ) + }, serializeArray : function () { + return this.map( + function () { + return this.elements ? f.makeArray( this.elements ) : this + } ).filter( + function () { + return this.name && !this.disabled && (this.checked || bO.test( this.nodeName ) || bI.test( this.type )) + } ).map( + function ( a, b ) { + var c = f( this ).val(); + return c == null ? null : f.isArray( c ) ? f.map( c, function ( a, c ) { + return{name : b.name, value : a.replace( bF, "\r\n" )} + } ) : {name : b.name, value : c.replace( bF, "\r\n" )} + } ).get() + }} ), f.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function ( a, b ) { + f.fn[b] = function ( a ) { + return this.on( b, a ) + } + } ), f.each( ["get", "post"], function ( a, c ) { + f[c] = function ( a, d, e, g ) { + f.isFunction( d ) && (g = g || e, e = d, d = b); + return f.ajax( {type : c, url : a, data : d, success : e, dataType : g} ) + } + } ), f.extend( {getScript : function ( a, c ) { + return f.get( a, b, c, "script" ) + }, getJSON : function ( a, b, c ) { + return f.get( a, b, c, "json" ) + }, ajaxSetup : function ( a, b ) { + b ? b_( a, f.ajaxSettings ) : (b = a, a = f.ajaxSettings), b_( a, b ); + return a + }, ajaxSettings : {url : bV, isLocal : bJ.test( bW[1] ), global : !0, type : "GET", contentType : "application/x-www-form-urlencoded", processData : !0, async : !0, accepts : {xml : "application/xml, text/xml", html : "text/html", text : "text/plain", json : "application/json, text/javascript", "*" : bX}, contents : {xml : /xml/, html : /html/, json : /json/}, responseFields : {xml : "responseXML", text : "responseText"}, converters : {"* text" : a.String, "text html" : !0, "text json" : f.parseJSON, "text xml" : f.parseXML}, flatOptions : {context : !0, url : !0}}, ajaxPrefilter : bZ( bT ), ajaxTransport : bZ( bU ), ajax : function ( a, c ) { + function w( a, c, l, m ) { + if ( s !== 2 ) { + s = 2, q && clearTimeout( q ), p = b, n = m || "", v.readyState = a > 0 ? 4 : 0; + var o, r, u, w = c, x = l ? cb( d, v, l ) : b, y, z; + if ( a >= 200 && a < 300 || a === 304 ) { + if ( d.ifModified ) { + if ( y = v.getResponseHeader( "Last-Modified" ) ) { + f.lastModified[k] = y; + } + if ( z = v.getResponseHeader( "Etag" ) ) { + f.etag[k] = z + } + } + if ( a === 304 ) { + w = "notmodified", o = !0; + } else { + try { + r = cc( d, x ), w = "success", o = !0 + } catch ( A ) { + w = "parsererror", u = A + } + } + } else { + u = w; + if ( !w || a ) { + w = "error", a < 0 && (a = 0) + } + } + v.status = a, v.statusText = "" + (c || w), o ? h.resolveWith( e, [r, w, v] ) : h.rejectWith( e, [v, w, u] ), v.statusCode( j ), j = b, t && g.trigger( "ajax" + (o ? "Success" : "Error"), [v, d, o ? r : u] ), i.fireWith( e, [v, w] ), t && (g.trigger( "ajaxComplete", [v, d] ), --f.active || f.event.trigger( "ajaxStop" )) + } + } + + typeof a == "object" && (c = a, a = b), c = c || {}; + var d = f.ajaxSetup( {}, c ), e = d.context || d, g = e !== d && (e.nodeType || e instanceof f) ? f( e ) : f.event, h = f.Deferred(), i = f.Callbacks( "once memory" ), j = d.statusCode || {}, k, l = {}, m = {}, n, o, p, q, r, s = 0, t, u, v = {readyState : 0, setRequestHeader : function ( a, b ) { + if ( !s ) { + var c = a.toLowerCase(); + a = m[c] = m[c] || a, l[a] = b + } + return this + }, getAllResponseHeaders : function () { + return s === 2 ? n : null + }, getResponseHeader : function ( a ) { + var c; + if ( s === 2 ) { + if ( !o ) { + o = {}; + while ( c = bH.exec( n ) ) { + o[c[1].toLowerCase()] = c[2] + } + } + c = o[a.toLowerCase()] + } + return c === b ? null : c + }, overrideMimeType : function ( a ) { + s || (d.mimeType = a); + return this + }, abort : function ( a ) { + a = a || "abort", p && p.abort( a ), w( 0, a ); + return this + }}; + h.promise( v ), v.success = v.done, v.error = v.fail, v.complete = i.add, v.statusCode = function ( a ) { + if ( a ) { + var b; + if ( s < 2 ) { + for ( b in a ) { + j[b] = [j[b], a[b]]; + } + } else { + b = a[v.status], v.then( b, b ) + } + } + return this + }, d.url = ((a || d.url) + "").replace( bG, "" ).replace( bL, bW[1] + "//" ), d.dataTypes = f.trim( d.dataType || "*" ).toLowerCase().split( bP ), d.crossDomain == null && (r = bR.exec( d.url.toLowerCase() ), d.crossDomain = !(!r || r[1] == bW[1] && r[2] == bW[2] && (r[3] || (r[1] === "http:" ? 80 : 443)) == (bW[3] || (bW[1] === "http:" ? 80 : 443)))), d.data && d.processData && typeof d.data != "string" && (d.data = f.param( d.data, d.traditional )), b$( bT, d, c, v ); + if ( s === 2 ) { + return!1; + } + t = d.global, d.type = d.type.toUpperCase(), d.hasContent = !bK.test( d.type ), t && f.active++ === 0 && f.event.trigger( "ajaxStart" ); + if ( !d.hasContent ) { + d.data && (d.url += (bM.test( d.url ) ? "&" : "?") + d.data, delete d.data), k = d.url; + if ( d.cache === !1 ) { + var x = f.now(), y = d.url.replace( bQ, "$1_=" + x ); + d.url = y + (y === d.url ? (bM.test( d.url ) ? "&" : "?") + "_=" + x : "") + } + } + (d.data && d.hasContent && d.contentType !== !1 || c.contentType) && v.setRequestHeader( "Content-Type", d.contentType ), d.ifModified && (k = k || d.url, f.lastModified[k] && v.setRequestHeader( "If-Modified-Since", f.lastModified[k] ), f.etag[k] && v.setRequestHeader( "If-None-Match", f.etag[k] )), v.setRequestHeader( "Accept", d.dataTypes[0] && d.accepts[d.dataTypes[0]] ? d.accepts[d.dataTypes[0]] + (d.dataTypes[0] !== "*" ? ", " + bX + "; q=0.01" : "") : d.accepts["*"] ); + for ( u in d.headers ) { + v.setRequestHeader( u, d.headers[u] ); + } + if ( d.beforeSend && (d.beforeSend.call( e, v, d ) === !1 || s === 2) ) { + v.abort(); + return!1 + } + for ( u in{success : 1, error : 1, complete : 1} ) { + v[u]( d[u] ); + } + p = b$( bU, d, c, v ); + if ( !p ) { + w( -1, "No Transport" ); + } else { + v.readyState = 1, t && g.trigger( "ajaxSend", [v, d] ), d.async && d.timeout > 0 && (q = setTimeout( function () { + v.abort( "timeout" ) + }, d.timeout )); + try { + s = 1, p.send( l, w ) + } catch ( z ) { + if ( s < 2 ) { + w( -1, z ); + } else { + throw z + } + } + } + return v + }, param : function ( a, c ) { + var d = [], e = function ( a, b ) { + b = f.isFunction( b ) ? b() : b, d[d.length] = encodeURIComponent( a ) + "=" + encodeURIComponent( b ) + }; + c === b && (c = f.ajaxSettings.traditional); + if ( f.isArray( a ) || a.jquery && !f.isPlainObject( a ) ) { + f.each( a, function () { + e( this.name, this.value ) + } ); + } else { + for ( var g in a ) { + ca( g, a[g], c, e ); + } + } + return d.join( "&" ).replace( bD, "+" ) + }} ), f.extend( {active : 0, lastModified : {}, etag : {}} ); + var cd = f.now(), ce = /(\=)\?(&|$)|\?\?/i; + f.ajaxSetup( {jsonp : "callback", jsonpCallback : function () { + return f.expando + "_" + cd++ + }} ), f.ajaxPrefilter( "json jsonp", function ( b, c, d ) { + var e = b.contentType === "application/x-www-form-urlencoded" && typeof b.data == "string"; + if ( b.dataTypes[0] === "jsonp" || b.jsonp !== !1 && (ce.test( b.url ) || e && ce.test( b.data )) ) { + var g, h = b.jsonpCallback = f.isFunction( b.jsonpCallback ) ? b.jsonpCallback() : b.jsonpCallback, i = a[h], j = b.url, k = b.data, l = "$1" + h + "$2"; + b.jsonp !== !1 && (j = j.replace( ce, l ), b.url === j && (e && (k = k.replace( ce, l )), b.data === k && (j += (/\?/.test( j ) ? "&" : "?") + b.jsonp + "=" + h))), b.url = j, b.data = k, a[h] = function ( a ) { + g = [a] + }, d.always( function () { + a[h] = i, g && f.isFunction( i ) && a[h]( g[0] ) + } ), b.converters["script json"] = function () { + g || f.error( h + " was not called" ); + return g[0] + }, b.dataTypes[0] = "json"; + return"script" + } + } ), f.ajaxSetup( {accepts : {script : "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"}, contents : {script : /javascript|ecmascript/}, converters : {"text script" : function ( a ) { + f.globalEval( a ); + return a + }}} ), f.ajaxPrefilter( "script", function ( a ) { + a.cache === b && (a.cache = !1), a.crossDomain && (a.type = "GET", a.global = !1) + } ), f.ajaxTransport( "script", function ( a ) { + if ( a.crossDomain ) { + var d, e = c.head || c.getElementsByTagName( "head" )[0] || c.documentElement; + return{send : function ( f, g ) { + d = c.createElement( "script" ), d.async = "async", a.scriptCharset && (d.charset = a.scriptCharset), d.src = a.url, d.onload = d.onreadystatechange = function ( a, c ) { + if ( c || !d.readyState || /loaded|complete/.test( d.readyState ) ) { + d.onload = d.onreadystatechange = null, e && d.parentNode && e.removeChild( d ), d = b, c || g( 200, "success" ) + } + }, e.insertBefore( d, e.firstChild ) + }, abort : function () { + d && d.onload( 0, 1 ) + }} + } + } ); + var cf = a.ActiveXObject ? function () { + for ( var a in ch ) { + ch[a]( 0, 1 ) + } + } : !1, cg = 0, ch; + f.ajaxSettings.xhr = a.ActiveXObject ? function () { + return!this.isLocal && ci() || cj() + } : ci, function ( a ) { + f.extend( f.support, {ajax : !!a, cors : !!a && "withCredentials"in a} ) + }( f.ajaxSettings.xhr() ), f.support.ajax && f.ajaxTransport( function ( c ) { + if ( !c.crossDomain || f.support.cors ) { + var d; + return{send : function ( e, g ) { + var h = c.xhr(), i, j; + c.username ? h.open( c.type, c.url, c.async, c.username, c.password ) : h.open( c.type, c.url, c.async ); + if ( c.xhrFields ) { + for ( j in c.xhrFields ) { + h[j] = c.xhrFields[j]; + } + } + c.mimeType && h.overrideMimeType && h.overrideMimeType( c.mimeType ), !c.crossDomain && !e["X-Requested-With"] && (e["X-Requested-With"] = "XMLHttpRequest"); + try { + for ( j in e ) { + h.setRequestHeader( j, e[j] ) + } + } catch ( k ) { + } + h.send( c.hasContent && c.data || null ), d = function ( a, e ) { + var j, k, l, m, n; + try { + if ( d && (e || h.readyState === 4) ) { + d = b, i && (h.onreadystatechange = f.noop, cf && delete ch[i]); + if ( e ) { + h.readyState !== 4 && h.abort(); + } else { + j = h.status, l = h.getAllResponseHeaders(), m = {}, n = h.responseXML, n && n.documentElement && (m.xml = n), m.text = h.responseText; + try { + k = h.statusText + } catch ( o ) { + k = "" + } + !j && c.isLocal && !c.crossDomain ? j = m.text ? 200 : 404 : j === 1223 && (j = 204) + } + } + } catch ( p ) { + e || g( -1, p ) + } + m && g( j, k, m, l ) + }, !c.async || h.readyState === 4 ? d() : (i = ++cg, cf && (ch || (ch = {}, f( a ).unload( cf )), ch[i] = d), h.onreadystatechange = d) + }, abort : function () { + d && d( 0, 1 ) + }} + } + } ); + var ck = {}, cl, cm, cn = /^(?:toggle|show|hide)$/, co = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, cp, cq = [ + ["height", "marginTop", "marginBottom", "paddingTop", "paddingBottom"], + ["width", "marginLeft", "marginRight", "paddingLeft", "paddingRight"], + ["opacity"] + ], cr; + f.fn.extend( {show : function ( a, b, c ) { + var d, e; + if ( a || a === 0 ) { + return this.animate( cu( "show", 3 ), a, b, c ); + } + for ( var g = 0, h = this.length; g < h; g++ ) { + d = this[g], d.style && (e = d.style.display, !f._data( d, "olddisplay" ) && e === "none" && (e = d.style.display = ""), e === "" && f.css( d, "display" ) === "none" && f._data( d, "olddisplay", cv( d.nodeName ) )); + } + for ( g = 0; g < h; g++ ) { + d = this[g]; + if ( d.style ) { + e = d.style.display; + if ( e === "" || e === "none" ) { + d.style.display = f._data( d, "olddisplay" ) || "" + } + } + } + return this + }, hide : function ( a, b, c ) { + if ( a || a === 0 ) { + return this.animate( cu( "hide", 3 ), a, b, c ); + } + var d, e, g = 0, h = this.length; + for ( ; g < h; g++ ) { + d = this[g], d.style && (e = f.css( d, "display" ), e !== "none" && !f._data( d, "olddisplay" ) && f._data( d, "olddisplay", e )); + } + for ( g = 0; g < h; g++ ) { + this[g].style && (this[g].style.display = "none"); + } + return this + }, _toggle : f.fn.toggle, toggle : function ( a, b, c ) { + var d = typeof a == "boolean"; + f.isFunction( a ) && f.isFunction( b ) ? this._toggle.apply( this, arguments ) : a == null || d ? this.each( function () { + var b = d ? a : f( this ).is( ":hidden" ); + f( this )[b ? "show" : "hide"]() + } ) : this.animate( cu( "toggle", 3 ), a, b, c ); + return this + }, fadeTo : function ( a, b, c, d ) { + return this.filter( ":hidden" ).css( "opacity", 0 ).show().end().animate( {opacity : b}, a, c, d ) + }, animate : function ( a, b, c, d ) { + function g() { + e.queue === !1 && f._mark( this ); + var b = f.extend( {}, e ), c = this.nodeType === 1, d = c && f( this ).is( ":hidden" ), g, h, i, j, k, l, m, n, o; + b.animatedProperties = {}; + for ( i in a ) { + g = f.camelCase( i ), i !== g && (a[g] = a[i], delete a[i]), h = a[g], f.isArray( h ) ? (b.animatedProperties[g] = h[1], h = a[g] = h[0]) : b.animatedProperties[g] = b.specialEasing && b.specialEasing[g] || b.easing || "swing"; + if ( h === "hide" && d || h === "show" && !d ) { + return b.complete.call( this ); + } + c && (g === "height" || g === "width") && (b.overflow = [this.style.overflow, this.style.overflowX, this.style.overflowY], f.css( this, "display" ) === "inline" && f.css( this, "float" ) === "none" && (!f.support.inlineBlockNeedsLayout || cv( this.nodeName ) === "inline" ? this.style.display = "inline-block" : this.style.zoom = 1)) + } + b.overflow != null && (this.style.overflow = "hidden"); + for ( i in a ) { + j = new f.fx( this, b, i ), h = a[i], cn.test( h ) ? (o = f._data( this, "toggle" + i ) || (h === "toggle" ? d ? "show" : "hide" : 0), o ? (f._data( this, "toggle" + i, o === "show" ? "hide" : "show" ), j[o]()) : j[h]()) : (k = co.exec( h ), l = j.cur(), k ? (m = parseFloat( k[2] ), n = k[3] || (f.cssNumber[i] ? "" : "px"), n !== "px" && (f.style( this, i, (m || 1) + n ), l = (m || 1) / j.cur() * l, f.style( this, i, l + n )), k[1] && (m = (k[1] === "-=" ? -1 : 1) * m + l), j.custom( l, m, n )) : j.custom( l, h, "" )); + } + return!0 + } + + var e = f.speed( b, c, d ); + if ( f.isEmptyObject( a ) ) { + return this.each( e.complete, [!1] ); + } + a = f.extend( {}, a ); + return e.queue === !1 ? this.each( g ) : this.queue( e.queue, g ) + }, stop : function ( a, c, d ) { + typeof a != "string" && (d = c, c = a, a = b), c && a !== !1 && this.queue( a || "fx", [] ); + return this.each( function () { + function h( a, b, c ) { + var e = b[c]; + f.removeData( a, c, !0 ), e.stop( d ) + } + + var b, c = !1, e = f.timers, g = f._data( this ); + d || f._unmark( !0, this ); + if ( a == null ) { + for ( b in g ) { + g[b] && g[b].stop && b.indexOf( ".run" ) === b.length - 4 && h( this, g, b ); + } + } else { + g[b = a + ".run"] && g[b].stop && h( this, g, b ); + } + for ( b = e.length; b--; ) { + e[b].elem === this && (a == null || e[b].queue === a) && (d ? e[b]( !0 ) : e[b].saveState(), c = !0, e.splice( b, 1 )); + } + (!d || !c) && f.dequeue( this, a ) + } ) + }} ), f.each( {slideDown : cu( "show", 1 ), slideUp : cu( "hide", 1 ), slideToggle : cu( "toggle", 1 ), fadeIn : {opacity : "show"}, fadeOut : {opacity : "hide"}, fadeToggle : {opacity : "toggle"}}, function ( a, b ) { + f.fn[a] = function ( a, c, d ) { + return this.animate( b, a, c, d ) + } + } ), f.extend( {speed : function ( a, b, c ) { + var d = a && typeof a == "object" ? f.extend( {}, a ) : {complete : c || !c && b || f.isFunction( a ) && a, duration : a, easing : c && b || b && !f.isFunction( b ) && b}; + d.duration = f.fx.off ? 0 : typeof d.duration == "number" ? d.duration : d.duration in f.fx.speeds ? f.fx.speeds[d.duration] : f.fx.speeds._default; + if ( d.queue == null || d.queue === !0 ) { + d.queue = "fx"; + } + d.old = d.complete, d.complete = function ( a ) { + f.isFunction( d.old ) && d.old.call( this ), d.queue ? f.dequeue( this, d.queue ) : a !== !1 && f._unmark( this ) + }; + return d + }, easing : {linear : function ( a, b, c, d ) { + return c + d * a + }, swing : function ( a, b, c, d ) { + return(-Math.cos( a * Math.PI ) / 2 + .5) * d + c + }}, timers : [], fx : function ( a, b, c ) { + this.options = b, this.elem = a, this.prop = c, b.orig = b.orig || {} + }} ), f.fx.prototype = {update : function () { + this.options.step && this.options.step.call( this.elem, this.now, this ), (f.fx.step[this.prop] || f.fx.step._default)( this ) + }, cur : function () { + if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { + return this.elem[this.prop]; + } + var a, b = f.css( this.elem, this.prop ); + return isNaN( a = parseFloat( b ) ) ? !b || b === "auto" ? 0 : b : a + }, custom : function ( a, c, d ) { + function h( a ) { + return e.step( a ) + } + + var e = this, g = f.fx; + this.startTime = cr || cs(), this.end = c, this.now = this.start = a, this.pos = this.state = 0, this.unit = d || this.unit || (f.cssNumber[this.prop] ? "" : "px"), h.queue = this.options.queue, h.elem = this.elem, h.saveState = function () { + e.options.hide && f._data( e.elem, "fxshow" + e.prop ) === b && f._data( e.elem, "fxshow" + e.prop, e.start ) + }, h() && f.timers.push( h ) && !cp && (cp = setInterval( g.tick, g.interval )) + }, show : function () { + var a = f._data( this.elem, "fxshow" + this.prop ); + this.options.orig[this.prop] = a || f.style( this.elem, this.prop ), this.options.show = !0, a !== b ? this.custom( this.cur(), a ) : this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ), f( this.elem ).show() + }, hide : function () { + this.options.orig[this.prop] = f._data( this.elem, "fxshow" + this.prop ) || f.style( this.elem, this.prop ), this.options.hide = !0, this.custom( this.cur(), 0 ) + }, step : function ( a ) { + var b, c, d, e = cr || cs(), g = !0, h = this.elem, i = this.options; + if ( a || e >= i.duration + this.startTime ) { + this.now = this.end, this.pos = this.state = 1, this.update(), i.animatedProperties[this.prop] = !0; + for ( b in i.animatedProperties ) { + i.animatedProperties[b] !== !0 && (g = !1); + } + if ( g ) { + i.overflow != null && !f.support.shrinkWrapBlocks && f.each( ["", "X", "Y"], function ( a, b ) { + h.style["overflow" + b] = i.overflow[a] + } ), i.hide && f( h ).hide(); + if ( i.hide || i.show ) { + for ( b in i.animatedProperties ) { + f.style( h, b, i.orig[b] ), f.removeData( h, "fxshow" + b, !0 ), f.removeData( h, "toggle" + b, !0 ); + } + } + d = i.complete, d && (i.complete = !1, d.call( h )) + } + return!1 + } + i.duration == Infinity ? this.now = e : (c = e - this.startTime, this.state = c / i.duration, this.pos = f.easing[i.animatedProperties[this.prop]]( this.state, c, 0, 1, i.duration ), this.now = this.start + (this.end - this.start) * this.pos), this.update(); + return!0 + }}, f.extend( f.fx, {tick : function () { + var a, b = f.timers, c = 0; + for ( ; c < b.length; c++ ) { + a = b[c], !a() && b[c] === a && b.splice( c--, 1 ); + } + b.length || f.fx.stop() + }, interval : 13, stop : function () { + clearInterval( cp ), cp = null + }, speeds : {slow : 600, fast : 200, _default : 400}, step : {opacity : function ( a ) { + f.style( a.elem, "opacity", a.now ) + }, _default : function ( a ) { + a.elem.style && a.elem.style[a.prop] != null ? a.elem.style[a.prop] = a.now + a.unit : a.elem[a.prop] = a.now + }}} ), f.each( ["width", "height"], function ( a, b ) { + f.fx.step[b] = function ( a ) { + f.style( a.elem, b, Math.max( 0, a.now ) + a.unit ) + } + } ), f.expr && f.expr.filters && (f.expr.filters.animated = function ( a ) { + return f.grep( f.timers, + function ( b ) { + return a === b.elem + } ).length + }); + var cw = /^t(?:able|d|h)$/i, cx = /^(?:body|html)$/i; + "getBoundingClientRect"in c.documentElement ? f.fn.offset = function ( a ) { + var b = this[0], c; + if ( a ) { + return this.each( function ( b ) { + f.offset.setOffset( this, a, b ) + } ); + } + if ( !b || !b.ownerDocument ) { + return null; + } + if ( b === b.ownerDocument.body ) { + return f.offset.bodyOffset( b ); + } + try { + c = b.getBoundingClientRect() + } catch ( d ) { + } + var e = b.ownerDocument, g = e.documentElement; + if ( !c || !f.contains( g, b ) ) { + return c ? {top : c.top, left : c.left} : {top : 0, left : 0}; + } + var h = e.body, i = cy( e ), j = g.clientTop || h.clientTop || 0, k = g.clientLeft || h.clientLeft || 0, l = i.pageYOffset || f.support.boxModel && g.scrollTop || h.scrollTop, m = i.pageXOffset || f.support.boxModel && g.scrollLeft || h.scrollLeft, n = c.top + l - j, o = c.left + m - k; + return{top : n, left : o} + } : f.fn.offset = function ( a ) { + var b = this[0]; + if ( a ) { + return this.each( function ( b ) { + f.offset.setOffset( this, a, b ) + } ); + } + if ( !b || !b.ownerDocument ) { + return null; + } + if ( b === b.ownerDocument.body ) { + return f.offset.bodyOffset( b ); + } + var c, d = b.offsetParent, e = b, g = b.ownerDocument, h = g.documentElement, i = g.body, j = g.defaultView, k = j ? j.getComputedStyle( b, null ) : b.currentStyle, l = b.offsetTop, m = b.offsetLeft; + while ( (b = b.parentNode) && b !== i && b !== h ) { + if ( f.support.fixedPosition && k.position === "fixed" ) { + break; + } + c = j ? j.getComputedStyle( b, null ) : b.currentStyle, l -= b.scrollTop, m -= b.scrollLeft, b === d && (l += b.offsetTop, m += b.offsetLeft, f.support.doesNotAddBorder && (!f.support.doesAddBorderForTableAndCells || !cw.test( b.nodeName )) && (l += parseFloat( c.borderTopWidth ) || 0, m += parseFloat( c.borderLeftWidth ) || 0), e = d, d = b.offsetParent), f.support.subtractsBorderForOverflowNotVisible && c.overflow !== "visible" && (l += parseFloat( c.borderTopWidth ) || 0, m += parseFloat( c.borderLeftWidth ) || 0), k = c + } + if ( k.position === "relative" || k.position === "static" ) { + l += i.offsetTop, m += i.offsetLeft; + } + f.support.fixedPosition && k.position === "fixed" && (l += Math.max( h.scrollTop, i.scrollTop ), m += Math.max( h.scrollLeft, i.scrollLeft )); + return{top : l, left : m} + }, f.offset = {bodyOffset : function ( a ) { + var b = a.offsetTop, c = a.offsetLeft; + f.support.doesNotIncludeMarginInBodyOffset && (b += parseFloat( f.css( a, "marginTop" ) ) || 0, c += parseFloat( f.css( a, "marginLeft" ) ) || 0); + return{top : b, left : c} + }, setOffset : function ( a, b, c ) { + var d = f.css( a, "position" ); + d === "static" && (a.style.position = "relative"); + var e = f( a ), g = e.offset(), h = f.css( a, "top" ), i = f.css( a, "left" ), j = (d === "absolute" || d === "fixed") && f.inArray( "auto", [h, i] ) > -1, k = {}, l = {}, m, n; + j ? (l = e.position(), m = l.top, n = l.left) : (m = parseFloat( h ) || 0, n = parseFloat( i ) || 0), f.isFunction( b ) && (b = b.call( a, c, g )), b.top != null && (k.top = b.top - g.top + m), b.left != null && (k.left = b.left - g.left + n), "using"in b ? b.using.call( a, k ) : e.css( k ) + }}, f.fn.extend( {position : function () { + if ( !this[0] ) { + return null; + } + var a = this[0], b = this.offsetParent(), c = this.offset(), d = cx.test( b[0].nodeName ) ? {top : 0, left : 0} : b.offset(); + c.top -= parseFloat( f.css( a, "marginTop" ) ) || 0, c.left -= parseFloat( f.css( a, "marginLeft" ) ) || 0, d.top += parseFloat( f.css( b[0], "borderTopWidth" ) ) || 0, d.left += parseFloat( f.css( b[0], "borderLeftWidth" ) ) || 0; + return{top : c.top - d.top, left : c.left - d.left} + }, offsetParent : function () { + return this.map( function () { + var a = this.offsetParent || c.body; + while ( a && !cx.test( a.nodeName ) && f.css( a, "position" ) === "static" ) { + a = a.offsetParent; + } + return a + } ) + }} ), f.each( ["Left", "Top"], function ( a, c ) { + var d = "scroll" + c; + f.fn[d] = function ( c ) { + var e, g; + if ( c === b ) { + e = this[0]; + if ( !e ) { + return null; + } + g = cy( e ); + return g ? "pageXOffset"in g ? g[a ? "pageYOffset" : "pageXOffset"] : f.support.boxModel && g.document.documentElement[d] || g.document.body[d] : e[d] + } + return this.each( function () { + g = cy( this ), g ? g.scrollTo( a ? f( g ).scrollLeft() : c, a ? c : f( g ).scrollTop() ) : this[d] = c + } ) + } + } ), f.each( ["Height", "Width"], function ( a, c ) { + var d = c.toLowerCase(); + f.fn["inner" + c] = function () { + var a = this[0]; + return a ? a.style ? parseFloat( f.css( a, d, "padding" ) ) : this[d]() : null + }, f.fn["outer" + c] = function ( a ) { + var b = this[0]; + return b ? b.style ? parseFloat( f.css( b, d, a ? "margin" : "border" ) ) : this[d]() : null + }, f.fn[d] = function ( a ) { + var e = this[0]; + if ( !e ) { + return a == null ? null : this; + } + if ( f.isFunction( a ) ) { + return this.each( function ( b ) { + var c = f( this ); + c[d]( a.call( this, b, c[d]() ) ) + } ); + } + if ( f.isWindow( e ) ) { + var g = e.document.documentElement["client" + c], h = e.document.body; + return e.document.compatMode === "CSS1Compat" && g || h && h["client" + c] || g + } + if ( e.nodeType === 9 ) { + return Math.max( e.documentElement["client" + c], e.body["scroll" + c], e.documentElement["scroll" + c], e.body["offset" + c], e.documentElement["offset" + c] ); + } + if ( a === b ) { + var i = f.css( e, d ), j = parseFloat( i ); + return f.isNumeric( j ) ? j : i + } + return this.css( d, typeof a == "string" ? a : a + "px" ) + } + } ), a.jQuery = a.$ = f, typeof define == "function" && define.amd && define.amd.jQuery && define( "jquery", [], function () { + return f + } ) +})( window ); \ No newline at end of file diff --git a/example/amd/js/libs/postal/postal.diagnostics.js b/example/amd/js/libs/postal/postal.diagnostics.js index e65e89b..754a85b 100644 --- a/example/amd/js/libs/postal/postal.diagnostics.js +++ b/example/amd/js/libs/postal/postal.diagnostics.js @@ -47,7 +47,9 @@ define( [ "postal", "underscore" ], function ( postal, _, undefined ) { } } ); - postal.diagnostics = { + postal.diagnostics = postal.diagnostics || {}; + + postal.diagnostics.console = { clearFilters : function () { filters = []; }, @@ -60,13 +62,13 @@ define( [ "postal", "underscore" ], function ( postal, _, undefined ) { if ( !_.isArray( constraint ) ) { constraint = [ constraint ]; } - _.each( constraint, function( item ){ + _.each( constraint, function ( item ) { if ( filters.length === 0 || !_.any( filters, function ( filter ) { return _.isEqual( filter, item ); } ) ) { filters.push( item ); } - }); + } ); }, getCurrentFilters : function () { diff --git a/example/amd/js/libs/postal/postal.diagnostics.min.gz.js b/example/amd/js/libs/postal/postal.diagnostics.min.gz.js index 1deacc9..f72f832 100644 Binary files a/example/amd/js/libs/postal/postal.diagnostics.min.gz.js and b/example/amd/js/libs/postal/postal.diagnostics.min.gz.js differ diff --git a/example/amd/js/libs/postal/postal.diagnostics.min.js b/example/amd/js/libs/postal/postal.diagnostics.min.js index 2b27caa..e301ec9 100644 --- a/example/amd/js/libs/postal/postal.diagnostics.min.js +++ b/example/amd/js/libs/postal/postal.diagnostics.min.js @@ -1 +1 @@ -define(["postal","underscore"],function(a,b,c){var d=[],e=function(a,c){var d=0,f=0;return b.each(a,function(a,g){c[g]&&(f++,b.isObject(c[g])&&!b.isArray(c[g])?e(a,c[g])&&d++:b.isEqual(c[g],a)&&d++)}),d===f},f=a.addWireTap(function(a,c){if(!d.length||b.any(d,function(a){return e(a,c)})){if(!JSON)throw"This browser or environment does not provide JSON support";try{console.log(JSON.stringify(c))}catch(f){try{var g=b.extend({},c);delete g.data,console.log(JSON.stringify(g)+"\n "+"JSON.stringify Error: "+f.message)}catch(h){console.log("Unable to parse data to JSON: "+f)}}}});a.diagnostics={clearFilters:function(){d=[]},removeFilter:function(a){d=b.filter(d,function(c){return!b.isEqual(c,a)})},addFilter:function(a){b.isArray(a)||(a=[a]),b.each(a,function(a){(d.length===0||!b.any(d,function(c){return b.isEqual(c,a)}))&&d.push(a)})},getCurrentFilters:function(){return d},removeWireTap:function(){f&&f()}}}) \ No newline at end of file +define(["postal","underscore"],function(a,b,c){var d=[],e=function(a,c){var d=0,f=0;return b.each(a,function(a,g){c[g]&&(f++,b.isObject(c[g])&&!b.isArray(c[g])?e(a,c[g])&&d++:b.isEqual(c[g],a)&&d++)}),d===f},f=a.addWireTap(function(a,c){if(!d.length||b.any(d,function(a){return e(a,c)})){if(!JSON)throw"This browser or environment does not provide JSON support";try{console.log(JSON.stringify(c))}catch(f){try{var g=b.extend({},c);delete g.data,console.log(JSON.stringify(g)+"\n "+"JSON.stringify Error: "+f.message)}catch(h){console.log("Unable to parse data to JSON: "+f)}}}});a.diagnostics=a.diagnostics||{},a.diagnostics.console={clearFilters:function(){d=[]},removeFilter:function(a){d=b.filter(d,function(c){return!b.isEqual(c,a)})},addFilter:function(a){b.isArray(a)||(a=[a]),b.each(a,function(a){(d.length===0||!b.any(d,function(c){return b.isEqual(c,a)}))&&d.push(a)})},getCurrentFilters:function(){return d},removeWireTap:function(){f&&f()}}}) \ No newline at end of file diff --git a/example/amd/js/libs/postal/postal.js b/example/amd/js/libs/postal/postal.js index 8ef6b5f..8c36cc0 100644 --- a/example/amd/js/libs/postal/postal.js +++ b/example/amd/js/libs/postal/postal.js @@ -1,225 +1,228 @@ /* - postal.js - Author: Jim Cowart - License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) - Version 0.6.0 + postal.js + Author: Jim Cowart + License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) + Version 0.6.0 */ // This is the amd-module version of postal.js // If you need the standard lib style version, go to http://github.com/ifandelse/postal.js -define(["underscore"], function(_, undefined) { +define( ["underscore"], function ( _, undefined ) { var DEFAULT_CHANNEL = "/", DEFAULT_PRIORITY = 50, DEFAULT_DISPOSEAFTER = 0, SYSTEM_CHANNEL = "postal", - NO_OP = function() { }; + NO_OP = function () { + }; -var DistinctPredicate = function() { +var DistinctPredicate = function () { var previous; - return function(data) { + return function ( data ) { var eq = false; - if(_.isString(data)) { + if ( _.isString( data ) ) { eq = data === previous; previous = data; } else { - eq = _.isEqual(data, previous); - previous = _.clone(data); + eq = _.isEqual( data, previous ); + previous = _.clone( data ); } return !eq; }; }; -var ChannelDefinition = function(channelName, defaultTopic) { +var ChannelDefinition = function ( channelName, defaultTopic ) { this.channel = channelName || DEFAULT_CHANNEL; this._topic = defaultTopic || ""; }; ChannelDefinition.prototype = { - subscribe: function() { + subscribe : function () { var len = arguments.length; - if(len === 1) { - return new SubscriptionDefinition(this.channel, this._topic, arguments[0]); + if ( len === 1 ) { + return new SubscriptionDefinition( this.channel, this._topic, arguments[0] ); } - else if (len === 2) { - return new SubscriptionDefinition(this.channel, arguments[0], arguments[1]); + else if ( len === 2 ) { + return new SubscriptionDefinition( this.channel, arguments[0], arguments[1] ); } }, - publish: function(obj) { + publish : function ( obj ) { var envelope = { - channel: this.channel, - topic: this._topic, - data: obj || {} + channel : this.channel, + topic : this._topic, + data : obj || {} }; // If this is an envelope.... - if( obj.topic && obj.data ) { + if ( obj.topic && obj.data ) { envelope = obj; envelope.channel = envelope.channel || this.channel; } envelope.timeStamp = new Date(); - postal.configuration.bus.publish(envelope); + postal.configuration.bus.publish( envelope ); return envelope; }, - topic: function(topic) { - if(topic === this._topic) { + topic : function ( topic ) { + if ( topic === this._topic ) { return this; } - return new ChannelDefinition(this.channel, topic); + return new ChannelDefinition( this.channel, topic ); } }; -var SubscriptionDefinition = function(channel, topic, callback) { +var SubscriptionDefinition = function ( channel, topic, callback ) { this.channel = channel; this.topic = topic; this.callback = callback; this.priority = DEFAULT_PRIORITY; - this.constraints = new Array(0); + this.constraints = new Array( 0 ); this.maxCalls = DEFAULT_DISPOSEAFTER; this.onHandled = NO_OP; this.context = null; - postal.configuration.bus.publish({ - channel: SYSTEM_CHANNEL, - topic: "subscription.created", - timeStamp: new Date(), - data: { - event: "subscription.created", - channel: channel, - topic: topic + postal.configuration.bus.publish( { + channel : SYSTEM_CHANNEL, + topic : "subscription.created", + timeStamp : new Date(), + data : { + event : "subscription.created", + channel : channel, + topic : topic } - }); + } ); - postal.configuration.bus.subscribe(this); + postal.configuration.bus.subscribe( this ); }; SubscriptionDefinition.prototype = { - unsubscribe: function() { - postal.configuration.bus.unsubscribe(this); - postal.configuration.bus.publish({ - channel: SYSTEM_CHANNEL, - topic: "subscription.removed", - timeStamp: new Date(), - data: { - event: "subscription.removed", - channel: this.channel, - topic: this.topic + unsubscribe : function () { + postal.configuration.bus.unsubscribe( this ); + postal.configuration.bus.publish( { + channel : SYSTEM_CHANNEL, + topic : "subscription.removed", + timeStamp : new Date(), + data : { + event : "subscription.removed", + channel : this.channel, + topic : this.topic } - }); + } ); }, - defer: function() { + defer : function () { var fn = this.callback; - this.callback = function(data) { - setTimeout(fn,0,data); + this.callback = function ( data ) { + setTimeout( fn, 0, data ); }; return this; }, - disposeAfter: function(maxCalls) { - if(_.isNaN(maxCalls) || maxCalls <= 0) { + disposeAfter : function ( maxCalls ) { + if ( _.isNaN( maxCalls ) || maxCalls <= 0 ) { throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero."; } var fn = this.onHandled; - var dispose = _.after(maxCalls, _.bind(function() { - this.unsubscribe(this); - }, this)); + var dispose = _.after( maxCalls, _.bind( function () { + this.unsubscribe( this ); + }, this ) ); - this.onHandled = function() { - fn.apply(this.context, arguments); + this.onHandled = function () { + fn.apply( this.context, arguments ); dispose(); }; return this; }, - ignoreDuplicates: function() { - this.withConstraint(new DistinctPredicate()); + ignoreDuplicates : function () { + this.withConstraint( new DistinctPredicate() ); return this; }, - withConstraint: function(predicate) { - if(! _.isFunction(predicate)) { + withConstraint : function ( predicate ) { + if ( !_.isFunction( predicate ) ) { throw "Predicate constraint must be a function"; } - this.constraints.push(predicate); + this.constraints.push( predicate ); return this; }, - withConstraints: function(predicates) { + withConstraints : function ( predicates ) { var self = this; - if(_.isArray(predicates)) { - _.each(predicates, function(predicate) { self.withConstraint(predicate); } ); + if ( _.isArray( predicates ) ) { + _.each( predicates, function ( predicate ) { + self.withConstraint( predicate ); + } ); } return self; }, - withContext: function(context) { + withContext : function ( context ) { this.context = context; return this; }, - withDebounce: function(milliseconds) { - if(_.isNaN(milliseconds)) { + withDebounce : function ( milliseconds ) { + if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; - this.callback = _.debounce(fn, milliseconds); + this.callback = _.debounce( fn, milliseconds ); return this; }, - withDelay: function(milliseconds) { - if(_.isNaN(milliseconds)) { + withDelay : function ( milliseconds ) { + if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; - this.callback = function(data) { - setTimeout(function(){ - fn(data); - }, milliseconds); + this.callback = function ( data ) { + setTimeout( function () { + fn( data ); + }, milliseconds ); }; return this; }, - withPriority: function(priority) { - if(_.isNaN(priority)) { + withPriority : function ( priority ) { + if ( _.isNaN( priority ) ) { throw "Priority must be a number"; } this.priority = priority; return this; }, - withThrottle: function(milliseconds) { - if(_.isNaN(milliseconds)) { + withThrottle : function ( milliseconds ) { + if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; - this.callback = _.throttle(fn, milliseconds); + this.callback = _.throttle( fn, milliseconds ); return this; }, - subscribe: function(callback) { + subscribe : function ( callback ) { this.callback = callback; return this; } }; var bindingsResolver = { - cache: { }, + cache : { }, - compare: function(binding, topic) { - if(this.cache[topic] && this.cache[topic][binding]) { + compare : function ( binding, topic ) { + if ( this.cache[topic] && this.cache[topic][binding] ) { return true; } // binding.replace(/\./g,"\\.") // escape actual periods // .replace(/\*/g, ".*") // asterisks match any value // .replace(/#/g, "[A-Z,a-z,0-9]*"); // hash matches any alpha-numeric 'word' - var rgx = new RegExp("^" + binding.replace(/\./g,"\\.").replace(/\*/g, ".*").replace(/#/g, "[A-Z,a-z,0-9]*") + "$"), - result = rgx.test(topic); - if(result) { - if(!this.cache[topic]) { + var rgx = new RegExp( "^" + binding.replace( /\./g, "\\." ).replace( /\*/g, ".*" ).replace( /#/g, "[A-Z,a-z,0-9]*" ) + "$" ), + result = rgx.test( topic ); + if ( result ) { + if ( !this.cache[topic] ) { this.cache[topic] = {}; } this.cache[topic][binding] = true; @@ -227,91 +230,93 @@ var bindingsResolver = { return result; }, - reset: function() { + reset : function () { this.cache = {}; } }; var localBus = { - addWireTap: function(callback) { + addWireTap : function ( callback ) { var self = this; - self.wireTaps.push(callback); - return function() { - var idx = self.wireTaps.indexOf(callback); - if(idx !== -1) { - self.wireTaps.splice(idx,1); + self.wireTaps.push( callback ); + return function () { + var idx = self.wireTaps.indexOf( callback ); + if ( idx !== -1 ) { + self.wireTaps.splice( idx, 1 ); } }; }, - publish: function(envelope) { - _.each(this.wireTaps,function(tap) { - tap(envelope.data, envelope); - }); + publish : function ( envelope ) { + _.each( this.wireTaps, function ( tap ) { + tap( envelope.data, envelope ); + } ); - _.each(this.subscriptions[envelope.channel], function(topic) { - _.each(topic, function(subDef){ - if(postal.configuration.resolver.compare(subDef.topic, envelope.topic)) { - if(_.all(subDef.constraints, function(constraint) { return constraint(envelope.data,envelope); })) { - if(typeof subDef.callback === 'function') { - subDef.callback.apply(subDef.context, [envelope.data, envelope]); + _.each( this.subscriptions[envelope.channel], function ( topic ) { + _.each( topic, function ( subDef ) { + if ( postal.configuration.resolver.compare( subDef.topic, envelope.topic ) ) { + if ( _.all( subDef.constraints, function ( constraint ) { + return constraint( envelope.data, envelope ); + } ) ) { + if ( typeof subDef.callback === 'function' ) { + subDef.callback.apply( subDef.context, [envelope.data, envelope] ); subDef.onHandled(); } } } - }); - }); + } ); + } ); }, - reset: function() { - if( this.subscriptions ) { - _.each( this.subscriptions , function( channel ){ - _.each( channel, function( topic ){ - while( topic.length ) { + reset : function () { + if ( this.subscriptions ) { + _.each( this.subscriptions, function ( channel ) { + _.each( channel, function ( topic ) { + while ( topic.length ) { topic.pop().unsubscribe(); } - }); - }); + } ); + } ); this.subscriptions = {}; } }, - subscribe: function(subDef) { + subscribe : function ( subDef ) { var idx, found, fn, channel = this.subscriptions[subDef.channel], subs; - if(!channel) { + if ( !channel ) { channel = this.subscriptions[subDef.channel] = {}; } subs = this.subscriptions[subDef.channel][subDef.topic]; - if(!subs) { - subs = this.subscriptions[subDef.channel][subDef.topic] = new Array(0); + if ( !subs ) { + subs = this.subscriptions[subDef.channel][subDef.topic] = new Array( 0 ); } idx = subs.length - 1; - for(; idx >= 0; idx--) { - if(subs[idx].priority <= subDef.priority) { - subs.splice(idx + 1, 0, subDef); + for ( ; idx >= 0; idx-- ) { + if ( subs[idx].priority <= subDef.priority ) { + subs.splice( idx + 1, 0, subDef ); found = true; break; } } - if(!found) { - subs.unshift(subDef); + if ( !found ) { + subs.unshift( subDef ); } return subDef; }, - subscriptions: {}, + subscriptions : {}, - wireTaps: new Array(0), + wireTaps : new Array( 0 ), - unsubscribe: function(config) { - if(this.subscriptions[config.channel][config.topic]) { + unsubscribe : function ( config ) { + if ( this.subscriptions[config.channel][config.topic] ) { var len = this.subscriptions[config.channel][config.topic].length, idx = 0; for ( ; idx < len; idx++ ) { - if (this.subscriptions[config.channel][config.topic][idx] === config) { + if ( this.subscriptions[config.channel][config.topic][idx] === config ) { this.subscriptions[config.channel][config.topic].splice( idx, 1 ); break; } @@ -321,50 +326,50 @@ var localBus = { }; var publishPicker = { - "1" : function(envelope) { - if(!envelope) { - throw new Error("publishing from the 'global' postal.publish call requires a valid envelope."); + "1" : function ( envelope ) { + if ( !envelope ) { + throw new Error( "publishing from the 'global' postal.publish call requires a valid envelope." ); } envelope.channel = envelope.channel || DEFAULT_CHANNEL; envelope.timeStamp = new Date(); - postal.configuration.bus.publish(envelope); - return envelope; - }, - "2" : function(topic, data) { - var envelope = { channel: DEFAULT_CHANNEL, topic: topic, timeStamp: new Date(), data: data }; postal.configuration.bus.publish( envelope ); return envelope; }, - "3" : function(channel, topic, data) { - var envelope = { channel: channel, topic: topic, timeStamp: new Date(), data: data }; + "2" : function ( topic, data ) { + var envelope = { channel : DEFAULT_CHANNEL, topic : topic, timeStamp : new Date(), data : data }; + postal.configuration.bus.publish( envelope ); + return envelope; + }, + "3" : function ( channel, topic, data ) { + var envelope = { channel : channel, topic : topic, timeStamp : new Date(), data : data }; postal.configuration.bus.publish( envelope ); return envelope; } }, channelPicker = { - "1" : function( chn ) { + "1" : function ( chn ) { var channel = chn, topic, options = {}; - if( Object.prototype.toString.call( channel ) === "[object String]" ) { + if ( Object.prototype.toString.call( channel ) === "[object String]" ) { channel = DEFAULT_CHANNEL; - topic = chn; + topic = chn; } else { channel = chn.channel || DEFAULT_CHANNEL; - topic = chn.topic; + topic = chn.topic; options = chn.options || options; } return new postal.channelTypes[ options.type || "local" ]( channel, topic ); }, - "2" : function( chn, tpc ) { + "2" : function ( chn, tpc ) { var channel = chn, topic = tpc, options = {}; - if( Object.prototype.toString.call( tpc ) === "[object Object]" ) { + if ( Object.prototype.toString.call( tpc ) === "[object Object]" ) { channel = DEFAULT_CHANNEL; - topic = chn; + topic = chn; options = tpc; } return new postal.channelTypes[ options.type || "local" ]( channel, topic ); }, - "3" : function( channel, topic, options ) { + "3" : function ( channel, topic, options ) { return new postal.channelTypes[ options.type || "local" ]( channel, topic ); } }, @@ -374,110 +379,110 @@ var publishPicker = { localBus.subscriptions[SYSTEM_CHANNEL] = {}; var postal = { - configuration: { - bus: localBus, - resolver: bindingsResolver, - getSessionIdAction: function( callback ) { + configuration : { + bus : localBus, + resolver : bindingsResolver, + getSessionIdAction : function ( callback ) { callback( sessionInfo ); }, - setSessionIdAction: function( info, callback ) { + setSessionIdAction : function ( info, callback ) { sessionInfo = info; callback( sessionInfo ); }, - DEFAULT_CHANNEL: DEFAULT_CHANNEL, - DEFAULT_PRIORITY: DEFAULT_PRIORITY, - DEFAULT_DISPOSEAFTER: DEFAULT_DISPOSEAFTER, - SYSTEM_CHANNEL: SYSTEM_CHANNEL + DEFAULT_CHANNEL : DEFAULT_CHANNEL, + DEFAULT_PRIORITY : DEFAULT_PRIORITY, + DEFAULT_DISPOSEAFTER : DEFAULT_DISPOSEAFTER, + SYSTEM_CHANNEL : SYSTEM_CHANNEL }, - channelTypes: { - local: ChannelDefinition + channelTypes : { + local : ChannelDefinition }, - channel: function() { + channel : function () { var len = arguments.length; - if(channelPicker[len]) { - return channelPicker[len].apply(this, arguments); + if ( channelPicker[len] ) { + return channelPicker[len].apply( this, arguments ); } }, - subscribe: function(options) { + subscribe : function ( options ) { var callback = options.callback, topic = options.topic, channel = options.channel || DEFAULT_CHANNEL; - return new SubscriptionDefinition(channel, topic, callback); + return new SubscriptionDefinition( channel, topic, callback ); }, - publish: function() { + publish : function () { var len = arguments.length; - if(publishPicker[len]) { - return publishPicker[len].apply(this, arguments); + if ( publishPicker[len] ) { + return publishPicker[len].apply( this, arguments ); } }, - addWireTap: function(callback) { - return this.configuration.bus.addWireTap(callback); + addWireTap : function ( callback ) { + return this.configuration.bus.addWireTap( callback ); }, - linkChannels: function(sources, destinations) { + linkChannels : function ( sources, destinations ) { var result = []; - if(!_.isArray(sources)) { + if ( !_.isArray( sources ) ) { sources = [sources]; } - if(!_.isArray(destinations)) { + if ( !_.isArray( destinations ) ) { destinations = [destinations]; } - _.each(sources, function(source){ + _.each( sources, function ( source ) { var sourceTopic = source.topic || "*"; - _.each(destinations, function(destination) { + _.each( destinations, function ( destination ) { var destChannel = destination.channel || DEFAULT_CHANNEL; result.push( - postal.subscribe({ - channel: source.channel || DEFAULT_CHANNEL, - topic: source.topic || "*", - callback : function(data, env) { + postal.subscribe( { + channel : source.channel || DEFAULT_CHANNEL, + topic : source.topic || "*", + callback : function ( data, env ) { var newEnv = env; - newEnv.topic = _.isFunction(destination.topic) ? destination.topic(env.topic) : destination.topic || env.topic; + newEnv.topic = _.isFunction( destination.topic ) ? destination.topic( env.topic ) : destination.topic || env.topic; newEnv.channel = destChannel; newEnv.data = data; - postal.publish(newEnv); + postal.publish( newEnv ); } - }) + } ) ); - }); - }); + } ); + } ); return result; }, - utils: { - getSessionId: function( callback ) { + utils : { + getSessionId : function ( callback ) { postal.configuration.getSessionIdAction.call( this, callback ); }, - setSessionId: function( value, callback ) { - postal.utils.getSessionId( function( info ) { + setSessionId : function ( value, callback ) { + postal.utils.getSessionId( function ( info ) { // get the session info to move id to last id info.lastId = info.id; info.id = value; // invoke the callback the user provided to handle storing session - postal.configuration.setSessionIdAction( info, function( session ) { + postal.configuration.setSessionIdAction( info, function ( session ) { callback( session ); // publish postal event msg about the change - postal.publish({ - channel: SYSTEM_CHANNEL, - topic: "sessionId.changed", - data: session - }); + postal.publish( { + channel : SYSTEM_CHANNEL, + topic : "sessionId.changed", + data : session + } ); } ); - }); + } ); }, - getSubscribersFor: function() { + getSubscribersFor : function () { var channel = arguments[ 0 ], tpc = arguments[ 1 ], result = []; - if( arguments.length === 1 ) { - if( Object.prototype.toString.call( channel ) === "[object String]" ) { + if ( arguments.length === 1 ) { + if ( Object.prototype.toString.call( channel ) === "[object String]" ) { channel = postal.configuration.DEFAULT_CHANNEL; tpc = arguments[ 0 ]; } @@ -486,14 +491,14 @@ var postal = { tpc = arguments[ 0 ].topic; } } - if( postal.configuration.bus.subscriptions[ channel ] && - postal.configuration.bus.subscriptions[ channel ].hasOwnProperty( tpc )) { + if ( postal.configuration.bus.subscriptions[ channel ] && + postal.configuration.bus.subscriptions[ channel ].hasOwnProperty( tpc ) ) { result = postal.configuration.bus.subscriptions[ channel ][ tpc ]; } return result; }, - reset: function() { + reset : function () { postal.configuration.bus.reset(); postal.configuration.resolver.reset(); } @@ -501,4 +506,4 @@ var postal = { }; return postal; -}); \ No newline at end of file +} ); \ No newline at end of file diff --git a/example/amd/js/libs/postal/postal.min.gz.js b/example/amd/js/libs/postal/postal.min.gz.js index 442f9e6..57db928 100644 Binary files a/example/amd/js/libs/postal/postal.min.gz.js and b/example/amd/js/libs/postal/postal.min.gz.js differ diff --git a/example/amd/js/libs/require/require.js b/example/amd/js/libs/require/require.js index b6090d1..edc08bb 100644 --- a/example/amd/js/libs/require/require.js +++ b/example/amd/js/libs/require/require.js @@ -2,30 +2,620 @@ RequireJS 1.0.2 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. Available via the MIT or new BSD license. see: http://github.com/jrburke/requirejs for details -*/ -var requirejs,require,define; -(function(){function J(a){return M.call(a)==="[object Function]"}function E(a){return M.call(a)==="[object Array]"}function Z(a,c,h){for(var k in c)if(!(k in K)&&(!(k in a)||h))a[k]=c[k];return d}function N(a,c,d){a=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+a);if(d)a.originalError=d;return a}function $(a,c,d){var k,j,q;for(k=0;q=c[k];k++){q=typeof q==="string"?{name:q}:q;j=q.location;if(d&&(!j||j.indexOf("/")!==0&&j.indexOf(":")===-1))j=d+"/"+(j||q.name);a[q.name]={name:q.name,location:j|| -q.name,main:(q.main||"main").replace(ea,"").replace(aa,"")}}}function V(a,c){a.holdReady?a.holdReady(c):c?a.readyWait+=1:a.ready(!0)}function fa(a){function c(b,l){var f,a;if(b&&b.charAt(0)===".")if(l){p.pkgs[l]?l=[l]:(l=l.split("/"),l=l.slice(0,l.length-1));f=b=l.concat(b.split("/"));var c;for(a=0;c=f[a];a++)if(c===".")f.splice(a,1),a-=1;else if(c==="..")if(a===1&&(f[2]===".."||f[0]===".."))break;else a>0&&(f.splice(a-1,2),a-=2);a=p.pkgs[f=b[0]];b=b.join("/");a&&b===f+"/"+a.main&&(b=f)}else b.indexOf("./")=== -0&&(b=b.substring(2));return b}function h(b,l){var f=b?b.indexOf("!"):-1,a=null,d=l?l.name:null,i=b,e,h;f!==-1&&(a=b.substring(0,f),b=b.substring(f+1,b.length));a&&(a=c(a,d));b&&(a?e=(f=m[a])&&f.normalize?f.normalize(b,function(b){return c(b,d)}):c(b,d):(e=c(b,d),h=E[e],h||(h=g.nameToUrl(e,null,l),E[e]=h)));return{prefix:a,name:e,parentMap:l,url:h,originalName:i,fullName:a?a+"!"+(e||""):e}}function k(){var b=!0,l=p.priorityWait,f,a;if(l){for(a=0;f=l[a];a++)if(!s[f]){b=!1;break}b&&delete p.priorityWait}return b} -function j(b,l,f){return function(){var a=ga.call(arguments,0),c;if(f&&J(c=a[a.length-1]))c.__requireJsBuild=!0;a.push(l);return b.apply(null,a)}}function q(b,l){var a=j(g.require,b,l);Z(a,{nameToUrl:j(g.nameToUrl,b),toUrl:j(g.toUrl,b),defined:j(g.requireDefined,b),specified:j(g.requireSpecified,b),isBrowser:d.isBrowser});return a}function o(b){var l,a,c,C=b.callback,i=b.map,e=i.fullName,ba=b.deps;c=b.listeners;if(C&&J(C)){if(p.catchError.define)try{a=d.execCb(e,b.callback,ba,m[e])}catch(k){l=k}else a= -d.execCb(e,b.callback,ba,m[e]);if(e)(C=b.cjsModule)&&C.exports!==void 0&&C.exports!==m[e]?a=m[e]=b.cjsModule.exports:a===void 0&&b.usingExports?a=m[e]:(m[e]=a,F[e]&&(Q[e]=!0))}else e&&(a=m[e]=C,F[e]&&(Q[e]=!0));if(D[b.id])delete D[b.id],b.isDone=!0,g.waitCount-=1,g.waitCount===0&&(I=[]);delete R[e];if(d.onResourceLoad&&!b.placeholder)d.onResourceLoad(g,i,b.depArray);if(l)return a=(e?h(e).url:"")||l.fileName||l.sourceURL,c=l.moduleTree,l=N("defineerror",'Error evaluating module "'+e+'" at location "'+ -a+'":\n'+l+"\nfileName:"+a+"\nlineNumber: "+(l.lineNumber||l.line),l),l.moduleName=e,l.moduleTree=c,d.onError(l);for(l=0;C=c[l];l++)C(a)}function r(b,a){return function(f){b.depDone[a]||(b.depDone[a]=!0,b.deps[a]=f,b.depCount-=1,b.depCount||o(b))}}function u(b,a){var f=a.map,c=f.fullName,h=f.name,i=L[b]||(L[b]=m[b]),e;if(!a.loading)a.loading=!0,e=function(b){a.callback=function(){return b};o(a);s[a.id]=!0;w()},e.fromText=function(b,a){var l=O;s[b]=!1;g.scriptCount+=1;g.fake[b]=!0;l&&(O=!1);d.exec(a); -l&&(O=!0);g.completeLoad(b)},c in m?e(m[c]):i.load(h,q(f.parentMap,!0),e,p)}function v(b){D[b.id]||(D[b.id]=b,I.push(b),g.waitCount+=1)}function B(b){this.listeners.push(b)}function t(b,a){var f=b.fullName,c=b.prefix,d=c?L[c]||(L[c]=m[c]):null,i,e;f&&(i=R[f]);if(!i&&(e=!0,i={id:(c&&!d?M++ +"__p@:":"")+(f||"__r@"+M++),map:b,depCount:0,depDone:[],depCallbacks:[],deps:[],listeners:[],add:B},y[i.id]=!0,f&&(!c||L[c])))R[f]=i;c&&!d?(f=t(h(c),!0),f.add(function(){var a=h(b.originalName,b.parentMap),a=t(a, -!0);i.placeholder=!0;a.add(function(b){i.callback=function(){return b};o(i)})})):e&&a&&(s[i.id]=!1,g.paused.push(i),v(i));return i}function x(b,a,f,c){var b=h(b,c),d=b.name,i=b.fullName,e=t(b),k=e.id,j=e.deps,n;if(i){if(i in m||s[k]===!0||i==="jquery"&&p.jQuery&&p.jQuery!==f().fn.jquery)return;y[k]=!0;s[k]=!0;i==="jquery"&&f&&S(f())}e.depArray=a;e.callback=f;for(f=0;f0)){if(p.priorityWait)if(k())w();else return;for(j in s)if(!(j in K)&&(c=!0,!s[j]))if(a)b+=j+" ";else{h=!0;break}if(c||g.waitCount){if(a&&b)return j=N("timeout","Load timeout for modules: "+b),j.requireType="timeout",j.requireModules=b,d.onError(j);if(h||g.scriptCount){if((G||ca)&&!W)W=setTimeout(function(){W=0;A()},50)}else{if(g.waitCount){for(H= -0;b=I[H];H++)z(b,{});g.paused.length&&w();X<5&&(X+=1,A())}X=0;d.checkReadyState()}}}}var g,w,p={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},catchError:{}},P=[],y={require:!0,exports:!0,module:!0},E={},m={},s={},D={},I=[],T={},M=0,R={},L={},F={},Q={},Y=0;S=function(b){if(!g.jQuery&&(b=b||(typeof jQuery!=="undefined"?jQuery:null))&&!(p.jQuery&&b.fn.jquery!==p.jQuery)&&("holdReady"in b||"readyWait"in b))if(g.jQuery=b,n(["jquery",[],function(){return jQuery}]),g.scriptCount)V(b,!0),g.jQueryIncremented= -!0};w=function(){var b,a,c,h,j,i;Y+=1;if(g.scriptCount<=0)g.scriptCount=0;for(;P.length;)if(b=P.shift(),b[0]===null)return d.onError(N("mismatch","Mismatched anonymous define() module: "+b[b.length-1]));else n(b);if(!p.priorityWait||k())for(;g.paused.length;){j=g.paused;g.pausedCount+=j.length;g.paused=[];for(h=0;b=j[h];h++)a=b.map,c=a.url,i=a.fullName,a.prefix?u(a.prefix,b):!T[c]&&!s[i]&&(d.load(g,i,c),c.indexOf("empty:")!==0&&(T[c]=!0));g.startTime=(new Date).getTime();g.pausedCount-=j.length}Y=== -1&&A();Y-=1};g={contextName:a,config:p,defQueue:P,waiting:D,waitCount:0,specified:y,loaded:s,urlMap:E,urlFetched:T,scriptCount:0,defined:m,paused:[],pausedCount:0,plugins:L,needFullExec:F,fake:{},fullExec:Q,managerCallbacks:R,makeModuleMap:h,normalize:c,configure:function(b){var a,c,d;b.baseUrl&&b.baseUrl.charAt(b.baseUrl.length-1)!=="/"&&(b.baseUrl+="/");a=p.paths;d=p.pkgs;Z(p,b,!0);if(b.paths){for(c in b.paths)c in K||(a[c]=b.paths[c]);p.paths=a}if((a=b.packagePaths)||b.packages){if(a)for(c in a)c in -K||$(d,a[c],c);b.packages&&$(d,b.packages);p.pkgs=d}if(b.priority)c=g.requireWait,g.requireWait=!1,g.takeGlobalQueue(),w(),g.require(b.priority),w(),g.requireWait=c,p.priorityWait=b.priority;if(b.deps||b.callback)g.require(b.deps||[],b.callback)},requireDefined:function(b,a){return h(b,a).fullName in m},requireSpecified:function(b,a){return h(b,a).fullName in y},require:function(b,c,f){if(typeof b==="string"){if(J(c))return d.onError(N("requireargs","Invalid require call"));if(d.get)return d.get(g, -b,c);c=h(b,c);b=c.fullName;return!(b in m)?d.onError(N("notloaded","Module name '"+c.fullName+"' has not been loaded yet for context: "+a)):m[b]}(b&&b.length||c)&&x(null,b,c,f);if(!g.requireWait)for(;!g.scriptCount&&g.paused.length;)g.takeGlobalQueue(),w();return g.require},takeGlobalQueue:function(){U.length&&(ha.apply(g.defQueue,[g.defQueue.length-1,0].concat(U)),U=[])},completeLoad:function(b){var a;for(g.takeGlobalQueue();P.length;)if(a=P.shift(),a[0]===null){a[0]=b;break}else if(a[0]===b)break; -else n(a),a=null;a?n(a):n([b,[],b==="jquery"&&typeof jQuery!=="undefined"?function(){return jQuery}:null]);S();d.isAsync&&(g.scriptCount-=1);w();d.isAsync||(g.scriptCount-=1)},toUrl:function(a,c){var d=a.lastIndexOf("."),h=null;d!==-1&&(h=a.substring(d,a.length),a=a.substring(0,d));return g.nameToUrl(a,h,c)},nameToUrl:function(a,h,f){var j,k,i,e,m=g.config,a=c(a,f&&f.fullName);if(d.jsExtRegExp.test(a))h=a+(h?h:"");else{j=m.paths;k=m.pkgs;f=a.split("/");for(e=f.length;e>0;e--)if(i=f.slice(0,e).join("/"), -j[i]){f.splice(0,e,j[i]);break}else if(i=k[i]){a=a===i.name?i.location+"/"+i.main:i.location;f.splice(0,e,a);break}h=f.join("/")+(h||".js");h=(h.charAt(0)==="/"||h.match(/^\w+:/)?"":m.baseUrl)+h}return m.urlArgs?h+((h.indexOf("?")===-1?"?":"&")+m.urlArgs):h}};g.jQueryCheck=S;g.resume=w;return g}function ia(){var a,c,d;if(n&&n.readyState==="interactive")return n;a=document.getElementsByTagName("script");for(c=a.length-1;c>-1&&(d=a[c]);c--)if(d.readyState==="interactive")return n=d;return null}var ja= -/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ka=/require\(\s*["']([^'"\s]+)["']\s*\)/g,ea=/^\.\//,aa=/\.js$/,M=Object.prototype.toString,r=Array.prototype,ga=r.slice,ha=r.splice,G=!!(typeof window!=="undefined"&&navigator&&document),ca=!G&&typeof importScripts!=="undefined",la=G&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,da=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",K={},t={},U=[],n=null,X=0,O=!1,d,r={},I,v,x,y,u,z,A,H,B,S,W;if(typeof define==="undefined"){if(typeof requirejs!== -"undefined")if(J(requirejs))return;else r=requirejs,requirejs=void 0;typeof require!=="undefined"&&!J(require)&&(r=require,require=void 0);d=requirejs=function(a,c,d){var k="_",j;!E(a)&&typeof a!=="string"&&(j=a,E(c)?(a=c,c=d):a=[]);if(j&&j.context)k=j.context;d=t[k]||(t[k]=fa(k));j&&d.configure(j);return d.require(a,c)};d.config=function(a){return d(a)};require||(require=d);d.toUrl=function(a){return t._.toUrl(a)};d.version="1.0.2";d.jsExtRegExp=/^\/|:|\?|\.js$/;v=d.s={contexts:t,skipAsync:{}};if(d.isAsync= -d.isBrowser=G)if(x=v.head=document.getElementsByTagName("head")[0],y=document.getElementsByTagName("base")[0])x=v.head=y.parentNode;d.onError=function(a){throw a;};d.load=function(a,c,h){d.resourcesReady(!1);a.scriptCount+=1;d.attach(h,a,c);if(a.jQuery&&!a.jQueryIncremented)V(a.jQuery,!0),a.jQueryIncremented=!0};define=function(a,c,d){var k,j;typeof a!=="string"&&(d=c,c=a,a=null);E(c)||(d=c,c=[]);!c.length&&J(d)&&d.length&&(d.toString().replace(ja,"").replace(ka,function(a,d){c.push(d)}),c=(d.length=== -1?["require"]:["require","exports","module"]).concat(c));if(O&&(k=I||ia()))a||(a=k.getAttribute("data-requiremodule")),j=t[k.getAttribute("data-requirecontext")];(j?j.defQueue:U).push([a,c,d])};define.amd={multiversion:!0,plugins:!0,jQuery:!0};d.exec=function(a){return eval(a)};d.execCb=function(a,c,d,k){return c.apply(k,d)};d.addScriptToDom=function(a){I=a;y?x.insertBefore(a,y):x.appendChild(a);I=null};d.onScriptLoad=function(a){var c=a.currentTarget||a.srcElement,h;if(a.type==="load"||c&&la.test(c.readyState))n= -null,a=c.getAttribute("data-requirecontext"),h=c.getAttribute("data-requiremodule"),t[a].completeLoad(h),c.detachEvent&&!da?c.detachEvent("onreadystatechange",d.onScriptLoad):c.removeEventListener("load",d.onScriptLoad,!1)};d.attach=function(a,c,h,k,j,n){var o;if(G)return k=k||d.onScriptLoad,o=c&&c.config&&c.config.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script"),o.type=j||"text/javascript",o.charset="utf-8",o.async=!v.skipAsync[a],c&&o.setAttribute("data-requirecontext", -c.contextName),o.setAttribute("data-requiremodule",h),o.attachEvent&&!da?(O=!0,n?o.onreadystatechange=function(){if(o.readyState==="loaded")o.onreadystatechange=null,o.attachEvent("onreadystatechange",k),n(o)}:o.attachEvent("onreadystatechange",k)):o.addEventListener("load",k,!1),o.src=a,n||d.addScriptToDom(o),o;else ca&&(importScripts(a),c.completeLoad(h));return null};if(G){u=document.getElementsByTagName("script");for(H=u.length-1;H>-1&&(z=u[H]);H--){if(!x)x=z.parentNode;if(A=z.getAttribute("data-main")){if(!r.baseUrl)u= -A.split("/"),z=u.pop(),u=u.length?u.join("/")+"/":"./",r.baseUrl=u,A=z.replace(aa,"");r.deps=r.deps?r.deps.concat(A):[A];break}}}d.checkReadyState=function(){var a=v.contexts,c;for(c in a)if(!(c in K)&&a[c].waitCount)return;d.resourcesReady(!0)};d.resourcesReady=function(a){var c,h;d.resourcesDone=a;if(d.resourcesDone)for(h in a=v.contexts,a)if(!(h in K)&&(c=a[h],c.jQueryIncremented))V(c.jQuery,!1),c.jQueryIncremented=!1};d.pageLoaded=function(){if(document.readyState!=="complete")document.readyState= -"complete"};if(G&&document.addEventListener&&!document.readyState)document.readyState="loading",window.addEventListener("load",d.pageLoaded,!1);d(r);if(d.isAsync&&typeof setTimeout!=="undefined")B=v.contexts[r.context||"_"],B.requireWait=!0,setTimeout(function(){B.requireWait=!1;B.takeGlobalQueue();B.jQueryCheck();B.scriptCount||B.resume();d.checkReadyState()},0)}})(); + */ +var requirejs, require, define; +(function () { + function J( a ) { + return M.call( a ) === "[object Function]" + } + + function E( a ) { + return M.call( a ) === "[object Array]" + } + + function Z( a, c, h ) { + for ( var k in c ) { + if ( !(k in K) && (!(k in a) || h) ) { + a[k] = c[k]; + } + } + return d + } + + function N( a, c, d ) { + a = Error( c + "\nhttp://requirejs.org/docs/errors.html#" + a ); + if ( d ) { + a.originalError = d; + } + return a + } + + function $( a, c, d ) { + var k, j, q; + for ( k = 0; q = c[k]; k++ ) { + q = typeof q === "string" ? {name : q} : q; + j = q.location; + if ( d && (!j || j.indexOf( "/" ) !== 0 && j.indexOf( ":" ) === -1) ) { + j = d + "/" + (j || q.name); + } + a[q.name] = {name : q.name, location : j || + q.name, main : (q.main || "main").replace( ea, "" ).replace( aa, "" )} + } + } + + function V( a, c ) { + a.holdReady ? a.holdReady( c ) : c ? a.readyWait += 1 : a.ready( !0 ) + } + + function fa( a ) { + function c( b, l ) { + var f, a; + if ( b && b.charAt( 0 ) === "." ) { + if ( l ) { + p.pkgs[l] ? l = [l] : (l = l.split( "/" ), l = l.slice( 0, l.length - 1 )); + f = b = l.concat( b.split( "/" ) ); + var c; + for ( a = 0; c = f[a]; a++ ) { + if ( c === "." ) { + f.splice( a, 1 ), a -= 1; + } else if ( c === ".." ) { + if ( a === 1 && (f[2] === ".." || f[0] === "..") ) { + break; + } else { + a > 0 && (f.splice( a - 1, 2 ), a -= 2); + } + } + } + a = p.pkgs[f = b[0]]; + b = b.join( "/" ); + a && b === f + "/" + a.main && (b = f) + } else { + b.indexOf( "./" ) === + 0 && (b = b.substring( 2 )); + } + } + return b + } + + function h( b, l ) { + var f = b ? b.indexOf( "!" ) : -1, a = null, d = l ? l.name : null, i = b, e, h; + f !== -1 && (a = b.substring( 0, f ), b = b.substring( f + 1, b.length )); + a && (a = c( a, d )); + b && (a ? e = (f = m[a]) && f.normalize ? f.normalize( b, function ( b ) { + return c( b, d ) + } ) : c( b, d ) : (e = c( b, d ), h = E[e], h || (h = g.nameToUrl( e, null, l ), E[e] = h))); + return{prefix : a, name : e, parentMap : l, url : h, originalName : i, fullName : a ? a + "!" + (e || "") : e} + } + + function k() { + var b = !0, l = p.priorityWait, f, a; + if ( l ) { + for ( a = 0; f = l[a]; a++ ) { + if ( !s[f] ) { + b = !1; + break + } + } + b && delete p.priorityWait + } + return b + } + + function j( b, l, f ) { + return function () { + var a = ga.call( arguments, 0 ), c; + if ( f && J( c = a[a.length - 1] ) ) { + c.__requireJsBuild = !0; + } + a.push( l ); + return b.apply( null, a ) + } + } + + function q( b, l ) { + var a = j( g.require, b, l ); + Z( a, {nameToUrl : j( g.nameToUrl, b ), toUrl : j( g.toUrl, b ), defined : j( g.requireDefined, b ), specified : j( g.requireSpecified, b ), isBrowser : d.isBrowser} ); + return a + } + + function o( b ) { + var l, a, c, C = b.callback, i = b.map, e = i.fullName, ba = b.deps; + c = b.listeners; + if ( C && J( C ) ) { + if ( p.catchError.define ) { + try { + a = d.execCb( e, b.callback, ba, m[e] ) + } catch ( k ) { + l = k + } + } else { + a = + d.execCb( e, b.callback, ba, m[e] ); + } + if ( e ) { + (C = b.cjsModule) && C.exports !== void 0 && C.exports !== m[e] ? a = m[e] = b.cjsModule.exports : a === void 0 && b.usingExports ? a = m[e] : (m[e] = a, F[e] && (Q[e] = !0)) + } + } else { + e && (a = m[e] = C, F[e] && (Q[e] = !0)); + } + if ( D[b.id] ) { + delete D[b.id], b.isDone = !0, g.waitCount -= 1, g.waitCount === 0 && (I = []); + } + delete R[e]; + if ( d.onResourceLoad && !b.placeholder ) { + d.onResourceLoad( g, i, b.depArray ); + } + if ( l ) { + return a = (e ? h( e ).url : "") || l.fileName || l.sourceURL, c = l.moduleTree, l = N( "defineerror", 'Error evaluating module "' + e + '" at location "' + + a + '":\n' + l + "\nfileName:" + a + "\nlineNumber: " + (l.lineNumber || l.line), l ), l.moduleName = e, l.moduleTree = c, d.onError( l ); + } + for ( l = 0; C = c[l]; l++ ) { + C( a ) + } + } + + function r( b, a ) { + return function ( f ) { + b.depDone[a] || (b.depDone[a] = !0, b.deps[a] = f, b.depCount -= 1, b.depCount || o( b )) + } + } + + function u( b, a ) { + var f = a.map, c = f.fullName, h = f.name, i = L[b] || (L[b] = m[b]), e; + if ( !a.loading ) { + a.loading = !0, e = function ( b ) { + a.callback = function () { + return b + }; + o( a ); + s[a.id] = !0; + w() + }, e.fromText = function ( b, a ) { + var l = O; + s[b] = !1; + g.scriptCount += 1; + g.fake[b] = !0; + l && (O = !1); + d.exec( a ); + l && (O = !0); + g.completeLoad( b ) + }, c in m ? e( m[c] ) : i.load( h, q( f.parentMap, !0 ), e, p ) + } + } + + function v( b ) { + D[b.id] || (D[b.id] = b, I.push( b ), g.waitCount += 1) + } + + function B( b ) { + this.listeners.push( b ) + } + + function t( b, a ) { + var f = b.fullName, c = b.prefix, d = c ? L[c] || (L[c] = m[c]) : null, i, e; + f && (i = R[f]); + if ( !i && (e = !0, i = {id : (c && !d ? M++ + "__p@:" : "") + (f || "__r@" + M++), map : b, depCount : 0, depDone : [], depCallbacks : [], deps : [], listeners : [], add : B}, y[i.id] = !0, f && (!c || L[c])) ) { + R[f] = i; + } + c && !d ? (f = t( h( c ), !0 ), f.add( function () { + var a = h( b.originalName, b.parentMap ), a = t( a, + !0 ); + i.placeholder = !0; + a.add( function ( b ) { + i.callback = function () { + return b + }; + o( i ) + } ) + } )) : e && a && (s[i.id] = !1, g.paused.push( i ), v( i )); + return i + } + + function x( b, a, f, c ) { + var b = h( b, c ), d = b.name, i = b.fullName, e = t( b ), k = e.id, j = e.deps, n; + if ( i ) { + if ( i in m || s[k] === !0 || i === "jquery" && p.jQuery && p.jQuery !== f().fn.jquery ) { + return; + } + y[k] = !0; + s[k] = !0; + i === "jquery" && f && S( f() ) + } + e.depArray = a; + e.callback = f; + for ( f = 0; f < a.length; f++ ) { + if ( k = a[f] ) { + k = h( k, d ? b : c ), n = k.fullName, a[f] = n, n === "require" ? j[f] = q( b ) : n === "exports" ? (j[f] = m[i] = {}, e.usingExports = !0) : n === + "module" ? e.cjsModule = j[f] = {id : d, uri : d ? g.nameToUrl( d, null, c ) : void 0, exports : m[i]} : n in m && !(n in D) && (!(i in F) || i in F && Q[n]) ? j[f] = m[n] : (i in F && (F[n] = !0, delete m[n], T[k.url] = !1), e.depCount += 1, e.depCallbacks[f] = r( e, f ), t( k, !0 ).add( e.depCallbacks[f] )); + } + } + e.depCount ? v( e ) : o( e ) + } + + function n( b ) { + x.apply( null, b ) + } + + function z( b, a ) { + if ( !b.isDone ) { + var c = b.map.fullName, d = b.depArray, g, i, e, k; + if ( c ) { + if ( a[c] ) { + return m[c]; + } + a[c] = !0 + } + if ( d ) { + for ( g = 0; g < d.length; g++ ) { + if ( i = d[g] ) { + if ( (e = h( i ).prefix) && (k = D[e]) && z( k, a ), (e = D[i]) && !e.isDone && + s[i] ) { + i = z( e, a ), b.depCallbacks[g]( i ); + } + } + } + } + return c ? m[c] : void 0 + } + } + + function A() { + var b = p.waitSeconds * 1E3, a = b && g.startTime + b < (new Date).getTime(), b = "", c = !1, h = !1, j; + if ( !(g.pausedCount > 0) ) { + if ( p.priorityWait ) { + if ( k() ) { + w(); + } else { + return; + } + } + for ( j in s ) { + if ( !(j in K) && (c = !0, !s[j]) ) { + if ( a ) { + b += j + " "; + } else { + h = !0; + break + } + } + } + if ( c || g.waitCount ) { + if ( a && b ) { + return j = N( "timeout", "Load timeout for modules: " + b ), j.requireType = "timeout", j.requireModules = b, d.onError( j ); + } + if ( h || g.scriptCount ) { + if ( (G || ca) && !W ) { + W = setTimeout( function () { + W = 0; + A() + }, 50 ) + } + } else { + if ( g.waitCount ) { + for ( H = + 0; b = I[H]; H++ ) { + z( b, {} ); + } + g.paused.length && w(); + X < 5 && (X += 1, A()) + } + X = 0; + d.checkReadyState() + } + } + } + } + + var g, w, p = {waitSeconds : 7, baseUrl : "./", paths : {}, pkgs : {}, catchError : {}}, P = [], y = {require : !0, exports : !0, module : !0}, E = {}, m = {}, s = {}, D = {}, I = [], T = {}, M = 0, R = {}, L = {}, F = {}, Q = {}, Y = 0; + S = function ( b ) { + if ( !g.jQuery && (b = b || (typeof jQuery !== "undefined" ? jQuery : null)) && !(p.jQuery && b.fn.jquery !== p.jQuery) && ("holdReady"in b || "readyWait"in b) ) { + if ( g.jQuery = b, n( ["jquery", [], function () { + return jQuery + }] ), g.scriptCount ) { + V( b, !0 ), g.jQueryIncremented = + !0 + } + } + }; + w = function () { + var b, a, c, h, j, i; + Y += 1; + if ( g.scriptCount <= 0 ) { + g.scriptCount = 0; + } + for ( ; P.length; ) { + if ( b = P.shift(), b[0] === null ) { + return d.onError( N( "mismatch", "Mismatched anonymous define() module: " + b[b.length - 1] ) ); + } else { + n( b ); + } + } + if ( !p.priorityWait || k() ) { + for ( ; g.paused.length; ) { + j = g.paused; + g.pausedCount += j.length; + g.paused = []; + for ( h = 0; b = j[h]; h++ ) { + a = b.map, c = a.url, i = a.fullName, a.prefix ? u( a.prefix, b ) : !T[c] && !s[i] && (d.load( g, i, c ), c.indexOf( "empty:" ) !== 0 && (T[c] = !0)); + } + g.startTime = (new Date).getTime(); + g.pausedCount -= j.length + } + } + Y === + 1 && A(); + Y -= 1 + }; + g = {contextName : a, config : p, defQueue : P, waiting : D, waitCount : 0, specified : y, loaded : s, urlMap : E, urlFetched : T, scriptCount : 0, defined : m, paused : [], pausedCount : 0, plugins : L, needFullExec : F, fake : {}, fullExec : Q, managerCallbacks : R, makeModuleMap : h, normalize : c, configure : function ( b ) { + var a, c, d; + b.baseUrl && b.baseUrl.charAt( b.baseUrl.length - 1 ) !== "/" && (b.baseUrl += "/"); + a = p.paths; + d = p.pkgs; + Z( p, b, !0 ); + if ( b.paths ) { + for ( c in b.paths ) { + c in K || (a[c] = b.paths[c]); + } + p.paths = a + } + if ( (a = b.packagePaths) || b.packages ) { + if ( a ) { + for ( c in a ) { + c in + K || $( d, a[c], c ); + } + } + b.packages && $( d, b.packages ); + p.pkgs = d + } + if ( b.priority ) { + c = g.requireWait, g.requireWait = !1, g.takeGlobalQueue(), w(), g.require( b.priority ), w(), g.requireWait = c, p.priorityWait = b.priority; + } + if ( b.deps || b.callback ) { + g.require( b.deps || [], b.callback ) + } + }, requireDefined : function ( b, a ) { + return h( b, a ).fullName in m + }, requireSpecified : function ( b, a ) { + return h( b, a ).fullName in y + }, require : function ( b, c, f ) { + if ( typeof b === "string" ) { + if ( J( c ) ) { + return d.onError( N( "requireargs", "Invalid require call" ) ); + } + if ( d.get ) { + return d.get( g, + b, c ); + } + c = h( b, c ); + b = c.fullName; + return!(b in m) ? d.onError( N( "notloaded", "Module name '" + c.fullName + "' has not been loaded yet for context: " + a ) ) : m[b] + } + (b && b.length || c) && x( null, b, c, f ); + if ( !g.requireWait ) { + for ( ; !g.scriptCount && g.paused.length; ) { + g.takeGlobalQueue(), w(); + } + } + return g.require + }, takeGlobalQueue : function () { + U.length && (ha.apply( g.defQueue, [g.defQueue.length - 1, 0].concat( U ) ), U = []) + }, completeLoad : function ( b ) { + var a; + for ( g.takeGlobalQueue(); P.length; ) { + if ( a = P.shift(), a[0] === null ) { + a[0] = b; + break + } else if ( a[0] === b ) { + break; + } + else { + n( a ), a = null; + } + } + a ? n( a ) : n( [b, [], b === "jquery" && typeof jQuery !== "undefined" ? function () { + return jQuery + } : null] ); + S(); + d.isAsync && (g.scriptCount -= 1); + w(); + d.isAsync || (g.scriptCount -= 1) + }, toUrl : function ( a, c ) { + var d = a.lastIndexOf( "." ), h = null; + d !== -1 && (h = a.substring( d, a.length ), a = a.substring( 0, d )); + return g.nameToUrl( a, h, c ) + }, nameToUrl : function ( a, h, f ) { + var j, k, i, e, m = g.config, a = c( a, f && f.fullName ); + if ( d.jsExtRegExp.test( a ) ) { + h = a + (h ? h : ""); + } else { + j = m.paths; + k = m.pkgs; + f = a.split( "/" ); + for ( e = f.length; e > 0; e-- ) { + if ( i = f.slice( 0, e ).join( "/" ), + j[i] ) { + f.splice( 0, e, j[i] ); + break + } else if ( i = k[i] ) { + a = a === i.name ? i.location + "/" + i.main : i.location; + f.splice( 0, e, a ); + break + } + } + h = f.join( "/" ) + (h || ".js"); + h = (h.charAt( 0 ) === "/" || h.match( /^\w+:/ ) ? "" : m.baseUrl) + h + } + return m.urlArgs ? h + ((h.indexOf( "?" ) === -1 ? "?" : "&") + m.urlArgs) : h + }}; + g.jQueryCheck = S; + g.resume = w; + return g + } + + function ia() { + var a, c, d; + if ( n && n.readyState === "interactive" ) { + return n; + } + a = document.getElementsByTagName( "script" ); + for ( c = a.length - 1; c > -1 && (d = a[c]); c-- ) { + if ( d.readyState === "interactive" ) { + return n = d; + } + } + return null + } + + var ja = + /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, ka = /require\(\s*["']([^'"\s]+)["']\s*\)/g, ea = /^\.\//, aa = /\.js$/, M = Object.prototype.toString, r = Array.prototype, ga = r.slice, ha = r.splice, G = !!(typeof window !== "undefined" && navigator && document), ca = !G && typeof importScripts !== "undefined", la = G && navigator.platform === "PLAYSTATION 3" ? /^complete$/ : /^(complete|loaded)$/, da = typeof opera !== "undefined" && opera.toString() === "[object Opera]", K = {}, t = {}, U = [], n = null, X = 0, O = !1, d, r = {}, I, v, x, y, u, z, A, H, B, S, W; + if ( typeof define === "undefined" ) { + if ( typeof requirejs !== + "undefined" ) { + if ( J( requirejs ) ) { + return; + } else { + r = requirejs, requirejs = void 0; + } + } + typeof require !== "undefined" && !J( require ) && (r = require, require = void 0); + d = requirejs = function ( a, c, d ) { + var k = "_", j; + !E( a ) && typeof a !== "string" && (j = a, E( c ) ? (a = c, c = d) : a = []); + if ( j && j.context ) { + k = j.context; + } + d = t[k] || (t[k] = fa( k )); + j && d.configure( j ); + return d.require( a, c ) + }; + d.config = function ( a ) { + return d( a ) + }; + require || (require = d); + d.toUrl = function ( a ) { + return t._.toUrl( a ) + }; + d.version = "1.0.2"; + d.jsExtRegExp = /^\/|:|\?|\.js$/; + v = d.s = {contexts : t, skipAsync : {}}; + if ( d.isAsync = + d.isBrowser = G ) { + if ( x = v.head = document.getElementsByTagName( "head" )[0], y = document.getElementsByTagName( "base" )[0] ) { + x = v.head = y.parentNode; + } + } + d.onError = function ( a ) { + throw a; + }; + d.load = function ( a, c, h ) { + d.resourcesReady( !1 ); + a.scriptCount += 1; + d.attach( h, a, c ); + if ( a.jQuery && !a.jQueryIncremented ) { + V( a.jQuery, !0 ), a.jQueryIncremented = !0 + } + }; + define = function ( a, c, d ) { + var k, j; + typeof a !== "string" && (d = c, c = a, a = null); + E( c ) || (d = c, c = []); + !c.length && J( d ) && d.length && (d.toString().replace( ja, "" ).replace( ka, function ( a, d ) { + c.push( d ) + } ), c = (d.length === + 1 ? ["require"] : ["require", "exports", "module"]).concat( c )); + if ( O && (k = I || ia()) ) { + a || (a = k.getAttribute( "data-requiremodule" )), j = t[k.getAttribute( "data-requirecontext" )]; + } + (j ? j.defQueue : U).push( [a, c, d] ) + }; + define.amd = {multiversion : !0, plugins : !0, jQuery : !0}; + d.exec = function ( a ) { + return eval( a ) + }; + d.execCb = function ( a, c, d, k ) { + return c.apply( k, d ) + }; + d.addScriptToDom = function ( a ) { + I = a; + y ? x.insertBefore( a, y ) : x.appendChild( a ); + I = null + }; + d.onScriptLoad = function ( a ) { + var c = a.currentTarget || a.srcElement, h; + if ( a.type === "load" || c && la.test( c.readyState ) ) { + n = + null, a = c.getAttribute( "data-requirecontext" ), h = c.getAttribute( "data-requiremodule" ), t[a].completeLoad( h ), c.detachEvent && !da ? c.detachEvent( "onreadystatechange", d.onScriptLoad ) : c.removeEventListener( "load", d.onScriptLoad, !1 ) + } + }; + d.attach = function ( a, c, h, k, j, n ) { + var o; + if ( G ) { + return k = k || d.onScriptLoad, o = c && c.config && c.config.xhtml ? document.createElementNS( "http://www.w3.org/1999/xhtml", "html:script" ) : document.createElement( "script" ), o.type = j || "text/javascript", o.charset = "utf-8", o.async = !v.skipAsync[a], c && o.setAttribute( "data-requirecontext", + c.contextName ), o.setAttribute( "data-requiremodule", h ), o.attachEvent && !da ? (O = !0, n ? o.onreadystatechange = function () { + if ( o.readyState === "loaded" ) { + o.onreadystatechange = null, o.attachEvent( "onreadystatechange", k ), n( o ) + } + } : o.attachEvent( "onreadystatechange", k )) : o.addEventListener( "load", k, !1 ), o.src = a, n || d.addScriptToDom( o ), o; + } else { + ca && (importScripts( a ), c.completeLoad( h )); + } + return null + }; + if ( G ) { + u = document.getElementsByTagName( "script" ); + for ( H = u.length - 1; H > -1 && (z = u[H]); H-- ) { + if ( !x ) { + x = z.parentNode; + } + if ( A = z.getAttribute( "data-main" ) ) { + if ( !r.baseUrl ) { + u = + A.split( "/" ), z = u.pop(), u = u.length ? u.join( "/" ) + "/" : "./", r.baseUrl = u, A = z.replace( aa, "" ); + } + r.deps = r.deps ? r.deps.concat( A ) : [A]; + break + } + } + } + d.checkReadyState = function () { + var a = v.contexts, c; + for ( c in a ) { + if ( !(c in K) && a[c].waitCount ) { + return; + } + } + d.resourcesReady( !0 ) + }; + d.resourcesReady = function ( a ) { + var c, h; + d.resourcesDone = a; + if ( d.resourcesDone ) { + for ( h in a = v.contexts, a ) { + if ( !(h in K) && (c = a[h], c.jQueryIncremented) ) { + V( c.jQuery, !1 ), c.jQueryIncremented = !1 + } + } + } + }; + d.pageLoaded = function () { + if ( document.readyState !== "complete" ) { + document.readyState = + "complete" + } + }; + if ( G && document.addEventListener && !document.readyState ) { + document.readyState = "loading", window.addEventListener( "load", d.pageLoaded, !1 ); + } + d( r ); + if ( d.isAsync && typeof setTimeout !== "undefined" ) { + B = v.contexts[r.context || "_"], B.requireWait = !0, setTimeout( function () { + B.requireWait = !1; + B.takeGlobalQueue(); + B.jQueryCheck(); + B.scriptCount || B.resume(); + d.checkReadyState() + }, 0 ) + } + } +})(); diff --git a/example/amd/js/libs/underscore/underscore-min.js b/example/amd/js/libs/underscore/underscore-min.js index fadc96e..9bd5f31 100644 --- a/example/amd/js/libs/underscore/underscore-min.js +++ b/example/amd/js/libs/underscore/underscore-min.js @@ -5,26 +5,691 @@ // Oliver Steele's Functional, and John Resig's Micro-Templating. // For all details and documentation: // http://documentcloud.github.com/underscore -(function(){function r(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(b.isFunction(a.isEqual))return a.isEqual(c);if(b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return String(a)==String(c);case "[object Number]":return a=+a,c=+c,a!=a?c!=c:a==0?1/a==1/c:a==c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source== -c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&r(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(m.call(a,h)&&(f++,!(g=m.call(c,h)&&r(a[h],c[h],d))))break;if(g){for(h in c)if(m.call(c, -h)&&!f--)break;g=!f}}d.pop();return g}var s=this,F=s._,o={},k=Array.prototype,p=Object.prototype,i=k.slice,G=k.unshift,l=p.toString,m=p.hasOwnProperty,v=k.forEach,w=k.map,x=k.reduce,y=k.reduceRight,z=k.filter,A=k.every,B=k.some,q=k.indexOf,C=k.lastIndexOf,p=Array.isArray,H=Object.keys,t=Function.prototype.bind,b=function(a){return new n(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else typeof define==="function"&&define.amd? -define("underscore",function(){return b}):s._=b;b.VERSION="1.2.2";var j=b.each=b.forEach=function(a,c,b){if(a!=null)if(v&&a.forEach===v)a.forEach(c,b);else if(a.length===+a.length)for(var e=0,f=a.length;e=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;bd?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,c){var b=e(a,c);(d[b]||(d[b]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||(d=b.identity);for(var e=0,f=a.length;e< -f;){var g=e+f>>1;d(a[g])=0})})};b.difference=function(a,c){return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e=0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=H||function(a){if(a!== -Object(a))throw new TypeError("Invalid object");var b=[],d;for(d in a)m.call(a,d)&&(b[b.length]=d);return b};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)b[d]!==void 0&&(a[d]=b[d])});return a};b.defaults=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)? -a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return r(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(m.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=p||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};b.isArguments=l.call(arguments)=="[object Arguments]"?function(a){return l.call(a)=="[object Arguments]"}: -function(a){return!(!a||!m.call(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null}; -b.isUndefined=function(a){return a===void 0};b.noConflict=function(){s._=F;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.mixin=function(a){j(b.functions(a),function(c){I(c,b[c]=a[c])})};var J=0;b.uniqueId=function(a){var b=J++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g, -interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape,function(a,b){return"',_.escape("+b.replace(/\\'/g,"'")+"),'"}).replace(d.interpolate,function(a,b){return"',"+b.replace(/\\'/g,"'")+",'"}).replace(d.evaluate||null,function(a,b){return"');"+b.replace(/\\'/g,"'").replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g, -"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e(a,b)}};var n=function(a){this._wrapped=a};b.prototype=n.prototype;var u=function(a,c){return c?b(a).chain():a},I=function(a,c){n.prototype[a]=function(){var a=i.call(arguments);G.call(a,this._wrapped);return u(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];n.prototype[a]=function(){b.apply(this._wrapped, -arguments);return u(this._wrapped,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];n.prototype[a]=function(){return u(b.apply(this._wrapped,arguments),this._chain)}});n.prototype.chain=function(){this._chain=true;return this};n.prototype.value=function(){return this._wrapped}}).call(this); +(function () { + function r( a, c, d ) { + if ( a === c ) { + return a !== 0 || 1 / a == 1 / c; + } + if ( a == null || c == null ) { + return a === c; + } + if ( a._chain ) { + a = a._wrapped; + } + if ( c._chain ) { + c = c._wrapped; + } + if ( b.isFunction( a.isEqual ) ) { + return a.isEqual( c ); + } + if ( b.isFunction( c.isEqual ) ) { + return c.isEqual( a ); + } + var e = l.call( a ); + if ( e != l.call( c ) ) { + return false; + } + switch ( e ) { + case "[object String]": + return String( a ) == String( c ); + case "[object Number]": + return a = +a, c = +c, a != a ? c != c : a == 0 ? 1 / a == 1 / c : a == c; + case "[object Date]": + case "[object Boolean]": + return+a == +c; + case "[object RegExp]": + return a.source == + c.source && a.global == c.global && a.multiline == c.multiline && a.ignoreCase == c.ignoreCase + } + if ( typeof a != "object" || typeof c != "object" ) { + return false; + } + for ( var f = d.length; f--; ) { + if ( d[f] == a ) { + return true; + } + } + d.push( a ); + var f = 0, g = true; + if ( e == "[object Array]" ) { + if ( f = a.length, g = f == c.length ) { + for ( ; f--; ) { + if ( !(g = f in a == f in c && r( a[f], c[f], d )) ) { + break + } + } + } + } else { + if ( "constructor"in a != "constructor"in c || a.constructor != c.constructor ) { + return false; + } + for ( var h in a ) { + if ( m.call( a, h ) && (f++, !(g = m.call( c, h ) && r( a[h], c[h], d ))) ) { + break; + } + } + if ( g ) { + for ( h in c ) { + if ( m.call( c, + h ) && !f-- ) { + break; + } + } + g = !f + } + } + d.pop(); + return g + } + + var s = this, F = s._, o = {}, k = Array.prototype, p = Object.prototype, i = k.slice, G = k.unshift, l = p.toString, m = p.hasOwnProperty, v = k.forEach, w = k.map, x = k.reduce, y = k.reduceRight, z = k.filter, A = k.every, B = k.some, q = k.indexOf, C = k.lastIndexOf, p = Array.isArray, H = Object.keys, t = Function.prototype.bind, b = function ( a ) { + return new n( a ) + }; + if ( typeof exports !== "undefined" ) { + if ( typeof module !== "undefined" && module.exports ) { + exports = module.exports = b; + } + exports._ = b + } else { + typeof define === "function" && define.amd ? + define( "underscore", function () { + return b + } ) : s._ = b; + } + b.VERSION = "1.2.2"; + var j = b.each = b.forEach = function ( a, c, b ) { + if ( a != null ) { + if ( v && a.forEach === v ) { + a.forEach( c, b ); + } else if ( a.length === +a.length ) { + for ( var e = 0, f = a.length; e < f; e++ ) { + if ( e in a && c.call( b, a[e], e, a ) === o ) { + break + } + } + } else { + for ( e in a ) { + if ( m.call( a, e ) && c.call( b, a[e], e, a ) === o ) { + break + } + } + } + } + }; + b.map = function ( a, c, b ) { + var e = []; + if ( a == null ) { + return e; + } + if ( w && a.map === w ) { + return a.map( c, b ); + } + j( a, function ( a, g, h ) { + e[e.length] = c.call( b, a, g, h ) + } ); + return e + }; + b.reduce = b.foldl = b.inject = function ( a, c, d, e ) { + var f = + d !== void 0; + a == null && (a = []); + if ( x && a.reduce === x ) { + return e && (c = b.bind( c, e )), f ? a.reduce( c, d ) : a.reduce( c ); + } + j( a, function ( a, b, i ) { + f ? d = c.call( e, d, a, b, i ) : (d = a, f = true) + } ); + if ( !f ) { + throw new TypeError( "Reduce of empty array with no initial value" ); + } + return d + }; + b.reduceRight = b.foldr = function ( a, c, d, e ) { + a == null && (a = []); + if ( y && a.reduceRight === y ) { + return e && (c = b.bind( c, e )), d !== void 0 ? a.reduceRight( c, d ) : a.reduceRight( c ); + } + a = (b.isArray( a ) ? a.slice() : b.toArray( a )).reverse(); + return b.reduce( a, c, d, e ) + }; + b.find = b.detect = function ( a, c, b ) { + var e; + D( a, function ( a, g, h ) { + if ( c.call( b, a, g, h ) ) { + return e = a, true + } + } ); + return e + }; + b.filter = b.select = function ( a, c, b ) { + var e = []; + if ( a == null ) { + return e; + } + if ( z && a.filter === z ) { + return a.filter( c, b ); + } + j( a, function ( a, g, h ) { + c.call( b, a, g, h ) && (e[e.length] = a) + } ); + return e + }; + b.reject = function ( a, c, b ) { + var e = []; + if ( a == null ) { + return e; + } + j( a, function ( a, g, h ) { + c.call( b, a, g, h ) || (e[e.length] = a) + } ); + return e + }; + b.every = b.all = function ( a, c, b ) { + var e = true; + if ( a == null ) { + return e; + } + if ( A && a.every === A ) { + return a.every( c, b ); + } + j( a, function ( a, g, h ) { + if ( !(e = e && c.call( b, a, g, h )) ) { + return o + } + } ); + return e + }; + var D = b.some = b.any = function ( a, c, d ) { + var c = c || b.identity, e = false; + if ( a == null ) { + return e; + } + if ( B && a.some === B ) { + return a.some( c, d ); + } + j( a, function ( a, b, h ) { + if ( e || (e = c.call( d, a, b, h )) ) { + return o + } + } ); + return!!e + }; + b.include = b.contains = function ( a, c ) { + var b = false; + if ( a == null ) { + return b; + } + return q && a.indexOf === q ? a.indexOf( c ) != -1 : b = D( a, function ( a ) { + return a === c + } ) + }; + b.invoke = function ( a, c ) { + var d = i.call( arguments, 2 ); + return b.map( a, function ( a ) { + return(c.call ? c || a : a[c]).apply( a, d ) + } ) + }; + b.pluck = function ( a, c ) { + return b.map( a, function ( a ) { + return a[c] + } ) + }; + b.max = function ( a, c, d ) { + if ( !c && b.isArray( a ) ) { + return Math.max.apply( Math, a ); + } + if ( !c && b.isEmpty( a ) ) { + return-Infinity; + } + var e = {computed : -Infinity}; + j( a, function ( a, b, h ) { + b = c ? c.call( d, a, b, h ) : a; + b >= e.computed && (e = {value : a, computed : b}) + } ); + return e.value + }; + b.min = function ( a, c, d ) { + if ( !c && b.isArray( a ) ) { + return Math.min.apply( Math, a ); + } + if ( !c && b.isEmpty( a ) ) { + return Infinity; + } + var e = {computed : Infinity}; + j( a, function ( a, b, h ) { + b = c ? c.call( d, a, b, h ) : a; + b < e.computed && (e = {value : a, computed : b}) + } ); + return e.value + }; + b.shuffle = function ( a ) { + var c = [], b; + j( a, function ( a, f ) { + f == 0 ? c[0] = a : (b = Math.floor( Math.random() * (f + 1) ), c[f] = c[b], c[b] = a) + } ); + return c + }; + b.sortBy = function ( a, c, d ) { + return b.pluck( b.map( a, + function ( a, b, g ) { + return{value : a, criteria : c.call( d, a, b, g )} + } ).sort( function ( a, c ) { + var b = a.criteria, d = c.criteria; + return b < d ? -1 : b > d ? 1 : 0 + } ), "value" ) + }; + b.groupBy = function ( a, c ) { + var d = {}, e = b.isFunction( c ) ? c : function ( a ) { + return a[c] + }; + j( a, function ( a, c ) { + var b = e( a, c ); + (d[b] || (d[b] = [])).push( a ) + } ); + return d + }; + b.sortedIndex = function ( a, c, d ) { + d || (d = b.identity); + for ( var e = 0, f = a.length; e < + f; ) { + var g = e + f >> 1; + d( a[g] ) < d( c ) ? e = g + 1 : f = g + } + return e + }; + b.toArray = function ( a ) { + return!a ? [] : a.toArray ? a.toArray() : b.isArray( a ) ? i.call( a ) : b.isArguments( a ) ? i.call( a ) : b.values( a ) + }; + b.size = function ( a ) { + return b.toArray( a ).length + }; + b.first = b.head = function ( a, b, d ) { + return b != null && !d ? i.call( a, 0, b ) : a[0] + }; + b.initial = function ( a, b, d ) { + return i.call( a, 0, a.length - (b == null || d ? 1 : b) ) + }; + b.last = function ( a, b, d ) { + return b != null && !d ? i.call( a, Math.max( a.length - b, 0 ) ) : a[a.length - 1] + }; + b.rest = b.tail = function ( a, b, d ) { + return i.call( a, b == null || + d ? 1 : b ) + }; + b.compact = function ( a ) { + return b.filter( a, function ( a ) { + return!!a + } ) + }; + b.flatten = function ( a, c ) { + return b.reduce( a, function ( a, e ) { + if ( b.isArray( e ) ) { + return a.concat( c ? e : b.flatten( e ) ); + } + a[a.length] = e; + return a + }, [] ) + }; + b.without = function ( a ) { + return b.difference( a, i.call( arguments, 1 ) ) + }; + b.uniq = b.unique = function ( a, c, d ) { + var d = d ? b.map( a, d ) : a, e = []; + b.reduce( d, function ( d, g, h ) { + if ( 0 == h || (c === true ? b.last( d ) != g : !b.include( d, g )) ) { + d[d.length] = g, e[e.length] = a[h]; + } + return d + }, [] ); + return e + }; + b.union = function () { + return b.uniq( b.flatten( arguments, + true ) ) + }; + b.intersection = b.intersect = function ( a ) { + var c = i.call( arguments, 1 ); + return b.filter( b.uniq( a ), function ( a ) { + return b.every( c, function ( c ) { + return b.indexOf( c, a ) >= 0 + } ) + } ) + }; + b.difference = function ( a, c ) { + return b.filter( a, function ( a ) { + return!b.include( c, a ) + } ) + }; + b.zip = function () { + for ( var a = i.call( arguments ), c = b.max( b.pluck( a, "length" ) ), d = Array( c ), e = 0; e < c; e++ ) { + d[e] = b.pluck( a, "" + e ); + } + return d + }; + b.indexOf = function ( a, c, d ) { + if ( a == null ) { + return-1; + } + var e; + if ( d ) { + return d = b.sortedIndex( a, c ), a[d] === c ? d : -1; + } + if ( q && a.indexOf === q ) { + return a.indexOf( c ); + } + for ( d = 0, e = a.length; d < e; d++ ) { + if ( a[d] === c ) { + return d; + } + } + return-1 + }; + b.lastIndexOf = function ( a, b ) { + if ( a == null ) { + return-1; + } + if ( C && a.lastIndexOf === C ) { + return a.lastIndexOf( b ); + } + for ( var d = a.length; d--; ) { + if ( a[d] === b ) { + return d; + } + } + return-1 + }; + b.range = function ( a, b, d ) { + arguments.length <= 1 && (b = a || 0, a = 0); + for ( var d = arguments[2] || 1, e = Math.max( Math.ceil( (b - a) / d ), 0 ), f = 0, g = Array( e ); f < e; ) { + g[f++] = a, a += d; + } + return g + }; + var E = function () { + }; + b.bind = function ( a, c ) { + var d, e; + if ( a.bind === t && t ) { + return t.apply( a, i.call( arguments, 1 ) ); + } + if ( !b.isFunction( a ) ) { + throw new TypeError; + } + e = i.call( arguments, 2 ); + return d = function () { + if ( !(this instanceof d) ) { + return a.apply( c, e.concat( i.call( arguments ) ) ); + } + E.prototype = a.prototype; + var b = new E, g = a.apply( b, e.concat( i.call( arguments ) ) ); + return Object( g ) === g ? g : b + } + }; + b.bindAll = function ( a ) { + var c = i.call( arguments, 1 ); + c.length == 0 && (c = b.functions( a )); + j( c, function ( c ) { + a[c] = b.bind( a[c], a ) + } ); + return a + }; + b.memoize = function ( a, c ) { + var d = {}; + c || (c = b.identity); + return function () { + var b = c.apply( this, arguments ); + return m.call( d, b ) ? d[b] : d[b] = a.apply( this, arguments ) + } + }; + b.delay = + function ( a, b ) { + var d = i.call( arguments, 2 ); + return setTimeout( function () { + return a.apply( a, d ) + }, b ) + }; + b.defer = function ( a ) { + return b.delay.apply( b, [a, 1].concat( i.call( arguments, 1 ) ) ) + }; + b.throttle = function ( a, c ) { + var d, e, f, g, h, i = b.debounce( function () { + h = g = false + }, c ); + return function () { + d = this; + e = arguments; + var b; + f || (f = setTimeout( function () { + f = null; + h && a.apply( d, e ); + i() + }, c )); + g ? h = true : a.apply( d, e ); + i(); + g = true + } + }; + b.debounce = function ( a, b ) { + var d; + return function () { + var e = this, f = arguments; + clearTimeout( d ); + d = setTimeout( function () { + d = + null; + a.apply( e, f ) + }, b ) + } + }; + b.once = function ( a ) { + var b = false, d; + return function () { + if ( b ) { + return d; + } + b = true; + return d = a.apply( this, arguments ) + } + }; + b.wrap = function ( a, b ) { + return function () { + var d = [a].concat( i.call( arguments ) ); + return b.apply( this, d ) + } + }; + b.compose = function () { + var a = i.call( arguments ); + return function () { + for ( var b = i.call( arguments ), d = a.length - 1; d >= 0; d-- ) { + b = [a[d].apply( this, b )]; + } + return b[0] + } + }; + b.after = function ( a, b ) { + return a <= 0 ? b() : function () { + if ( --a < 1 ) { + return b.apply( this, arguments ) + } + } + }; + b.keys = H || function ( a ) { + if ( a !== + Object( a ) ) { + throw new TypeError( "Invalid object" ); + } + var b = [], d; + for ( d in a ) { + m.call( a, d ) && (b[b.length] = d); + } + return b + }; + b.values = function ( a ) { + return b.map( a, b.identity ) + }; + b.functions = b.methods = function ( a ) { + var c = [], d; + for ( d in a ) { + b.isFunction( a[d] ) && c.push( d ); + } + return c.sort() + }; + b.extend = function ( a ) { + j( i.call( arguments, 1 ), function ( b ) { + for ( var d in b ) { + b[d] !== void 0 && (a[d] = b[d]) + } + } ); + return a + }; + b.defaults = function ( a ) { + j( i.call( arguments, 1 ), function ( b ) { + for ( var d in b ) { + a[d] == null && (a[d] = b[d]) + } + } ); + return a + }; + b.clone = function ( a ) { + return!b.isObject( a ) ? + a : b.isArray( a ) ? a.slice() : b.extend( {}, a ) + }; + b.tap = function ( a, b ) { + b( a ); + return a + }; + b.isEqual = function ( a, b ) { + return r( a, b, [] ) + }; + b.isEmpty = function ( a ) { + if ( b.isArray( a ) || b.isString( a ) ) { + return a.length === 0; + } + for ( var c in a ) { + if ( m.call( a, c ) ) { + return false; + } + } + return true + }; + b.isElement = function ( a ) { + return!!(a && a.nodeType == 1) + }; + b.isArray = p || function ( a ) { + return l.call( a ) == "[object Array]" + }; + b.isObject = function ( a ) { + return a === Object( a ) + }; + b.isArguments = l.call( arguments ) == "[object Arguments]" ? function ( a ) { + return l.call( a ) == "[object Arguments]" + } : + function ( a ) { + return!(!a || !m.call( a, "callee" )) + }; + b.isFunction = function ( a ) { + return l.call( a ) == "[object Function]" + }; + b.isString = function ( a ) { + return l.call( a ) == "[object String]" + }; + b.isNumber = function ( a ) { + return l.call( a ) == "[object Number]" + }; + b.isNaN = function ( a ) { + return a !== a + }; + b.isBoolean = function ( a ) { + return a === true || a === false || l.call( a ) == "[object Boolean]" + }; + b.isDate = function ( a ) { + return l.call( a ) == "[object Date]" + }; + b.isRegExp = function ( a ) { + return l.call( a ) == "[object RegExp]" + }; + b.isNull = function ( a ) { + return a === null + }; + b.isUndefined = function ( a ) { + return a === void 0 + }; + b.noConflict = function () { + s._ = F; + return this + }; + b.identity = function ( a ) { + return a + }; + b.times = function ( a, b, d ) { + for ( var e = 0; e < a; e++ ) { + b.call( d, e ) + } + }; + b.escape = function ( a ) { + return("" + a).replace( /&/g, "&" ).replace( //g, ">" ).replace( /"/g, """ ).replace( /'/g, "'" ).replace( /\//g, "/" ) + }; + b.mixin = function ( a ) { + j( b.functions( a ), function ( c ) { + I( c, b[c] = a[c] ) + } ) + }; + var J = 0; + b.uniqueId = function ( a ) { + var b = J++; + return a ? a + b : b + }; + b.templateSettings = {evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g}; + b.template = function ( a, c ) { + var d = b.templateSettings, d = "var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('" + a.replace( /\\/g, "\\\\" ).replace( /'/g, "\\'" ).replace( d.escape, + function ( a, b ) { + return"',_.escape(" + b.replace( /\\'/g, "'" ) + "),'" + } ).replace( d.interpolate, + function ( a, b ) { + return"'," + b.replace( /\\'/g, "'" ) + ",'" + } ).replace( d.evaluate || null, + function ( a, b ) { + return"');" + b.replace( /\\'/g, "'" ).replace( /[\r\n\t]/g, " " ) + ";__p.push('" + } ).replace( /\r/g, + "\\r" ).replace( /\n/g, "\\n" ).replace( /\t/g, "\\t" ) + "');}return __p.join('');", e = new Function( "obj", "_", d ); + return c ? e( c, b ) : function ( a ) { + return e( a, b ) + } + }; + var n = function ( a ) { + this._wrapped = a + }; + b.prototype = n.prototype; + var u = function ( a, c ) { + return c ? b( a ).chain() : a + }, I = function ( a, c ) { + n.prototype[a] = function () { + var a = i.call( arguments ); + G.call( a, this._wrapped ); + return u( c.apply( b, a ), this._chain ) + } + }; + b.mixin( b ); + j( "pop,push,reverse,shift,sort,splice,unshift".split( "," ), function ( a ) { + var b = k[a]; + n.prototype[a] = function () { + b.apply( this._wrapped, + arguments ); + return u( this._wrapped, this._chain ) + } + } ); + j( ["concat", "join", "slice"], function ( a ) { + var b = k[a]; + n.prototype[a] = function () { + return u( b.apply( this._wrapped, arguments ), this._chain ) + } + } ); + n.prototype.chain = function () { + this._chain = true; + return this + }; + n.prototype.value = function () { + return this._wrapped + } +}).call( this ); diff --git a/example/amd/js/main.js b/example/amd/js/main.js index a747fb6..7981894 100644 --- a/example/amd/js/main.js +++ b/example/amd/js/main.js @@ -1,14 +1,14 @@ -require.config({ - paths: { - underscore: 'libs/underscore/underscore-min', - postal: 'libs/postal/postal', - postaldiags:'libs/postal/postal.diagnostics', - jquery: 'libs/jquery/jquery-min' +require.config( { + paths : { + underscore : 'libs/underscore/underscore-min', + postal : 'libs/postal/postal', + postaldiags : 'libs/postal/postal.diagnostics', + jquery : 'libs/jquery/jquery-min' } -}); +} ); -require( [ 'jquery' ], function( $ ){ - $(function(){ +require( [ 'jquery' ], function ( $ ) { + $( function () { require( [ 'examples' ] ); - }); -}); \ No newline at end of file + } ); +} ); \ No newline at end of file diff --git a/example/amd/style.css b/example/amd/style.css index a746620..21d30ab 100644 --- a/example/amd/style.css +++ b/example/amd/style.css @@ -4,7 +4,7 @@ div { } .results { - margin-bottom:20px; + margin-bottom: 20px; padding: 10px; border-top: 1pt solid lightsteelblue; border-bottom: 1pt solid lightsteelblue; diff --git a/example/node/client/index.html b/example/node/client/index.html index a7b8e6f..67fc58a 100644 --- a/example/node/client/index.html +++ b/example/node/client/index.html @@ -2,8 +2,8 @@ - Twitter Hash Tag Stats Demo - + Twitter Hash Tag Stats Demo + diff --git a/example/node/client/js/infrastructure/app.js b/example/node/client/js/infrastructure/app.js index 69159ec..91eb029 100644 --- a/example/node/client/js/infrastructure/app.js +++ b/example/node/client/js/infrastructure/app.js @@ -1,4 +1,4 @@ -define([ +define( [ 'jquery', 'backbone', 'bus', @@ -12,41 +12,40 @@ define([ 'views/hash-tag-count', 'views/profanity-percentage', 'views/search-requests' -], function( $, Backbone, bus, Router, ViewManager, ContainerView, MenuView, TweetCountView, MentionCountView, - MentionerCountView, HashTagCountView, ProfanityPercentage, SearchRequestView ) { +], function ( $, Backbone, bus, Router, ViewManager, ContainerView, MenuView, TweetCountView, MentionCountView, MentionerCountView, HashTagCountView, ProfanityPercentage, SearchRequestView ) { var app = { - bus: bus, - router: new Router() + bus : bus, + router : new Router() }; // Set up UI concerns app.viewManager = new ViewManager(); - app.bus.viewManager.subscribe( "ui.show", function( data, env ) { + app.bus.viewManager.subscribe( "ui.show", function ( data, env ) { app.viewManager.UI[ data.name ].activate( data.context ); - }); + } ); - app.viewManager.registerViews([ - { name: "container", ctor: ContainerView }, - { name: "menu", ctor: MenuView }, - { name: "tweetCount", ctor: TweetCountView }, - { name: "mentionCount", ctor: MentionCountView }, - { name: "mentionerCount", ctor: MentionerCountView }, - { name: "hashTagCount", ctor: HashTagCountView }, - { name: "profanityPercentage", ctor: ProfanityPercentage }, - { name: "searchRequests", ctor: SearchRequestView } - ]); - app.viewManager.defineUIs([ - { name: "homeUI", dependencies: [ "container", "menu", "tweetCount", "mentionCount", "mentionerCount", "hashTagCount", "profanityPercentage" ] }, - { name: "searchRequestUI", dependencies: [ "container", "menu", "searchRequests" ] }, - { name: "wireTapLogUI", dependencies: [ "menu" ], options: { noHide: true } } - ]); + app.viewManager.registerViews( [ + { name : "container", ctor : ContainerView }, + { name : "menu", ctor : MenuView }, + { name : "tweetCount", ctor : TweetCountView }, + { name : "mentionCount", ctor : MentionCountView }, + { name : "mentionerCount", ctor : MentionerCountView }, + { name : "hashTagCount", ctor : HashTagCountView }, + { name : "profanityPercentage", ctor : ProfanityPercentage }, + { name : "searchRequests", ctor : SearchRequestView } + ] ); + app.viewManager.defineUIs( [ + { name : "homeUI", dependencies : [ "container", "menu", "tweetCount", "mentionCount", "mentionerCount", "hashTagCount", "profanityPercentage" ] }, + { name : "searchRequestUI", dependencies : [ "container", "menu", "searchRequests" ] }, + { name : "wireTapLogUI", dependencies : [ "menu" ], options : { noHide : true } } + ] ); - $(function() { - Backbone.history.start({ - pushState: true, - root: $( "base" ).attr( "href" ) - }); - }); + $( function () { + Backbone.history.start( { + pushState : true, + root : $( "base" ).attr( "href" ) + } ); + } ); return app; -}); \ No newline at end of file +} ); \ No newline at end of file diff --git a/example/node/client/js/infrastructure/bus.js b/example/node/client/js/infrastructure/bus.js index 1e5ecdf..afb50a7 100644 --- a/example/node/client/js/infrastructure/bus.js +++ b/example/node/client/js/infrastructure/bus.js @@ -1,11 +1,11 @@ -define([ +define( [ 'postal' ], function ( postal ) { return { - router : postal.channel( "router", "*" ), + router : postal.channel( "router", "*" ), viewManager : postal.channel( "viewmanager", "*" ), - data : postal.channel( "data", "*" ), - app : postal.channel( "statsApp", "*", { type: "websocket" } ), - stats : postal.channel( "stats", "*", { type: "websocket" } ) + data : postal.channel( "data", "*" ), + app : postal.channel( "statsApp", "*", { type : "websocket" } ), + stats : postal.channel( "stats", "*", { type : "websocket" } ) } -}); \ No newline at end of file +} ); \ No newline at end of file diff --git a/example/node/client/js/infrastructure/postal.socket-client.js b/example/node/client/js/infrastructure/postal.socket-client.js index d3b1c07..2a56270 100644 --- a/example/node/client/js/infrastructure/postal.socket-client.js +++ b/example/node/client/js/infrastructure/postal.socket-client.js @@ -1,315 +1,298 @@ -/* - postal.socket - Author: Jim Cowart - License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) - Version 0.1.0 -*/ +/* + postal.socket + Author: Jim Cowart + License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) + Version 0.1.0 + */ -(function( root, doc, factory ) { +(function ( root, doc, factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. - define( [ "underscore", "machina", "postal" ], function( _, machina, postal ) { + define( [ "underscore", "machina", "postal" ], function ( _, machina, postal ) { return factory( _, machina, postal, root, doc ); - }); + } ); } else { // Browser globals factory( root._, root.machina, root.postal, root, doc ); } -}(this, document, function( _, machina, postal, global, document, undefined ) { +}( this, document, function ( _, machina, postal, global, document, undefined ) { /* - adding a socket namespace to postal - which provides the following members: - 1.) config - provides values used to manage the socket connection - 2.) goOffline() - tells the manager to close the connection intentionally - 3.) goOnline() - tells the manager to try to connect. - 4.) manifest - an array of objects describing the subscriptions that have been - set up on the remote end. - 5.) publish() - takes a valid postal envelope and pushes it through the socket - to be published to the server instance of postal. - 6.) socketMgr - the FSM managing the socket connection - 7.) socketNamespace - exposed currently for debugging only - 8.) subscribe() - passes an object through the socket to the server - which contains data necessary to set up a remote subscription. The - options passed to the socket would look similar to this: - { - "channel":"SomeChannel", - "topic":"my.topic", - "correlationId":"2073383865318591267" - } - The "correlationId" is used on the remote side to apply a constraint to - the subscription, enabling just this specific client to be targeted on - and otherwise public channel. - 9.) unsubscribe() - passes an object through the socket to the server - which contains data necessary to remove a remote subscription. The options - passed would look similar to the example above in #8. + adding a socket namespace to postal + which provides the following members: + 1.) config - provides values used to manage the socket connection + 2.) goOffline() - tells the manager to close the connection intentionally + 3.) goOnline() - tells the manager to try to connect. + 4.) manifest - an array of objects describing the subscriptions that have been + set up on the remote end. + 5.) publish() - takes a valid postal envelope and pushes it through the socket + to be published to the server instance of postal. + 6.) socketMgr - the FSM managing the socket connection + 7.) socketNamespace - exposed currently for debugging only + 8.) subscribe() - passes an object through the socket to the server + which contains data necessary to set up a remote subscription. The + options passed to the socket would look similar to this: + { + "channel":"SomeChannel", + "topic":"my.topic", + "correlationId":"2073383865318591267" + } + The "correlationId" is used on the remote side to apply a constraint to + the subscription, enabling just this specific client to be targeted on + and otherwise public channel. + 9.) unsubscribe() - passes an object through the socket to the server + which contains data necessary to remove a remote subscription. The options + passed would look similar to the example above in #8. */ postal.connections = postal.connections || {}; - - var postalSocket = postal.connections.socket = (function(){ + + var postalSocket = postal.connections.socket = (function () { var socketNamespace, - fsm = new machina.Fsm({ - retryFn: undefined, - - session: undefined, - - wireUpSocketEvents: function() { + fsm = new machina.Fsm( { + retryFn : undefined, + + session : undefined, + + wireUpSocketEvents : function () { var self = this; - _.each([ "connect", "connecting", "connect_failed", "disconnect", "reconnect", "reconnect_failed", - "reconnecting", "postal.socket.remote", "postal.socket.identified", "postal.socket.migration" ], - function( evnt ) { - socketNamespace.on( evnt, function( data ) { + _.each( [ "connect", "connecting", "connect_failed", "disconnect", "reconnect", "reconnect_failed", + "reconnecting", "postal.socket.remote", "postal.socket.identified", "postal.socket.migration" ], + function ( evnt ) { + socketNamespace.on( evnt, function ( data ) { self.handle( evnt, data ); - }); - }); + } ); + } ); }, - - states: { - uninitialized: { - tryConnect: function() { - this.transition("initializing"); + + states : { + uninitialized : { + tryConnect : function () { + this.transition( "initializing" ); } }, - initializing: { - _onEnter: function() { - socketNamespace = io.connect(postalSocket.config.url, { "auto connect": false }); + initializing : { + _onEnter : function () { + socketNamespace = io.connect( postalSocket.config.url, { "auto connect" : false } ); this.wireUpSocketEvents(); - this.transition("probing") + this.transition( "probing" ) }, - socketTransmit: function() { - this.deferUntilTransition("online"); + socketTransmit : function () { + this.deferUntilTransition( "online" ); } }, - probing: { - _onEnter: function() { - clearTimeout(this.retryFn); - if(!socketNamespace.socket.connecting && !socketNamespace.socket.reconnecting) { + probing : { + _onEnter : function () { + clearTimeout( this.retryFn ); + if ( !socketNamespace.socket.connecting && !socketNamespace.socket.reconnecting ) { socketNamespace.socket.connect(); } else { - this.transition("settingSessionInfo"); + this.transition( "settingSessionInfo" ); } }, - connect: function(){ - this.transition("settingSessionInfo"); + connect : function () { + this.transition( "settingSessionInfo" ); }, - connect_failed: function() { - this.transition("disconnected"); + connect_failed : function () { + this.transition( "disconnected" ); }, - maxAttempts: function() { - this.transition("offline"); + maxAttempts : function () { + this.transition( "offline" ); }, - "postal.socket.remote" : function() { - this.deferUntilTransition("online"); + "postal.socket.remote" : function () { + this.deferUntilTransition( "online" ); }, - reconnect: function(){ - this.transition("settingSessionInfo"); + reconnect : function () { + this.transition( "settingSessionInfo" ); }, - reconnect_failed: function() { - this.transition("disconnected"); + reconnect_failed : function () { + this.transition( "disconnected" ); }, - socketTransmit: function() { - this.deferUntilTransition("online"); + socketTransmit : function () { + this.deferUntilTransition( "online" ); } }, - settingSessionInfo: { - _onEnter: function() { + settingSessionInfo : { + _onEnter : function () { var self = this; - postal.utils.getSessionId( function( session ) { - if( !session || !session.id ) { - self.handle("useFallbackSessionId" ); - } else { - self.session = session; - self.transition("identifying"); - } - }); - }, - useFallbackSessionId : function () { - var self = this; - postal.utils.setSessionId( socketNamespace.socket.sessionid , function( session ) { + postal.utils.setSessionId( socketNamespace.socket.sessionid, function ( session ) { self.session = session; - self.transition("identifying"); - }); + self.transition( "identifying" ); + } ); } }, - identifying: { - _onEnter: function() { + identifying : { + _onEnter : function () { var self = this; - self.retryFn = setTimeout(function() { + self.retryFn = setTimeout( function () { self.handle( "timeout.identifying" ); - },postalSocket.config.reconnectInterval ); + }, postalSocket.config.reconnectInterval ); self.handle( "client.identifier" ); }, - "client.identifier" : function() { + "client.identifier" : function () { clearTimeout( this.retryFn ); - socketNamespace.emit( "postal.clientId", { sessionId: this.session.id, lastSessionId: this.session.lastId } ); + socketNamespace.emit( "postal.clientId", { id : this.session.id, lastId : this.session.lastId } ); }, - "postal.session.changed" : function() { - socketNamespace.socket.disconnect(); + connect_failed : function () { + this.transition( "disconnected" ); }, - connect_failed: function() { - this.transition("disconnected"); + disconnect : function () { + this.transition( "probing" ); }, - disconnect: function() { - this.transition("probing"); + "postal.socket.identified" : function ( data ) { + this.transition( "online" ); }, - "postal.socket.identified" : function( data ) { - this.transition("online"); - }, - "postal.socket.migration" : function() { - _.each(postal.socket.manifest, function( sub ) { + "postal.socket.migration" : function () { + _.each( postal.connections.socket.manifest, function ( sub ) { fsm.handle( "socketTransmit", "postal.subscribe", sub ); - }); + } ); socketNamespace.emit( "postal.migrationComplete", {} ); }, - "postal.socket.remote" : function() { - this.deferUntilTransition("online"); + "postal.socket.remote" : function () { + this.deferUntilTransition( "online" ); }, - reconnect_failed: function() { - this.transition("disconnected"); + reconnect_failed : function () { + this.transition( "disconnected" ); }, - socketTransmit: function( evntName, envelope ) { - if( evntName === "postal.subscribe" ){ + socketTransmit : function ( evntName, envelope ) { + if ( evntName === "postal.subscribe" ) { // we risk mutating the message here, so extend // and add the correlationId to the extended copy var socketEnv = _.extend( {}, envelope ); socketEnv.correlationId = this.session.id; - socketNamespace.emit(evntName, socketEnv); + socketNamespace.emit( evntName, socketEnv ); } else { - this.deferUntilTransition("online"); + this.deferUntilTransition( "online" ); } }, - "timeout.identifying" : function() { - this.transition("probing"); + "timeout.identifying" : function () { + this.transition( "probing" ); } }, - online: { - disconnect: function() { - this.transition("probing"); + online : { + disconnect : function () { + this.transition( "probing" ); }, - "postal.session.changed" : function() { - socketNamespace.socket.disconnect(); + goOffline : function () { + this.transition( "offline" ); }, - goOffline: function() { - this.transition("offline"); - }, - "postal.socket.remote" : function( envelope ) { + "postal.socket.remote" : function ( envelope ) { postal.publish( envelope ); }, - socketTransmit: function( evntName, envelope ) { + socketTransmit : function ( evntName, envelope ) { // we risk mutating the message here, so extend // and add the correlationId to the extended copy var socketEnv = _.extend( {}, envelope ); socketEnv.correlationId = this.session.id; - socketNamespace.emit(evntName, socketEnv); + socketNamespace.emit( evntName, socketEnv ); } }, - offline: { - _onEnter: function() { + offline : { + _onEnter : function () { socketNamespace.socket.disconnect(); }, - socketTransmit: function() { - this.deferUntilTransition("online"); + socketTransmit : function () { + this.deferUntilTransition( "online" ); }, - "tryConnect": function() { - this.transition("probing"); + "tryConnect" : function () { + this.transition( "probing" ); } }, - disconnected: { - _onEnter: function() { + disconnected : { + _onEnter : function () { var self = this; - self.retryFn = setTimeout(function() { - self.transition("probing"); - },postalSocket.config.reconnectInterval); + self.retryFn = setTimeout( function () { + self.transition( "probing" ); + }, postalSocket.config.reconnectInterval ); }, - connecting: function() { - this.transition("probing"); + connecting : function () { + this.transition( "probing" ); }, - reconnecting: function() { - this.transition("probing"); + reconnecting : function () { + this.transition( "probing" ); }, - socketTransmit: function() { - this.deferUntilTransition("online"); + socketTransmit : function () { + this.deferUntilTransition( "online" ); } } } - }); - postal.subscribe({ - channel: "postal", - topic: "sessionId.changed", - callback: function() { - fsm.handle("postal.session.changed"); + } ); + postal.subscribe( { + channel : "postal", + topic : "sessionId.changed", + callback : function () { + fsm.handle( "postal.session.changed" ); } - }); + } ); return { config : { - url: window.location.origin, - reconnectInterval: 4000 + url : window.location.origin, + reconnectInterval : 4000 }, - goOffline: function() { + goOffline : function () { fsm.handle( "goOffline" ); }, - goOnline: function() { + goOnline : function () { fsm.handle( "tryConnect" ); }, - manifest: [], - publish: function( envelope ) { + manifest : [], + publish : function ( envelope ) { fsm.handle( "socketTransmit", "postal.publish", envelope ); }, - subscribe: function( options ) { + subscribe : function ( options ) { options.channel = options.channel || postal.configuration.DEFAULT_CHANNEL; options.topic = options.topic || "*"; - if( !_.any( this.manifest, function( item ){ + if ( !_.any( this.manifest, function ( item ) { return item.channel === options.channel && item.topic === options.topic; - })) { + } ) ) { this.manifest.push( options ); fsm.handle( "socketTransmit", "postal.subscribe", options ); } }, - socketMgr: fsm, - socketNamespace: socketNamespace, - unsubscribe: function( options ) { + socketMgr : fsm, + socketNamespace : socketNamespace, + unsubscribe : function ( options ) { options.channel = options.channel || postal.configuration.DEFAULT_CHANNEL; options.topic = options.topic || "*"; - if( !postal.getSubscribersFor( options.channel, options.topic ).length ) { - fsm.handle( "socketTransmit", "postal.unsubscribe", options); + if ( !postal.getSubscribersFor( options.channel, options.topic ).length ) { + fsm.handle( "socketTransmit", "postal.unsubscribe", options ); } } } })(); - + postal.connections.socket.goOnline(); - var SocketChannel = postal.channelTypes.websocket = function( channelName, defaultTopic ) { + var SocketChannel = postal.channelTypes.websocket = function ( channelName, defaultTopic ) { var channel = postal.channel( channelName, defaultTopic ), localSubscribe = channel.subscribe, localPublish = channel.publish, localTopic = channel.topic; - - channel.publish = function() { - postalSocket.publish( localPublish.apply( channel, arguments) ); + + channel.publish = function () { + postalSocket.publish( localPublish.apply( channel, arguments ) ); }; - - channel.subscribe = function() { - var sub = localSubscribe.apply( channel, arguments), + + channel.subscribe = function () { + var sub = localSubscribe.apply( channel, arguments ), origUnsubscribe; origUnsubscribe = sub.unsubscribe; - sub.unsubscribe = function() { - origUnsubscribe.call(sub); - postalSocket.unsubscribe({ channel: sub.channel, topic: sub.topic }); + sub.unsubscribe = function () { + origUnsubscribe.call( sub ); + postalSocket.unsubscribe( { channel : sub.channel, topic : sub.topic } ); }; - postalSocket.subscribe({ channel: sub.channel, topic: sub.topic }); + postalSocket.subscribe( { channel : sub.channel, topic : sub.topic } ); return sub; }; - - channel.topic = function( topic ) { - if(topic === channel._topic) { + + channel.topic = function ( topic ) { + if ( topic === channel._topic ) { return this; } - return new SocketChannel(this.channel, topic); + return new SocketChannel( this.channel, topic ); }; - + return channel; }; -})); \ No newline at end of file +} )); \ No newline at end of file diff --git a/example/node/client/js/infrastructure/router.js b/example/node/client/js/infrastructure/router.js index b2f35d0..efc8256 100644 --- a/example/node/client/js/infrastructure/router.js +++ b/example/node/client/js/infrastructure/router.js @@ -1,52 +1,52 @@ -define([ +define( [ 'jquery', 'backbone', 'bus' -], function( $, Backbone, bus ){ +], function ( $, Backbone, bus ) { - return Backbone.Router.extend({ - routes: { - "" : "home", - "requests" : "requests", - "wiretap" : "wiretap", + return Backbone.Router.extend( { + routes : { + "" : "home", + "requests" : "requests", + "wiretap" : "wiretap", "*anything" : "redirect" }, - initialize: function() { + initialize : function () { var self = this; _.bindAll( self ); - $( document ).delegate( "a.ps-nav", "click", function( e ){ + $( document ).delegate( "a.ps-nav", "click", function ( e ) { e.preventDefault(); - self.navigate( $( this ).attr( 'href' ), { trigger: true }); - }); + self.navigate( $( this ).attr( 'href' ), { trigger : true } ); + } ); bus.router.publish( "initialized" ); }, - activateUI: function( uiName, context ) { - bus.viewManager.publish({ - topic: "ui.show", - data: { - name: uiName, - context: context + activateUI : function ( uiName, context ) { + bus.viewManager.publish( { + topic : "ui.show", + data : { + name : uiName, + context : context } - }); + } ); }, - home: function() { + home : function () { this.activateUI( "homeUI" ); }, - requests: function() { + requests : function () { this.activateUI( "searchRequestUI" ); }, - wiretap: function() { + wiretap : function () { this.activateUI( "wireTapLogUI" ); }, - redirect: function() { - this.navigate( "/", { trigger: true }); + redirect : function () { + this.navigate( "/", { trigger : true } ); } - }); -}); \ No newline at end of file + } ); +} ); \ No newline at end of file diff --git a/example/node/client/js/infrastructure/view-manager.js b/example/node/client/js/infrastructure/view-manager.js index 4adf9d7..2508575 100644 --- a/example/node/client/js/infrastructure/view-manager.js +++ b/example/node/client/js/infrastructure/view-manager.js @@ -1,8 +1,8 @@ -define([ +define( [ 'underscore', 'bus' -], function( _, bus ){ - var ViewManager = function() { +], function ( _, bus ) { + var ViewManager = function () { this.views = {}; // holds the views that are registered with the manager this.UI = {}; // holds the UI configurations that are defined this.priorContext = undefined; // holds the name of the last UI configuration @@ -17,16 +17,16 @@ define([ // then the ViewManager will create a new instance of the view. If options.args // exists, it will be passed into the constructor function of the view. //---------------------------------------------------------------------------- - ViewManager.prototype.registerView = function(name, viewCtor) { + ViewManager.prototype.registerView = function ( name, viewCtor ) { this.views[name] = { - rendered: false, - visible: false, - getInstance: (function(){ + rendered : false, + visible : false, + getInstance : (function () { var _instance; - return function(options){ + return function ( options ) { var _options = options || {}; - if(!_instance || _options.forceNew) { - _instance = new viewCtor(_options.args || {}); + if ( !_instance || _options.forceNew ) { + _instance = new viewCtor( _options.args || {} ); } return _instance; } @@ -34,8 +34,8 @@ define([ } }; - ViewManager.prototype.registerViews = function(views) { - _.each( views, function( view ){ + ViewManager.prototype.registerViews = function ( views ) { + _.each( views, function ( view ) { this.registerView( view.name, view.ctor ); }, this ); }; @@ -46,76 +46,76 @@ define([ // name, second arg is the array of view names (in the order they need to be // instantiated/rendered/shown) //---------------------------------------------------------------------------- - ViewManager.prototype.defineUI = function( name, dependencies, options ) { + ViewManager.prototype.defineUI = function ( name, dependencies, options ) { var self = this; self.UI[ name ] = { - options: options || {}, - dependencies: dependencies, - activate: function( data ) { + options : options || {}, + dependencies : dependencies, + activate : function ( data ) { data = data || {}; data.priorContext = self.priorContext; data.targetContext = name; - if( !this.options.noHide ) { + if ( !this.options.noHide ) { // hide anything visible that's not in the dependencies for this UI configuration - var shouldHide = _.reduce( self.views, function( memo, val, key ){ - if( val.visible && !_.include( this.dependencies, key ) ){ + var shouldHide = _.reduce( self.views, function ( memo, val, key ) { + if ( val.visible && !_.include( this.dependencies, key ) ) { memo.push( key ); } return memo; }, [], this ); - _.each( shouldHide, function( viewName ){ + _.each( shouldHide, function ( viewName ) { var instance = self.views[ viewName ].getInstance(); - if( instance.hide ) { + if ( instance.hide ) { instance.hide(); } self.views[ viewName ].visible = false; - }); + } ); } // set up, render & show the dependencies for this UI configuration - _.each(this.dependencies, function(viewName){ - var instance = self.views[viewName].getInstance(data); - if(!self.views[viewName].rendered) { - instance.render(data); + _.each( this.dependencies, function ( viewName ) { + var instance = self.views[viewName].getInstance( data ); + if ( !self.views[viewName].rendered ) { + instance.render( data ); self.views[viewName].rendered = true; } - if(!self.views[viewName].visible) { - if(instance.show) { - instance.show(data); + if ( !self.views[viewName].visible ) { + if ( instance.show ) { + instance.show( data ); } self.views[viewName].visible = true; } - if(instance.update) { - instance.update(data); + if ( instance.update ) { + instance.update( data ); } - }); + } ); self.priorContext = name; } }; }; - ViewManager.prototype.defineUIs = function( uis ) { - _.each( uis, function( ui ){ + ViewManager.prototype.defineUIs = function ( uis ) { + _.each( uis, function ( ui ) { this.defineUI( ui.name, ui.dependencies, ui.options ); }, this ); }; - ViewManager.prototype.addViewToUI = function( uiName, viewName, viewCtor ) { + ViewManager.prototype.addViewToUI = function ( uiName, viewName, viewCtor ) { var uis = _.isArray( uiName ) ? uiName : [ uiName ]; - if( !this.views[ viewName ] ) { + if ( !this.views[ viewName ] ) { this.registerView( viewName, viewCtor ); } - _.each( uis, function( ui ) { - if( this.UI[ ui ] ) { + _.each( uis, function ( ui ) { + if ( this.UI[ ui ] ) { this.UI[ ui ].dependencies.push( viewName ); } }, this ); }; return ViewManager; -}); \ No newline at end of file +} ); \ No newline at end of file diff --git a/example/node/client/js/lib/amplify.js b/example/node/client/js/lib/amplify.js index 715e483..7394022 100644 --- a/example/node/client/js/lib/amplify.js +++ b/example/node/client/js/lib/amplify.js @@ -7,4 +7,354 @@ * * http://amplifyjs.com */ -(function(a,b,c){typeof define=="function"&&define.amd?define(["jquery"],function(d){return c(d,a,b)}):c(a.jQuery,a,b)})(this,document,function(a,b,c,d){return function(a,b){var c=[].slice,d={},e=a.amplify={publish:function(a){var b=c.call(arguments,1),e,f,g,h=0,i;if(!d[a])return!0;e=d[a].slice();for(g=e.length;h=0;j--)if(d[a][j].priority<=e){d[a].splice(j+1,0,k),i=!0;break}i||d[a].unshift(k)}return c},unsubscribe:function(a,b){if(!d[a])return;var c=d[a].length,e=0;for(;e= 0; j-- ) { + if ( d[a][j].priority <= e ) { + d[a].splice( j + 1, 0, k ), i = !0; + break + } + } + i || d[a].unshift( k ) + } + return c + }, unsubscribe : function ( a, b ) { + if ( !d[a] ) { + return; + } + var c = d[a].length, e = 0; + for ( ; e < c; e++ ) { + if ( d[a][e].callback === b ) { + d[a].splice( e, 1 ); + break + } + } + }} + }( this ), function ( a, b ) { + function f( a, c ) { + d.addType( a, function ( f, g, h ) { + var i, j, k, l, m = g, n = (new Date).getTime(); + if ( !f ) { + m = {}, l = [], k = 0; + try { + f = c.length; + while ( f = c.key( k++ ) ) { + e.test( f ) && (j = JSON.parse( c.getItem( f ) ), j.expires && j.expires <= n ? l.push( f ) : m[f.replace( e, "" )] = j.data); + } + while ( f = l.pop() ) { + c.removeItem( f ) + } + } catch ( o ) { + } + return m + } + f = "__amplify__" + f; + if ( g === b ) { + i = c.getItem( f ), j = i ? JSON.parse( i ) : {expires : -1}; + if ( !(j.expires && j.expires <= n) ) { + return j.data; + } + c.removeItem( f ) + } else if ( g === null ) { + c.removeItem( f ); + } else { + j = JSON.stringify( {data : g, expires : h.expires ? n + h.expires : null} ); + try { + c.setItem( f, j ) + } catch ( o ) { + d[a](); + try { + c.setItem( f, j ) + } catch ( o ) { + throw d.error() + } + } + } + return m + } ) + } + + var d = a.store = function ( a, b, c, e ) { + var e = d.type; + return c && c.type && c.type in d.types && (e = c.type), d.types[e]( a, b, c || {} ) + }; + d.types = {}, d.type = null, d.addType = function ( a, b ) { + d.type || (d.type = a), d.types[a] = b, d[a] = function ( b, c, e ) { + return e = e || {}, e.type = a, d( b, c, e ) + } + }, d.error = function () { + return"amplify.store quota exceeded" + }; + var e = /^__amplify__/; + for ( var g in{localStorage : 1, sessionStorage : 1} ) { + try { + window[g].getItem && f( g, window[g] ) + } catch ( h ) { + } + } + if ( !d.types.localStorage && window.globalStorage ) { + try { + f( "globalStorage", window.globalStorage[window.location.hostname] ), d.type === "sessionStorage" && (d.type = "globalStorage") + } catch ( h ) { + } + } + (function () { + if ( d.types.localStorage ) { + return; + } + var a = c.createElement( "div" ), e = "amplify"; + a.style.display = "none", c.getElementsByTagName( "head" )[0].appendChild( a ); + try { + a.addBehavior( "#default#userdata" ), a.load( e ) + } catch ( f ) { + a.parentNode.removeChild( a ); + return + } + d.addType( "userData", function ( c, f, g ) { + a.load( e ); + var h, i, j, k, l, m = f, n = (new Date).getTime(); + if ( !c ) { + m = {}, l = [], k = 0; + while ( h = a.XMLDocument.documentElement.attributes[k++] ) { + i = JSON.parse( h.value ), i.expires && i.expires <= n ? l.push( h.name ) : m[h.name] = i.data; + } + while ( c = l.pop() ) { + a.removeAttribute( c ); + } + return a.save( e ), m + } + c = c.replace( /[^-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u37f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g, "-" ), c = c.replace( /^-/, "_-" ); + if ( f === b ) { + h = a.getAttribute( c ), i = h ? JSON.parse( h ) : {expires : -1}; + if ( !(i.expires && i.expires <= n) ) { + return i.data; + } + a.removeAttribute( c ) + } else { + f === null ? a.removeAttribute( c ) : (j = a.getAttribute( c ), i = JSON.stringify( {data : f, expires : g.expires ? n + g.expires : null} ), a.setAttribute( c, i )); + } + try { + a.save( e ) + } catch ( o ) { + j === null ? a.removeAttribute( c ) : a.setAttribute( c, j ), d.userData(); + try { + a.setAttribute( c, i ), a.save( e ) + } catch ( o ) { + throw j === null ? a.removeAttribute( c ) : a.setAttribute( c, j ), d.error() + } + } + return m + } ) + })(), function () { + function e( a ) { + return a === b ? b : JSON.parse( JSON.stringify( a ) ) + } + + var a = {}, c = {}; + d.addType( "memory", function ( d, f, g ) { + return d ? f === b ? e( a[d] ) : (c[d] && (clearTimeout( c[d] ), delete c[d]), f === null ? (delete a[d], null) : (a[d] = f, g.expires && (c[d] = setTimeout( function () { + delete a[d], delete c[d] + }, g.expires )), f)) : e( a ) + } ) + }() + }( this.amplify = this.amplify || {} ), function ( a, b ) { + function c() { + } + + function d( a ) { + return{}.toString.call( a ) === "[object Function]" + } + + function e( a ) { + var b = !1; + return setTimeout( function () { + b = !0 + }, 1 ), function () { + var c = this, d = arguments; + b ? a.apply( c, d ) : setTimeout( function () { + a.apply( c, d ) + }, 1 ) + } + } + + a.request = function ( b, f, g ) { + var h = b || {}; + typeof h == "string" && (d( f ) && (g = f, f = {}), h = {resourceId : b, data : f || {}, success : g}); + var i = {abort : c}, j = a.request.resources[h.resourceId], k = h.success || c, l = h.error || c; + h.success = e( function ( b, c ) { + c = c || "success", a.publish( "request.success", h, b, c ), a.publish( "request.complete", h, b, c ), k( b, c ) + } ), h.error = e( function ( b, c ) { + c = c || "error", a.publish( "request.error", h, b, c ), a.publish( "request.complete", h, b, c ), l( b, c ) + } ); + if ( !j ) { + throw h.resourceId ? "amplify.request: unknown resourceId: " + h.resourceId : "amplify.request: no resourceId provided"; + } + if ( !a.publish( "request.before", h ) ) { + h.error( null, "abort" ); + return + } + return a.request.resources[h.resourceId]( h, i ), i + }, a.request.types = {}, a.request.resources = {}, a.request.define = function ( b, c, d ) { + if ( typeof c == "string" ) { + if ( !(c in a.request.types) ) { + throw"amplify.request.define: unknown type: " + c; + } + d.resourceId = b, a.request.resources[b] = a.request.types[c]( d ) + } else { + a.request.resources[b] = c + } + } + }( amplify ), function ( a, b, c ) { + var d = ["status", "statusText", "responseText", "responseXML", "readyState"], e = /\{([^\}]+)\}/g; + a.request.types.ajax = function ( e ) { + return e = b.extend( {type : "GET"}, e ), function ( f, g ) { + function n( a, e ) { + b.each( d, function ( a, b ) { + try { + m[b] = h[b] + } catch ( c ) { + } + } ), /OK$/.test( m.statusText ) && (m.statusText = "success"), a === c && (a = null), l && (e = "abort"), /timeout|error|abort/.test( e ) ? m.error( a, e ) : m.success( a, e ), n = b.noop + } + + var h, i = e.url, j = g.abort, k = b.extend( !0, {}, e, {data : f.data} ), l = !1, m = {readyState : 0, setRequestHeader : function ( a, b ) { + return h.setRequestHeader( a, b ) + }, getAllResponseHeaders : function () { + return h.getAllResponseHeaders() + }, getResponseHeader : function ( a ) { + return h.getResponseHeader( a ) + }, overrideMimeType : function ( a ) { + return h.overrideMideType( a ) + }, abort : function () { + l = !0; + try { + h.abort() + } catch ( a ) { + } + n( null, "abort" ) + }, success : function ( a, b ) { + f.success( a, b ) + }, error : function ( a, b ) { + f.error( a, b ) + }}; + a.publish( "request.ajax.preprocess", e, f, k, m ), b.extend( k, {success : function ( a, b ) { + n( a, b ) + }, error : function ( a, b ) { + n( null, b ) + }, beforeSend : function ( b, c ) { + h = b, k = c; + var d = e.beforeSend ? e.beforeSend.call( this, m, k ) : !0; + return d && a.publish( "request.before.ajax", e, f, k, m ) + }} ), b.ajax( k ), g.abort = function () { + m.abort(), j.call( this ) + } + } + }, a.subscribe( "request.ajax.preprocess", function ( a, c, d ) { + var f = [], g = d.data; + if ( typeof g == "string" ) { + return; + } + g = b.extend( !0, {}, a.data, g ), d.url = d.url.replace( e, function ( a, b ) { + if ( b in g ) { + return f.push( b ), g[b] + } + } ), b.each( f, function ( a, b ) { + delete g[b] + } ), d.data = g + } ), a.subscribe( "request.ajax.preprocess", function ( a, c, d ) { + var e = d.data, f = a.dataMap; + if ( !f || typeof e == "string" ) { + return; + } + b.isFunction( f ) ? d.data = f( e ) : (b.each( a.dataMap, function ( a, b ) { + a in e && (e[b] = e[a], delete e[a]) + } ), d.data = e) + } ); + var f = a.request.cache = {_key : function ( a, b, c ) { + function g() { + return c.charCodeAt( e++ ) << 24 | c.charCodeAt( e++ ) << 16 | c.charCodeAt( e++ ) << 8 | c.charCodeAt( e++ ) << 0 + } + + c = b + c; + var d = c.length, e = 0, f = g(); + while ( e < d ) { + f ^= g(); + } + return"request-" + a + "-" + f + }, _default : function () { + var a = {}; + return function ( b, c, d, e ) { + var g = f._key( c.resourceId, d.url, d.data ), h = b.cache; + if ( g in a ) { + return e.success( a[g] ), !1; + } + var i = e.success; + e.success = function ( b ) { + a[g] = b, typeof h == "number" && setTimeout( function () { + delete a[g] + }, h ), i.apply( this, arguments ) + } + } + }()}; + a.store && (b.each( a.store.types, function ( b ) { + f[b] = function ( c, d, e, g ) { + var h = f._key( d.resourceId, e.url, e.data ), i = a.store[b]( h ); + if ( i ) { + return e.success( i ), !1; + } + var j = g.success; + g.success = function ( d ) { + a.store[b]( h, d, {expires : c.cache.expires} ), j.apply( this, arguments ) + } + } + } ), f.persist = f[a.store.type]), a.subscribe( "request.before.ajax", function ( a ) { + var b = a.cache; + if ( b ) { + return b = b.type || b, f[b in f ? b : "_default"].apply( this, arguments ) + } + } ), a.request.decoders = {jsend : function ( a, b, c, d, e ) { + a.status === "success" ? d( a.data ) : a.status === "fail" ? e( a.data, "fail" ) : a.status === "error" && (delete a.status, e( a, "error" )) + }}, a.subscribe( "request.before.ajax", function ( c, d, e, f ) { + function j( a, b ) { + g( a, b ) + } + + function k( a, b ) { + h( a, b ) + } + + var g = f.success, h = f.error, i = b.isFunction( c.decoder ) ? c.decoder : c.decoder in a.request.decoders ? a.request.decoders[c.decoder] : a.request.decoders._default; + if ( !i ) { + return; + } + f.success = function ( a, b ) { + i( a, b, f, j, k ) + }, f.error = function ( a, b ) { + i( a, b, f, j, k ) + } + } ) + }( amplify, jQuery ), amplify +} ) \ No newline at end of file diff --git a/example/node/client/js/lib/backbone.js b/example/node/client/js/lib/backbone.js index ffd4b7e..8b5f909 100644 --- a/example/node/client/js/lib/backbone.js +++ b/example/node/client/js/lib/backbone.js @@ -4,36 +4,707 @@ // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org -(function(h,g){typeof exports!=="undefined"?g(h,exports,require("underscore")):typeof define==="function"&&define.amd?define(["underscore","jquery","exports"],function(f,i,p){h.Backbone=g(h,p,f,i)}):h.Backbone=g(h,{},h._,h.jQuery||h.Zepto||h.ender)})(this,function(h,g,f,i){var p=h.Backbone,y=Array.prototype.slice,z=Array.prototype.splice;g.VERSION="0.9.2";g.setDomLibrary=function(a){i=a};g.noConflict=function(){h.Backbone=p;return g};g.emulateHTTP=false;g.emulateJSON=false;var q=/\s+/,l=g.Events= -{on:function(a,b,c){var d,e,f,g,j;if(!b)return this;a=a.split(q);for(d=this._callbacks||(this._callbacks={});e=a.shift();)f=(j=d[e])?j.tail:{},f.next=g={},f.context=c,f.callback=b,d[e]={tail:g,next:j?j.next:f};return this},off:function(a,b,c){var d,e,k,g,j,h;if(e=this._callbacks){if(!a&&!b&&!c)return delete this._callbacks,this;for(a=a?a.split(q):f.keys(e);d=a.shift();)if(k=e[d],delete e[d],k&&(b||c))for(g=k.tail;(k=k.next)!==g;)if(j=k.callback,h=k.context,b&&j!==b||c&&h!==c)this.on(d,j,h);return this}}, -trigger:function(a){var b,c,d,e,f,g;if(!(d=this._callbacks))return this;f=d.all;a=a.split(q);for(g=y.call(arguments,1);b=a.shift();){if(c=d[b])for(e=c.tail;(c=c.next)!==e;)c.callback.apply(c.context||this,g);if(c=f){e=c.tail;for(b=[b].concat(g);(c=c.next)!==e;)c.callback.apply(c.context||this,b)}}return this}};l.bind=l.on;l.unbind=l.off;var o=g.Model=function(a,b){var c;a||(a={});b&&b.parse&&(a=this.parse(a));if(c=n(this,"defaults"))a=f.extend({},c,a);if(b&&b.collection)this.collection=b.collection; -this.attributes={};this._escapedAttributes={};this.cid=f.uniqueId("c");this.changed={};this._silent={};this._pending={};this.set(a,{silent:true});this.changed={};this._silent={};this._pending={};this._previousAttributes=f.clone(this.attributes);this.initialize.apply(this,arguments)};f.extend(o.prototype,l,{changed:null,_silent:null,_pending:null,idAttribute:"id",initialize:function(){},toJSON:function(){return f.clone(this.attributes)},get:function(a){return this.attributes[a]},escape:function(a){var b; -if(b=this._escapedAttributes[a])return b;b=this.get(a);return this._escapedAttributes[a]=f.escape(b==null?"":""+b)},has:function(a){return this.get(a)!=null},set:function(a,b,c){var d,e;f.isObject(a)||a==null?(d=a,c=b):(d={},d[a]=b);c||(c={});if(!d)return this;if(d instanceof o)d=d.attributes;if(c.unset)for(e in d)d[e]=void 0;if(!this._validate(d,c))return false;if(this.idAttribute in d)this.id=d[this.idAttribute];var b=c.changes={},g=this.attributes,h=this._escapedAttributes,j=this._previousAttributes|| -{};for(e in d){a=d[e];if(!f.isEqual(g[e],a)||c.unset&&f.has(g,e))delete h[e],(c.silent?this._silent:b)[e]=true;c.unset?delete g[e]:g[e]=a;!f.isEqual(j[e],a)||f.has(g,e)!=f.has(j,e)?(this.changed[e]=a,c.silent||(this._pending[e]=true)):(delete this.changed[e],delete this._pending[e])}c.silent||this.change(c);return this},unset:function(a,b){(b||(b={})).unset=true;return this.set(a,null,b)},clear:function(a){(a||(a={})).unset=true;return this.set(f.clone(this.attributes),a)},fetch:function(a){var a= -a?f.clone(a):{},b=this,c=a.success;a.success=function(d,e,f){if(!b.set(b.parse(d,f),a))return false;c&&c(b,d)};a.error=g.wrapError(a.error,b,a);return(this.sync||g.sync).call(this,"read",this,a)},save:function(a,b,c){var d,e;f.isObject(a)||a==null?(d=a,c=b):(d={},d[a]=b);c=c?f.clone(c):{};if(c.wait){if(!this._validate(d,c))return false;e=f.clone(this.attributes)}a=f.extend({},c,{silent:true});if(d&&!this.set(d,c.wait?a:c))return false;var k=this,h=c.success;c.success=function(a,b,e){b=k.parse(a,e); -c.wait&&(delete c.wait,b=f.extend(d||{},b));if(!k.set(b,c))return false;h?h(k,a):k.trigger("sync",k,a,c)};c.error=g.wrapError(c.error,k,c);b=this.isNew()?"create":"update";b=(this.sync||g.sync).call(this,b,this,c);c.wait&&this.set(e,a);return b},destroy:function(a){var a=a?f.clone(a):{},b=this,c=a.success,d=function(){b.trigger("destroy",b,b.collection,a)};if(this.isNew())return d(),false;a.success=function(e){a.wait&&d();c?c(b,e):b.trigger("sync",b,e,a)};a.error=g.wrapError(a.error,b,a);var e=(this.sync|| -g.sync).call(this,"delete",this,a);a.wait||d();return e},url:function(){var a=n(this,"urlRoot")||n(this.collection,"url")||t();return this.isNew()?a:a+(a.charAt(a.length-1)=="/"?"":"/")+encodeURIComponent(this.id)},parse:function(a){return a},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return this.id==null},change:function(a){a||(a={});var b=this._changing;this._changing=true;for(var c in this._silent)this._pending[c]=true;var d=f.extend({},a.changes,this._silent); -this._silent={};for(c in d)this.trigger("change:"+c,this,this.get(c),a);if(b)return this;for(;!f.isEmpty(this._pending);){this._pending={};this.trigger("change",this,a);for(c in this.changed)!this._pending[c]&&!this._silent[c]&&delete this.changed[c];this._previousAttributes=f.clone(this.attributes)}this._changing=false;return this},hasChanged:function(a){return!arguments.length?!f.isEmpty(this.changed):f.has(this.changed,a)},changedAttributes:function(a){if(!a)return this.hasChanged()?f.clone(this.changed): -false;var b,c=false,d=this._previousAttributes,e;for(e in a)if(!f.isEqual(d[e],b=a[e]))(c||(c={}))[e]=b;return c},previous:function(a){return!arguments.length||!this._previousAttributes?null:this._previousAttributes[a]},previousAttributes:function(){return f.clone(this._previousAttributes)},isValid:function(){return!this.validate(this.attributes)},_validate:function(a,b){if(b.silent||!this.validate)return true;var a=f.extend({},this.attributes,a),c=this.validate(a,b);if(!c)return true;b&&b.error? -b.error(this,c,b):this.trigger("error",this,c,b);return false}});var r=g.Collection=function(a,b){b||(b={});if(b.model)this.model=b.model;if(b.comparator)this.comparator=b.comparator;this._reset();this.initialize.apply(this,arguments);a&&this.reset(a,{silent:true,parse:b.parse})};f.extend(r.prototype,l,{model:o,initialize:function(){},toJSON:function(a){return this.map(function(b){return b.toJSON(a)})},add:function(a,b){var c,d,e,g,h,j={},i={},l=[];b||(b={});a=f.isArray(a)?a.slice():[a];for(c=0,d= -a.length;c').hide().appendTo("body")[0].contentWindow,this.navigate(a);if(this._hasPushState)i(window).bind("popstate", -this.checkUrl);else if(this._wantsHashChange&&"onhashchange"in window&&!b)i(window).bind("hashchange",this.checkUrl);else if(this._wantsHashChange)this._checkUrlInterval=setInterval(this.checkUrl,this.interval);this.fragment=a;a=window.location;b=a.pathname==this.options.root;if(this._wantsHashChange&&this._wantsPushState&&!this._hasPushState&&!b)return this.fragment=this.getFragment(null,true),window.location.replace(this.options.root+"#"+this.fragment),true;else if(this._wantsPushState&&this._hasPushState&& -b&&a.hash)this.fragment=this.getHash().replace(s,""),window.history.replaceState({},document.title,a.protocol+"//"+a.host+this.options.root+this.fragment);if(!this.options.silent)return this.loadUrl()},stop:function(){i(window).unbind("popstate",this.checkUrl).unbind("hashchange",this.checkUrl);clearInterval(this._checkUrlInterval);m.started=false},route:function(a,b){this.handlers.unshift({route:a,callback:b})},checkUrl:function(){var a=this.getFragment();a==this.fragment&&this.iframe&&(a=this.getFragment(this.getHash(this.iframe))); -if(a==this.fragment)return false;this.iframe&&this.navigate(a);this.loadUrl()||this.loadUrl(this.getHash())},loadUrl:function(a){var b=this.fragment=this.getFragment(a);return f.any(this.handlers,function(a){if(a.route.test(b))return a.callback(b),true})},navigate:function(a,b){if(!m.started)return false;if(!b||b===true)b={trigger:b};var c=(a||"").replace(s,"");if(this.fragment!=c)this._hasPushState?(c.indexOf(this.options.root)!=0&&(c=this.options.root+c),this.fragment=c,window.history[b.replace? -"replaceState":"pushState"]({},document.title,c)):this._wantsHashChange?(this.fragment=c,this._updateHash(window.location,c,b.replace),this.iframe&&c!=this.getFragment(this.getHash(this.iframe))&&(b.replace||this.iframe.document.open().close(),this._updateHash(this.iframe.location,c,b.replace))):window.location.assign(this.options.root+a),b.trigger&&this.loadUrl(a)},_updateHash:function(a,b,c){c?a.replace(a.toString().replace(/(javascript:|#).*$/,"")+"#"+b):a.hash=b}});var v=g.View=function(a){this.cid= -f.uniqueId("view");this._configure(a||{});this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents()},E=/^(\S+)\s*(.*)$/,w="model,collection,el,id,attributes,className,tagName".split(",");f.extend(v.prototype,l,{tagName:"div",$:function(a){return this.$el.find(a)},initialize:function(){},render:function(){return this},remove:function(){this.$el.remove();return this},make:function(a,b,c){a=document.createElement(a);b&&i(a).attr(b);c!=null&&i(a).html(c);return a},setElement:function(a, -b){this.$el&&this.undelegateEvents();this.$el=a instanceof i?a:i(a);this.el=this.$el[0];b!==false&&this.delegateEvents();return this},delegateEvents:function(a){if(a||(a=n(this,"events"))){this.undelegateEvents();for(var b in a){var c=a[b];f.isFunction(c)||(c=this[a[b]]);if(!c)throw Error('Method "'+a[b]+'" does not exist');var d=b.match(E),e=d[1],d=d[2],c=f.bind(c,this);e+=".delegateEvents"+this.cid;d===""?this.$el.bind(e,c):this.$el.delegate(d,e,c)}}},undelegateEvents:function(){this.$el.unbind(".delegateEvents"+ -this.cid)},_configure:function(a){this.options&&(a=f.extend({},this.options,a));for(var b=0,c=w.length;b' ).hide().appendTo( "body" )[0].contentWindow, this.navigate( a ); + } + if ( this._hasPushState ) { + i( window ).bind( "popstate", + this.checkUrl ); + } else if ( this._wantsHashChange && "onhashchange"in window && !b ) { + i( window ).bind( "hashchange", this.checkUrl ); + } else if ( this._wantsHashChange ) { + this._checkUrlInterval = setInterval( this.checkUrl, this.interval ); + } + this.fragment = a; + a = window.location; + b = a.pathname == this.options.root; + if ( this._wantsHashChange && this._wantsPushState && !this._hasPushState && !b ) { + return this.fragment = this.getFragment( null, true ), window.location.replace( this.options.root + "#" + this.fragment ), true; + } else if ( this._wantsPushState && this._hasPushState && + b && a.hash ) { + this.fragment = this.getHash().replace( s, "" ), window.history.replaceState( {}, document.title, a.protocol + "//" + a.host + this.options.root + this.fragment ); + } + if ( !this.options.silent ) { + return this.loadUrl() + } + }, stop : function () { + i( window ).unbind( "popstate", this.checkUrl ).unbind( "hashchange", this.checkUrl ); + clearInterval( this._checkUrlInterval ); + m.started = false + }, route : function ( a, b ) { + this.handlers.unshift( {route : a, callback : b} ) + }, checkUrl : function () { + var a = this.getFragment(); + a == this.fragment && this.iframe && (a = this.getFragment( this.getHash( this.iframe ) )); + if ( a == this.fragment ) { + return false; + } + this.iframe && this.navigate( a ); + this.loadUrl() || this.loadUrl( this.getHash() ) + }, loadUrl : function ( a ) { + var b = this.fragment = this.getFragment( a ); + return f.any( this.handlers, function ( a ) { + if ( a.route.test( b ) ) { + return a.callback( b ), true + } + } ) + }, navigate : function ( a, b ) { + if ( !m.started ) { + return false; + } + if ( !b || b === true ) { + b = {trigger : b}; + } + var c = (a || "").replace( s, "" ); + if ( this.fragment != c ) { + this._hasPushState ? (c.indexOf( this.options.root ) != 0 && (c = this.options.root + c), this.fragment = c, window.history[b.replace ? + "replaceState" : "pushState"]( {}, document.title, c )) : this._wantsHashChange ? (this.fragment = c, this._updateHash( window.location, c, b.replace ), this.iframe && c != this.getFragment( this.getHash( this.iframe ) ) && (b.replace || this.iframe.document.open().close(), this._updateHash( this.iframe.location, c, b.replace ))) : window.location.assign( this.options.root + a ), b.trigger && this.loadUrl( a ) + } + }, _updateHash : function ( a, b, c ) { + c ? a.replace( a.toString().replace( /(javascript:|#).*$/, "" ) + "#" + b ) : a.hash = b + }} ); + var v = g.View = function ( a ) { + this.cid = + f.uniqueId( "view" ); + this._configure( a || {} ); + this._ensureElement(); + this.initialize.apply( this, arguments ); + this.delegateEvents() + }, E = /^(\S+)\s*(.*)$/, w = "model,collection,el,id,attributes,className,tagName".split( "," ); + f.extend( v.prototype, l, {tagName : "div", $ : function ( a ) { + return this.$el.find( a ) + }, initialize : function () { + }, render : function () { + return this + }, remove : function () { + this.$el.remove(); + return this + }, make : function ( a, b, c ) { + a = document.createElement( a ); + b && i( a ).attr( b ); + c != null && i( a ).html( c ); + return a + }, setElement : function ( a, b ) { + this.$el && this.undelegateEvents(); + this.$el = a instanceof i ? a : i( a ); + this.el = this.$el[0]; + b !== false && this.delegateEvents(); + return this + }, delegateEvents : function ( a ) { + if ( a || (a = n( this, "events" )) ) { + this.undelegateEvents(); + for ( var b in a ) { + var c = a[b]; + f.isFunction( c ) || (c = this[a[b]]); + if ( !c ) { + throw Error( 'Method "' + a[b] + '" does not exist' ); + } + var d = b.match( E ), e = d[1], d = d[2], c = f.bind( c, this ); + e += ".delegateEvents" + this.cid; + d === "" ? this.$el.bind( e, c ) : this.$el.delegate( d, e, c ) + } + } + }, undelegateEvents : function () { + this.$el.unbind( ".delegateEvents" + + this.cid ) + }, _configure : function ( a ) { + this.options && (a = f.extend( {}, this.options, a )); + for ( var b = 0, c = w.length; b < c; b++ ) { + var d = w[b]; + a[d] && (this[d] = a[d]) + } + this.options = a + }, _ensureElement : function () { + if ( this.el ) { + this.setElement( this.el, false ); + } else { + var a = n( this, "attributes" ) || {}; + if ( this.id ) { + a.id = this.id; + } + if ( this.className ) { + a["class"] = this.className; + } + this.setElement( this.make( this.tagName, a ), false ) + } + }} ); + o.extend = r.extend = u.extend = v.extend = function ( a, b ) { + var c = F( this, a, b ); + c.extend = this.extend; + return c + }; + var G = {create : "POST", + update : "PUT", "delete" : "DELETE", read : "GET"}; + g.sync = function ( a, b, c ) { + var d = G[a]; + c || (c = {}); + var e = {type : d, dataType : "json"}; + if ( !c.url ) { + e.url = n( b, "url" ) || t(); + } + if ( !c.data && b && (a == "create" || a == "update") ) { + e.contentType = "application/json", e.data = JSON.stringify( b.toJSON() ); + } + if ( g.emulateJSON ) { + e.contentType = "application/x-www-form-urlencoded", e.data = e.data ? {model : e.data} : {}; + } + if ( g.emulateHTTP && (d === "PUT" || d === "DELETE") ) { + if ( g.emulateJSON ) { + e.data._method = d; + } + e.type = "POST"; + e.beforeSend = function ( a ) { + a.setRequestHeader( "X-HTTP-Method-Override", + d ) + } + } + if ( e.type !== "GET" && !g.emulateJSON ) { + e.processData = false; + } + return i.ajax( f.extend( e, c ) ) + }; + g.wrapError = function ( a, b, c ) { + return function ( d, e ) { + e = d === b ? e : d; + a ? a( b, e, c ) : b.trigger( "error", b, e, c ) + } + }; + var x = function () { + }, F = function ( a, b, c ) { + var d; + d = b && b.hasOwnProperty( "constructor" ) ? b.constructor : function () { + a.apply( this, arguments ) + }; + f.extend( d, a ); + x.prototype = a.prototype; + d.prototype = new x; + b && f.extend( d.prototype, b ); + c && f.extend( d, c ); + d.prototype.constructor = d; + d.__super__ = a.prototype; + return d + }, n = function ( a, b ) { + return!a || + !a[b] ? null : f.isFunction( a[b] ) ? a[b]() : a[b] + }, t = function () { + throw Error( 'A "url" property or function must be specified' ); + }; + return g +} ); diff --git a/example/node/client/js/lib/machina.js b/example/node/client/js/lib/machina.js index 8a0c221..b02e9a5 100644 --- a/example/node/client/js/lib/machina.js +++ b/example/node/client/js/lib/machina.js @@ -1,212 +1,212 @@ -/* - machina.js - Author: Jim Cowart - License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) - Version 0.1.0 -*/ +/* + machina.js + Author: Jim Cowart + License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) + Version 0.1.0 + */ -(function(root, doc, factory) { - if (typeof define === "function" && define.amd) { +(function ( root, doc, factory ) { + if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. - define(["underscore"], function(_) { - return factory(_, root, doc); - }); + define( ["underscore"], function ( _ ) { + return factory( _, root, doc ); + } ); } else { // Browser globals - factory(root._, root, doc); + factory( root._, root, doc ); } -}(this, document, function(_, global, document, undefined) { +}( this, document, function ( _, global, document, undefined ) { var slice = [].slice, - NEXT_TRANSITION = "transition", - NEXT_HANDLER = "handler", - transformEventListToObject = function(eventList){ - var obj = {}; - _.each(eventList, function(evntName) { - obj[evntName] = []; - }); - return obj; - }, - parseEventListeners = function(evnts) { - var obj = evnts; - if(_.isArray(evnts)) { - obj = transformEventListToObject(evnts); - } - return obj; - }; + NEXT_TRANSITION = "transition", + NEXT_HANDLER = "handler", + transformEventListToObject = function ( eventList ) { + var obj = {}; + _.each( eventList, function ( evntName ) { + obj[evntName] = []; + } ); + return obj; + }, + parseEventListeners = function ( evnts ) { + var obj = evnts; + if ( _.isArray( evnts ) ) { + obj = transformEventListToObject( evnts ); + } + return obj; + }; var utils = { - makeFsmNamespace: (function(){ - var machinaCount = 0; - return function() { - return "fsm." + machinaCount++; - }; - })(), - getDefaultOptions: function() { - return { - initialState: "uninitialized", - eventListeners: { - "*" : [] - }, - states: {}, - eventQueue: [], - namespace: utils.makeFsmNamespace() - }; - } -}; - var Fsm = function(options) { - var opt, initialState, defaults = utils.getDefaultOptions(); - if(options) { - if(options.eventListeners) { - options.eventListeners = parseEventListeners(options.eventListeners); + makeFsmNamespace : (function () { + var machinaCount = 0; + return function () { + return "fsm." + machinaCount++; + }; + })(), + getDefaultOptions : function () { + return { + initialState : "uninitialized", + eventListeners : { + "*" : [] + }, + states : {}, + eventQueue : [], + namespace : utils.makeFsmNamespace() + }; } - if(options.messaging) { - options.messaging = _.extend({}, defaults.messaging, options.messaging); - } - } - opt = _.extend(defaults , options || {}); - initialState = opt.initialState; - delete opt.initialState; - _.extend(this,opt); - - this.state = undefined; - this._priorAction = ""; - this._currentAction = ""; - if(initialState) { - this.transition(initialState); - } - machina.fireEvent("newFsm", this); -}; - -Fsm.prototype.fireEvent = function(eventName) { - var args = arguments; - _.each(this.eventListeners["*"], function(callback) { - try { - callback.apply(this,slice.call(args, 0)); - } catch(exception) { - if(console && typeof console.log !== "undefined") { - console.log(exception.toString()); + }; + var Fsm = function ( options ) { + var opt, initialState, defaults = utils.getDefaultOptions(); + if ( options ) { + if ( options.eventListeners ) { + options.eventListeners = parseEventListeners( options.eventListeners ); + } + if ( options.messaging ) { + options.messaging = _.extend( {}, defaults.messaging, options.messaging ); } } - }); - if(this.eventListeners[eventName]) { - _.each(this.eventListeners[eventName], function(callback) { - try { - callback.apply(this,slice.call(args, 1)); - } catch(exception) { - if(console && typeof console.log !== "undefined") { - console.log(exception.toString()); - } - } - }); - } -}; + opt = _.extend( defaults, options || {} ); + initialState = opt.initialState; + delete opt.initialState; + _.extend( this, opt ); -Fsm.prototype.handle = function(msgType) { - // vars to avoid a "this." fest - var states = this.states, current = this.state, args = slice.call(arguments,0), handlerName; - this.currentActionArgs = args; - if(states[current] && (states[current][msgType] || states[current]["*"])) { - handlerName = states[current][msgType] ? msgType : "*"; - this._currentAction = current + "." + handlerName; - this.fireEvent.apply(this, ["Handling"].concat(args)); - states[current][handlerName].apply(this, args.slice(1)); - this.fireEvent.apply(this, ["Handled"].concat(args)); - this._priorAction = this._currentAction; - this._currentAction = ""; - this.processQueue(NEXT_HANDLER); - } - else { - this.fireEvent.apply(this, ["NoHandler"].concat(args)); - } - this.currentActionArgs = undefined; -}; + this.state = undefined; + this._priorAction = ""; + this._currentAction = ""; + if ( initialState ) { + this.transition( initialState ); + } + machina.fireEvent( "newFsm", this ); + }; -Fsm.prototype.transition = function(newState) { - if(this.states[newState]){ - var oldState = this.state; - this.state = newState; - if(this.states[newState]._onEnter) { - this.states[newState]._onEnter.call( this ); - } - this.fireEvent.apply(this, ["Transitioned", oldState, this.state ]); - this.processQueue(NEXT_TRANSITION); - return; - } - this.fireEvent.apply(this, ["InvalidState", this.state, newState ]); -}; + Fsm.prototype.fireEvent = function ( eventName ) { + var args = arguments; + _.each( this.eventListeners["*"], function ( callback ) { + try { + callback.apply( this, slice.call( args, 0 ) ); + } catch ( exception ) { + if ( console && typeof console.log !== "undefined" ) { + console.log( exception.toString() ); + } + } + } ); + if ( this.eventListeners[eventName] ) { + _.each( this.eventListeners[eventName], function ( callback ) { + try { + callback.apply( this, slice.call( args, 1 ) ); + } catch ( exception ) { + if ( console && typeof console.log !== "undefined" ) { + console.log( exception.toString() ); + } + } + } ); + } + }; -Fsm.prototype.processQueue = function(type) { - var filterFn = type === NEXT_TRANSITION ? - function(item){ - return item.type === NEXT_TRANSITION && ((!item.untilState) || (item.untilState === this.state)); - } : - function(item) { - return item.type === NEXT_HANDLER; - }, - toProcess = _.filter(this.eventQueue, filterFn, this); - this.eventQueue = _.difference(this.eventQueue, toProcess); - _.each(toProcess, function(item, index){ - this.handle.apply(this, item.args); - }, this); -}; + Fsm.prototype.handle = function ( msgType ) { + // vars to avoid a "this." fest + var states = this.states, current = this.state, args = slice.call( arguments, 0 ), handlerName; + this.currentActionArgs = args; + if ( states[current] && (states[current][msgType] || states[current]["*"]) ) { + handlerName = states[current][msgType] ? msgType : "*"; + this._currentAction = current + "." + handlerName; + this.fireEvent.apply( this, ["Handling"].concat( args ) ); + states[current][handlerName].apply( this, args.slice( 1 ) ); + this.fireEvent.apply( this, ["Handled"].concat( args ) ); + this._priorAction = this._currentAction; + this._currentAction = ""; + this.processQueue( NEXT_HANDLER ); + } + else { + this.fireEvent.apply( this, ["NoHandler"].concat( args ) ); + } + this.currentActionArgs = undefined; + }; -Fsm.prototype.deferUntilTransition = function(stateName) { - if(this.currentActionArgs) { - var queued = { type: NEXT_TRANSITION, untilState: stateName, args: this.currentActionArgs }; - this.eventQueue.push(queued); - this.fireEvent.apply(this, [ "Deferred", this.state, queued ]); - } -}; + Fsm.prototype.transition = function ( newState ) { + if ( this.states[newState] ) { + var oldState = this.state; + this.state = newState; + if ( this.states[newState]._onEnter ) { + this.states[newState]._onEnter.call( this ); + } + this.fireEvent.apply( this, ["Transitioned", oldState, this.state ] ); + this.processQueue( NEXT_TRANSITION ); + return; + } + this.fireEvent.apply( this, ["InvalidState", this.state, newState ] ); + }; -Fsm.prototype.deferUntilNextHandler = function() { - if(this.currentActionArgs) { - var queued = { type: NEXT_TRANSITION, args: this.currentActionArgs }; - this.eventQueue.push(queued); - this.fireEvent.apply(this, [ "Deferred", this.state, queued ]); - } -}; + Fsm.prototype.processQueue = function ( type ) { + var filterFn = type === NEXT_TRANSITION ? + function ( item ) { + return item.type === NEXT_TRANSITION && ((!item.untilState) || (item.untilState === this.state)); + } : + function ( item ) { + return item.type === NEXT_HANDLER; + }, + toProcess = _.filter( this.eventQueue, filterFn, this ); + this.eventQueue = _.difference( this.eventQueue, toProcess ); + _.each( toProcess, function ( item, index ) { + this.handle.apply( this, item.args ); + }, this ); + }; -Fsm.prototype.on = function(eventName, callback) { - if(!this.eventListeners[eventName]) { - this.eventListeners[eventName] = []; - } - this.eventListeners[eventName].push(callback); -}; + Fsm.prototype.deferUntilTransition = function ( stateName ) { + if ( this.currentActionArgs ) { + var queued = { type : NEXT_TRANSITION, untilState : stateName, args : this.currentActionArgs }; + this.eventQueue.push( queued ); + this.fireEvent.apply( this, [ "Deferred", this.state, queued ] ); + } + }; -Fsm.prototype.off = function(eventName, callback) { - if(this.eventListeners[eventName]){ - this.eventListeners[eventName] = _.without(this.eventListeners[eventName], callback); - } -}; + Fsm.prototype.deferUntilNextHandler = function () { + if ( this.currentActionArgs ) { + var queued = { type : NEXT_TRANSITION, args : this.currentActionArgs }; + this.eventQueue.push( queued ); + this.fireEvent.apply( this, [ "Deferred", this.state, queued ] ); + } + }; + + Fsm.prototype.on = function ( eventName, callback ) { + if ( !this.eventListeners[eventName] ) { + this.eventListeners[eventName] = []; + } + this.eventListeners[eventName].push( callback ); + }; + + Fsm.prototype.off = function ( eventName, callback ) { + if ( this.eventListeners[eventName] ) { + this.eventListeners[eventName] = _.without( this.eventListeners[eventName], callback ); + } + }; var machina = { - Fsm: Fsm, - bus: undefined, - utils: utils, - on: function(eventName, callback) { - if(!this.eventListeners[eventName]) { + Fsm : Fsm, + bus : undefined, + utils : utils, + on : function ( eventName, callback ) { + if ( !this.eventListeners[eventName] ) { this.eventListeners[eventName] = []; } - this.eventListeners[eventName].push(callback); + this.eventListeners[eventName].push( callback ); }, - off: function(eventName, callback) { - if(this.eventListeners[eventName]){ - this.eventListeners[eventName] = _.without(this.eventListeners[eventName], callback); + off : function ( eventName, callback ) { + if ( this.eventListeners[eventName] ) { + this.eventListeners[eventName] = _.without( this.eventListeners[eventName], callback ); } }, - fireEvent: function(eventName) { + fireEvent : function ( eventName ) { var i = 0, len, args = arguments, listeners = this.eventListeners[eventName]; - if(listeners && listeners.length) { - _.each(listeners, function(callback) { - callback.apply(null,slice.call(args, 1)); - }); + if ( listeners && listeners.length ) { + _.each( listeners, function ( callback ) { + callback.apply( null, slice.call( args, 1 ) ); + } ); } }, - eventListeners: { + eventListeners : { newFsm : [] } }; global.machina = machina; return machina; -})); \ No newline at end of file +} )); \ No newline at end of file diff --git a/example/node/client/js/lib/postal.diagnostics.js b/example/node/client/js/lib/postal.diagnostics.js index e65e89b..754a85b 100644 --- a/example/node/client/js/lib/postal.diagnostics.js +++ b/example/node/client/js/lib/postal.diagnostics.js @@ -47,7 +47,9 @@ define( [ "postal", "underscore" ], function ( postal, _, undefined ) { } } ); - postal.diagnostics = { + postal.diagnostics = postal.diagnostics || {}; + + postal.diagnostics.console = { clearFilters : function () { filters = []; }, @@ -60,13 +62,13 @@ define( [ "postal", "underscore" ], function ( postal, _, undefined ) { if ( !_.isArray( constraint ) ) { constraint = [ constraint ]; } - _.each( constraint, function( item ){ + _.each( constraint, function ( item ) { if ( filters.length === 0 || !_.any( filters, function ( filter ) { return _.isEqual( filter, item ); } ) ) { filters.push( item ); } - }); + } ); }, getCurrentFilters : function () { diff --git a/example/node/client/js/lib/postal.js b/example/node/client/js/lib/postal.js index 8ef6b5f..8c36cc0 100644 --- a/example/node/client/js/lib/postal.js +++ b/example/node/client/js/lib/postal.js @@ -1,225 +1,228 @@ /* - postal.js - Author: Jim Cowart - License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) - Version 0.6.0 + postal.js + Author: Jim Cowart + License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) + Version 0.6.0 */ // This is the amd-module version of postal.js // If you need the standard lib style version, go to http://github.com/ifandelse/postal.js -define(["underscore"], function(_, undefined) { +define( ["underscore"], function ( _, undefined ) { var DEFAULT_CHANNEL = "/", DEFAULT_PRIORITY = 50, DEFAULT_DISPOSEAFTER = 0, SYSTEM_CHANNEL = "postal", - NO_OP = function() { }; + NO_OP = function () { + }; -var DistinctPredicate = function() { +var DistinctPredicate = function () { var previous; - return function(data) { + return function ( data ) { var eq = false; - if(_.isString(data)) { + if ( _.isString( data ) ) { eq = data === previous; previous = data; } else { - eq = _.isEqual(data, previous); - previous = _.clone(data); + eq = _.isEqual( data, previous ); + previous = _.clone( data ); } return !eq; }; }; -var ChannelDefinition = function(channelName, defaultTopic) { +var ChannelDefinition = function ( channelName, defaultTopic ) { this.channel = channelName || DEFAULT_CHANNEL; this._topic = defaultTopic || ""; }; ChannelDefinition.prototype = { - subscribe: function() { + subscribe : function () { var len = arguments.length; - if(len === 1) { - return new SubscriptionDefinition(this.channel, this._topic, arguments[0]); + if ( len === 1 ) { + return new SubscriptionDefinition( this.channel, this._topic, arguments[0] ); } - else if (len === 2) { - return new SubscriptionDefinition(this.channel, arguments[0], arguments[1]); + else if ( len === 2 ) { + return new SubscriptionDefinition( this.channel, arguments[0], arguments[1] ); } }, - publish: function(obj) { + publish : function ( obj ) { var envelope = { - channel: this.channel, - topic: this._topic, - data: obj || {} + channel : this.channel, + topic : this._topic, + data : obj || {} }; // If this is an envelope.... - if( obj.topic && obj.data ) { + if ( obj.topic && obj.data ) { envelope = obj; envelope.channel = envelope.channel || this.channel; } envelope.timeStamp = new Date(); - postal.configuration.bus.publish(envelope); + postal.configuration.bus.publish( envelope ); return envelope; }, - topic: function(topic) { - if(topic === this._topic) { + topic : function ( topic ) { + if ( topic === this._topic ) { return this; } - return new ChannelDefinition(this.channel, topic); + return new ChannelDefinition( this.channel, topic ); } }; -var SubscriptionDefinition = function(channel, topic, callback) { +var SubscriptionDefinition = function ( channel, topic, callback ) { this.channel = channel; this.topic = topic; this.callback = callback; this.priority = DEFAULT_PRIORITY; - this.constraints = new Array(0); + this.constraints = new Array( 0 ); this.maxCalls = DEFAULT_DISPOSEAFTER; this.onHandled = NO_OP; this.context = null; - postal.configuration.bus.publish({ - channel: SYSTEM_CHANNEL, - topic: "subscription.created", - timeStamp: new Date(), - data: { - event: "subscription.created", - channel: channel, - topic: topic + postal.configuration.bus.publish( { + channel : SYSTEM_CHANNEL, + topic : "subscription.created", + timeStamp : new Date(), + data : { + event : "subscription.created", + channel : channel, + topic : topic } - }); + } ); - postal.configuration.bus.subscribe(this); + postal.configuration.bus.subscribe( this ); }; SubscriptionDefinition.prototype = { - unsubscribe: function() { - postal.configuration.bus.unsubscribe(this); - postal.configuration.bus.publish({ - channel: SYSTEM_CHANNEL, - topic: "subscription.removed", - timeStamp: new Date(), - data: { - event: "subscription.removed", - channel: this.channel, - topic: this.topic + unsubscribe : function () { + postal.configuration.bus.unsubscribe( this ); + postal.configuration.bus.publish( { + channel : SYSTEM_CHANNEL, + topic : "subscription.removed", + timeStamp : new Date(), + data : { + event : "subscription.removed", + channel : this.channel, + topic : this.topic } - }); + } ); }, - defer: function() { + defer : function () { var fn = this.callback; - this.callback = function(data) { - setTimeout(fn,0,data); + this.callback = function ( data ) { + setTimeout( fn, 0, data ); }; return this; }, - disposeAfter: function(maxCalls) { - if(_.isNaN(maxCalls) || maxCalls <= 0) { + disposeAfter : function ( maxCalls ) { + if ( _.isNaN( maxCalls ) || maxCalls <= 0 ) { throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero."; } var fn = this.onHandled; - var dispose = _.after(maxCalls, _.bind(function() { - this.unsubscribe(this); - }, this)); + var dispose = _.after( maxCalls, _.bind( function () { + this.unsubscribe( this ); + }, this ) ); - this.onHandled = function() { - fn.apply(this.context, arguments); + this.onHandled = function () { + fn.apply( this.context, arguments ); dispose(); }; return this; }, - ignoreDuplicates: function() { - this.withConstraint(new DistinctPredicate()); + ignoreDuplicates : function () { + this.withConstraint( new DistinctPredicate() ); return this; }, - withConstraint: function(predicate) { - if(! _.isFunction(predicate)) { + withConstraint : function ( predicate ) { + if ( !_.isFunction( predicate ) ) { throw "Predicate constraint must be a function"; } - this.constraints.push(predicate); + this.constraints.push( predicate ); return this; }, - withConstraints: function(predicates) { + withConstraints : function ( predicates ) { var self = this; - if(_.isArray(predicates)) { - _.each(predicates, function(predicate) { self.withConstraint(predicate); } ); + if ( _.isArray( predicates ) ) { + _.each( predicates, function ( predicate ) { + self.withConstraint( predicate ); + } ); } return self; }, - withContext: function(context) { + withContext : function ( context ) { this.context = context; return this; }, - withDebounce: function(milliseconds) { - if(_.isNaN(milliseconds)) { + withDebounce : function ( milliseconds ) { + if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; - this.callback = _.debounce(fn, milliseconds); + this.callback = _.debounce( fn, milliseconds ); return this; }, - withDelay: function(milliseconds) { - if(_.isNaN(milliseconds)) { + withDelay : function ( milliseconds ) { + if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; - this.callback = function(data) { - setTimeout(function(){ - fn(data); - }, milliseconds); + this.callback = function ( data ) { + setTimeout( function () { + fn( data ); + }, milliseconds ); }; return this; }, - withPriority: function(priority) { - if(_.isNaN(priority)) { + withPriority : function ( priority ) { + if ( _.isNaN( priority ) ) { throw "Priority must be a number"; } this.priority = priority; return this; }, - withThrottle: function(milliseconds) { - if(_.isNaN(milliseconds)) { + withThrottle : function ( milliseconds ) { + if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; - this.callback = _.throttle(fn, milliseconds); + this.callback = _.throttle( fn, milliseconds ); return this; }, - subscribe: function(callback) { + subscribe : function ( callback ) { this.callback = callback; return this; } }; var bindingsResolver = { - cache: { }, + cache : { }, - compare: function(binding, topic) { - if(this.cache[topic] && this.cache[topic][binding]) { + compare : function ( binding, topic ) { + if ( this.cache[topic] && this.cache[topic][binding] ) { return true; } // binding.replace(/\./g,"\\.") // escape actual periods // .replace(/\*/g, ".*") // asterisks match any value // .replace(/#/g, "[A-Z,a-z,0-9]*"); // hash matches any alpha-numeric 'word' - var rgx = new RegExp("^" + binding.replace(/\./g,"\\.").replace(/\*/g, ".*").replace(/#/g, "[A-Z,a-z,0-9]*") + "$"), - result = rgx.test(topic); - if(result) { - if(!this.cache[topic]) { + var rgx = new RegExp( "^" + binding.replace( /\./g, "\\." ).replace( /\*/g, ".*" ).replace( /#/g, "[A-Z,a-z,0-9]*" ) + "$" ), + result = rgx.test( topic ); + if ( result ) { + if ( !this.cache[topic] ) { this.cache[topic] = {}; } this.cache[topic][binding] = true; @@ -227,91 +230,93 @@ var bindingsResolver = { return result; }, - reset: function() { + reset : function () { this.cache = {}; } }; var localBus = { - addWireTap: function(callback) { + addWireTap : function ( callback ) { var self = this; - self.wireTaps.push(callback); - return function() { - var idx = self.wireTaps.indexOf(callback); - if(idx !== -1) { - self.wireTaps.splice(idx,1); + self.wireTaps.push( callback ); + return function () { + var idx = self.wireTaps.indexOf( callback ); + if ( idx !== -1 ) { + self.wireTaps.splice( idx, 1 ); } }; }, - publish: function(envelope) { - _.each(this.wireTaps,function(tap) { - tap(envelope.data, envelope); - }); + publish : function ( envelope ) { + _.each( this.wireTaps, function ( tap ) { + tap( envelope.data, envelope ); + } ); - _.each(this.subscriptions[envelope.channel], function(topic) { - _.each(topic, function(subDef){ - if(postal.configuration.resolver.compare(subDef.topic, envelope.topic)) { - if(_.all(subDef.constraints, function(constraint) { return constraint(envelope.data,envelope); })) { - if(typeof subDef.callback === 'function') { - subDef.callback.apply(subDef.context, [envelope.data, envelope]); + _.each( this.subscriptions[envelope.channel], function ( topic ) { + _.each( topic, function ( subDef ) { + if ( postal.configuration.resolver.compare( subDef.topic, envelope.topic ) ) { + if ( _.all( subDef.constraints, function ( constraint ) { + return constraint( envelope.data, envelope ); + } ) ) { + if ( typeof subDef.callback === 'function' ) { + subDef.callback.apply( subDef.context, [envelope.data, envelope] ); subDef.onHandled(); } } } - }); - }); + } ); + } ); }, - reset: function() { - if( this.subscriptions ) { - _.each( this.subscriptions , function( channel ){ - _.each( channel, function( topic ){ - while( topic.length ) { + reset : function () { + if ( this.subscriptions ) { + _.each( this.subscriptions, function ( channel ) { + _.each( channel, function ( topic ) { + while ( topic.length ) { topic.pop().unsubscribe(); } - }); - }); + } ); + } ); this.subscriptions = {}; } }, - subscribe: function(subDef) { + subscribe : function ( subDef ) { var idx, found, fn, channel = this.subscriptions[subDef.channel], subs; - if(!channel) { + if ( !channel ) { channel = this.subscriptions[subDef.channel] = {}; } subs = this.subscriptions[subDef.channel][subDef.topic]; - if(!subs) { - subs = this.subscriptions[subDef.channel][subDef.topic] = new Array(0); + if ( !subs ) { + subs = this.subscriptions[subDef.channel][subDef.topic] = new Array( 0 ); } idx = subs.length - 1; - for(; idx >= 0; idx--) { - if(subs[idx].priority <= subDef.priority) { - subs.splice(idx + 1, 0, subDef); + for ( ; idx >= 0; idx-- ) { + if ( subs[idx].priority <= subDef.priority ) { + subs.splice( idx + 1, 0, subDef ); found = true; break; } } - if(!found) { - subs.unshift(subDef); + if ( !found ) { + subs.unshift( subDef ); } return subDef; }, - subscriptions: {}, + subscriptions : {}, - wireTaps: new Array(0), + wireTaps : new Array( 0 ), - unsubscribe: function(config) { - if(this.subscriptions[config.channel][config.topic]) { + unsubscribe : function ( config ) { + if ( this.subscriptions[config.channel][config.topic] ) { var len = this.subscriptions[config.channel][config.topic].length, idx = 0; for ( ; idx < len; idx++ ) { - if (this.subscriptions[config.channel][config.topic][idx] === config) { + if ( this.subscriptions[config.channel][config.topic][idx] === config ) { this.subscriptions[config.channel][config.topic].splice( idx, 1 ); break; } @@ -321,50 +326,50 @@ var localBus = { }; var publishPicker = { - "1" : function(envelope) { - if(!envelope) { - throw new Error("publishing from the 'global' postal.publish call requires a valid envelope."); + "1" : function ( envelope ) { + if ( !envelope ) { + throw new Error( "publishing from the 'global' postal.publish call requires a valid envelope." ); } envelope.channel = envelope.channel || DEFAULT_CHANNEL; envelope.timeStamp = new Date(); - postal.configuration.bus.publish(envelope); - return envelope; - }, - "2" : function(topic, data) { - var envelope = { channel: DEFAULT_CHANNEL, topic: topic, timeStamp: new Date(), data: data }; postal.configuration.bus.publish( envelope ); return envelope; }, - "3" : function(channel, topic, data) { - var envelope = { channel: channel, topic: topic, timeStamp: new Date(), data: data }; + "2" : function ( topic, data ) { + var envelope = { channel : DEFAULT_CHANNEL, topic : topic, timeStamp : new Date(), data : data }; + postal.configuration.bus.publish( envelope ); + return envelope; + }, + "3" : function ( channel, topic, data ) { + var envelope = { channel : channel, topic : topic, timeStamp : new Date(), data : data }; postal.configuration.bus.publish( envelope ); return envelope; } }, channelPicker = { - "1" : function( chn ) { + "1" : function ( chn ) { var channel = chn, topic, options = {}; - if( Object.prototype.toString.call( channel ) === "[object String]" ) { + if ( Object.prototype.toString.call( channel ) === "[object String]" ) { channel = DEFAULT_CHANNEL; - topic = chn; + topic = chn; } else { channel = chn.channel || DEFAULT_CHANNEL; - topic = chn.topic; + topic = chn.topic; options = chn.options || options; } return new postal.channelTypes[ options.type || "local" ]( channel, topic ); }, - "2" : function( chn, tpc ) { + "2" : function ( chn, tpc ) { var channel = chn, topic = tpc, options = {}; - if( Object.prototype.toString.call( tpc ) === "[object Object]" ) { + if ( Object.prototype.toString.call( tpc ) === "[object Object]" ) { channel = DEFAULT_CHANNEL; - topic = chn; + topic = chn; options = tpc; } return new postal.channelTypes[ options.type || "local" ]( channel, topic ); }, - "3" : function( channel, topic, options ) { + "3" : function ( channel, topic, options ) { return new postal.channelTypes[ options.type || "local" ]( channel, topic ); } }, @@ -374,110 +379,110 @@ var publishPicker = { localBus.subscriptions[SYSTEM_CHANNEL] = {}; var postal = { - configuration: { - bus: localBus, - resolver: bindingsResolver, - getSessionIdAction: function( callback ) { + configuration : { + bus : localBus, + resolver : bindingsResolver, + getSessionIdAction : function ( callback ) { callback( sessionInfo ); }, - setSessionIdAction: function( info, callback ) { + setSessionIdAction : function ( info, callback ) { sessionInfo = info; callback( sessionInfo ); }, - DEFAULT_CHANNEL: DEFAULT_CHANNEL, - DEFAULT_PRIORITY: DEFAULT_PRIORITY, - DEFAULT_DISPOSEAFTER: DEFAULT_DISPOSEAFTER, - SYSTEM_CHANNEL: SYSTEM_CHANNEL + DEFAULT_CHANNEL : DEFAULT_CHANNEL, + DEFAULT_PRIORITY : DEFAULT_PRIORITY, + DEFAULT_DISPOSEAFTER : DEFAULT_DISPOSEAFTER, + SYSTEM_CHANNEL : SYSTEM_CHANNEL }, - channelTypes: { - local: ChannelDefinition + channelTypes : { + local : ChannelDefinition }, - channel: function() { + channel : function () { var len = arguments.length; - if(channelPicker[len]) { - return channelPicker[len].apply(this, arguments); + if ( channelPicker[len] ) { + return channelPicker[len].apply( this, arguments ); } }, - subscribe: function(options) { + subscribe : function ( options ) { var callback = options.callback, topic = options.topic, channel = options.channel || DEFAULT_CHANNEL; - return new SubscriptionDefinition(channel, topic, callback); + return new SubscriptionDefinition( channel, topic, callback ); }, - publish: function() { + publish : function () { var len = arguments.length; - if(publishPicker[len]) { - return publishPicker[len].apply(this, arguments); + if ( publishPicker[len] ) { + return publishPicker[len].apply( this, arguments ); } }, - addWireTap: function(callback) { - return this.configuration.bus.addWireTap(callback); + addWireTap : function ( callback ) { + return this.configuration.bus.addWireTap( callback ); }, - linkChannels: function(sources, destinations) { + linkChannels : function ( sources, destinations ) { var result = []; - if(!_.isArray(sources)) { + if ( !_.isArray( sources ) ) { sources = [sources]; } - if(!_.isArray(destinations)) { + if ( !_.isArray( destinations ) ) { destinations = [destinations]; } - _.each(sources, function(source){ + _.each( sources, function ( source ) { var sourceTopic = source.topic || "*"; - _.each(destinations, function(destination) { + _.each( destinations, function ( destination ) { var destChannel = destination.channel || DEFAULT_CHANNEL; result.push( - postal.subscribe({ - channel: source.channel || DEFAULT_CHANNEL, - topic: source.topic || "*", - callback : function(data, env) { + postal.subscribe( { + channel : source.channel || DEFAULT_CHANNEL, + topic : source.topic || "*", + callback : function ( data, env ) { var newEnv = env; - newEnv.topic = _.isFunction(destination.topic) ? destination.topic(env.topic) : destination.topic || env.topic; + newEnv.topic = _.isFunction( destination.topic ) ? destination.topic( env.topic ) : destination.topic || env.topic; newEnv.channel = destChannel; newEnv.data = data; - postal.publish(newEnv); + postal.publish( newEnv ); } - }) + } ) ); - }); - }); + } ); + } ); return result; }, - utils: { - getSessionId: function( callback ) { + utils : { + getSessionId : function ( callback ) { postal.configuration.getSessionIdAction.call( this, callback ); }, - setSessionId: function( value, callback ) { - postal.utils.getSessionId( function( info ) { + setSessionId : function ( value, callback ) { + postal.utils.getSessionId( function ( info ) { // get the session info to move id to last id info.lastId = info.id; info.id = value; // invoke the callback the user provided to handle storing session - postal.configuration.setSessionIdAction( info, function( session ) { + postal.configuration.setSessionIdAction( info, function ( session ) { callback( session ); // publish postal event msg about the change - postal.publish({ - channel: SYSTEM_CHANNEL, - topic: "sessionId.changed", - data: session - }); + postal.publish( { + channel : SYSTEM_CHANNEL, + topic : "sessionId.changed", + data : session + } ); } ); - }); + } ); }, - getSubscribersFor: function() { + getSubscribersFor : function () { var channel = arguments[ 0 ], tpc = arguments[ 1 ], result = []; - if( arguments.length === 1 ) { - if( Object.prototype.toString.call( channel ) === "[object String]" ) { + if ( arguments.length === 1 ) { + if ( Object.prototype.toString.call( channel ) === "[object String]" ) { channel = postal.configuration.DEFAULT_CHANNEL; tpc = arguments[ 0 ]; } @@ -486,14 +491,14 @@ var postal = { tpc = arguments[ 0 ].topic; } } - if( postal.configuration.bus.subscriptions[ channel ] && - postal.configuration.bus.subscriptions[ channel ].hasOwnProperty( tpc )) { + if ( postal.configuration.bus.subscriptions[ channel ] && + postal.configuration.bus.subscriptions[ channel ].hasOwnProperty( tpc ) ) { result = postal.configuration.bus.subscriptions[ channel ][ tpc ]; } return result; }, - reset: function() { + reset : function () { postal.configuration.bus.reset(); postal.configuration.resolver.reset(); } @@ -501,4 +506,4 @@ var postal = { }; return postal; -}); \ No newline at end of file +} ); \ No newline at end of file diff --git a/example/node/client/js/lib/require-jquery.js b/example/node/client/js/lib/require-jquery.js index 60ca9df..d06b8cf 100644 --- a/example/node/client/js/lib/require-jquery.js +++ b/example/node/client/js/lib/require-jquery.js @@ -8,2048 +8,2048 @@ var requirejs, require, define; (function () { - //Change this version number for each release. - var version = "1.0.7", - commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, - cjsRequireRegExp = /require\(\s*["']([^'"\s]+)["']\s*\)/g, - currDirRegExp = /^\.\//, - jsSuffixRegExp = /\.js$/, - ostring = Object.prototype.toString, - ap = Array.prototype, - aps = ap.slice, - apsp = ap.splice, - isBrowser = !!(typeof window !== "undefined" && navigator && document), - isWebWorker = !isBrowser && typeof importScripts !== "undefined", - //PS3 indicates loaded and complete, but need to wait for complete - //specifically. Sequence is "loading", "loaded", execution, - // then "complete". The UA check is unfortunate, but not sure how - //to feature test w/o causing perf issues. - readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? - /^complete$/ : /^(complete|loaded)$/, - defContextName = "_", - //Oh the tragedy, detecting opera. See the usage of isOpera for reason. - isOpera = typeof opera !== "undefined" && opera.toString() === "[object Opera]", - empty = {}, - contexts = {}, - globalDefQueue = [], - interactiveScript = null, - checkLoadedDepth = 0, - useInteractive = false, - reservedDependencies = { - require: true, - module: true, - exports: true - }, - req, cfg = {}, currentlyAddingScript, s, head, baseElement, scripts, script, - src, subPath, mainScript, dataMain, globalI, ctx, jQueryCheck, checkLoadedTimeoutId; - - function isFunction(it) { - return ostring.call(it) === "[object Function]"; - } - - function isArray(it) { - return ostring.call(it) === "[object Array]"; - } - - /** - * Simple function to mix in properties from source into target, - * but only if target does not already have a property of the same name. - * This is not robust in IE for transferring methods that match - * Object.prototype names, but the uses of mixin here seem unlikely to - * trigger a problem related to that. - */ - function mixin(target, source, force) { - for (var prop in source) { - if (!(prop in empty) && (!(prop in target) || force)) { - target[prop] = source[prop]; - } - } - return req; - } - - /** - * Constructs an error with a pointer to an URL with more information. - * @param {String} id the error ID that maps to an ID on a web page. - * @param {String} message human readable error. - * @param {Error} [err] the original error, if there is one. - * - * @returns {Error} - */ - function makeError(id, msg, err) { - var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); - if (err) { - e.originalError = err; - } - return e; - } - - /** - * Used to set up package paths from a packagePaths or packages config object. - * @param {Object} pkgs the object to store the new package config - * @param {Array} currentPackages an array of packages to configure - * @param {String} [dir] a prefix dir to use. - */ - function configurePackageDir(pkgs, currentPackages, dir) { - var i, location, pkgObj; - - for (i = 0; (pkgObj = currentPackages[i]); i++) { - pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj; - location = pkgObj.location; - - //Add dir to the path, but avoid paths that start with a slash - //or have a colon (indicates a protocol) - if (dir && (!location || (location.indexOf("/") !== 0 && location.indexOf(":") === -1))) { - location = dir + "/" + (location || pkgObj.name); - } - - //Create a brand new object on pkgs, since currentPackages can - //be passed in again, and config.pkgs is the internal transformed - //state for all package configs. - pkgs[pkgObj.name] = { - name: pkgObj.name, - location: location || pkgObj.name, - //Remove leading dot in main, so main paths are normalized, - //and remove any trailing .js, since different package - //envs have different conventions: some use a module name, - //some use a file name. - main: (pkgObj.main || "main") - .replace(currDirRegExp, '') - .replace(jsSuffixRegExp, '') - }; - } - } - - /** - * jQuery 1.4.3-1.5.x use a readyWait/ready() pairing to hold DOM - * ready callbacks, but jQuery 1.6 supports a holdReady() API instead. - * At some point remove the readyWait/ready() support and just stick - * with using holdReady. - */ - function jQueryHoldReady($, shouldHold) { - if ($.holdReady) { - $.holdReady(shouldHold); - } else if (shouldHold) { - $.readyWait += 1; - } else { - $.ready(true); - } - } - - if (typeof define !== "undefined") { - //If a define is already in play via another AMD loader, - //do not overwrite. - return; - } - - if (typeof requirejs !== "undefined") { - if (isFunction(requirejs)) { - //Do not overwrite and existing requirejs instance. - return; - } else { - cfg = requirejs; - requirejs = undefined; - } - } - - //Allow for a require config object - if (typeof require !== "undefined" && !isFunction(require)) { - //assume it is a config object. - cfg = require; - require = undefined; - } - - /** - * Creates a new context for use in require and define calls. - * Handle most of the heavy lifting. Do not want to use an object - * with prototype here to avoid using "this" in require, in case it - * needs to be used in more super secure envs that do not want this. - * Also there should not be that many contexts in the page. Usually just - * one for the default context, but could be extra for multiversion cases - * or if a package needs a special context for a dependency that conflicts - * with the standard context. - */ - function newContext(contextName) { - var context, resume, - config = { - waitSeconds: 7, - baseUrl: "./", - paths: {}, - pkgs: {}, - catchError: {} - }, - defQueue = [], - specified = { - "require": true, - "exports": true, - "module": true - }, - urlMap = {}, - defined = {}, - loaded = {}, - waiting = {}, - waitAry = [], - urlFetched = {}, - managerCounter = 0, - managerCallbacks = {}, - plugins = {}, - //Used to indicate which modules in a build scenario - //need to be full executed. - needFullExec = {}, - fullExec = {}, - resumeDepth = 0; - - /** - * Trims the . and .. from an array of path segments. - * It will keep a leading path segment if a .. will become - * the first path segment, to help with module name lookups, - * which act like paths, but can be remapped. But the end result, - * all paths that use this function should look normalized. - * NOTE: this method MODIFIES the input array. - * @param {Array} ary the array of path segments. - */ - function trimDots(ary) { - var i, part; - for (i = 0; (part = ary[i]); i++) { - if (part === ".") { - ary.splice(i, 1); - i -= 1; - } else if (part === "..") { - if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { - //End of the line. Keep at least one non-dot - //path segment at the front so it can be mapped - //correctly to disk. Otherwise, there is likely - //no path mapping for a path starting with '..'. - //This can still fail, but catches the most reasonable - //uses of .. - break; - } else if (i > 0) { - ary.splice(i - 1, 2); - i -= 2; - } - } - } - } - - /** - * Given a relative module name, like ./something, normalize it to - * a real name that can be mapped to a path. - * @param {String} name the relative name - * @param {String} baseName a real name that the name arg is relative - * to. - * @returns {String} normalized name - */ - function normalize(name, baseName) { - var pkgName, pkgConfig; - - //Adjust any relative paths. - if (name && name.charAt(0) === ".") { - //If have a base name, try to normalize against it, - //otherwise, assume it is a top-level require that will - //be relative to baseUrl in the end. - if (baseName) { - if (config.pkgs[baseName]) { - //If the baseName is a package name, then just treat it as one - //name to concat the name with. - baseName = [baseName]; - } else { - //Convert baseName to array, and lop off the last part, - //so that . matches that "directory" and not name of the baseName's - //module. For instance, baseName of "one/two/three", maps to - //"one/two/three.js", but we want the directory, "one/two" for - //this normalization. - baseName = baseName.split("/"); - baseName = baseName.slice(0, baseName.length - 1); - } - - name = baseName.concat(name.split("/")); - trimDots(name); - - //Some use of packages may use a . path to reference the - //"main" module name, so normalize for that. - pkgConfig = config.pkgs[(pkgName = name[0])]; - name = name.join("/"); - if (pkgConfig && name === pkgName + '/' + pkgConfig.main) { - name = pkgName; - } - } else if (name.indexOf("./") === 0) { - // No baseName, so this is ID is resolved relative - // to baseUrl, pull off the leading dot. - name = name.substring(2); - } - } - return name; - } - - /** - * Creates a module mapping that includes plugin prefix, module - * name, and path. If parentModuleMap is provided it will - * also normalize the name via require.normalize() - * - * @param {String} name the module name - * @param {String} [parentModuleMap] parent module map - * for the module name, used to resolve relative names. - * - * @returns {Object} - */ - function makeModuleMap(name, parentModuleMap) { - var index = name ? name.indexOf("!") : -1, - prefix = null, - parentName = parentModuleMap ? parentModuleMap.name : null, - originalName = name, - normalizedName, url, pluginModule; - - if (index !== -1) { - prefix = name.substring(0, index); - name = name.substring(index + 1, name.length); - } - - if (prefix) { - prefix = normalize(prefix, parentName); - } - - //Account for relative paths if there is a base name. - if (name) { - if (prefix) { - pluginModule = defined[prefix]; - if (pluginModule && pluginModule.normalize) { - //Plugin is loaded, use its normalize method. - normalizedName = pluginModule.normalize(name, function (name) { - return normalize(name, parentName); - }); - } else { - normalizedName = normalize(name, parentName); - } - } else { - //A regular module. - normalizedName = normalize(name, parentName); - - url = urlMap[normalizedName]; - if (!url) { - //Calculate url for the module, if it has a name. - //Use name here since nameToUrl also calls normalize, - //and for relative names that are outside the baseUrl - //this causes havoc. Was thinking of just removing - //parentModuleMap to avoid extra normalization, but - //normalize() still does a dot removal because of - //issue #142, so just pass in name here and redo - //the normalization. Paths outside baseUrl are just - //messy to support. - url = context.nameToUrl(name, null, parentModuleMap); - - //Store the URL mapping for later. - urlMap[normalizedName] = url; - } - } - } - - return { - prefix: prefix, - name: normalizedName, - parentMap: parentModuleMap, - url: url, - originalName: originalName, - fullName: prefix ? prefix + "!" + (normalizedName || '') : normalizedName - }; - } - - /** - * Determine if priority loading is done. If so clear the priorityWait - */ - function isPriorityDone() { - var priorityDone = true, - priorityWait = config.priorityWait, - priorityName, i; - if (priorityWait) { - for (i = 0; (priorityName = priorityWait[i]); i++) { - if (!loaded[priorityName]) { - priorityDone = false; - break; - } - } - if (priorityDone) { - delete config.priorityWait; - } - } - return priorityDone; - } - - function makeContextModuleFunc(func, relModuleMap, enableBuildCallback) { - return function () { - //A version of a require function that passes a moduleName - //value for items that may need to - //look up paths relative to the moduleName - var args = aps.call(arguments, 0), lastArg; - if (enableBuildCallback && - isFunction((lastArg = args[args.length - 1]))) { - lastArg.__requireJsBuild = true; - } - args.push(relModuleMap); - return func.apply(null, args); - }; - } - - /** - * Helper function that creates a require function object to give to - * modules that ask for it as a dependency. It needs to be specific - * per module because of the implication of path mappings that may - * need to be relative to the module name. - */ - function makeRequire(relModuleMap, enableBuildCallback, altRequire) { - var modRequire = makeContextModuleFunc(altRequire || context.require, relModuleMap, enableBuildCallback); - - mixin(modRequire, { - nameToUrl: makeContextModuleFunc(context.nameToUrl, relModuleMap), - toUrl: makeContextModuleFunc(context.toUrl, relModuleMap), - defined: makeContextModuleFunc(context.requireDefined, relModuleMap), - specified: makeContextModuleFunc(context.requireSpecified, relModuleMap), - isBrowser: req.isBrowser - }); - return modRequire; - } - - /* - * Queues a dependency for checking after the loader is out of a - * "paused" state, for example while a script file is being loaded - * in the browser, where it may have many modules defined in it. - */ - function queueDependency(manager) { - context.paused.push(manager); - } - - function execManager(manager) { - var i, ret, err, errFile, errModuleTree, - cb = manager.callback, - map = manager.map, - fullName = map.fullName, - args = manager.deps, - listeners = manager.listeners, - cjsModule; - - //Call the callback to define the module, if necessary. - if (cb && isFunction(cb)) { - if (config.catchError.define) { - try { - ret = req.execCb(fullName, manager.callback, args, defined[fullName]); - } catch (e) { - err = e; - } - } else { - ret = req.execCb(fullName, manager.callback, args, defined[fullName]); - } - - if (fullName) { - //If setting exports via "module" is in play, - //favor that over return value and exports. After that, - //favor a non-undefined return value over exports use. - cjsModule = manager.cjsModule; - if (cjsModule && - cjsModule.exports !== undefined && - //Make sure it is not already the exports value - cjsModule.exports !== defined[fullName]) { - ret = defined[fullName] = manager.cjsModule.exports; - } else if (ret === undefined && manager.usingExports) { - //exports already set the defined value. - ret = defined[fullName]; - } else { - //Use the return value from the function. - defined[fullName] = ret; - //If this module needed full execution in a build - //environment, mark that now. - if (needFullExec[fullName]) { - fullExec[fullName] = true; - } - } - } - } else if (fullName) { - //May just be an object definition for the module. Only - //worry about defining if have a module name. - ret = defined[fullName] = cb; - - //If this module needed full execution in a build - //environment, mark that now. - if (needFullExec[fullName]) { - fullExec[fullName] = true; - } - } - - //Clean up waiting. Do this before error calls, and before - //calling back listeners, so that bookkeeping is correct - //in the event of an error and error is reported in correct order, - //since the listeners will likely have errors if the - //onError function does not throw. - if (waiting[manager.id]) { - delete waiting[manager.id]; - manager.isDone = true; - context.waitCount -= 1; - if (context.waitCount === 0) { - //Clear the wait array used for cycles. - waitAry = []; - } - } - - //Do not need to track manager callback now that it is defined. - delete managerCallbacks[fullName]; - - //Allow instrumentation like the optimizer to know the order - //of modules executed and their dependencies. - if (req.onResourceLoad && !manager.placeholder) { - req.onResourceLoad(context, map, manager.depArray); - } - - if (err) { - errFile = (fullName ? makeModuleMap(fullName).url : '') || - err.fileName || err.sourceURL; - errModuleTree = err.moduleTree; - err = makeError('defineerror', 'Error evaluating ' + - 'module "' + fullName + '" at location "' + - errFile + '":\n' + - err + '\nfileName:' + errFile + - '\nlineNumber: ' + (err.lineNumber || err.line), err); - err.moduleName = fullName; - err.moduleTree = errModuleTree; - return req.onError(err); - } - - //Let listeners know of this manager's value. - for (i = 0; (cb = listeners[i]); i++) { - cb(ret); - } - - return undefined; - } - - /** - * Helper that creates a callack function that is called when a dependency - * is ready, and sets the i-th dependency for the manager as the - * value passed to the callback generated by this function. - */ - function makeArgCallback(manager, i) { - return function (value) { - //Only do the work if it has not been done - //already for a dependency. Cycle breaking - //logic in forceExec could mean this function - //is called more than once for a given dependency. - if (!manager.depDone[i]) { - manager.depDone[i] = true; - manager.deps[i] = value; - manager.depCount -= 1; - if (!manager.depCount) { - //All done, execute! - execManager(manager); - } - } - }; - } - - function callPlugin(pluginName, depManager) { - var map = depManager.map, - fullName = map.fullName, - name = map.name, - plugin = plugins[pluginName] || - (plugins[pluginName] = defined[pluginName]), - load; - - //No need to continue if the manager is already - //in the process of loading. - if (depManager.loading) { - return; - } - depManager.loading = true; - - load = function (ret) { - depManager.callback = function () { - return ret; - }; - execManager(depManager); - - loaded[depManager.id] = true; - - //The loading of this plugin - //might have placed other things - //in the paused queue. In particular, - //a loader plugin that depends on - //a different plugin loaded resource. - resume(); - }; - - //Allow plugins to load other code without having to know the - //context or how to "complete" the load. - load.fromText = function (moduleName, text) { - /*jslint evil: true */ - var hasInteractive = useInteractive; - - //Indicate a the module is in process of loading. - loaded[moduleName] = false; - context.scriptCount += 1; - - //Indicate this is not a "real" module, so do not track it - //for builds, it does not map to a real file. - context.fake[moduleName] = true; - - //Turn off interactive script matching for IE for any define - //calls in the text, then turn it back on at the end. - if (hasInteractive) { - useInteractive = false; - } - - req.exec(text); - - if (hasInteractive) { - useInteractive = true; - } - - //Support anonymous modules. - context.completeLoad(moduleName); - }; - - //No need to continue if the plugin value has already been - //defined by a build. - if (fullName in defined) { - load(defined[fullName]); - } else { - //Use parentName here since the plugin's name is not reliable, - //could be some weird string with no path that actually wants to - //reference the parentName's path. - plugin.load(name, makeRequire(map.parentMap, true, function (deps, cb) { - var moduleDeps = [], - i, dep, depMap; - //Convert deps to full names and hold on to them - //for reference later, when figuring out if they - //are blocked by a circular dependency. - for (i = 0; (dep = deps[i]); i++) { - depMap = makeModuleMap(dep, map.parentMap); - deps[i] = depMap.fullName; - if (!depMap.prefix) { - moduleDeps.push(deps[i]); - } - } - depManager.moduleDeps = (depManager.moduleDeps || []).concat(moduleDeps); - return context.require(deps, cb); - }), load, config); - } - } - - /** - * Adds the manager to the waiting queue. Only fully - * resolved items should be in the waiting queue. - */ - function addWait(manager) { - if (!waiting[manager.id]) { - waiting[manager.id] = manager; - waitAry.push(manager); - context.waitCount += 1; - } - } - - /** - * Function added to every manager object. Created out here - * to avoid new function creation for each manager instance. - */ - function managerAdd(cb) { - this.listeners.push(cb); - } - - function getManager(map, shouldQueue) { - var fullName = map.fullName, - prefix = map.prefix, - plugin = prefix ? plugins[prefix] || - (plugins[prefix] = defined[prefix]) : null, - manager, created, pluginManager, prefixMap; - - if (fullName) { - manager = managerCallbacks[fullName]; - } - - if (!manager) { - created = true; - manager = { - //ID is just the full name, but if it is a plugin resource - //for a plugin that has not been loaded, - //then add an ID counter to it. - id: (prefix && !plugin ? - (managerCounter++) + '__p@:' : '') + - (fullName || '__r@' + (managerCounter++)), - map: map, - depCount: 0, - depDone: [], - depCallbacks: [], - deps: [], - listeners: [], - add: managerAdd - }; - - specified[manager.id] = true; - - //Only track the manager/reuse it if this is a non-plugin - //resource. Also only track plugin resources once - //the plugin has been loaded, and so the fullName is the - //true normalized value. - if (fullName && (!prefix || plugins[prefix])) { - managerCallbacks[fullName] = manager; - } - } - - //If there is a plugin needed, but it is not loaded, - //first load the plugin, then continue on. - if (prefix && !plugin) { - prefixMap = makeModuleMap(prefix); - - //Clear out defined and urlFetched if the plugin was previously - //loaded/defined, but not as full module (as in a build - //situation). However, only do this work if the plugin is in - //defined but does not have a module export value. - if (prefix in defined && !defined[prefix]) { - delete defined[prefix]; - delete urlFetched[prefixMap.url]; - } - - pluginManager = getManager(prefixMap, true); - pluginManager.add(function (plugin) { - //Create a new manager for the normalized - //resource ID and have it call this manager when - //done. - var newMap = makeModuleMap(map.originalName, map.parentMap), - normalizedManager = getManager(newMap, true); - - //Indicate this manager is a placeholder for the real, - //normalized thing. Important for when trying to map - //modules and dependencies, for instance, in a build. - manager.placeholder = true; - - normalizedManager.add(function (resource) { - manager.callback = function () { - return resource; - }; - execManager(manager); - }); - }); - } else if (created && shouldQueue) { - //Indicate the resource is not loaded yet if it is to be - //queued. - loaded[manager.id] = false; - queueDependency(manager); - addWait(manager); - } - - return manager; - } - - function main(inName, depArray, callback, relModuleMap) { - var moduleMap = makeModuleMap(inName, relModuleMap), - name = moduleMap.name, - fullName = moduleMap.fullName, - manager = getManager(moduleMap), - id = manager.id, - deps = manager.deps, - i, depArg, depName, depPrefix, cjsMod; - - if (fullName) { - //If module already defined for context, or already loaded, - //then leave. Also leave if jQuery is registering but it does - //not match the desired version number in the config. - if (fullName in defined || loaded[id] === true || - (fullName === "jquery" && config.jQuery && - config.jQuery !== callback().fn.jquery)) { - return; - } - - //Set specified/loaded here for modules that are also loaded - //as part of a layer, where onScriptLoad is not fired - //for those cases. Do this after the inline define and - //dependency tracing is done. - specified[id] = true; - loaded[id] = true; - - //If module is jQuery set up delaying its dom ready listeners. - if (fullName === "jquery" && callback) { - jQueryCheck(callback()); - } - } - - //Attach real depArray and callback to the manager. Do this - //only if the module has not been defined already, so do this after - //the fullName checks above. IE can call main() more than once - //for a module. - manager.depArray = depArray; - manager.callback = callback; - - //Add the dependencies to the deps field, and register for callbacks - //on the dependencies. - for (i = 0; i < depArray.length; i++) { - depArg = depArray[i]; - //There could be cases like in IE, where a trailing comma will - //introduce a null dependency, so only treat a real dependency - //value as a dependency. - if (depArg) { - //Split the dependency name into plugin and name parts - depArg = makeModuleMap(depArg, (name ? moduleMap : relModuleMap)); - depName = depArg.fullName; - depPrefix = depArg.prefix; - - //Fix the name in depArray to be just the name, since - //that is how it will be called back later. - depArray[i] = depName; - - //Fast path CommonJS standard dependencies. - if (depName === "require") { - deps[i] = makeRequire(moduleMap); - } else if (depName === "exports") { - //CommonJS module spec 1.1 - deps[i] = defined[fullName] = {}; - manager.usingExports = true; - } else if (depName === "module") { - //CommonJS module spec 1.1 - manager.cjsModule = cjsMod = deps[i] = { - id: name, - uri: name ? context.nameToUrl(name, null, relModuleMap) : undefined, - exports: defined[fullName] - }; - } else if (depName in defined && !(depName in waiting) && - (!(fullName in needFullExec) || - (fullName in needFullExec && fullExec[depName]))) { - //Module already defined, and not in a build situation - //where the module is a something that needs full - //execution and this dependency has not been fully - //executed. See r.js's requirePatch.js for more info - //on fullExec. - deps[i] = defined[depName]; - } else { - //Mark this dependency as needing full exec if - //the current module needs full exec. - if (fullName in needFullExec) { - needFullExec[depName] = true; - //Reset state so fully executed code will get - //picked up correctly. - delete defined[depName]; - urlFetched[depArg.url] = false; - } - - //Either a resource that is not loaded yet, or a plugin - //resource for either a plugin that has not - //loaded yet. - manager.depCount += 1; - manager.depCallbacks[i] = makeArgCallback(manager, i); - getManager(depArg, true).add(manager.depCallbacks[i]); - } - } - } - - //Do not bother tracking the manager if it is all done. - if (!manager.depCount) { - //All done, execute! - execManager(manager); - } else { - addWait(manager); - } - } - - /** - * Convenience method to call main for a define call that was put on - * hold in the defQueue. - */ - function callDefMain(args) { - main.apply(null, args); - } - - /** - * jQuery 1.4.3+ supports ways to hold off calling - * calling jQuery ready callbacks until all scripts are loaded. Be sure - * to track it if the capability exists.. Also, since jQuery 1.4.3 does - * not register as a module, need to do some global inference checking. - * Even if it does register as a module, not guaranteed to be the precise - * name of the global. If a jQuery is tracked for this context, then go - * ahead and register it as a module too, if not already in process. - */ - jQueryCheck = function (jqCandidate) { - if (!context.jQuery) { - var $ = jqCandidate || (typeof jQuery !== "undefined" ? jQuery : null); - - if ($) { - //If a specific version of jQuery is wanted, make sure to only - //use this jQuery if it matches. - if (config.jQuery && $.fn.jquery !== config.jQuery) { - return; - } - - if ("holdReady" in $ || "readyWait" in $) { - context.jQuery = $; - - //Manually create a "jquery" module entry if not one already - //or in process. Note this could trigger an attempt at - //a second jQuery registration, but does no harm since - //the first one wins, and it is the same value anyway. - callDefMain(["jquery", [], function () { - return jQuery; - }]); - - //Ask jQuery to hold DOM ready callbacks. - if (context.scriptCount) { - jQueryHoldReady($, true); - context.jQueryIncremented = true; - } - } - } - } - }; - - function findCycle(manager, traced) { - var fullName = manager.map.fullName, - depArray = manager.depArray, - fullyLoaded = true, - i, depName, depManager, result; - - if (manager.isDone || !fullName || !loaded[fullName]) { - return result; - } - - //Found the cycle. - if (traced[fullName]) { - return manager; - } - - traced[fullName] = true; - - //Trace through the dependencies. - if (depArray) { - for (i = 0; i < depArray.length; i++) { - //Some array members may be null, like if a trailing comma - //IE, so do the explicit [i] access and check if it has a value. - depName = depArray[i]; - if (!loaded[depName] && !reservedDependencies[depName]) { - fullyLoaded = false; - break; - } - depManager = waiting[depName]; - if (depManager && !depManager.isDone && loaded[depName]) { - result = findCycle(depManager, traced); - if (result) { - break; - } - } - } - if (!fullyLoaded) { - //Discard the cycle that was found, since it cannot - //be forced yet. Also clear this module from traced. - result = undefined; - delete traced[fullName]; - } - } - - return result; - } - - function forceExec(manager, traced) { - var fullName = manager.map.fullName, - depArray = manager.depArray, - i, depName, depManager, prefix, prefixManager, value; - - - if (manager.isDone || !fullName || !loaded[fullName]) { - return undefined; - } - - if (fullName) { - if (traced[fullName]) { - return defined[fullName]; - } - - traced[fullName] = true; - } - - //Trace through the dependencies. - if (depArray) { - for (i = 0; i < depArray.length; i++) { - //Some array members may be null, like if a trailing comma - //IE, so do the explicit [i] access and check if it has a value. - depName = depArray[i]; - if (depName) { - //First, make sure if it is a plugin resource that the - //plugin is not blocked. - prefix = makeModuleMap(depName).prefix; - if (prefix && (prefixManager = waiting[prefix])) { - forceExec(prefixManager, traced); - } - depManager = waiting[depName]; - if (depManager && !depManager.isDone && loaded[depName]) { - value = forceExec(depManager, traced); - manager.depCallbacks[i](value); - } - } - } - } - - return defined[fullName]; - } - - /** - * Checks if all modules for a context are loaded, and if so, evaluates the - * new ones in right dependency order. - * - * @private - */ - function checkLoaded() { - var waitInterval = config.waitSeconds * 1000, - //It is possible to disable the wait interval by using waitSeconds of 0. - expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), - noLoads = "", hasLoadedProp = false, stillLoading = false, - cycleDeps = [], - i, prop, err, manager, cycleManager, moduleDeps; - - //If there are items still in the paused queue processing wait. - //This is particularly important in the sync case where each paused - //item is processed right away but there may be more waiting. - if (context.pausedCount > 0) { - return undefined; - } - - //Determine if priority loading is done. If so clear the priority. If - //not, then do not check - if (config.priorityWait) { - if (isPriorityDone()) { - //Call resume, since it could have - //some waiting dependencies to trace. - resume(); - } else { - return undefined; - } - } - - //See if anything is still in flight. - for (prop in loaded) { - if (!(prop in empty)) { - hasLoadedProp = true; - if (!loaded[prop]) { - if (expired) { - noLoads += prop + " "; - } else { - stillLoading = true; - if (prop.indexOf('!') === -1) { - //No reason to keep looking for unfinished - //loading. If the only stillLoading is a - //plugin resource though, keep going, - //because it may be that a plugin resource - //is waiting on a non-plugin cycle. - cycleDeps = []; - break; - } else { - moduleDeps = managerCallbacks[prop] && managerCallbacks[prop].moduleDeps; - if (moduleDeps) { - cycleDeps.push.apply(cycleDeps, moduleDeps); - } - } - } - } - } - } - - //Check for exit conditions. - if (!hasLoadedProp && !context.waitCount) { - //If the loaded object had no items, then the rest of - //the work below does not need to be done. - return undefined; - } - if (expired && noLoads) { - //If wait time expired, throw error of unloaded modules. - err = makeError("timeout", "Load timeout for modules: " + noLoads); - err.requireType = "timeout"; - err.requireModules = noLoads; - err.contextName = context.contextName; - return req.onError(err); - } - - //If still loading but a plugin is waiting on a regular module cycle - //break the cycle. - if (stillLoading && cycleDeps.length) { - for (i = 0; (manager = waiting[cycleDeps[i]]); i++) { - if ((cycleManager = findCycle(manager, {}))) { - forceExec(cycleManager, {}); - break; - } - } - - } - - //If still waiting on loads, and the waiting load is something - //other than a plugin resource, or there are still outstanding - //scripts, then just try back later. - if (!expired && (stillLoading || context.scriptCount)) { - //Something is still waiting to load. Wait for it, but only - //if a timeout is not already in effect. - if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { - checkLoadedTimeoutId = setTimeout(function () { - checkLoadedTimeoutId = 0; - checkLoaded(); - }, 50); - } - return undefined; - } - - //If still have items in the waiting cue, but all modules have - //been loaded, then it means there are some circular dependencies - //that need to be broken. - //However, as a waiting thing is fired, then it can add items to - //the waiting cue, and those items should not be fired yet, so - //make sure to redo the checkLoaded call after breaking a single - //cycle, if nothing else loaded then this logic will pick it up - //again. - if (context.waitCount) { - //Cycle through the waitAry, and call items in sequence. - for (i = 0; (manager = waitAry[i]); i++) { - forceExec(manager, {}); - } - - //If anything got placed in the paused queue, run it down. - if (context.paused.length) { - resume(); - } - - //Only allow this recursion to a certain depth. Only - //triggered by errors in calling a module in which its - //modules waiting on it cannot finish loading, or some circular - //dependencies that then may add more dependencies. - //The value of 5 is a bit arbitrary. Hopefully just one extra - //pass, or two for the case of circular dependencies generating - //more work that gets resolved in the sync node case. - if (checkLoadedDepth < 5) { - checkLoadedDepth += 1; - checkLoaded(); - } - } - - checkLoadedDepth = 0; - - //Check for DOM ready, and nothing is waiting across contexts. - req.checkReadyState(); - - return undefined; - } - - /** - * Resumes tracing of dependencies and then checks if everything is loaded. - */ - resume = function () { - var manager, map, url, i, p, args, fullName; - - //Any defined modules in the global queue, intake them now. - context.takeGlobalQueue(); - - resumeDepth += 1; - - if (context.scriptCount <= 0) { - //Synchronous envs will push the number below zero with the - //decrement above, be sure to set it back to zero for good measure. - //require() calls that also do not end up loading scripts could - //push the number negative too. - context.scriptCount = 0; - } - - //Make sure any remaining defQueue items get properly processed. - while (defQueue.length) { - args = defQueue.shift(); - if (args[0] === null) { - return req.onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); - } else { - callDefMain(args); - } - } - - //Skip the resume of paused dependencies - //if current context is in priority wait. - if (!config.priorityWait || isPriorityDone()) { - while (context.paused.length) { - p = context.paused; - context.pausedCount += p.length; - //Reset paused list - context.paused = []; - - for (i = 0; (manager = p[i]); i++) { - map = manager.map; - url = map.url; - fullName = map.fullName; - - //If the manager is for a plugin managed resource, - //ask the plugin to load it now. - if (map.prefix) { - callPlugin(map.prefix, manager); - } else { - //Regular dependency. - if (!urlFetched[url] && !loaded[fullName]) { - req.load(context, fullName, url); - - //Mark the URL as fetched, but only if it is - //not an empty: URL, used by the optimizer. - //In that case we need to be sure to call - //load() for each module that is mapped to - //empty: so that dependencies are satisfied - //correctly. - if (url.indexOf('empty:') !== 0) { - urlFetched[url] = true; - } - } - } - } - - //Move the start time for timeout forward. - context.startTime = (new Date()).getTime(); - context.pausedCount -= p.length; - } - } - - //Only check if loaded when resume depth is 1. It is likely that - //it is only greater than 1 in sync environments where a factory - //function also then calls the callback-style require. In those - //cases, the checkLoaded should not occur until the resume - //depth is back at the top level. - if (resumeDepth === 1) { - checkLoaded(); - } - - resumeDepth -= 1; - - return undefined; - }; - - //Define the context object. Many of these fields are on here - //just to make debugging easier. - context = { - contextName: contextName, - config: config, - defQueue: defQueue, - waiting: waiting, - waitCount: 0, - specified: specified, - loaded: loaded, - urlMap: urlMap, - urlFetched: urlFetched, - scriptCount: 0, - defined: defined, - paused: [], - pausedCount: 0, - plugins: plugins, - needFullExec: needFullExec, - fake: {}, - fullExec: fullExec, - managerCallbacks: managerCallbacks, - makeModuleMap: makeModuleMap, - normalize: normalize, - /** - * Set a configuration for the context. - * @param {Object} cfg config object to integrate. - */ - configure: function (cfg) { - var paths, prop, packages, pkgs, packagePaths, requireWait; - - //Make sure the baseUrl ends in a slash. - if (cfg.baseUrl) { - if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== "/") { - cfg.baseUrl += "/"; - } - } - - //Save off the paths and packages since they require special processing, - //they are additive. - paths = config.paths; - packages = config.packages; - pkgs = config.pkgs; - - //Mix in the config values, favoring the new values over - //existing ones in context.config. - mixin(config, cfg, true); - - //Adjust paths if necessary. - if (cfg.paths) { - for (prop in cfg.paths) { - if (!(prop in empty)) { - paths[prop] = cfg.paths[prop]; - } - } - config.paths = paths; - } - - packagePaths = cfg.packagePaths; - if (packagePaths || cfg.packages) { - //Convert packagePaths into a packages config. - if (packagePaths) { - for (prop in packagePaths) { - if (!(prop in empty)) { - configurePackageDir(pkgs, packagePaths[prop], prop); - } - } - } - - //Adjust packages if necessary. - if (cfg.packages) { - configurePackageDir(pkgs, cfg.packages); - } - - //Done with modifications, assing packages back to context config - config.pkgs = pkgs; - } - - //If priority loading is in effect, trigger the loads now - if (cfg.priority) { - //Hold on to requireWait value, and reset it after done - requireWait = context.requireWait; - - //Allow tracing some require calls to allow the fetching - //of the priority config. - context.requireWait = false; - //But first, call resume to register any defined modules that may - //be in a data-main built file before the priority config - //call. - resume(); - - context.require(cfg.priority); - - //Trigger a resume right away, for the case when - //the script with the priority load is done as part - //of a data-main call. In that case the normal resume - //call will not happen because the scriptCount will be - //at 1, since the script for data-main is being processed. - resume(); - - //Restore previous state. - context.requireWait = requireWait; - config.priorityWait = cfg.priority; - } - - //If a deps array or a config callback is specified, then call - //require with those args. This is useful when require is defined as a - //config object before require.js is loaded. - if (cfg.deps || cfg.callback) { - context.require(cfg.deps || [], cfg.callback); - } - }, - - requireDefined: function (moduleName, relModuleMap) { - return makeModuleMap(moduleName, relModuleMap).fullName in defined; - }, - - requireSpecified: function (moduleName, relModuleMap) { - return makeModuleMap(moduleName, relModuleMap).fullName in specified; - }, - - require: function (deps, callback, relModuleMap) { - var moduleName, fullName, moduleMap; - if (typeof deps === "string") { - if (isFunction(callback)) { - //Invalid call - return req.onError(makeError("requireargs", "Invalid require call")); - } - - //Synchronous access to one module. If require.get is - //available (as in the Node adapter), prefer that. - //In this case deps is the moduleName and callback is - //the relModuleMap - if (req.get) { - return req.get(context, deps, callback); - } - - //Just return the module wanted. In this scenario, the - //second arg (if passed) is just the relModuleMap. - moduleName = deps; - relModuleMap = callback; - - //Normalize module name, if it contains . or .. - moduleMap = makeModuleMap(moduleName, relModuleMap); - fullName = moduleMap.fullName; - - if (!(fullName in defined)) { - return req.onError(makeError("notloaded", "Module name '" + - moduleMap.fullName + - "' has not been loaded yet for context: " + - contextName)); - } - return defined[fullName]; - } - - //Call main but only if there are dependencies or - //a callback to call. - if (deps && deps.length || callback) { - main(null, deps, callback, relModuleMap); - } - - //If the require call does not trigger anything new to load, - //then resume the dependency processing. - if (!context.requireWait) { - while (!context.scriptCount && context.paused.length) { - resume(); - } - } - return context.require; - }, - - /** - * Internal method to transfer globalQueue items to this context's - * defQueue. - */ - takeGlobalQueue: function () { - //Push all the globalDefQueue items into the context's defQueue - if (globalDefQueue.length) { - //Array splice in the values since the context code has a - //local var ref to defQueue, so cannot just reassign the one - //on context. - apsp.apply(context.defQueue, - [context.defQueue.length - 1, 0].concat(globalDefQueue)); - globalDefQueue = []; - } - }, - - /** - * Internal method used by environment adapters to complete a load event. - * A load event could be a script load or just a load pass from a synchronous - * load call. - * @param {String} moduleName the name of the module to potentially complete. - */ - completeLoad: function (moduleName) { - var args; - - context.takeGlobalQueue(); - - while (defQueue.length) { - args = defQueue.shift(); - - if (args[0] === null) { - args[0] = moduleName; - break; - } else if (args[0] === moduleName) { - //Found matching define call for this script! - break; - } else { - //Some other named define call, most likely the result - //of a build layer that included many define calls. - callDefMain(args); - args = null; - } - } - if (args) { - callDefMain(args); - } else { - //A script that does not call define(), so just simulate - //the call for it. Special exception for jQuery dynamic load. - callDefMain([moduleName, [], - moduleName === "jquery" && typeof jQuery !== "undefined" ? - function () { - return jQuery; - } : null]); - } - - //Doing this scriptCount decrement branching because sync envs - //need to decrement after resume, otherwise it looks like - //loading is complete after the first dependency is fetched. - //For browsers, it works fine to decrement after, but it means - //the checkLoaded setTimeout 50 ms cost is taken. To avoid - //that cost, decrement beforehand. - if (req.isAsync) { - context.scriptCount -= 1; - } - resume(); - if (!req.isAsync) { - context.scriptCount -= 1; - } - }, - - /** - * Converts a module name + .extension into an URL path. - * *Requires* the use of a module name. It does not support using - * plain URLs like nameToUrl. - */ - toUrl: function (moduleNamePlusExt, relModuleMap) { - var index = moduleNamePlusExt.lastIndexOf("."), - ext = null; - - if (index !== -1) { - ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); - moduleNamePlusExt = moduleNamePlusExt.substring(0, index); - } - - return context.nameToUrl(moduleNamePlusExt, ext, relModuleMap); - }, - - /** - * Converts a module name to a file path. Supports cases where - * moduleName may actually be just an URL. - */ - nameToUrl: function (moduleName, ext, relModuleMap) { - var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, - config = context.config; - - //Normalize module name if have a base relative module name to work from. - moduleName = normalize(moduleName, relModuleMap && relModuleMap.fullName); - - //If a colon is in the URL, it indicates a protocol is used and it is just - //an URL to a file, or if it starts with a slash or ends with .js, it is just a plain file. - //The slash is important for protocol-less URLs as well as full paths. - if (req.jsExtRegExp.test(moduleName)) { - //Just a plain path, not module name lookup, so just return it. - //Add extension if it is included. This is a bit wonky, only non-.js things pass - //an extension, this method probably needs to be reworked. - url = moduleName + (ext ? ext : ""); - } else { - //A module that needs to be converted to a path. - paths = config.paths; - pkgs = config.pkgs; - - syms = moduleName.split("/"); - //For each module name segment, see if there is a path - //registered for it. Start with most specific name - //and work up from it. - for (i = syms.length; i > 0; i--) { - parentModule = syms.slice(0, i).join("/"); - if (paths[parentModule]) { - syms.splice(0, i, paths[parentModule]); - break; - } else if ((pkg = pkgs[parentModule])) { - //If module name is just the package name, then looking - //for the main module. - if (moduleName === pkg.name) { - pkgPath = pkg.location + '/' + pkg.main; - } else { - pkgPath = pkg.location; - } - syms.splice(0, i, pkgPath); - break; - } - } - - //Join the path parts together, then figure out if baseUrl is needed. - url = syms.join("/") + (ext || ".js"); - url = (url.charAt(0) === '/' || url.match(/^\w+:/) ? "" : config.baseUrl) + url; - } - - return config.urlArgs ? url + - ((url.indexOf('?') === -1 ? '?' : '&') + - config.urlArgs) : url; - } - }; - - //Make these visible on the context so can be called at the very - //end of the file to bootstrap - context.jQueryCheck = jQueryCheck; - context.resume = resume; - - return context; - } - - /** - * Main entry point. - * - * If the only argument to require is a string, then the module that - * is represented by that string is fetched for the appropriate context. - * - * If the first argument is an array, then it will be treated as an array - * of dependency string names to fetch. An optional function callback can - * be specified to execute when all of those dependencies are available. - * - * Make a local req variable to help Caja compliance (it assumes things - * on a require that are not standardized), and to give a short - * name for minification/local scope use. - */ - req = requirejs = function (deps, callback) { - - //Find the right context, use default - var contextName = defContextName, - context, config; - - // Determine if have config object in the call. - if (!isArray(deps) && typeof deps !== "string") { - // deps is a config object - config = deps; - if (isArray(callback)) { - // Adjust args if there are dependencies - deps = callback; - callback = arguments[2]; - } else { - deps = []; - } - } - - if (config && config.context) { - contextName = config.context; - } - - context = contexts[contextName] || - (contexts[contextName] = newContext(contextName)); - - if (config) { - context.configure(config); - } - - return context.require(deps, callback); - }; - - /** - * Support require.config() to make it easier to cooperate with other - * AMD loaders on globally agreed names. - */ - req.config = function (config) { - return req(config); - }; - - /** - * Export require as a global, but only if it does not already exist. - */ - if (!require) { - require = req; - } - - /** - * Global require.toUrl(), to match global require, mostly useful - * for debugging/work in the global space. - */ - req.toUrl = function (moduleNamePlusExt) { - return contexts[defContextName].toUrl(moduleNamePlusExt); - }; - - req.version = version; - - //Used to filter out dependencies that are already paths. - req.jsExtRegExp = /^\/|:|\?|\.js$/; - s = req.s = { - contexts: contexts, - //Stores a list of URLs that should not get async script tag treatment. - skipAsync: {} - }; - - req.isAsync = req.isBrowser = isBrowser; - if (isBrowser) { - head = s.head = document.getElementsByTagName("head")[0]; - //If BASE tag is in play, using appendChild is a problem for IE6. - //When that browser dies, this can be removed. Details in this jQuery bug: - //http://dev.jquery.com/ticket/2709 - baseElement = document.getElementsByTagName("base")[0]; - if (baseElement) { - head = s.head = baseElement.parentNode; - } - } - - /** - * Any errors that require explicitly generates will be passed to this - * function. Intercept/override it if you want custom error handling. - * @param {Error} err the error object. - */ - req.onError = function (err) { - throw err; - }; - - /** - * Does the request to load a module for the browser case. - * Make this a separate function to allow other environments - * to override it. - * - * @param {Object} context the require context to find state. - * @param {String} moduleName the name of the module. - * @param {Object} url the URL to the module. - */ - req.load = function (context, moduleName, url) { - req.resourcesReady(false); - - context.scriptCount += 1; - req.attach(url, context, moduleName); - - //If tracking a jQuery, then make sure its ready callbacks - //are put on hold to prevent its ready callbacks from - //triggering too soon. - if (context.jQuery && !context.jQueryIncremented) { - jQueryHoldReady(context.jQuery, true); - context.jQueryIncremented = true; - } - }; - - function getInteractiveScript() { - var scripts, i, script; - if (interactiveScript && interactiveScript.readyState === 'interactive') { - return interactiveScript; - } - - scripts = document.getElementsByTagName('script'); - for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) { - if (script.readyState === 'interactive') { - return (interactiveScript = script); - } - } - - return null; - } - - /** - * The function that handles definitions of modules. Differs from - * require() in that a string for the module should be the first argument, - * and the function to execute after dependencies are loaded should - * return a value to define the module corresponding to the first argument's - * name. - */ - define = function (name, deps, callback) { - var node, context; - - //Allow for anonymous functions - if (typeof name !== 'string') { - //Adjust args appropriately - callback = deps; - deps = name; - name = null; - } - - //This module may not have dependencies - if (!isArray(deps)) { - callback = deps; - deps = []; - } - - //If no name, and callback is a function, then figure out if it a - //CommonJS thing with dependencies. - if (!deps.length && isFunction(callback)) { - //Remove comments from the callback string, - //look for require calls, and pull them into the dependencies, - //but only if there are function args. - if (callback.length) { - callback - .toString() - .replace(commentRegExp, "") - .replace(cjsRequireRegExp, function (match, dep) { - deps.push(dep); - }); - - //May be a CommonJS thing even without require calls, but still - //could use exports, and module. Avoid doing exports and module - //work though if it just needs require. - //REQUIRES the function to expect the CommonJS variables in the - //order listed below. - deps = (callback.length === 1 ? ["require"] : ["require", "exports", "module"]).concat(deps); - } - } - - //If in IE 6-8 and hit an anonymous define() call, do the interactive - //work. - if (useInteractive) { - node = currentlyAddingScript || getInteractiveScript(); - if (node) { - if (!name) { - name = node.getAttribute("data-requiremodule"); - } - context = contexts[node.getAttribute("data-requirecontext")]; - } - } - - //Always save off evaluating the def call until the script onload handler. - //This allows multiple modules to be in a file without prematurely - //tracing dependencies, and allows for anonymous module support, - //where the module name is not known until the script onload event - //occurs. If no context, use the global queue, and get it processed - //in the onscript load callback. - (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); - - return undefined; - }; - - define.amd = { - multiversion: true, - plugins: true, - jQuery: true - }; - - /** - * Executes the text. Normally just uses eval, but can be modified - * to use a more environment specific call. - * @param {String} text the text to execute/evaluate. - */ - req.exec = function (text) { - return eval(text); - }; - - /** - * Executes a module callack function. Broken out as a separate function - * solely to allow the build system to sequence the files in the built - * layer in the right sequence. - * - * @private - */ - req.execCb = function (name, callback, args, exports) { - return callback.apply(exports, args); - }; - - - /** - * Adds a node to the DOM. Public function since used by the order plugin. - * This method should not normally be called by outside code. - */ - req.addScriptToDom = function (node) { - //For some cache cases in IE 6-8, the script executes before the end - //of the appendChild execution, so to tie an anonymous define - //call to the module name (which is stored on the node), hold on - //to a reference to this node, but clear after the DOM insertion. - currentlyAddingScript = node; - if (baseElement) { - head.insertBefore(node, baseElement); - } else { - head.appendChild(node); - } - currentlyAddingScript = null; - }; - - /** - * callback for script loads, used to check status of loading. - * - * @param {Event} evt the event from the browser for the script - * that was loaded. - * - * @private - */ - req.onScriptLoad = function (evt) { - //Using currentTarget instead of target for Firefox 2.0's sake. Not - //all old browsers will be supported, but this one was easy enough - //to support and still makes sense. - var node = evt.currentTarget || evt.srcElement, contextName, moduleName, - context; - - if (evt.type === "load" || (node && readyRegExp.test(node.readyState))) { - //Reset interactive script so a script node is not held onto for - //to long. - interactiveScript = null; - - //Pull out the name of the module and the context. - contextName = node.getAttribute("data-requirecontext"); - moduleName = node.getAttribute("data-requiremodule"); - context = contexts[contextName]; - - contexts[contextName].completeLoad(moduleName); - - //Clean up script binding. Favor detachEvent because of IE9 - //issue, see attachEvent/addEventListener comment elsewhere - //in this file. - if (node.detachEvent && !isOpera) { - //Probably IE. If not it will throw an error, which will be - //useful to know. - node.detachEvent("onreadystatechange", req.onScriptLoad); - } else { - node.removeEventListener("load", req.onScriptLoad, false); - } - } - }; - - /** - * Attaches the script represented by the URL to the current - * environment. Right now only supports browser loading, - * but can be redefined in other environments to do the right thing. - * @param {String} url the url of the script to attach. - * @param {Object} context the context that wants the script. - * @param {moduleName} the name of the module that is associated with the script. - * @param {Function} [callback] optional callback, defaults to require.onScriptLoad - * @param {String} [type] optional type, defaults to text/javascript - * @param {Function} [fetchOnlyFunction] optional function to indicate the script node - * should be set up to fetch the script but do not attach it to the DOM - * so that it can later be attached to execute it. This is a way for the - * order plugin to support ordered loading in IE. Once the script is fetched, - * but not executed, the fetchOnlyFunction will be called. - */ - req.attach = function (url, context, moduleName, callback, type, fetchOnlyFunction) { - var node; - if (isBrowser) { - //In the browser so use a script tag - callback = callback || req.onScriptLoad; - node = context && context.config && context.config.xhtml ? - document.createElementNS("http://www.w3.org/1999/xhtml", "html:script") : - document.createElement("script"); - node.type = type || (context && context.config.scriptType) || - "text/javascript"; - node.charset = "utf-8"; - //Use async so Gecko does not block on executing the script if something - //like a long-polling comet tag is being run first. Gecko likes - //to evaluate scripts in DOM order, even for dynamic scripts. - //It will fetch them async, but only evaluate the contents in DOM - //order, so a long-polling script tag can delay execution of scripts - //after it. But telling Gecko we expect async gets us the behavior - //we want -- execute it whenever it is finished downloading. Only - //Helps Firefox 3.6+ - //Allow some URLs to not be fetched async. Mostly helps the order! - //plugin - node.async = !s.skipAsync[url]; - - if (context) { - node.setAttribute("data-requirecontext", context.contextName); - } - node.setAttribute("data-requiremodule", moduleName); - - //Set up load listener. Test attachEvent first because IE9 has - //a subtle issue in its addEventListener and script onload firings - //that do not match the behavior of all other browsers with - //addEventListener support, which fire the onload event for a - //script right after the script execution. See: - //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution - //UNFORTUNATELY Opera implements attachEvent but does not follow the script - //script execution mode. - if (node.attachEvent && !isOpera) { - //Probably IE. IE (at least 6-8) do not fire - //script onload right after executing the script, so - //we cannot tie the anonymous define call to a name. - //However, IE reports the script as being in "interactive" - //readyState at the time of the define call. - useInteractive = true; - - - if (fetchOnlyFunction) { - //Need to use old school onreadystate here since - //when the event fires and the node is not attached - //to the DOM, the evt.srcElement is null, so use - //a closure to remember the node. - node.onreadystatechange = function (evt) { - //Script loaded but not executed. - //Clear loaded handler, set the real one that - //waits for script execution. - if (node.readyState === 'loaded') { - node.onreadystatechange = null; - node.attachEvent("onreadystatechange", callback); - fetchOnlyFunction(node); - } - }; - } else { - node.attachEvent("onreadystatechange", callback); - } - } else { - node.addEventListener("load", callback, false); - } - node.src = url; - - //Fetch only means waiting to attach to DOM after loaded. - if (!fetchOnlyFunction) { - req.addScriptToDom(node); - } - - return node; - } else if (isWebWorker) { - //In a web worker, use importScripts. This is not a very - //efficient use of importScripts, importScripts will block until - //its script is downloaded and evaluated. However, if web workers - //are in play, the expectation that a build has been done so that - //only one script needs to be loaded anyway. This may need to be - //reevaluated if other use cases become common. - importScripts(url); - - //Account for anonymous modules - context.completeLoad(moduleName); - } - return null; - }; - - //Look for a data-main script attribute, which could also adjust the baseUrl. - if (isBrowser) { - //Figure out baseUrl. Get it from the script tag with require.js in it. - scripts = document.getElementsByTagName("script"); - - for (globalI = scripts.length - 1; globalI > -1 && (script = scripts[globalI]); globalI--) { - //Set the "head" where we can append children by - //using the script's parent. - if (!head) { - head = script.parentNode; - } - - //Look for a data-main attribute to set main script for the page - //to load. If it is there, the path to data main becomes the - //baseUrl, if it is not already set. - if ((dataMain = script.getAttribute('data-main'))) { - if (!cfg.baseUrl) { - //Pull off the directory of data-main for use as the - //baseUrl. - src = dataMain.split('/'); - mainScript = src.pop(); - subPath = src.length ? src.join('/') + '/' : './'; - - //Set final config. - cfg.baseUrl = subPath; - //Strip off any trailing .js since dataMain is now - //like a module name. - dataMain = mainScript.replace(jsSuffixRegExp, ''); - } - - //Put the data-main script in the files to load. - cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain]; - - break; - } - } - } - - //See if there is nothing waiting across contexts, and if not, trigger - //resourcesReady. - req.checkReadyState = function () { - var contexts = s.contexts, prop; - for (prop in contexts) { - if (!(prop in empty)) { - if (contexts[prop].waitCount) { - return; - } - } - } - req.resourcesReady(true); - }; - - /** - * Internal function that is triggered whenever all scripts/resources - * have been loaded by the loader. Can be overridden by other, for - * instance the domReady plugin, which wants to know when all resources - * are loaded. - */ - req.resourcesReady = function (isReady) { - var contexts, context, prop; - - //First, set the public variable indicating that resources are loading. - req.resourcesDone = isReady; - - if (req.resourcesDone) { - //If jQuery with DOM ready delayed, release it now. - contexts = s.contexts; - for (prop in contexts) { - if (!(prop in empty)) { - context = contexts[prop]; - if (context.jQueryIncremented) { - jQueryHoldReady(context.jQuery, false); - context.jQueryIncremented = false; - } - } - } - } - }; - - //FF < 3.6 readyState fix. Needed so that domReady plugin - //works well in that environment, since require.js is normally - //loaded via an HTML script tag so it will be there before window load, - //where the domReady plugin is more likely to be loaded after window load. - req.pageLoaded = function () { - if (document.readyState !== "complete") { - document.readyState = "complete"; - } - }; - if (isBrowser) { - if (document.addEventListener) { - if (!document.readyState) { - document.readyState = "loading"; - window.addEventListener("load", req.pageLoaded, false); - } - } - } - - //Set up default context. If require was a configuration object, use that as base config. - req(cfg); - - //If modules are built into require.js, then need to make sure dependencies are - //traced. Use a setTimeout in the browser world, to allow all the modules to register - //themselves. In a non-browser env, assume that modules are not built into require.js, - //which seems odd to do on the server. - if (req.isAsync && typeof setTimeout !== "undefined") { - ctx = s.contexts[(cfg.context || defContextName)]; - //Indicate that the script that includes require() is still loading, - //so that require()'d dependencies are not traced until the end of the - //file is parsed (approximated via the setTimeout call). - ctx.requireWait = true; - setTimeout(function () { - ctx.requireWait = false; - - if (!ctx.scriptCount) { - ctx.resume(); - } - req.checkReadyState(); - }, 0); - } + //Change this version number for each release. + var version = "1.0.7", + commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, + cjsRequireRegExp = /require\(\s*["']([^'"\s]+)["']\s*\)/g, + currDirRegExp = /^\.\//, + jsSuffixRegExp = /\.js$/, + ostring = Object.prototype.toString, + ap = Array.prototype, + aps = ap.slice, + apsp = ap.splice, + isBrowser = !!(typeof window !== "undefined" && navigator && document), + isWebWorker = !isBrowser && typeof importScripts !== "undefined", + //PS3 indicates loaded and complete, but need to wait for complete + //specifically. Sequence is "loading", "loaded", execution, + // then "complete". The UA check is unfortunate, but not sure how + //to feature test w/o causing perf issues. + readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? + /^complete$/ : /^(complete|loaded)$/, + defContextName = "_", + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== "undefined" && opera.toString() === "[object Opera]", + empty = {}, + contexts = {}, + globalDefQueue = [], + interactiveScript = null, + checkLoadedDepth = 0, + useInteractive = false, + reservedDependencies = { + require : true, + module : true, + exports : true + }, + req, cfg = {}, currentlyAddingScript, s, head, baseElement, scripts, script, + src, subPath, mainScript, dataMain, globalI, ctx, jQueryCheck, checkLoadedTimeoutId; + + function isFunction( it ) { + return ostring.call( it ) === "[object Function]"; + } + + function isArray( it ) { + return ostring.call( it ) === "[object Array]"; + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + * This is not robust in IE for transferring methods that match + * Object.prototype names, but the uses of mixin here seem unlikely to + * trigger a problem related to that. + */ + function mixin( target, source, force ) { + for ( var prop in source ) { + if ( !(prop in empty) && (!(prop in target) || force) ) { + target[prop] = source[prop]; + } + } + return req; + } + + /** + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. + * + * @returns {Error} + */ + function makeError( id, msg, err ) { + var e = new Error( msg + '\nhttp://requirejs.org/docs/errors.html#' + id ); + if ( err ) { + e.originalError = err; + } + return e; + } + + /** + * Used to set up package paths from a packagePaths or packages config object. + * @param {Object} pkgs the object to store the new package config + * @param {Array} currentPackages an array of packages to configure + * @param {String} [dir] a prefix dir to use. + */ + function configurePackageDir( pkgs, currentPackages, dir ) { + var i, location, pkgObj; + + for ( i = 0; (pkgObj = currentPackages[i]); i++ ) { + pkgObj = typeof pkgObj === "string" ? { name : pkgObj } : pkgObj; + location = pkgObj.location; + + //Add dir to the path, but avoid paths that start with a slash + //or have a colon (indicates a protocol) + if ( dir && (!location || (location.indexOf( "/" ) !== 0 && location.indexOf( ":" ) === -1)) ) { + location = dir + "/" + (location || pkgObj.name); + } + + //Create a brand new object on pkgs, since currentPackages can + //be passed in again, and config.pkgs is the internal transformed + //state for all package configs. + pkgs[pkgObj.name] = { + name : pkgObj.name, + location : location || pkgObj.name, + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + main : (pkgObj.main || "main") + .replace( currDirRegExp, '' ) + .replace( jsSuffixRegExp, '' ) + }; + } + } + + /** + * jQuery 1.4.3-1.5.x use a readyWait/ready() pairing to hold DOM + * ready callbacks, but jQuery 1.6 supports a holdReady() API instead. + * At some point remove the readyWait/ready() support and just stick + * with using holdReady. + */ + function jQueryHoldReady( $, shouldHold ) { + if ( $.holdReady ) { + $.holdReady( shouldHold ); + } else if ( shouldHold ) { + $.readyWait += 1; + } else { + $.ready( true ); + } + } + + if ( typeof define !== "undefined" ) { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } + + if ( typeof requirejs !== "undefined" ) { + if ( isFunction( requirejs ) ) { + //Do not overwrite and existing requirejs instance. + return; + } else { + cfg = requirejs; + requirejs = undefined; + } + } + + //Allow for a require config object + if ( typeof require !== "undefined" && !isFunction( require ) ) { + //assume it is a config object. + cfg = require; + require = undefined; + } + + /** + * Creates a new context for use in require and define calls. + * Handle most of the heavy lifting. Do not want to use an object + * with prototype here to avoid using "this" in require, in case it + * needs to be used in more super secure envs that do not want this. + * Also there should not be that many contexts in the page. Usually just + * one for the default context, but could be extra for multiversion cases + * or if a package needs a special context for a dependency that conflicts + * with the standard context. + */ + function newContext( contextName ) { + var context, resume, + config = { + waitSeconds : 7, + baseUrl : "./", + paths : {}, + pkgs : {}, + catchError : {} + }, + defQueue = [], + specified = { + "require" : true, + "exports" : true, + "module" : true + }, + urlMap = {}, + defined = {}, + loaded = {}, + waiting = {}, + waitAry = [], + urlFetched = {}, + managerCounter = 0, + managerCallbacks = {}, + plugins = {}, + //Used to indicate which modules in a build scenario + //need to be full executed. + needFullExec = {}, + fullExec = {}, + resumeDepth = 0; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots( ary ) { + var i, part; + for ( i = 0; (part = ary[i]); i++ ) { + if ( part === "." ) { + ary.splice( i, 1 ); + i -= 1; + } else if ( part === ".." ) { + if ( i === 1 && (ary[2] === '..' || ary[0] === '..') ) { + //End of the line. Keep at least one non-dot + //path segment at the front so it can be mapped + //correctly to disk. Otherwise, there is likely + //no path mapping for a path starting with '..'. + //This can still fail, but catches the most reasonable + //uses of .. + break; + } else if ( i > 0 ) { + ary.splice( i - 1, 2 ); + i -= 2; + } + } + } + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @returns {String} normalized name + */ + function normalize( name, baseName ) { + var pkgName, pkgConfig; + + //Adjust any relative paths. + if ( name && name.charAt( 0 ) === "." ) { + //If have a base name, try to normalize against it, + //otherwise, assume it is a top-level require that will + //be relative to baseUrl in the end. + if ( baseName ) { + if ( config.pkgs[baseName] ) { + //If the baseName is a package name, then just treat it as one + //name to concat the name with. + baseName = [baseName]; + } else { + //Convert baseName to array, and lop off the last part, + //so that . matches that "directory" and not name of the baseName's + //module. For instance, baseName of "one/two/three", maps to + //"one/two/three.js", but we want the directory, "one/two" for + //this normalization. + baseName = baseName.split( "/" ); + baseName = baseName.slice( 0, baseName.length - 1 ); + } + + name = baseName.concat( name.split( "/" ) ); + trimDots( name ); + + //Some use of packages may use a . path to reference the + //"main" module name, so normalize for that. + pkgConfig = config.pkgs[(pkgName = name[0])]; + name = name.join( "/" ); + if ( pkgConfig && name === pkgName + '/' + pkgConfig.main ) { + name = pkgName; + } + } else if ( name.indexOf( "./" ) === 0 ) { + // No baseName, so this is ID is resolved relative + // to baseUrl, pull off the leading dot. + name = name.substring( 2 ); + } + } + return name; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * + * @returns {Object} + */ + function makeModuleMap( name, parentModuleMap ) { + var index = name ? name.indexOf( "!" ) : -1, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + normalizedName, url, pluginModule; + + if ( index !== -1 ) { + prefix = name.substring( 0, index ); + name = name.substring( index + 1, name.length ); + } + + if ( prefix ) { + prefix = normalize( prefix, parentName ); + } + + //Account for relative paths if there is a base name. + if ( name ) { + if ( prefix ) { + pluginModule = defined[prefix]; + if ( pluginModule && pluginModule.normalize ) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize( name, function ( name ) { + return normalize( name, parentName ); + } ); + } else { + normalizedName = normalize( name, parentName ); + } + } else { + //A regular module. + normalizedName = normalize( name, parentName ); + + url = urlMap[normalizedName]; + if ( !url ) { + //Calculate url for the module, if it has a name. + //Use name here since nameToUrl also calls normalize, + //and for relative names that are outside the baseUrl + //this causes havoc. Was thinking of just removing + //parentModuleMap to avoid extra normalization, but + //normalize() still does a dot removal because of + //issue #142, so just pass in name here and redo + //the normalization. Paths outside baseUrl are just + //messy to support. + url = context.nameToUrl( name, null, parentModuleMap ); + + //Store the URL mapping for later. + urlMap[normalizedName] = url; + } + } + } + + return { + prefix : prefix, + name : normalizedName, + parentMap : parentModuleMap, + url : url, + originalName : originalName, + fullName : prefix ? prefix + "!" + (normalizedName || '') : normalizedName + }; + } + + /** + * Determine if priority loading is done. If so clear the priorityWait + */ + function isPriorityDone() { + var priorityDone = true, + priorityWait = config.priorityWait, + priorityName, i; + if ( priorityWait ) { + for ( i = 0; (priorityName = priorityWait[i]); i++ ) { + if ( !loaded[priorityName] ) { + priorityDone = false; + break; + } + } + if ( priorityDone ) { + delete config.priorityWait; + } + } + return priorityDone; + } + + function makeContextModuleFunc( func, relModuleMap, enableBuildCallback ) { + return function () { + //A version of a require function that passes a moduleName + //value for items that may need to + //look up paths relative to the moduleName + var args = aps.call( arguments, 0 ), lastArg; + if ( enableBuildCallback && + isFunction( (lastArg = args[args.length - 1]) ) ) { + lastArg.__requireJsBuild = true; + } + args.push( relModuleMap ); + return func.apply( null, args ); + }; + } + + /** + * Helper function that creates a require function object to give to + * modules that ask for it as a dependency. It needs to be specific + * per module because of the implication of path mappings that may + * need to be relative to the module name. + */ + function makeRequire( relModuleMap, enableBuildCallback, altRequire ) { + var modRequire = makeContextModuleFunc( altRequire || context.require, relModuleMap, enableBuildCallback ); + + mixin( modRequire, { + nameToUrl : makeContextModuleFunc( context.nameToUrl, relModuleMap ), + toUrl : makeContextModuleFunc( context.toUrl, relModuleMap ), + defined : makeContextModuleFunc( context.requireDefined, relModuleMap ), + specified : makeContextModuleFunc( context.requireSpecified, relModuleMap ), + isBrowser : req.isBrowser + } ); + return modRequire; + } + + /* + * Queues a dependency for checking after the loader is out of a + * "paused" state, for example while a script file is being loaded + * in the browser, where it may have many modules defined in it. + */ + function queueDependency( manager ) { + context.paused.push( manager ); + } + + function execManager( manager ) { + var i, ret, err, errFile, errModuleTree, + cb = manager.callback, + map = manager.map, + fullName = map.fullName, + args = manager.deps, + listeners = manager.listeners, + cjsModule; + + //Call the callback to define the module, if necessary. + if ( cb && isFunction( cb ) ) { + if ( config.catchError.define ) { + try { + ret = req.execCb( fullName, manager.callback, args, defined[fullName] ); + } catch ( e ) { + err = e; + } + } else { + ret = req.execCb( fullName, manager.callback, args, defined[fullName] ); + } + + if ( fullName ) { + //If setting exports via "module" is in play, + //favor that over return value and exports. After that, + //favor a non-undefined return value over exports use. + cjsModule = manager.cjsModule; + if ( cjsModule && + cjsModule.exports !== undefined && + //Make sure it is not already the exports value + cjsModule.exports !== defined[fullName] ) { + ret = defined[fullName] = manager.cjsModule.exports; + } else if ( ret === undefined && manager.usingExports ) { + //exports already set the defined value. + ret = defined[fullName]; + } else { + //Use the return value from the function. + defined[fullName] = ret; + //If this module needed full execution in a build + //environment, mark that now. + if ( needFullExec[fullName] ) { + fullExec[fullName] = true; + } + } + } + } else if ( fullName ) { + //May just be an object definition for the module. Only + //worry about defining if have a module name. + ret = defined[fullName] = cb; + + //If this module needed full execution in a build + //environment, mark that now. + if ( needFullExec[fullName] ) { + fullExec[fullName] = true; + } + } + + //Clean up waiting. Do this before error calls, and before + //calling back listeners, so that bookkeeping is correct + //in the event of an error and error is reported in correct order, + //since the listeners will likely have errors if the + //onError function does not throw. + if ( waiting[manager.id] ) { + delete waiting[manager.id]; + manager.isDone = true; + context.waitCount -= 1; + if ( context.waitCount === 0 ) { + //Clear the wait array used for cycles. + waitAry = []; + } + } + + //Do not need to track manager callback now that it is defined. + delete managerCallbacks[fullName]; + + //Allow instrumentation like the optimizer to know the order + //of modules executed and their dependencies. + if ( req.onResourceLoad && !manager.placeholder ) { + req.onResourceLoad( context, map, manager.depArray ); + } + + if ( err ) { + errFile = (fullName ? makeModuleMap( fullName ).url : '') || + err.fileName || err.sourceURL; + errModuleTree = err.moduleTree; + err = makeError( 'defineerror', 'Error evaluating ' + + 'module "' + fullName + '" at location "' + + errFile + '":\n' + + err + '\nfileName:' + errFile + + '\nlineNumber: ' + (err.lineNumber || err.line), err ); + err.moduleName = fullName; + err.moduleTree = errModuleTree; + return req.onError( err ); + } + + //Let listeners know of this manager's value. + for ( i = 0; (cb = listeners[i]); i++ ) { + cb( ret ); + } + + return undefined; + } + + /** + * Helper that creates a callack function that is called when a dependency + * is ready, and sets the i-th dependency for the manager as the + * value passed to the callback generated by this function. + */ + function makeArgCallback( manager, i ) { + return function ( value ) { + //Only do the work if it has not been done + //already for a dependency. Cycle breaking + //logic in forceExec could mean this function + //is called more than once for a given dependency. + if ( !manager.depDone[i] ) { + manager.depDone[i] = true; + manager.deps[i] = value; + manager.depCount -= 1; + if ( !manager.depCount ) { + //All done, execute! + execManager( manager ); + } + } + }; + } + + function callPlugin( pluginName, depManager ) { + var map = depManager.map, + fullName = map.fullName, + name = map.name, + plugin = plugins[pluginName] || + (plugins[pluginName] = defined[pluginName]), + load; + + //No need to continue if the manager is already + //in the process of loading. + if ( depManager.loading ) { + return; + } + depManager.loading = true; + + load = function ( ret ) { + depManager.callback = function () { + return ret; + }; + execManager( depManager ); + + loaded[depManager.id] = true; + + //The loading of this plugin + //might have placed other things + //in the paused queue. In particular, + //a loader plugin that depends on + //a different plugin loaded resource. + resume(); + }; + + //Allow plugins to load other code without having to know the + //context or how to "complete" the load. + load.fromText = function ( moduleName, text ) { + /*jslint evil: true */ + var hasInteractive = useInteractive; + + //Indicate a the module is in process of loading. + loaded[moduleName] = false; + context.scriptCount += 1; + + //Indicate this is not a "real" module, so do not track it + //for builds, it does not map to a real file. + context.fake[moduleName] = true; + + //Turn off interactive script matching for IE for any define + //calls in the text, then turn it back on at the end. + if ( hasInteractive ) { + useInteractive = false; + } + + req.exec( text ); + + if ( hasInteractive ) { + useInteractive = true; + } + + //Support anonymous modules. + context.completeLoad( moduleName ); + }; + + //No need to continue if the plugin value has already been + //defined by a build. + if ( fullName in defined ) { + load( defined[fullName] ); + } else { + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load( name, makeRequire( map.parentMap, true, function ( deps, cb ) { + var moduleDeps = [], + i, dep, depMap; + //Convert deps to full names and hold on to them + //for reference later, when figuring out if they + //are blocked by a circular dependency. + for ( i = 0; (dep = deps[i]); i++ ) { + depMap = makeModuleMap( dep, map.parentMap ); + deps[i] = depMap.fullName; + if ( !depMap.prefix ) { + moduleDeps.push( deps[i] ); + } + } + depManager.moduleDeps = (depManager.moduleDeps || []).concat( moduleDeps ); + return context.require( deps, cb ); + } ), load, config ); + } + } + + /** + * Adds the manager to the waiting queue. Only fully + * resolved items should be in the waiting queue. + */ + function addWait( manager ) { + if ( !waiting[manager.id] ) { + waiting[manager.id] = manager; + waitAry.push( manager ); + context.waitCount += 1; + } + } + + /** + * Function added to every manager object. Created out here + * to avoid new function creation for each manager instance. + */ + function managerAdd( cb ) { + this.listeners.push( cb ); + } + + function getManager( map, shouldQueue ) { + var fullName = map.fullName, + prefix = map.prefix, + plugin = prefix ? plugins[prefix] || + (plugins[prefix] = defined[prefix]) : null, + manager, created, pluginManager, prefixMap; + + if ( fullName ) { + manager = managerCallbacks[fullName]; + } + + if ( !manager ) { + created = true; + manager = { + //ID is just the full name, but if it is a plugin resource + //for a plugin that has not been loaded, + //then add an ID counter to it. + id : (prefix && !plugin ? + (managerCounter++) + '__p@:' : '') + + (fullName || '__r@' + (managerCounter++)), + map : map, + depCount : 0, + depDone : [], + depCallbacks : [], + deps : [], + listeners : [], + add : managerAdd + }; + + specified[manager.id] = true; + + //Only track the manager/reuse it if this is a non-plugin + //resource. Also only track plugin resources once + //the plugin has been loaded, and so the fullName is the + //true normalized value. + if ( fullName && (!prefix || plugins[prefix]) ) { + managerCallbacks[fullName] = manager; + } + } + + //If there is a plugin needed, but it is not loaded, + //first load the plugin, then continue on. + if ( prefix && !plugin ) { + prefixMap = makeModuleMap( prefix ); + + //Clear out defined and urlFetched if the plugin was previously + //loaded/defined, but not as full module (as in a build + //situation). However, only do this work if the plugin is in + //defined but does not have a module export value. + if ( prefix in defined && !defined[prefix] ) { + delete defined[prefix]; + delete urlFetched[prefixMap.url]; + } + + pluginManager = getManager( prefixMap, true ); + pluginManager.add( function ( plugin ) { + //Create a new manager for the normalized + //resource ID and have it call this manager when + //done. + var newMap = makeModuleMap( map.originalName, map.parentMap ), + normalizedManager = getManager( newMap, true ); + + //Indicate this manager is a placeholder for the real, + //normalized thing. Important for when trying to map + //modules and dependencies, for instance, in a build. + manager.placeholder = true; + + normalizedManager.add( function ( resource ) { + manager.callback = function () { + return resource; + }; + execManager( manager ); + } ); + } ); + } else if ( created && shouldQueue ) { + //Indicate the resource is not loaded yet if it is to be + //queued. + loaded[manager.id] = false; + queueDependency( manager ); + addWait( manager ); + } + + return manager; + } + + function main( inName, depArray, callback, relModuleMap ) { + var moduleMap = makeModuleMap( inName, relModuleMap ), + name = moduleMap.name, + fullName = moduleMap.fullName, + manager = getManager( moduleMap ), + id = manager.id, + deps = manager.deps, + i, depArg, depName, depPrefix, cjsMod; + + if ( fullName ) { + //If module already defined for context, or already loaded, + //then leave. Also leave if jQuery is registering but it does + //not match the desired version number in the config. + if ( fullName in defined || loaded[id] === true || + (fullName === "jquery" && config.jQuery && + config.jQuery !== callback().fn.jquery) ) { + return; + } + + //Set specified/loaded here for modules that are also loaded + //as part of a layer, where onScriptLoad is not fired + //for those cases. Do this after the inline define and + //dependency tracing is done. + specified[id] = true; + loaded[id] = true; + + //If module is jQuery set up delaying its dom ready listeners. + if ( fullName === "jquery" && callback ) { + jQueryCheck( callback() ); + } + } + + //Attach real depArray and callback to the manager. Do this + //only if the module has not been defined already, so do this after + //the fullName checks above. IE can call main() more than once + //for a module. + manager.depArray = depArray; + manager.callback = callback; + + //Add the dependencies to the deps field, and register for callbacks + //on the dependencies. + for ( i = 0; i < depArray.length; i++ ) { + depArg = depArray[i]; + //There could be cases like in IE, where a trailing comma will + //introduce a null dependency, so only treat a real dependency + //value as a dependency. + if ( depArg ) { + //Split the dependency name into plugin and name parts + depArg = makeModuleMap( depArg, (name ? moduleMap : relModuleMap) ); + depName = depArg.fullName; + depPrefix = depArg.prefix; + + //Fix the name in depArray to be just the name, since + //that is how it will be called back later. + depArray[i] = depName; + + //Fast path CommonJS standard dependencies. + if ( depName === "require" ) { + deps[i] = makeRequire( moduleMap ); + } else if ( depName === "exports" ) { + //CommonJS module spec 1.1 + deps[i] = defined[fullName] = {}; + manager.usingExports = true; + } else if ( depName === "module" ) { + //CommonJS module spec 1.1 + manager.cjsModule = cjsMod = deps[i] = { + id : name, + uri : name ? context.nameToUrl( name, null, relModuleMap ) : undefined, + exports : defined[fullName] + }; + } else if ( depName in defined && !(depName in waiting) && + (!(fullName in needFullExec) || + (fullName in needFullExec && fullExec[depName])) ) { + //Module already defined, and not in a build situation + //where the module is a something that needs full + //execution and this dependency has not been fully + //executed. See r.js's requirePatch.js for more info + //on fullExec. + deps[i] = defined[depName]; + } else { + //Mark this dependency as needing full exec if + //the current module needs full exec. + if ( fullName in needFullExec ) { + needFullExec[depName] = true; + //Reset state so fully executed code will get + //picked up correctly. + delete defined[depName]; + urlFetched[depArg.url] = false; + } + + //Either a resource that is not loaded yet, or a plugin + //resource for either a plugin that has not + //loaded yet. + manager.depCount += 1; + manager.depCallbacks[i] = makeArgCallback( manager, i ); + getManager( depArg, true ).add( manager.depCallbacks[i] ); + } + } + } + + //Do not bother tracking the manager if it is all done. + if ( !manager.depCount ) { + //All done, execute! + execManager( manager ); + } else { + addWait( manager ); + } + } + + /** + * Convenience method to call main for a define call that was put on + * hold in the defQueue. + */ + function callDefMain( args ) { + main.apply( null, args ); + } + + /** + * jQuery 1.4.3+ supports ways to hold off calling + * calling jQuery ready callbacks until all scripts are loaded. Be sure + * to track it if the capability exists.. Also, since jQuery 1.4.3 does + * not register as a module, need to do some global inference checking. + * Even if it does register as a module, not guaranteed to be the precise + * name of the global. If a jQuery is tracked for this context, then go + * ahead and register it as a module too, if not already in process. + */ + jQueryCheck = function ( jqCandidate ) { + if ( !context.jQuery ) { + var $ = jqCandidate || (typeof jQuery !== "undefined" ? jQuery : null); + + if ( $ ) { + //If a specific version of jQuery is wanted, make sure to only + //use this jQuery if it matches. + if ( config.jQuery && $.fn.jquery !== config.jQuery ) { + return; + } + + if ( "holdReady" in $ || "readyWait" in $ ) { + context.jQuery = $; + + //Manually create a "jquery" module entry if not one already + //or in process. Note this could trigger an attempt at + //a second jQuery registration, but does no harm since + //the first one wins, and it is the same value anyway. + callDefMain( ["jquery", [], function () { + return jQuery; + }] ); + + //Ask jQuery to hold DOM ready callbacks. + if ( context.scriptCount ) { + jQueryHoldReady( $, true ); + context.jQueryIncremented = true; + } + } + } + } + }; + + function findCycle( manager, traced ) { + var fullName = manager.map.fullName, + depArray = manager.depArray, + fullyLoaded = true, + i, depName, depManager, result; + + if ( manager.isDone || !fullName || !loaded[fullName] ) { + return result; + } + + //Found the cycle. + if ( traced[fullName] ) { + return manager; + } + + traced[fullName] = true; + + //Trace through the dependencies. + if ( depArray ) { + for ( i = 0; i < depArray.length; i++ ) { + //Some array members may be null, like if a trailing comma + //IE, so do the explicit [i] access and check if it has a value. + depName = depArray[i]; + if ( !loaded[depName] && !reservedDependencies[depName] ) { + fullyLoaded = false; + break; + } + depManager = waiting[depName]; + if ( depManager && !depManager.isDone && loaded[depName] ) { + result = findCycle( depManager, traced ); + if ( result ) { + break; + } + } + } + if ( !fullyLoaded ) { + //Discard the cycle that was found, since it cannot + //be forced yet. Also clear this module from traced. + result = undefined; + delete traced[fullName]; + } + } + + return result; + } + + function forceExec( manager, traced ) { + var fullName = manager.map.fullName, + depArray = manager.depArray, + i, depName, depManager, prefix, prefixManager, value; + + + if ( manager.isDone || !fullName || !loaded[fullName] ) { + return undefined; + } + + if ( fullName ) { + if ( traced[fullName] ) { + return defined[fullName]; + } + + traced[fullName] = true; + } + + //Trace through the dependencies. + if ( depArray ) { + for ( i = 0; i < depArray.length; i++ ) { + //Some array members may be null, like if a trailing comma + //IE, so do the explicit [i] access and check if it has a value. + depName = depArray[i]; + if ( depName ) { + //First, make sure if it is a plugin resource that the + //plugin is not blocked. + prefix = makeModuleMap( depName ).prefix; + if ( prefix && (prefixManager = waiting[prefix]) ) { + forceExec( prefixManager, traced ); + } + depManager = waiting[depName]; + if ( depManager && !depManager.isDone && loaded[depName] ) { + value = forceExec( depManager, traced ); + manager.depCallbacks[i]( value ); + } + } + } + } + + return defined[fullName]; + } + + /** + * Checks if all modules for a context are loaded, and if so, evaluates the + * new ones in right dependency order. + * + * @private + */ + function checkLoaded() { + var waitInterval = config.waitSeconds * 1000, + //It is possible to disable the wait interval by using waitSeconds of 0. + expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), + noLoads = "", hasLoadedProp = false, stillLoading = false, + cycleDeps = [], + i, prop, err, manager, cycleManager, moduleDeps; + + //If there are items still in the paused queue processing wait. + //This is particularly important in the sync case where each paused + //item is processed right away but there may be more waiting. + if ( context.pausedCount > 0 ) { + return undefined; + } + + //Determine if priority loading is done. If so clear the priority. If + //not, then do not check + if ( config.priorityWait ) { + if ( isPriorityDone() ) { + //Call resume, since it could have + //some waiting dependencies to trace. + resume(); + } else { + return undefined; + } + } + + //See if anything is still in flight. + for ( prop in loaded ) { + if ( !(prop in empty) ) { + hasLoadedProp = true; + if ( !loaded[prop] ) { + if ( expired ) { + noLoads += prop + " "; + } else { + stillLoading = true; + if ( prop.indexOf( '!' ) === -1 ) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + cycleDeps = []; + break; + } else { + moduleDeps = managerCallbacks[prop] && managerCallbacks[prop].moduleDeps; + if ( moduleDeps ) { + cycleDeps.push.apply( cycleDeps, moduleDeps ); + } + } + } + } + } + } + + //Check for exit conditions. + if ( !hasLoadedProp && !context.waitCount ) { + //If the loaded object had no items, then the rest of + //the work below does not need to be done. + return undefined; + } + if ( expired && noLoads ) { + //If wait time expired, throw error of unloaded modules. + err = makeError( "timeout", "Load timeout for modules: " + noLoads ); + err.requireType = "timeout"; + err.requireModules = noLoads; + err.contextName = context.contextName; + return req.onError( err ); + } + + //If still loading but a plugin is waiting on a regular module cycle + //break the cycle. + if ( stillLoading && cycleDeps.length ) { + for ( i = 0; (manager = waiting[cycleDeps[i]]); i++ ) { + if ( (cycleManager = findCycle( manager, {} )) ) { + forceExec( cycleManager, {} ); + break; + } + } + + } + + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ( !expired && (stillLoading || context.scriptCount) ) { + //Something is still waiting to load. Wait for it, but only + //if a timeout is not already in effect. + if ( (isBrowser || isWebWorker) && !checkLoadedTimeoutId ) { + checkLoadedTimeoutId = setTimeout( function () { + checkLoadedTimeoutId = 0; + checkLoaded(); + }, 50 ); + } + return undefined; + } + + //If still have items in the waiting cue, but all modules have + //been loaded, then it means there are some circular dependencies + //that need to be broken. + //However, as a waiting thing is fired, then it can add items to + //the waiting cue, and those items should not be fired yet, so + //make sure to redo the checkLoaded call after breaking a single + //cycle, if nothing else loaded then this logic will pick it up + //again. + if ( context.waitCount ) { + //Cycle through the waitAry, and call items in sequence. + for ( i = 0; (manager = waitAry[i]); i++ ) { + forceExec( manager, {} ); + } + + //If anything got placed in the paused queue, run it down. + if ( context.paused.length ) { + resume(); + } + + //Only allow this recursion to a certain depth. Only + //triggered by errors in calling a module in which its + //modules waiting on it cannot finish loading, or some circular + //dependencies that then may add more dependencies. + //The value of 5 is a bit arbitrary. Hopefully just one extra + //pass, or two for the case of circular dependencies generating + //more work that gets resolved in the sync node case. + if ( checkLoadedDepth < 5 ) { + checkLoadedDepth += 1; + checkLoaded(); + } + } + + checkLoadedDepth = 0; + + //Check for DOM ready, and nothing is waiting across contexts. + req.checkReadyState(); + + return undefined; + } + + /** + * Resumes tracing of dependencies and then checks if everything is loaded. + */ + resume = function () { + var manager, map, url, i, p, args, fullName; + + //Any defined modules in the global queue, intake them now. + context.takeGlobalQueue(); + + resumeDepth += 1; + + if ( context.scriptCount <= 0 ) { + //Synchronous envs will push the number below zero with the + //decrement above, be sure to set it back to zero for good measure. + //require() calls that also do not end up loading scripts could + //push the number negative too. + context.scriptCount = 0; + } + + //Make sure any remaining defQueue items get properly processed. + while ( defQueue.length ) { + args = defQueue.shift(); + if ( args[0] === null ) { + return req.onError( makeError( 'mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1] ) ); + } else { + callDefMain( args ); + } + } + + //Skip the resume of paused dependencies + //if current context is in priority wait. + if ( !config.priorityWait || isPriorityDone() ) { + while ( context.paused.length ) { + p = context.paused; + context.pausedCount += p.length; + //Reset paused list + context.paused = []; + + for ( i = 0; (manager = p[i]); i++ ) { + map = manager.map; + url = map.url; + fullName = map.fullName; + + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if ( map.prefix ) { + callPlugin( map.prefix, manager ); + } else { + //Regular dependency. + if ( !urlFetched[url] && !loaded[fullName] ) { + req.load( context, fullName, url ); + + //Mark the URL as fetched, but only if it is + //not an empty: URL, used by the optimizer. + //In that case we need to be sure to call + //load() for each module that is mapped to + //empty: so that dependencies are satisfied + //correctly. + if ( url.indexOf( 'empty:' ) !== 0 ) { + urlFetched[url] = true; + } + } + } + } + + //Move the start time for timeout forward. + context.startTime = (new Date()).getTime(); + context.pausedCount -= p.length; + } + } + + //Only check if loaded when resume depth is 1. It is likely that + //it is only greater than 1 in sync environments where a factory + //function also then calls the callback-style require. In those + //cases, the checkLoaded should not occur until the resume + //depth is back at the top level. + if ( resumeDepth === 1 ) { + checkLoaded(); + } + + resumeDepth -= 1; + + return undefined; + }; + + //Define the context object. Many of these fields are on here + //just to make debugging easier. + context = { + contextName : contextName, + config : config, + defQueue : defQueue, + waiting : waiting, + waitCount : 0, + specified : specified, + loaded : loaded, + urlMap : urlMap, + urlFetched : urlFetched, + scriptCount : 0, + defined : defined, + paused : [], + pausedCount : 0, + plugins : plugins, + needFullExec : needFullExec, + fake : {}, + fullExec : fullExec, + managerCallbacks : managerCallbacks, + makeModuleMap : makeModuleMap, + normalize : normalize, + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure : function ( cfg ) { + var paths, prop, packages, pkgs, packagePaths, requireWait; + + //Make sure the baseUrl ends in a slash. + if ( cfg.baseUrl ) { + if ( cfg.baseUrl.charAt( cfg.baseUrl.length - 1 ) !== "/" ) { + cfg.baseUrl += "/"; + } + } + + //Save off the paths and packages since they require special processing, + //they are additive. + paths = config.paths; + packages = config.packages; + pkgs = config.pkgs; + + //Mix in the config values, favoring the new values over + //existing ones in context.config. + mixin( config, cfg, true ); + + //Adjust paths if necessary. + if ( cfg.paths ) { + for ( prop in cfg.paths ) { + if ( !(prop in empty) ) { + paths[prop] = cfg.paths[prop]; + } + } + config.paths = paths; + } + + packagePaths = cfg.packagePaths; + if ( packagePaths || cfg.packages ) { + //Convert packagePaths into a packages config. + if ( packagePaths ) { + for ( prop in packagePaths ) { + if ( !(prop in empty) ) { + configurePackageDir( pkgs, packagePaths[prop], prop ); + } + } + } + + //Adjust packages if necessary. + if ( cfg.packages ) { + configurePackageDir( pkgs, cfg.packages ); + } + + //Done with modifications, assing packages back to context config + config.pkgs = pkgs; + } + + //If priority loading is in effect, trigger the loads now + if ( cfg.priority ) { + //Hold on to requireWait value, and reset it after done + requireWait = context.requireWait; + + //Allow tracing some require calls to allow the fetching + //of the priority config. + context.requireWait = false; + //But first, call resume to register any defined modules that may + //be in a data-main built file before the priority config + //call. + resume(); + + context.require( cfg.priority ); + + //Trigger a resume right away, for the case when + //the script with the priority load is done as part + //of a data-main call. In that case the normal resume + //call will not happen because the scriptCount will be + //at 1, since the script for data-main is being processed. + resume(); + + //Restore previous state. + context.requireWait = requireWait; + config.priorityWait = cfg.priority; + } + + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if ( cfg.deps || cfg.callback ) { + context.require( cfg.deps || [], cfg.callback ); + } + }, + + requireDefined : function ( moduleName, relModuleMap ) { + return makeModuleMap( moduleName, relModuleMap ).fullName in defined; + }, + + requireSpecified : function ( moduleName, relModuleMap ) { + return makeModuleMap( moduleName, relModuleMap ).fullName in specified; + }, + + require : function ( deps, callback, relModuleMap ) { + var moduleName, fullName, moduleMap; + if ( typeof deps === "string" ) { + if ( isFunction( callback ) ) { + //Invalid call + return req.onError( makeError( "requireargs", "Invalid require call" ) ); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + //In this case deps is the moduleName and callback is + //the relModuleMap + if ( req.get ) { + return req.get( context, deps, callback ); + } + + //Just return the module wanted. In this scenario, the + //second arg (if passed) is just the relModuleMap. + moduleName = deps; + relModuleMap = callback; + + //Normalize module name, if it contains . or .. + moduleMap = makeModuleMap( moduleName, relModuleMap ); + fullName = moduleMap.fullName; + + if ( !(fullName in defined) ) { + return req.onError( makeError( "notloaded", "Module name '" + + moduleMap.fullName + + "' has not been loaded yet for context: " + + contextName ) ); + } + return defined[fullName]; + } + + //Call main but only if there are dependencies or + //a callback to call. + if ( deps && deps.length || callback ) { + main( null, deps, callback, relModuleMap ); + } + + //If the require call does not trigger anything new to load, + //then resume the dependency processing. + if ( !context.requireWait ) { + while ( !context.scriptCount && context.paused.length ) { + resume(); + } + } + return context.require; + }, + + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + takeGlobalQueue : function () { + //Push all the globalDefQueue items into the context's defQueue + if ( globalDefQueue.length ) { + //Array splice in the values since the context code has a + //local var ref to defQueue, so cannot just reassign the one + //on context. + apsp.apply( context.defQueue, + [context.defQueue.length - 1, 0].concat( globalDefQueue ) ); + globalDefQueue = []; + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad : function ( moduleName ) { + var args; + + context.takeGlobalQueue(); + + while ( defQueue.length ) { + args = defQueue.shift(); + + if ( args[0] === null ) { + args[0] = moduleName; + break; + } else if ( args[0] === moduleName ) { + //Found matching define call for this script! + break; + } else { + //Some other named define call, most likely the result + //of a build layer that included many define calls. + callDefMain( args ); + args = null; + } + } + if ( args ) { + callDefMain( args ); + } else { + //A script that does not call define(), so just simulate + //the call for it. Special exception for jQuery dynamic load. + callDefMain( [moduleName, [], + moduleName === "jquery" && typeof jQuery !== "undefined" ? + function () { + return jQuery; + } : null] ); + } + + //Doing this scriptCount decrement branching because sync envs + //need to decrement after resume, otherwise it looks like + //loading is complete after the first dependency is fetched. + //For browsers, it works fine to decrement after, but it means + //the checkLoaded setTimeout 50 ms cost is taken. To avoid + //that cost, decrement beforehand. + if ( req.isAsync ) { + context.scriptCount -= 1; + } + resume(); + if ( !req.isAsync ) { + context.scriptCount -= 1; + } + }, + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl : function ( moduleNamePlusExt, relModuleMap ) { + var index = moduleNamePlusExt.lastIndexOf( "." ), + ext = null; + + if ( index !== -1 ) { + ext = moduleNamePlusExt.substring( index, moduleNamePlusExt.length ); + moduleNamePlusExt = moduleNamePlusExt.substring( 0, index ); + } + + return context.nameToUrl( moduleNamePlusExt, ext, relModuleMap ); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + */ + nameToUrl : function ( moduleName, ext, relModuleMap ) { + var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url, + config = context.config; + + //Normalize module name if have a base relative module name to work from. + moduleName = normalize( moduleName, relModuleMap && relModuleMap.fullName ); + + //If a colon is in the URL, it indicates a protocol is used and it is just + //an URL to a file, or if it starts with a slash or ends with .js, it is just a plain file. + //The slash is important for protocol-less URLs as well as full paths. + if ( req.jsExtRegExp.test( moduleName ) ) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext ? ext : ""); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + pkgs = config.pkgs; + + syms = moduleName.split( "/" ); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for ( i = syms.length; i > 0; i-- ) { + parentModule = syms.slice( 0, i ).join( "/" ); + if ( paths[parentModule] ) { + syms.splice( 0, i, paths[parentModule] ); + break; + } else if ( (pkg = pkgs[parentModule]) ) { + //If module name is just the package name, then looking + //for the main module. + if ( moduleName === pkg.name ) { + pkgPath = pkg.location + '/' + pkg.main; + } else { + pkgPath = pkg.location; + } + syms.splice( 0, i, pkgPath ); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join( "/" ) + (ext || ".js"); + url = (url.charAt( 0 ) === '/' || url.match( /^\w+:/ ) ? "" : config.baseUrl) + url; + } + + return config.urlArgs ? url + + ((url.indexOf( '?' ) === -1 ? '?' : '&') + + config.urlArgs) : url; + } + }; + + //Make these visible on the context so can be called at the very + //end of the file to bootstrap + context.jQueryCheck = jQueryCheck; + context.resume = resume; + + return context; + } + + /** + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. + * + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. + */ + req = requirejs = function ( deps, callback ) { + + //Find the right context, use default + var contextName = defContextName, + context, config; + + // Determine if have config object in the call. + if ( !isArray( deps ) && typeof deps !== "string" ) { + // deps is a config object + config = deps; + if ( isArray( callback ) ) { + // Adjust args if there are dependencies + deps = callback; + callback = arguments[2]; + } else { + deps = []; + } + } + + if ( config && config.context ) { + contextName = config.context; + } + + context = contexts[contextName] || + (contexts[contextName] = newContext( contextName )); + + if ( config ) { + context.configure( config ); + } + + return context.require( deps, callback ); + }; + + /** + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. + */ + req.config = function ( config ) { + return req( config ); + }; + + /** + * Export require as a global, but only if it does not already exist. + */ + if ( !require ) { + require = req; + } + + /** + * Global require.toUrl(), to match global require, mostly useful + * for debugging/work in the global space. + */ + req.toUrl = function ( moduleNamePlusExt ) { + return contexts[defContextName].toUrl( moduleNamePlusExt ); + }; + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + s = req.s = { + contexts : contexts, + //Stores a list of URLs that should not get async script tag treatment. + skipAsync : {} + }; + + req.isAsync = req.isBrowser = isBrowser; + if ( isBrowser ) { + head = s.head = document.getElementsByTagName( "head" )[0]; + //If BASE tag is in play, using appendChild is a problem for IE6. + //When that browser dies, this can be removed. Details in this jQuery bug: + //http://dev.jquery.com/ticket/2709 + baseElement = document.getElementsByTagName( "base" )[0]; + if ( baseElement ) { + head = s.head = baseElement.parentNode; + } + } + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = function ( err ) { + throw err; + }; + + /** + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. + */ + req.load = function ( context, moduleName, url ) { + req.resourcesReady( false ); + + context.scriptCount += 1; + req.attach( url, context, moduleName ); + + //If tracking a jQuery, then make sure its ready callbacks + //are put on hold to prevent its ready callbacks from + //triggering too soon. + if ( context.jQuery && !context.jQueryIncremented ) { + jQueryHoldReady( context.jQuery, true ); + context.jQueryIncremented = true; + } + }; + + function getInteractiveScript() { + var scripts, i, script; + if ( interactiveScript && interactiveScript.readyState === 'interactive' ) { + return interactiveScript; + } + + scripts = document.getElementsByTagName( 'script' ); + for ( i = scripts.length - 1; i > -1 && (script = scripts[i]); i-- ) { + if ( script.readyState === 'interactive' ) { + return (interactiveScript = script); + } + } + + return null; + } + + /** + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. + */ + define = function ( name, deps, callback ) { + var node, context; + + //Allow for anonymous functions + if ( typeof name !== 'string' ) { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if ( !isArray( deps ) ) { + callback = deps; + deps = []; + } + + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if ( !deps.length && isFunction( callback ) ) { + //Remove comments from the callback string, + //look for require calls, and pull them into the dependencies, + //but only if there are function args. + if ( callback.length ) { + callback + .toString() + .replace( commentRegExp, "" ) + .replace( cjsRequireRegExp, function ( match, dep ) { + deps.push( dep ); + } ); + + //May be a CommonJS thing even without require calls, but still + //could use exports, and module. Avoid doing exports and module + //work though if it just needs require. + //REQUIRES the function to expect the CommonJS variables in the + //order listed below. + deps = (callback.length === 1 ? ["require"] : ["require", "exports", "module"]).concat( deps ); + } + } + + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if ( useInteractive ) { + node = currentlyAddingScript || getInteractiveScript(); + if ( node ) { + if ( !name ) { + name = node.getAttribute( "data-requiremodule" ); + } + context = contexts[node.getAttribute( "data-requirecontext" )]; + } + } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + (context ? context.defQueue : globalDefQueue).push( [name, deps, callback] ); + + return undefined; + }; + + define.amd = { + multiversion : true, + plugins : true, + jQuery : true + }; + + /** + * Executes the text. Normally just uses eval, but can be modified + * to use a more environment specific call. + * @param {String} text the text to execute/evaluate. + */ + req.exec = function ( text ) { + return eval( text ); + }; + + /** + * Executes a module callack function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + req.execCb = function ( name, callback, args, exports ) { + return callback.apply( exports, args ); + }; + + + /** + * Adds a node to the DOM. Public function since used by the order plugin. + * This method should not normally be called by outside code. + */ + req.addScriptToDom = function ( node ) { + //For some cache cases in IE 6-8, the script executes before the end + //of the appendChild execution, so to tie an anonymous define + //call to the module name (which is stored on the node), hold on + //to a reference to this node, but clear after the DOM insertion. + currentlyAddingScript = node; + if ( baseElement ) { + head.insertBefore( node, baseElement ); + } else { + head.appendChild( node ); + } + currentlyAddingScript = null; + }; + + /** + * callback for script loads, used to check status of loading. + * + * @param {Event} evt the event from the browser for the script + * that was loaded. + * + * @private + */ + req.onScriptLoad = function ( evt ) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + var node = evt.currentTarget || evt.srcElement, contextName, moduleName, + context; + + if ( evt.type === "load" || (node && readyRegExp.test( node.readyState )) ) { + //Reset interactive script so a script node is not held onto for + //to long. + interactiveScript = null; + + //Pull out the name of the module and the context. + contextName = node.getAttribute( "data-requirecontext" ); + moduleName = node.getAttribute( "data-requiremodule" ); + context = contexts[contextName]; + + contexts[contextName].completeLoad( moduleName ); + + //Clean up script binding. Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if ( node.detachEvent && !isOpera ) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + node.detachEvent( "onreadystatechange", req.onScriptLoad ); + } else { + node.removeEventListener( "load", req.onScriptLoad, false ); + } + } + }; + + /** + * Attaches the script represented by the URL to the current + * environment. Right now only supports browser loading, + * but can be redefined in other environments to do the right thing. + * @param {String} url the url of the script to attach. + * @param {Object} context the context that wants the script. + * @param {moduleName} the name of the module that is associated with the script. + * @param {Function} [callback] optional callback, defaults to require.onScriptLoad + * @param {String} [type] optional type, defaults to text/javascript + * @param {Function} [fetchOnlyFunction] optional function to indicate the script node + * should be set up to fetch the script but do not attach it to the DOM + * so that it can later be attached to execute it. This is a way for the + * order plugin to support ordered loading in IE. Once the script is fetched, + * but not executed, the fetchOnlyFunction will be called. + */ + req.attach = function ( url, context, moduleName, callback, type, fetchOnlyFunction ) { + var node; + if ( isBrowser ) { + //In the browser so use a script tag + callback = callback || req.onScriptLoad; + node = context && context.config && context.config.xhtml ? + document.createElementNS( "http://www.w3.org/1999/xhtml", "html:script" ) : + document.createElement( "script" ); + node.type = type || (context && context.config.scriptType) || + "text/javascript"; + node.charset = "utf-8"; + //Use async so Gecko does not block on executing the script if something + //like a long-polling comet tag is being run first. Gecko likes + //to evaluate scripts in DOM order, even for dynamic scripts. + //It will fetch them async, but only evaluate the contents in DOM + //order, so a long-polling script tag can delay execution of scripts + //after it. But telling Gecko we expect async gets us the behavior + //we want -- execute it whenever it is finished downloading. Only + //Helps Firefox 3.6+ + //Allow some URLs to not be fetched async. Mostly helps the order! + //plugin + node.async = !s.skipAsync[url]; + + if ( context ) { + node.setAttribute( "data-requirecontext", context.contextName ); + } + node.setAttribute( "data-requiremodule", moduleName ); + + //Set up load listener. Test attachEvent first because IE9 has + //a subtle issue in its addEventListener and script onload firings + //that do not match the behavior of all other browsers with + //addEventListener support, which fire the onload event for a + //script right after the script execution. See: + //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution + //UNFORTUNATELY Opera implements attachEvent but does not follow the script + //script execution mode. + if ( node.attachEvent && !isOpera ) { + //Probably IE. IE (at least 6-8) do not fire + //script onload right after executing the script, so + //we cannot tie the anonymous define call to a name. + //However, IE reports the script as being in "interactive" + //readyState at the time of the define call. + useInteractive = true; + + + if ( fetchOnlyFunction ) { + //Need to use old school onreadystate here since + //when the event fires and the node is not attached + //to the DOM, the evt.srcElement is null, so use + //a closure to remember the node. + node.onreadystatechange = function ( evt ) { + //Script loaded but not executed. + //Clear loaded handler, set the real one that + //waits for script execution. + if ( node.readyState === 'loaded' ) { + node.onreadystatechange = null; + node.attachEvent( "onreadystatechange", callback ); + fetchOnlyFunction( node ); + } + }; + } else { + node.attachEvent( "onreadystatechange", callback ); + } + } else { + node.addEventListener( "load", callback, false ); + } + node.src = url; + + //Fetch only means waiting to attach to DOM after loaded. + if ( !fetchOnlyFunction ) { + req.addScriptToDom( node ); + } + + return node; + } else if ( isWebWorker ) { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation that a build has been done so that + //only one script needs to be loaded anyway. This may need to be + //reevaluated if other use cases become common. + importScripts( url ); + + //Account for anonymous modules + context.completeLoad( moduleName ); + } + return null; + }; + + //Look for a data-main script attribute, which could also adjust the baseUrl. + if ( isBrowser ) { + //Figure out baseUrl. Get it from the script tag with require.js in it. + scripts = document.getElementsByTagName( "script" ); + + for ( globalI = scripts.length - 1; globalI > -1 && (script = scripts[globalI]); globalI-- ) { + //Set the "head" where we can append children by + //using the script's parent. + if ( !head ) { + head = script.parentNode; + } + + //Look for a data-main attribute to set main script for the page + //to load. If it is there, the path to data main becomes the + //baseUrl, if it is not already set. + if ( (dataMain = script.getAttribute( 'data-main' )) ) { + if ( !cfg.baseUrl ) { + //Pull off the directory of data-main for use as the + //baseUrl. + src = dataMain.split( '/' ); + mainScript = src.pop(); + subPath = src.length ? src.join( '/' ) + '/' : './'; + + //Set final config. + cfg.baseUrl = subPath; + //Strip off any trailing .js since dataMain is now + //like a module name. + dataMain = mainScript.replace( jsSuffixRegExp, '' ); + } + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat( dataMain ) : [dataMain]; + + break; + } + } + } + + //See if there is nothing waiting across contexts, and if not, trigger + //resourcesReady. + req.checkReadyState = function () { + var contexts = s.contexts, prop; + for ( prop in contexts ) { + if ( !(prop in empty) ) { + if ( contexts[prop].waitCount ) { + return; + } + } + } + req.resourcesReady( true ); + }; + + /** + * Internal function that is triggered whenever all scripts/resources + * have been loaded by the loader. Can be overridden by other, for + * instance the domReady plugin, which wants to know when all resources + * are loaded. + */ + req.resourcesReady = function ( isReady ) { + var contexts, context, prop; + + //First, set the public variable indicating that resources are loading. + req.resourcesDone = isReady; + + if ( req.resourcesDone ) { + //If jQuery with DOM ready delayed, release it now. + contexts = s.contexts; + for ( prop in contexts ) { + if ( !(prop in empty) ) { + context = contexts[prop]; + if ( context.jQueryIncremented ) { + jQueryHoldReady( context.jQuery, false ); + context.jQueryIncremented = false; + } + } + } + } + }; + + //FF < 3.6 readyState fix. Needed so that domReady plugin + //works well in that environment, since require.js is normally + //loaded via an HTML script tag so it will be there before window load, + //where the domReady plugin is more likely to be loaded after window load. + req.pageLoaded = function () { + if ( document.readyState !== "complete" ) { + document.readyState = "complete"; + } + }; + if ( isBrowser ) { + if ( document.addEventListener ) { + if ( !document.readyState ) { + document.readyState = "loading"; + window.addEventListener( "load", req.pageLoaded, false ); + } + } + } + + //Set up default context. If require was a configuration object, use that as base config. + req( cfg ); + + //If modules are built into require.js, then need to make sure dependencies are + //traced. Use a setTimeout in the browser world, to allow all the modules to register + //themselves. In a non-browser env, assume that modules are not built into require.js, + //which seems odd to do on the server. + if ( req.isAsync && typeof setTimeout !== "undefined" ) { + ctx = s.contexts[(cfg.context || defContextName)]; + //Indicate that the script that includes require() is still loading, + //so that require()'d dependencies are not traced until the end of the + //file is parsed (approximated via the setTimeout call). + ctx.requireWait = true; + setTimeout( function () { + ctx.requireWait = false; + + if ( !ctx.scriptCount ) { + ctx.resume(); + } + req.checkReadyState(); + }, 0 ); + } }()); /*! * jQuery JavaScript Library v1.7.2 @@ -2066,6800 +2066,6837 @@ var requirejs, require, define; * * Date: Wed Mar 21 12:46:34 2012 -0700 */ -(function( window, undefined ) { +(function ( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { + var document = window.document, + navigator = window.navigator, + location = window.location; + var jQuery = (function () { // Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, + var jQuery = function ( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, - // Map over the $ in case of overwrite - _$ = window.$, + // Map over the $ in case of overwrite + _$ = window.$, - // A central reference to the root jQuery(document) - rootjQuery, + // A central reference to the root jQuery(document) + rootjQuery, - // A simple way to check for HTML strings or ID strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + // A simple way to check for HTML strings or ID strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - // Matches dashed string for camelizing - rdashAlpha = /-([a-z]|[0-9])/ig, - rmsPrefix = /^-ms-/, + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return ( letter + "" ).toUpperCase(); - }, + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function ( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, - // For matching the engine and version of the browser - browserMatch, + // For matching the engine and version of the browser + browserMatch, - // The deferred used on DOM ready - readyList, + // The deferred used on DOM ready + readyList, - // The ready event handler - DOMContentLoaded, + // The ready event handler + DOMContentLoaded, - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, - // [[Class]] -> type pairs - class2type = {}; + // [[Class]] -> type pairs + class2type = {}; -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; + jQuery.fn = jQuery.prototype = { + constructor : jQuery, + init : function ( selector, context, rootjQuery ) { + var match, elem, ret, doc; - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = quickExpr.exec( selector ); - } - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = ( context ? context.ownerDocument || context : document ); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { return this; } - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt( 0 ) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } + } else { + match = quickExpr.exec( selector ); + } - return jQuery.makeArray( selector, this ); - }, + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { - // Start with an empty selector - selector: "", + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context ? context.ownerDocument || context : document ); - // The current version of jQuery being used - jquery: "1.7.2", + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); - // The default length of a jQuery object is 0 - length: 0, + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, + } else { + selector = [ doc.createElement( ret[1] ) ]; + } - toArray: function() { - return slice.call( this, 0 ); - }, + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = ( ret.cacheable ? jQuery.clone( ret.fragment ) : ret.fragment ).childNodes; + } - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? + return jQuery.merge( this, selector ); - // Return a 'clean' array - this.toArray() : + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); + this.context = document; + this.selector = selector; + return this; + } - } else { - jQuery.merge( ret, elems ); - } + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); - // Add the old object onto the stack (as a reference) - ret.prevObject = this; + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } - ret.context = this.context; + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } - if ( name === "find" ) { - ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } - // Return the newly-formed element set - return ret; - }, + return jQuery.makeArray( selector, this ); + }, - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, + // Start with an empty selector + selector : "", - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); + // The current version of jQuery being used + jquery : "1.7.2", - // Add the callback - readyList.add( fn ); + // The default length of a jQuery object is 0 + length : 0, - return this; - }, + // The number of elements contained in the matched element set + size : function () { + return this.length; + }, - eq: function( i ) { - i = +i; - return i === -1 ? - this.slice( i ) : - this.slice( i, i + 1 ); - }, + toArray : function () { + return slice.call( this, 0 ); + }, - first: function() { - return this.eq( 0 ); - }, + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get : function ( num ) { + return num == null ? - last: function() { - return this.eq( -1 ); - }, + // Return a 'clean' array + this.toArray() : - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack : function ( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); - end: function() { - return this.prevObject || this.constructor(null); - }, + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each : function ( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready : function ( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.add( fn ); + + return this; + }, + + eq : function ( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first : function () { + return this.eq( 0 ); + }, + + last : function () { + return this.eq( -1 ); + }, + + slice : function () { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call( arguments ).join( "," ) ); + }, + + map : function ( callback ) { + return this.pushStack( jQuery.map( this, function ( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + end : function () { + return this.prevObject || this.constructor( null ); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push : push, + sort : [].sort, + splice : [].splice + }; // Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; + jQuery.fn.init.prototype = jQuery.fn; -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; + jQuery.extend = jQuery.fn.extend = function () { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - // Either a released hold or an DOMready/load event and not yet ready - if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; } - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; } - // If there are functions bound, to execute - readyList.fireWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).off( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyList ) { - return; - } - - readyList = jQuery.Callbacks( "once memory" ); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", DOMContentLoaded ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - isWindow: function( obj ) { - return obj != null && obj == obj.window; - }, - - isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - try { - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw new Error( msg ); - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return ( new Function( "return " + data ) )(); - - } - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - parseXML: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - var xml, tmp; - try { - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - } catch( e ) { - xml = undefined; - } - if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && rnotwhite.test( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; } - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type( array ); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array, i ) { - var len; - - if ( array ) { - if ( indexOf ) { - return indexOf.call( array, elem, i ); - } - - len = array.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in array && array[ i ] === elem ) { - return i; - } - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; - - // Go through the array, translating each of the items to their - if ( isArray ) { for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - if ( typeof context === "string" ) { - var tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function( elems, fn, key, value, chainable, emptyGet, pass ) { - var exec, - bulk = key == null, - i = 0, - length = elems.length; - - // Sets many values - if ( key && typeof key === "object" ) { - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); - } - chainable = 1; - - // Sets one value - } else if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = pass === undefined && jQuery.isFunction( value ); - - if ( bulk ) { - // Bulk operations only iterate when executing function values - if ( exec ) { - exec = fn; - fn = function( elem, key, value ) { - return exec.call( jQuery( elem ), value ); - }; - - // Otherwise they run against the entire set - } else { - fn.call( elems, value ); - fn = null; - } - } - - if ( fn ) { - for (; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - } - - chainable = 1; - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - length ? fn( elems[0], key ) : emptyGet; - }, - - now: function() { - return ( new Date() ).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySub( selector, context ) { - return new jQuerySub.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySub, this ); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { - context = jQuerySub( context ); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -return jQuery; - -})(); - - -// String to Object flags format cache -var flagsCache = {}; - -// Convert String-formatted flags into Object-formatted ones and store in cache -function createFlags( flags ) { - var object = flagsCache[ flags ] = {}, - i, length; - flags = flags.split( /\s+/ ); - for ( i = 0, length = flags.length; i < length; i++ ) { - object[ flags[i] ] = true; - } - return object; -} - -/* - * Create a callback list using the following parameters: - * - * flags: an optional list of space-separated flags that will change how - * the callback list behaves - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible flags: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( flags ) { - - // Convert flags from String-formatted to Object-formatted - // (we check in cache first) - flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; - - var // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = [], - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Add one or several callbacks to the list - add = function( args ) { - var i, - length, - elem, - type, - actual; - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - // Inspect recursively - add( elem ); - } else if ( type === "function" ) { - // Add if not in unique mode and callback is not in - if ( !flags.unique || !self.has( elem ) ) { - list.push( elem ); - } - } - } - }, - // Fire callbacks - fire = function( context, args ) { - args = args || []; - memory = !flags.memory || [ context, args ]; - fired = true; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if ( list ) { - if ( !flags.once ) { - if ( stack && stack.length ) { - memory = stack.shift(); - self.fireWith( memory[ 0 ], memory[ 1 ] ); - } - } else if ( memory === true ) { - self.disable(); - } else { - list = []; - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - var length = list.length; - add( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away, unless previous - // firing was halted (stopOnFalse) - } else if ( memory && memory !== true ) { - firingStart = length; - fire( memory[ 0 ], memory[ 1 ] ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - var args = arguments, - argIndex = 0, - argLength = args.length; - for ( ; argIndex < argLength ; argIndex++ ) { - for ( var i = 0; i < list.length; i++ ) { - if ( args[ argIndex ] === list[ i ] ) { - // Handle firingIndex and firingLength - if ( firing ) { - if ( i <= firingLength ) { - firingLength--; - if ( i <= firingIndex ) { - firingIndex--; - } - } - } - // Remove the element - list.splice( i--, 1 ); - // If we have some unicity property then - // we only need to do this once - if ( flags.unique ) { - break; - } - } + // Prevent never-ending loop + if ( target === copy ) { + continue; } - } - } - return this; - }, - // Control if a given callback is in the list - has: function( fn ) { - if ( list ) { - var i = 0, - length = list.length; - for ( ; i < length; i++ ) { - if ( fn === list[ i ] ) { - return true; - } - } - } - return false; - }, - // Remove all callbacks from the list - empty: function() { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory || memory === true ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( stack ) { - if ( firing ) { - if ( !flags.once ) { - stack.push( [ context, args ] ); - } - } else if ( !( flags.once && memory ) ) { - fire( context, args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - return self; -}; + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || (copyIsArray = jQuery.isArray( copy )) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray( src ) ? src : []; - - - -var // Static reference to slice - sliceDeferred = [].slice; - -jQuery.extend({ - - Deferred: function( func ) { - var doneList = jQuery.Callbacks( "once memory" ), - failList = jQuery.Callbacks( "once memory" ), - progressList = jQuery.Callbacks( "memory" ), - state = "pending", - lists = { - resolve: doneList, - reject: failList, - notify: progressList - }, - promise = { - done: doneList.add, - fail: failList.add, - progress: progressList.add, - - state: function() { - return state; - }, - - // Deprecated - isResolved: doneList.fired, - isRejected: failList.fired, - - then: function( doneCallbacks, failCallbacks, progressCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); - return this; - }, - always: function() { - deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); - return this; - }, - pipe: function( fnDone, fnFail, fnProgress ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ], - progress: [ fnProgress, "notify" ] - }, function( handler, data ) { - var fn = data[ 0 ], - action = data[ 1 ], - returned; - if ( jQuery.isFunction( fn ) ) { - deferred[ handler ](function() { - returned = fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); - } - }); } else { - deferred[ handler ]( newDefer[ action ] ); + clone = src && jQuery.isPlainObject( src ) ? src : {}; } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - obj = promise; - } else { - for ( var key in promise ) { - obj[ key ] = promise[ key ]; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; } } - return obj; - } - }, - deferred = promise.promise({}), - key; - - for ( key in lists ) { - deferred[ key ] = lists[ key ].fire; - deferred[ key + "With" ] = lists[ key ].fireWith; - } - - // Handle state - deferred.done( function() { - state = "resolved"; - }, failList.disable, progressList.lock ).fail( function() { - state = "rejected"; - }, doneList.disable, progressList.lock ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( firstParam ) { - var args = sliceDeferred.call( arguments, 0 ), - i = 0, - length = args.length, - pValues = new Array( length ), - count = length, - pCount = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(), - promise = deferred.promise(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.resolveWith( deferred, args ); - } - }; - } - function progressFunc( i ) { - return function( value ) { - pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - deferred.notifyWith( promise, pValues ); - }; - } - if ( length > 1 ) { - for ( ; i < length; i++ ) { - if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); - } else { - --count; } } - if ( !count ) { - deferred.resolveWith( deferred, args ); - } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); - } - return promise; - } -}); - - - -jQuery.support = (function() { - - var support, - all, - a, - select, - opt, - input, - fragment, - tds, - events, - eventName, - i, - isSupported, - div = document.createElement( "div" ), - documentElement = document.documentElement; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
    a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute("href") === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Tests for enctype support on a form(#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true, - pixelMargin: true - }; - - // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead - jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains its value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.lastChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - fragment.removeChild( input ); - fragment.appendChild( div ); - - // Technique from Juriy Zaytsev - // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for ( i in { - submit: 1, - change: 1, - focusin: 1 - }) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - fragment.removeChild( div ); - - // Null elements to avoid leaks in IE - fragment = select = opt = div = input = null; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, outer, inner, table, td, offsetSupport, - marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, - paddingMarginBorderVisibility, paddingMarginBorder, - body = document.getElementsByTagName("body")[0]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - conMarginTop = 1; - paddingMarginBorder = "padding:0;margin:0;border:"; - positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; - paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; - style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; - html = "
    " + - "" + - "
    "; - - container = document.createElement("div"); - container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; - body.insertBefore( container, body.firstChild ); - - // Construct the test element - div = document.createElement("div"); - container.appendChild( div ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - div.innerHTML = "
    t
    "; - tds = div.getElementsByTagName( "td" ); - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE <= 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( window.getComputedStyle ) { - div.innerHTML = ""; - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.style.width = "2px"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - if ( typeof div.style.zoom !== "undefined" ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.innerHTML = ""; - div.style.width = div.style.padding = "1px"; - div.style.border = 0; - div.style.overflow = "hidden"; - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = "block"; - div.style.overflow = "visible"; - div.innerHTML = "
    "; - support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - } - - div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; - div.innerHTML = html; - - outer = div.firstChild; - inner = outer.firstChild; - td = outer.nextSibling.firstChild.firstChild; - - offsetSupport = { - doesNotAddBorder: ( inner.offsetTop !== 5 ), - doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) + // Return the modified object + return target; }; - inner.style.position = "fixed"; - inner.style.top = "20px"; + jQuery.extend( { + noConflict : function ( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } - // safari subtracts parent border width here which is 5px - offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); - inner.style.position = inner.style.top = ""; + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } - outer.style.overflow = "hidden"; - outer.style.position = "relative"; + return jQuery; + }, - offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); - offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + // Is the DOM ready to be used? Set to true once it occurs. + isReady : false, - if ( window.getComputedStyle ) { - div.style.marginTop = "1%"; - support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; - } + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait : 1, - if ( typeof container.style.zoom !== "undefined" ) { - container.style.zoom = 1; - } + // Hold (or release) the ready event + holdReady : function ( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, - body.removeChild( container ); - marginDiv = div = container = null; + // Handle when the DOM is ready + ready : function ( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } - jQuery.extend( support, offsetSupport ); - }); + // Remember that the DOM is ready + jQuery.isReady = true; - return support; -})(); + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + // If there are functions bound, to execute + readyList.fireWith( document, [ jQuery ] ); - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var privateCache, thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, - isEvents = name === "events"; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ internalKey ] = id = ++jQuery.uuid; - } else { - id = internalKey; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); - } - } - - privateCache = thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Users should not attempt to inspect the internal events object using jQuery.data, - // it is undocumented and subject to change. But does anyone listen? No. - if ( isEvents && !thisCache[ name ] ) { - return privateCache.events; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; - - // Test for null|undefined property data - if ( ret == null ) { - - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; - } - } else { - ret = thisCache; - } - - return ret; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, i, l, - - // Reference to internal data cache key - internalKey = jQuery.expando, - - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ internalKey ] : internalKey; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - - thisCache = pvt ? cache[ id ] : cache[ id ].data; - - if ( thisCache ) { - - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split( " " ); - } + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).off( "ready" ); } } + }, - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + bindReady : function () { + if ( readyList ) { return; } - } - } - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; + readyList = jQuery.Callbacks( "once memory" ); - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - // Ensure that `cache` is not a window object #10080 - if ( jQuery.support.deleteExpando || !cache.setInterval ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - // We destroyed the cache and need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ internalKey ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( internalKey ); - } else { - elem[ internalKey ] = null; - } - } - }, + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var parts, part, attr, name, l, - elem = this[0], - i = 0, - data = null; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); - - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - attr = elem.attributes; - for ( l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( elem, name, data[ name ] ); - } + try { + toplevel = window.frameElement == null; + } catch ( e ) { } - jQuery._data( elem, "parsedAttrs", true ); - } - } - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - parts = key.split( ".", 2 ); - parts[1] = parts[1] ? "." + parts[1] : ""; - part = parts[1] + "!"; - - return jQuery.access( this, function( value ) { - - if ( value === undefined ) { - data = this.triggerHandler( "getData" + part, [ parts[0] ] ); - - // Try to fetch any internally stored data first - if ( data === undefined && elem ) { - data = jQuery.data( elem, key ); - data = dataAttr( elem, key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - } - - parts[1] = value; - this.each(function() { - var self = jQuery( this ); - - self.triggerHandler( "setData" + part, parts ); - jQuery.data( this, key, value ); - self.triggerHandler( "changeData" + part, parts ); - }); - }, null, value, arguments.length > 1, null, false ); - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - jQuery.isNumeric( data ) ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery._data( elem, deferDataKey ); - if ( defer && - ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && - ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery._data( elem, queueDataKey ) && - !jQuery._data( elem, markDataKey ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.fire(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = ( type || "fx" ) + "mark"; - jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); - if ( count ) { - jQuery._data( elem, key, count ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - var q; - if ( elem ) { - type = ( type || "fx" ) + "queue"; - q = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - hooks = {}; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - jQuery._data( elem, type + ".run", hooks ); - fn.call( elem, function() { - jQuery.dequeue( elem, type ); - }, hooks ); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue " + type + ".run", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { - count++; - tmp.add( resolve ); - } - } - resolve(); - return defer.promise( object ); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - nodeHook, boolHook, fixSpecified; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); } } - } - } + }, - return this; - }, + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction : function ( obj ) { + return jQuery.type( obj ) === "function"; + }, - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; + isArray : Array.isArray || function ( obj ) { + return jQuery.type( obj ) === "array"; + }, - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } + isWindow : function ( obj ) { + return obj != null && obj == obj.window; + }, - if ( (value && typeof value === "string") || value === undefined ) { - classNames = ( value || "" ).split( rspace ); + isNumeric : function ( obj ) { + return !isNaN( parseFloat( obj ) ) && isFinite( obj ); + }, - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; + type : function ( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call( obj ) ] || "object"; + }, - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); + isPlainObject : function ( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } - } else { - elem.className = ""; + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call( obj, "constructor" ) && + !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { + return false; } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; } - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) { } - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, + return key === undefined || hasOwn.call( obj, key ); + }, - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + isEmptyObject : function ( obj ) { + for ( var name in obj ) { + return false; + } return true; - } - } + }, - return false; - }, + error : function ( msg ) { + throw new Error( msg ); + }, - val: function( value ) { - var hooks, ret, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { + parseJSON : function ( data ) { + if ( typeof data !== "string" || !data ) { return null; } - // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; - for ( ; i < max; i++ ) { - option = options[ i ]; + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); } - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "" ) ) ) { - return values; + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); }, - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; + // Cross-browser xml parsing + parseXML : function ( data ) { + if ( typeof data !== "string" || !data ) { + return null; } - return values; - } - } - }, + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data, "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch ( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, + noop : function () { + }, - attr: function( elem, name, value, pass ) { - var ret, hooks, notxml, - nType = elem.nodeType; + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval : function ( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function ( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase : function ( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } + nodeName : function ( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } + // args is for internal usage only + each : function ( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } - if ( value !== undefined ) { + return object; + }, - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; + // Use native String.trim function wherever possible + trim : trim ? + function ( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function ( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray : function ( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; + }, - } else { - elem.setAttribute( name, "" + value ); - return value; + inArray : function ( elem, array, i ) { + var len; + + if ( array ) { + if ( indexOf ) { + return indexOf.call( array, elem, i ); + } + + len = array.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in array && array[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge : function ( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep : function ( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map : function ( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length - 1 ] ) || length === 0 || jQuery.isArray( elems ) ); + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid : 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy : function ( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function () { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access : function ( elems, fn, key, value, chainable, emptyGet, pass ) { + var exec, + bulk = key == null, + i = 0, + length = elems.length; + + // Sets many values + if ( key && typeof key === "object" ) { + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); + } + chainable = 1; + + // Sets one value + } else if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = pass === undefined && jQuery.isFunction( value ); + + if ( bulk ) { + // Bulk operations only iterate when executing function values + if ( exec ) { + exec = fn; + fn = function ( elem, key, value ) { + return exec.call( jQuery( elem ), value ); + }; + + // Otherwise they run against the entire set + } else { + fn.call( elems, value ); + fn = null; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + } + + chainable = 1; + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now : function () { + return ( new Date() ).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch : function ( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf( "compatible" ) < 0 && rmozilla.exec( ua ) || + []; + + return { browser : match[1] || "", version : match[2] || "0" }; + }, + + sub : function () { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub( document ); + return jQuerySub; + }, + + browser : {} + } ); + +// Populate the class2type map + jQuery.each( "Boolean Number String Function Array Date RegExp Object".split( " " ), function ( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); + } ); + + browserMatch = jQuery.uaMatch( userAgent ); + if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; + } + +// Deprecated, use jQuery.browser.webkit instead + if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; + } + +// IE doesn't match non-breaking spaces with \s + if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; + } + +// All jQuery objects should point back to these + rootjQuery = jQuery( document ); + +// Cleanup functions for the document ready method + if ( document.addEventListener ) { + DOMContentLoaded = function () { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + + } else if ( document.attachEvent ) { + DOMContentLoaded = function () { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; + } + +// The DOM ready check for Internet Explorer + function doScrollCheck() { + if ( jQuery.isReady ) { + return; } - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll( "left" ); + } catch ( e ) { + setTimeout( doScrollCheck, 1 ); + return; + } - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; + // and execute any waiting functions + jQuery.ready(); } - }, - removeAttr: function( elem, value ) { - var propName, attrNames, name, l, isBool, - i = 0; + return jQuery; - if ( value && elem.nodeType === 1 ) { - attrNames = value.toLowerCase().split( rspace ); - l = attrNames.length; + })(); - for ( ; i < l; i++ ) { - name = attrNames[ i ]; - if ( name ) { - propName = jQuery.propFix[ name ] || name; - isBool = rboolean.test( name ); +// String to Object flags format cache + var flagsCache = {}; - // See #9699 for explanation of this approach (setting first, then removal) - // Do not do this for boolean attributes (see #10870) - if ( !isBool ) { - jQuery.attr( elem, name, "" ); +// Convert String-formatted flags into Object-formatted ones and store in cache + function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; + } + + /* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ + jQuery.Callbacks = function ( flags ) { + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Add one or several callbacks to the list + add = function ( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // Add if not in unique mode and callback is not in + if ( !flags.unique || !self.has( elem ) ) { + list.push( elem ); + } } - elem.removeAttribute( getSetAttribute ? name : propName ); + } + }, + // Fire callbacks + fire = function ( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + fired = true; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + self.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + self.disable(); + } else { + list = []; + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add : function () { + if ( list ) { + var length = list.length; + add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { + firingStart = length; + fire( memory[ 0 ], memory[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove : function () { + if ( list ) { + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } + } + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique ) { + break; + } + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has : function ( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty : function () { + list = []; + return this; + }, + // Have the list do nothing anymore + disable : function () { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled : function () { + return !list; + }, + // Lock the list in its current state + lock : function () { + stack = undefined; + if ( !memory || memory === true ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked : function () { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith : function ( context, args ) { + if ( stack ) { + if ( firing ) { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { + fire( context, args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire : function () { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired : function () { + return !!fired; + } + }; - // Set corresponding property to false for boolean attributes - if ( isBool && propName in elem ) { - elem[ propName ] = false; + return self; + }; + + + var // Static reference to slice + sliceDeferred = [].slice; + + jQuery.extend( { + + Deferred : function ( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + state = "pending", + lists = { + resolve : doneList, + reject : failList, + notify : progressList + }, + promise = { + done : doneList.add, + fail : failList.add, + progress : progressList.add, + + state : function () { + return state; + }, + + // Deprecated + isResolved : doneList.fired, + isRejected : failList.fired, + + then : function ( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always : function () { + deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); + return this; + }, + pipe : function ( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred( + function ( newDefer ) { + jQuery.each( { + done : [ fnDone, "resolve" ], + fail : [ fnFail, "reject" ], + progress : [ fnProgress, "notify" ] + }, function ( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ]( function () { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + } ); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + } ); + } ).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise : function ( obj ) { + if ( obj == null ) { + obj = promise; + } else { + for ( var key in promise ) { + obj[ key ] = promise[ key ]; + } + } + return obj; + } + }, + deferred = promise.promise( {} ), + key; + + for ( key in lists ) { + deferred[ key ] = lists[ key ].fire; + deferred[ key + "With" ] = lists[ key ].fireWith; + } + + // Handle state + deferred.done( + function () { + state = "resolved"; + }, failList.disable, progressList.lock ).fail( function () { + state = "rejected"; + }, doneList.disable, progressList.lock ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when : function ( firstParam ) { + var args = sliceDeferred.call( arguments, 0 ), + i = 0, + length = args.length, + pValues = new Array( length ), + count = length, + pCount = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(), + promise = deferred.promise(); + + function resolveFunc( i ) { + return function ( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( deferred, args ); + } + }; + } + + function progressFunc( i ) { + return function ( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + deferred.notifyWith( promise, pValues ); + }; + } + + if ( length > 1 ) { + for ( ; i < length; i++ ) { + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc( i ), deferred.reject, progressFunc( i ) ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return promise; + } + } ); + + + jQuery.support = (function () { + + var support, + all, + a, + select, + opt, + input, + fragment, + tds, + events, + eventName, + i, + isSupported, + div = document.createElement( "div" ), + documentElement = document.documentElement; + + // Preliminary tests + div.setAttribute( "className", "t" ); + div.innerHTML = "
    a"; + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement( "option" ) ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace : ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody : !div.getElementsByTagName( "tbody" ).length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize : !!div.getElementsByTagName( "link" ).length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style : /top/.test( a.getAttribute( "style" ) ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized : ( a.getAttribute( "href" ) === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity : /^0.55/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat : !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn : ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected : opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute : div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype : !!document.createElement( "form" ).enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone : document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>", + + // Will be defined later + submitBubbles : true, + changeBubbles : true, + focusinBubbles : false, + deleteExpando : true, + noCloneEvent : true, + inlineBlockNeedsLayout : false, + shrinkWrapBlocks : false, + reliableMarginRight : true, + pixelMargin : true + }; + + // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead + jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch ( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function () { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + } ); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement( "input" ); + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + input.setAttribute( "checked", "checked" ); + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for ( i in { + submit : 1, + change : 1, + focusin : 1 + } ) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + fragment.removeChild( div ); + + // Null elements to avoid leaks in IE + fragment = select = opt = div = input = null; + + // Run tests that need a body at doc ready + jQuery( function () { + var container, outer, inner, table, td, offsetSupport, + marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, + paddingMarginBorderVisibility, paddingMarginBorder, + body = document.getElementsByTagName( "body" )[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + conMarginTop = 1; + paddingMarginBorder = "padding:0;margin:0;border:"; + positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; + paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; + style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; + html = "
    " + + "" + + "
    "; + + container = document.createElement( "div" ); + container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement( "div" ); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
    t
    "; + tds = div.getElementsByTagName( "td" ); + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( window.getComputedStyle ) { + div.innerHTML = ""; + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.style.width = "2px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight : 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.innerHTML = ""; + div.style.width = div.style.padding = "1px"; + div.style.border = 0; + div.style.overflow = "hidden"; + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = "block"; + div.style.overflow = "visible"; + div.innerHTML = "
    "; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + } + + div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; + div.innerHTML = html; + + outer = div.firstChild; + inner = outer.firstChild; + td = outer.nextSibling.firstChild.firstChild; + + offsetSupport = { + doesNotAddBorder : ( inner.offsetTop !== 5 ), + doesAddBorderForTableAndCells : ( td.offsetTop === 5 ) + }; + + inner.style.position = "fixed"; + inner.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); + inner.style.position = inner.style.top = ""; + + outer.style.overflow = "hidden"; + outer.style.position = "relative"; + + offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); + offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + + if ( window.getComputedStyle ) { + div.style.marginTop = "1%"; + support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop : 0 } ).marginTop !== "1%"; + } + + if ( typeof container.style.zoom !== "undefined" ) { + container.style.zoom = 1; + } + + body.removeChild( container ); + marginDiv = div = container = null; + + jQuery.extend( support, offsetSupport ); + } ); + + return support; + })(); + + + var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + + jQuery.extend( { + cache : {}, + + // Please use with caution + uuid : 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando : "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData : { + "embed" : true, + // Ban all objects except for Flash (which handle expandos) + "object" : "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet" : true + }, + + hasData : function ( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data : function ( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var privateCache, thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, + isEvents = name === "events"; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = ++jQuery.uuid; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + privateCache = thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Users should not attempt to inspect the internal events object using jQuery.data, + // it is undocumented and subject to change. But does anyone listen? No. + if ( isEvents && !thisCache[ name ] ) { + return privateCache.events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData : function ( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ internalKey ] : internalKey; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; } } } - } - }, - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the cache and need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ internalKey ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + } else { + elem[ internalKey ] = null; } } }, - // Use the value property for back compat - // Use the nodeHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.get( elem, name ); + + // For internal use only. + _data : function ( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData : function ( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute( "classid" ) !== match); } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; } + + return true; } - }, + } ); - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, + jQuery.fn.extend( { + data : function ( key, value ) { + var parts, part, attr, name, l, + elem = this[0], + i = 0, + data = null; - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attr = elem.attributes; + for ( l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring( 5 ) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function () { + jQuery.data( this, key ); + } ); + } + + parts = key.split( ".", 2 ); + parts[1] = parts[1] ? "." + parts[1] : ""; + part = parts[1] + "!"; + + return jQuery.access( this, function ( value ) { + + if ( value === undefined ) { + data = this.triggerHandler( "getData" + part, [ parts[0] ] ); + + // Try to fetch any internally stored data first + if ( data === undefined && elem ) { + data = jQuery.data( elem, key ); + data = dataAttr( elem, key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } + + parts[1] = value; + this.each( function () { + var self = jQuery( this ); + + self.triggerHandler( "setData" + part, parts ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + part, parts ); + } ); + }, null, value, arguments.length > 1, null, false ); + }, + + removeData : function ( key ) { + return this.each( function () { + jQuery.removeData( this, key ); + } ); } + } ); - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + jQuery.isNumeric( data ) ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch ( e ) { + } + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); } else { - return ( elem[ name ] = value ); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - return elem[ name ]; + data = undefined; } } - }, - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); + return data; + } - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; +// checks a cache object for emptiness + function isEmptyDataObject( obj ) { + for ( var name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; + } + + + function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery._data( elem, deferDataKey ); + if ( defer && + ( src === "queue" || !jQuery._data( elem, queueDataKey ) ) && + ( src === "mark" || !jQuery._data( elem, markDataKey ) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function () { + if ( !jQuery._data( elem, queueDataKey ) && + !jQuery._data( elem, markDataKey ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.fire(); + } + }, 0 ); } } -}); + + jQuery.extend( { + + _mark : function ( elem, type ) { + if ( elem ) { + type = ( type || "fx" ) + "mark"; + jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); + } + }, + + _unmark : function ( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); + if ( count ) { + jQuery._data( elem, key, count ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue : function ( elem, type, data ) { + var q; + if ( elem ) { + type = ( type || "fx" ) + "queue"; + q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray( data ) ) { + q = jQuery._data( elem, type, jQuery.makeArray( data ) ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue : function ( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + hooks = {}; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + jQuery._data( elem, type + ".run", hooks ); + fn.call( elem, function () { + jQuery.dequeue( elem, type ); + }, hooks ); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue " + type + ".run", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } + } ); + + jQuery.fn.extend( { + queue : function ( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each( function () { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue : function ( type ) { + return this.each( function () { + jQuery.dequeue( this, type ); + } ); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay : function ( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function ( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function () { + clearTimeout( timeout ); + }; + } ); + }, + clearQueue : function ( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise : function ( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + + while ( i-- ) { + if ( ( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) ) ) { + count++; + tmp.add( resolve ); + } + } + resolve(); + return defer.promise( object ); + } + } ); + + + var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + nodeHook, boolHook, fixSpecified; + + jQuery.fn.extend( { + attr : function ( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr : function ( name ) { + return this.each( function () { + jQuery.removeAttr( this, name ); + } ); + }, + + prop : function ( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp : function ( name ) { + name = jQuery.propFix[ name ] || name; + return this.each( function () { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch ( e ) { + } + } ); + }, + + addClass : function ( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each( function ( j ) { + jQuery( this ).addClass( value.call( this, j, this.className ) ); + } ); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass : function ( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each( function ( j ) { + jQuery( this ).removeClass( value.call( this, j, this.className ) ); + } ); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = ( value || "" ).split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace( " " + classNames[ c ] + " ", " " ); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass : function ( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each( function ( i ) { + jQuery( this ).toggleClass( value.call( this, i, this.className, stateVal ), stateVal ); + } ); + } + + return this.each( function () { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + } ); + }, + + hasClass : function ( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace( rclass, " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val : function ( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace( rreturn, "" ) : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each( function ( i ) { + var self = jQuery( this ), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map( val, function ( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } + } ); + + jQuery.extend( { + valHooks : { + option : { + get : function ( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select : { + get : function ( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set : function ( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery( elem ).find( "option" ).each( function () { + this.selected = jQuery.inArray( jQuery( this ).val(), values ) >= 0; + } ); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn : { + val : true, + css : true, + html : true, + text : true, + data : true, + width : true, + height : true, + offset : true + }, + + attr : function ( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr : function ( elem, value ) { + var propName, attrNames, name, l, isBool, + i = 0; + + if ( value && elem.nodeType === 1 ) { + attrNames = value.toLowerCase().split( rspace ); + l = attrNames.length; + + for ( ; i < l; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + isBool = rboolean.test( name ); + + // See #9699 for explanation of this approach (setting first, then removal) + // Do not do this for boolean attributes (see #10870) + if ( !isBool ) { + jQuery.attr( elem, name, "" ); + } + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( isBool && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks : { + type : { + set : function ( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value : { + get : function ( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set : function ( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix : { + tabindex : "tabIndex", + readonly : "readOnly", + "for" : "htmlFor", + "class" : "className", + maxlength : "maxLength", + cellspacing : "cellSpacing", + cellpadding : "cellPadding", + rowspan : "rowSpan", + colspan : "colSpan", + usemap : "useMap", + frameborder : "frameBorder", + contenteditable : "contentEditable" + }, + + prop : function ( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks : { + tabIndex : { + get : function ( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode( "tabindex" ); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } + } ); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) -jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - // Fall back to attribute presence where some booleans are not supported - var attrNode, - property = jQuery.prop( elem, name ); - return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } + boolHook = { + get : function ( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode( name ) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set : function ( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } - elem.setAttribute( name, name.toLowerCase() ); + elem.setAttribute( name, name.toLowerCase() ); + } + return name; } - return name; - } -}; + }; // IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { + if ( !getSetAttribute ) { - fixSpecified = { - name: true, - id: true, - coords: true - }; + fixSpecified = { + name : true, + id : true, + coords : true + }; - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - ret = document.createAttribute( name ); - elem.setAttributeNode( ret ); - } - return ( ret.nodeValue = value + "" ); - } - }; - - // Apply the nodeHook to tabindex - jQuery.attrHooks.tabindex.set = nodeHook.set; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get : function ( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? + ret.nodeValue : + undefined; + }, + set : function ( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); } + return ( ret.nodeValue = value + "" ); } - }); - }); + }; - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - if ( value === "" ) { - value = "false"; + // Apply the nodeHook to tabindex + jQuery.attrHooks.tabindex.set = nodeHook.set; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each( [ "width", "height" ], function ( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set : function ( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + } ); + } ); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get : nodeHook.get, + set : function ( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); } - nodeHook.set( elem, value, name ); - } - }; -} + }; + } // Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} + if ( !jQuery.support.hrefNormalized ) { + jQuery.each( [ "href", "src", "width", "height" ], function ( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get : function ( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + } ); + } ); + } -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = "" + value ); - } - }; -} + if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get : function ( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set : function ( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; + } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; + if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get : function ( elem ) { + var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; + if ( parent ) { + parent.selectedIndex; - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } } + return null; } - return null; - } - }); -} + } ); + } // IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} + if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; + } // Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }); -}); - - - - -var rformElems = /^(?:textarea|input|select)$/i, - rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, - rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, - quickParse = function( selector ) { - var quick = rquickIs.exec( selector ); - if ( quick ) { - // 0 1 2 3 - // [ _, tag, id, class ] - quick[1] = ( quick[1] || "" ).toLowerCase(); - quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); - } - return quick; - }, - quickIs = function( elem, m ) { - var attrs = elem.attributes || {}; - return ( - (!m[1] || elem.nodeName.toLowerCase() === m[1]) && - (!m[2] || (attrs.id || {}).value === m[2]) && - (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) - ); - }, - hoverHack = function( events ) { - return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); - }; - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - add: function( elem, types, handler, data, selector ) { - - var elemData, eventHandle, events, - t, tns, type, namespaces, handleObj, - handleObjIn, quick, handlers, special; - - // Don't attach events to noData or text/comment nodes (allow plain objects tho) - if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - events = elemData.events; - if ( !events ) { - elemData.events = events = {}; - } - eventHandle = elemData.handle; - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; + if ( !jQuery.support.checkOn ) { + jQuery.each( [ "radio", "checkbox" ], function () { + jQuery.valHooks[ this ] = { + get : function ( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + } }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } + } ); + } + jQuery.each( [ "radio", "checkbox" ], function () { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set : function ( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) >= 0 ); + } + } + } ); + } ); - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = jQuery.trim( hoverHack(types) ).split( " " ); - for ( t = 0; t < types.length; t++ ) { - tns = rtypenamespace.exec( types[t] ) || []; - type = tns[1]; - namespaces = ( tns[2] || "" ).split( "." ).sort(); + var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, + rhoverHack = /(?:^|\s)hover(\.\S+)?\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, + quickParse = function ( selector ) { + var quick = rquickIs.exec( selector ); + if ( quick ) { + // 0 1 2 3 + // [ _, tag, id, class ] + quick[1] = ( quick[1] || "" ).toLowerCase(); + quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); + } + return quick; + }, + quickIs = function ( elem, m ) { + var attrs = elem.attributes || {}; + return ( + (!m[1] || elem.nodeName.toLowerCase() === m[1]) && + (!m[2] || (attrs.id || {}).value === m[2]) && + (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) + ); + }, + hoverHack = function ( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; - // If event changes its type, use the special event handlers for the changed type + /* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ + jQuery.event = { + + add : function ( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, quick, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function ( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack( types ) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type : type, + origType : tns[1], + data : data, + handler : handler, + guid : handler.guid, + selector : selector, + quick : selector && quickParse( selector ), + namespace : namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global : {}, + + // Detach an event or set of events from an element + remove : function ( elem, types, handler, selector, mappedTypes ) { + + var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + t, tns, type, origType, namespaces, origCount, + j, events, special, handle, eventType, handleObj; + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp( "(^|\\.)" + namespaces.split( "." ).sort().join( "\\.(?:.*\\.)?" ) + "(\\.|$)" ) : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, [ "events", "handle" ], true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent : { + "getData" : true, + "setData" : true, + "changeData" : true + }, + + trigger : function ( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var type = event.type || event, + namespaces = [], + cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice( 0, -1 ); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.)?" ) + "(\\.|$)" ) : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [ + [ elem, special.bindType || type ] + ]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + old = null; + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( [ cur, bubbleType ] ); + old = cur; + } - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: tns[1], - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - quick: selector && quickParse( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old && old === elem.ownerDocument ) { + eventPath.push( [ old.defaultView || old.parentWindow || window, bubbleType ] ); + } + } - // Init the event handler queue if we're the first - handlers = events[ type ]; - if ( !handlers ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); + cur = eventPath[i][0]; + event.type = eventPath[i][1]; - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } } } } - if ( special.add ) { - special.add.call( elem, handleObj ); + return event.result; + }, - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; + dispatch : function ( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments, 0 ), + run_all = !event.exclusive && !event.namespace, + special = jQuery.event.special[ event.type ] || {}, + handlerQueue = [], + i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers that should run if there are delegated events + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !(event.button && event.type === "click") ) { + + // Pregenerate a single jQuery object for reuse with .is() + jqcur = jQuery( this ); + jqcur.context = this.ownerDocument || this; + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + + // Don't process events on disabled elements (#6911, #8165) + if ( cur.disabled !== true ) { + selMatch = {}; + matches = []; + jqcur[0] = cur; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = ( + handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) + ); + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push( { elem : cur, matches : matches } ); + } + } } } - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push( { elem : this, matches : handlers.slice( delegateCount ) } ); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props : "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split( " " ), + + fixHooks : {}, + + keyHooks : { + props : "char charCode key keyCode".split( " " ), + filter : function ( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks : { + props : "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split( " " ), + filter : function ( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix : function ( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) + if ( event.metaKey === undefined ) { + event.metaKey = event.ctrlKey; + } + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + special : { + ready : { + // Make sure the ready event is setup + setup : jQuery.bindReady + }, + + load : { + // Prevent triggered image.load events from bubbling to window.load + noBubble : true + }, + + focus : { + delegateType : "focusin" + }, + blur : { + delegateType : "focusout" + }, + + beforeunload : { + setup : function ( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown : function ( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate : function ( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type : type, + isSimulated : true, + originalEvent : {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); } else { - handlers.push( handleObj ); + jQuery.event.dispatch.call( elem, e ); } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - t, tns, type, origType, namespaces, origCount, - j, events, special, handle, eventType, handleObj; - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = jQuery.trim( hoverHack( types || "" ) ).split(" "); - for ( t = 0; t < types.length; t++ ) { - tns = rtypenamespace.exec( types[t] ) || []; - type = origType = tns[1]; - namespaces = tns[2]; - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector? special.delegateType : special.bindType ) || type; - eventType = events[ type ] || []; - origCount = eventType.length; - namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - - // Remove matching events - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !namespaces || namespaces.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - eventType.splice( j--, 1 ); - - if ( handleObj.selector ) { - eventType.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( eventType.length === 0 && origCount !== eventType.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery.removeData( elem, [ "events", "handle" ], true ); - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Don't do events on text and comment nodes - if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { - return; - } - - // Event object or event type - var type = event.type || event, - namespaces = [], - cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "!" ) >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf( "." ) >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.isTrigger = true; - event.exclusive = exclusive; - event.namespace = namespaces.join( "." ); - event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; - - // Handle a global trigger - if ( !elem ) { - - // TODO: Stop taunting the data cache; remove global events and always attach to document - cache = jQuery.cache; - for ( i in cache ) { - if ( cache[ i ].events && cache[ i ].events[ type ] ) { - jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); - } - } - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - eventPath = [[ elem, special.bindType || type ]]; - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; - old = null; - for ( ; cur; cur = cur.parentNode ) { - eventPath.push([ cur, bubbleType ]); - old = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( old && old === elem.ownerDocument ) { - eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); - } - } - - // Fire handlers on the event path - for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { - - cur = eventPath[i][0]; - event.type = eventPath[i][1]; - - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - // Note that this is a bare JS function and not a jQuery handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + if ( e.isDefaultPrevented() ) { event.preventDefault(); } } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - // IE<9 dies on focus/blur to hidden element (#1486) - if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( old ) { - elem[ ontype ] = old; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event || window.event ); - - var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), - delegateCount = handlers.delegateCount, - args = [].slice.call( arguments, 0 ), - run_all = !event.exclusive && !event.namespace, - special = jQuery.event.special[ event.type ] || {}, - handlerQueue = [], - i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers that should run if there are delegated events - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && !(event.button && event.type === "click") ) { - - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this.ownerDocument || this; - - for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { - - // Don't process events on disabled elements (#6911, #8165) - if ( cur.disabled !== true ) { - selMatch = {}; - matches = []; - jqcur[0] = cur; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - sel = handleObj.selector; - - if ( selMatch[ sel ] === undefined ) { - selMatch[ sel ] = ( - handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) - ); - } - if ( selMatch[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, matches: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( handlers.length > delegateCount ) { - handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); - } - - // Run delegates first; they may want to stop propagation beneath us - for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { - matched = handlerQueue[ i ]; - event.currentTarget = matched.elem; - - for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { - handleObj = matched.matches[ j ]; - - // Triggered event must either 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { - - event.data = handleObj.data; - event.handleObj = handleObj; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** - props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, - originalEvent = event, - fixHook = jQuery.event.fixHooks[ event.type ] || {}, - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = jQuery.Event( originalEvent ); - - for ( i = copy.length; i; ) { - prop = copy[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } - - // Target should not be a text node (#504, Safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) - if ( event.metaKey === undefined ) { - event.metaKey = event.ctrlKey; - } - - return fixHook.filter? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, - - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - - focus: { - delegateType: "focusin" - }, - blur: { - delegateType: "focusout" - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; + }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. -jQuery.event.handle = jQuery.event.dispatch; + jQuery.event.handle = jQuery.event.dispatch; -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); + jQuery.removeEvent = document.removeEventListener ? + function ( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function ( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + + jQuery.Event = function ( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; }; -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); + function returnFalse() { + return false; } - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; + function returnTrue() { + return true; } - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; + jQuery.Event.prototype = { + preventDefault : function () { + this.isDefaultPrevented = returnTrue; - var e = this.originalEvent; - if ( !e ) { - return; - } + var e = this.originalEvent; + if ( !e ) { + return; + } - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation : function () { + this.isPropagationStopped = returnTrue; - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation : function () { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented : returnFalse, + isPropagationStopped : returnFalse, + isImmediatePropagationStopped : returnFalse + }; // Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, + jQuery.each( { + mouseenter : "mouseover", + mouseleave : "mouseout" + }, function ( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType : fix, + bindType : fix, - handle: function( event ) { - var target = this, - related = event.relatedTarget, - handleObj = event.handleObj, - selector = handleObj.selector, - ret; + handle : function ( event ) { + var target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector, + ret; - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !form._submit_attached ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - form._submit_attached = true; - } - }); - // return undefined since we don't need an event listener - }, - - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - } - }, - - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; -} - -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { - - jQuery.event.special.change = { - - setup: function() { - - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - jQuery.event.simulate( "change", this, event, true ); - } - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - elem._change_attached = true; - } - }); - }, - - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return rformElems.test( this.nodeName ); - } - }; -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; } + return ret; } }; - }); -} + } ); -jQuery.fn.extend({ +// IE submit delegation + if ( !jQuery.support.submitBubbles ) { - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; + jQuery.event.special.submit = { + setup : function () { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { // && selector != null - // ( types-Object, data ) - data = data || selector; + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function ( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !form._submit_attached ) { + jQuery.event.add( form, "submit._submit", function ( event ) { + event._submit_bubble = true; + } ); + form._submit_attached = true; + } + } ); + // return undefined since we don't need an event listener + }, + + postDispatch : function ( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown : function () { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; + } + +// IE change delegation and checkbox/radio fix + if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup : function () { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function ( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + } ); + jQuery.event.add( this, "click._change", function ( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + jQuery.event.simulate( "change", this, event, true ); + } + } ); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function ( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { + jQuery.event.add( elem, "change._change", function ( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + } ); + elem._change_attached = true; + } + } ); + }, + + handle : function ( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown : function () { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; + } + +// Create "bubbling" focus and blur events + if ( !jQuery.support.focusinBubbles ) { + jQuery.each( { focus : "focusin", blur : "focusout" }, function ( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function ( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup : function () { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown : function () { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + } ); + } + + jQuery.fn.extend( { + + on : function ( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { // && selector != null + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function ( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function () { + jQuery.event.add( this, types, fn, data, selector ); + } ); + }, + one : function ( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off : function ( types, selector, fn ) { + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( var type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; selector = undefined; } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); + if ( fn === false ) { + fn = returnFalse; } - return this; - } + return this.each( function () { + jQuery.event.remove( this, types, fn, selector ); + } ); + }, - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) + bind : function ( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind : function ( types, fn ) { + return this.off( types, null, fn ); + }, + + live : function ( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die : function ( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate : function ( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate : function ( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length == 1 ? this.off( selector, "**" ) : this.off( types, selector, fn ); + }, + + trigger : function ( type, data ) { + return this.each( function () { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler : function ( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle : function ( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function ( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover : function ( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } + } ); + + jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split( " " ), function ( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function ( data, fn ) { + if ( fn == null ) { fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; + data = null; } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; } - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - var handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( var type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - live: function( types, data, fn ) { - jQuery( this.context ).on( types, this.selector, data, fn ); - return this; - }, - die: function( types, fn ) { - jQuery( this.context ).off( types, this.selector || "**", fn ); - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } - - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } - - if ( rkeyEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; - } - - if ( rmouseEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; - } -}); + } ); + /*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ + (function () { -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - expando = "sizcache" + (Math.random() + '').replace('.', ''), - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rReturn = /\r\n/g, - rNonWord = /\W/; + var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + expando = "sizcache" + (Math.random() + '').replace( '.', '' ), + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rReturn = /\r\n/g, + rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); + [0, 0].sort( function () { + baseHasDuplicate = false; + return 0; + } ); -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; + var Sizzle = function ( selector, context, results, seed ) { + results = results || []; + context = context || document; - var origContext = context; + var origContext = context; - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; } - } - } while ( m ); - if ( parts.length > 1 && origPOS.exec( selector ) ) { + if ( !selector || typeof selector !== "string" ) { + return results; + } - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context, seed ); + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); - while ( parts.length ) { - selector = parts.shift(); + if ( m ) { + soFar = m[3]; - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } } + } while ( m ); - set = posProcess( selector, set, seed ); - } - } + if ( parts.length > 1 && origPOS.exec( selector ) ) { - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context, seed ); - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; } else { - pop = parts.pop(); - } + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); - if ( pop == null ) { - pop = context; - } + while ( parts.length ) { + selector = parts.shift(); - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set, i, len, match, type, left; - - if ( !expr ) { - return []; - } - - for ( i = 0, len = Expr.order.length; i < len; i++ ) { - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - type, found, item, filter, left, - i, pass, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - filter = Expr.filter[ type ]; - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; + set = posProcess( selector, set, seed ); } } - if ( match ) { - for ( i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - pass = not ^ found; + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test( parts[0] ) && !Expr.match.ID.test( parts[parts.length - 1] ) ) { - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } - } else { - curLoop[i] = false; - } + if ( context ) { + ret = seed ? + { expr : parts.pop(), set : makeArray( seed ) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - } else if ( pass ) { - result.push( item ); - anyFound = true; + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call( checkSet ) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains( context, checkSet[i] )) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; + }; + + Sizzle.uniqueSort = function ( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; + }; + + Sizzle.matches = function ( expr, set ) { + return Sizzle( expr, null, null, set ); + }; + + Sizzle.matchesSelector = function ( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; + }; + + Sizzle.find = function ( expr, context, isXML ) { + var set, i, len, match, type, left; + + if ( !expr ) { + return []; + } + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set : set, expr : expr }; + }; + + Sizzle.filter = function ( expr, set, inplace, not ) { + var match, anyFound, + type, found, item, filter, left, + i, pass, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + filter = Expr.filter[ type ]; + left = match[1]; + + anyFound = false; + + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; } } - } - } - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } + if ( match ) { + for ( i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + pass = not ^ found; - expr = expr.replace( Expr.match[ type ], "" ); + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; - if ( !anyFound ) { - return []; - } + } else { + curLoop[i] = false; + } - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Utility function for retreiving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -var getText = Sizzle.getText = function( elem ) { - var i, node, - nodeType = elem.nodeType, - ret = ""; - - if ( nodeType ) { - if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent || innerText for elements - if ( typeof elem.textContent === 'string' ) { - return elem.textContent; - } else if ( typeof elem.innerText === 'string' ) { - // Replace IE's carriage returns - return elem.innerText.replace( rReturn, '' ); - } else { - // Traverse it's children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - } else { - - // If no nodeType, this is expected to be an array - for ( i = 0; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - if ( node.nodeType !== 8 ) { - ret += getText( node ); - } - } - } - return ret; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } } - } else if ( inplace ) { - curLoop[i] = false; + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; + }; + + Sizzle.error = function ( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); + }; + + /** + * Utility function for retreiving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ + var getText = Sizzle.getText = function ( elem ) { + var i, node, + nodeType = elem.nodeType, + ret = ""; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent || innerText for elements + if ( typeof elem.textContent === 'string' ) { + return elem.textContent; + } else if ( typeof elem.innerText === 'string' ) { + // Replace IE's carriage returns + return elem.innerText.replace( rReturn, '' ); + } else { + // Traverse it's children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + } else { + + // If no nodeType, this is expected to be an array + for ( i = 0; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + if ( node.nodeType !== 8 ) { + ret += getText( node ); } } } + return ret; + }; - return false; - }, + var Expr = Sizzle.selectors = { + order : [ "ID", "NAME", "TAG" ], - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, + match : { + ID : /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS : /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME : /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR : /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG : /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD : /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS : /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO : /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, + leftMatch : {}, - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); + attrMap : { + "class" : "className", + "for" : "htmlFor" + }, + + attrHandle : { + href : function ( elem ) { + return elem.getAttribute( "href" ); + }, + type : function ( elem ) { + return elem.getAttribute( "type" ); } + }, - match[2] = match[2].replace(/^\+|\s*/g, ''); + relative : { + "+" : function ( checkSet, part ) { + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + if ( isTag ) { + part = part.toLowerCase(); + } - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) { + } - // TODO: Move to normal caching system - match[0] = done++; + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } - return match; - }, + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); + ">" : function ( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + for ( ; i < l; i++ ) { + elem = checkSet[i]; - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } - return match; - }, + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, - if ( !inplace ) { - result.push.apply( result, ret ); + "" : function ( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~" : function ( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find : { + ID : function ( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById( match[1] ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME : function ( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute( "name" ) === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG : function ( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter : { + CLASS : function ( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace( /[\t\n\r]/g, " " ).indexOf( match ) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } } return false; - } + }, - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } + ID : function ( match ) { + return match[1].replace( rBackslash, "" ); + }, - return match; - }, + TAG : function ( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, - POS: function( match ) { - match.unshift( true ); + CHILD : function ( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } - return match; - } - }, + match[2] = match[2].replace( /^\+|\s*/g, '' ); - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2] ); - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); } - } - return true; + // TODO: Move to normal caching system + match[0] = done++; - } else { - Sizzle.error( name ); - } - }, + return match; + }, - CHILD: function( elem, match ) { - var first, last, - doneName, parent, cache, - count, diff, - type = match[1], - node = elem; + ATTR : function ( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO : function ( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec( match[3] ) || "" ).length > 1 || /^\w/.test( match[3] ) ) { + match[3] = Sizzle( match[3], null, null, curLoop ); + + } else { + var ret = Sizzle.filter( match[3], curLoop, inplace, true ^ not ); + + if ( !inplace ) { + result.push.apply( result, ret ); + } - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { return false; } - } - if ( type === "first" ) { + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } - node = elem; + return match; + }, - /* falls through */ - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } + POS : function ( match ) { + match.unshift( true ); + + return match; + } + }, + + filters : { + enabled : function ( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled : function ( elem ) { + return elem.disabled === true; + }, + + checked : function ( elem ) { + return elem.checked === true; + }, + + selected : function ( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; } - return true; + return elem.selected === true; + }, - case "nth": - first = match[2]; - last = match[3]; + parent : function ( elem ) { + return !!elem.firstChild; + }, - if ( first === 1 && last === 0 ) { - return true; - } + empty : function ( elem ) { + return !elem.firstChild; + }, - doneName = match[0]; - parent = elem.parentNode; + has : function ( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, - if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { - count = 0; + header : function ( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; + text : function ( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio : function ( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox : function ( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file : function ( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password : function ( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit : function ( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image : function ( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset : function ( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button : function ( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input : function ( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus : function ( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters : { + first : function ( elem, i ) { + return i === 0; + }, + + last : function ( elem, i, match, array ) { + return i === array.length - 1; + }, + + even : function ( elem, i ) { + return i % 2 === 0; + }, + + odd : function ( elem, i ) { + return i % 2 === 1; + }, + + lt : function ( elem, i, match ) { + return i < match[3] - 0; + }, + + gt : function ( elem, i, match ) { + return i > match[3] - 0; + }, + + nth : function ( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq : function ( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter : { + PSEUDO : function ( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText( [ elem ] ) || "").indexOf( match[3] ) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; } } - parent[ expando ] = doneName; - } - - diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; + return true; } else { - return ( diff % first === 0 && diff / first >= 0 ); + Sizzle.error( name ); } + }, + + CHILD : function ( elem, match ) { + var first, last, + doneName, parent, cache, + count, diff, + type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + /* falls through */ + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + first = match[2]; + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + doneName = match[0]; + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { + count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent[ expando ] = doneName; + } + + diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID : function ( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute( "id" ) === match; + }, + + TAG : function ( elem, match ) { + return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; + }, + + CLASS : function ( elem, match ) { + return (" " + (elem.className || elem.getAttribute( "class" )) + " ") + .indexOf( match ) > -1; + }, + + ATTR : function ( elem, match ) { + var name = match[1], + result = Sizzle.attr ? + Sizzle.attr( elem, name ) : + Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + !type && Sizzle.attr ? + result != null : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf( check ) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf( check ) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf( check ) === 0 : + type === "$=" ? + value.substr( value.length - check.length ) === check : + type === "|=" ? + value === check || value.substr( 0, check.length + 1 ) === check + "-" : + false; + }, + + POS : function ( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } } - }, + }; - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, + var origPOS = Expr.match.POS, + fescape = function ( all, num ) { + return "\\" + (num - 0 + 1); + }; - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Sizzle.attr ? - Sizzle.attr( elem, name ) : - Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - !type && Sizzle.attr ? - result != null : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } + for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace( /\\(\d+)/g, fescape ) ); } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} // Expose origPOS // "global" as in regardless of relation to brackets/parens -Expr.match.globalPOS = origPOS; + Expr.match.globalPOS = origPOS; -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); + var makeArray = function ( array, results ) { + array = Array.prototype.slice.call( array, 0 ); - if ( results ) { - results.push.apply( results, array ); - return results; - } + if ( results ) { + results.push.apply( results, array ); + return results; + } - return array; -}; + return array; + }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; + } catch ( e ) { + makeArray = function ( array, results ) { + var i = 0, + ret = results || []; - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); + if ( toString.call( array ) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; + } + + var sortOrder, siblingCheck; + + if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function ( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition( b ) & 4 ? -1 : 1; + }; } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); + sortOrder = function ( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; } - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; } - } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function ( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; } - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; + (function () { + // We're going to inject a fake input element with a specified name + var form = document.createElement( "div" ), + id = "script" + (new Date()).getTime(), + root = document.documentElement; - form.innerHTML = ""; + form.innerHTML = ""; - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function ( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById( match[1] ); - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode( "id" ).nodeValue === match[1] ? + [m] : + undefined : + []; } - } + }; - results = tmp; + Expr.filter.ID = function ( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode( "id" ); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; } - return results; - }; - } + root.removeChild( form ); - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; + // release memory in IE + root = form = null; + })(); - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { + (function () { + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } + // Create a fake element + var div = document.createElement( "div" ); + div.appendChild( document.createComment( "" ) ); - // release memory in IE - div = null; -})(); + // Make sure no comments are found + if ( div.getElementsByTagName( "*" ).length > 0 ) { + Expr.find.TAG = function ( match, context ) { + var results = context.getElementsByTagName( match[1] ); -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; - div.innerHTML = "

    "; + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); + results = tmp; } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute( "href" ) !== "#" ) { + + Expr.attrHandle.href = function ( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; + })(); + + if ( document.querySelectorAll ) { + (function () { + var oldSizzle = Sizzle, + div = document.createElement( "div" ), + id = "__sizzle__"; + + div.innerHTML = "

    "; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll( ".TEST" ).length === 0 ) { + return; } - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); + Sizzle = function ( query, context, extra, seed ) { + context = context || document; - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML( context ) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } } - } else { - return makeArray( [], extra ); + try { + return makeArray( context.querySelectorAll( query ), extra ); + } catch ( qsaError ) { + } + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch ( pseudoError ) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } } } - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} + return oldSizzle( query, context, extra, seed ); + }; - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; } - } - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; + // release memory in IE + div = null; + })(); } - // release memory in IE - div = null; - })(); -} + (function () { + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; + } catch ( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function ( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace( /\=\s*([^'"\]]*)\s*\]/g, "='$1']" ); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch ( e ) { } } - } catch(e) {} + + return Sizzle( expr, null, null, [node] ).length > 0; + }; + } + })(); + + (function () { + var div = document.createElement( "div" ); + + div.innerHTML = "
    "; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName( "e" ).length === 0 ) { + return; } - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
    "; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; + if ( div.getElementsByClassName( "e" ).length === 1 ) { + return; } - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; + Expr.order.splice( 1, 0, "CLASS" ); + Expr.find.CLASS = function ( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName( match[1] ); } + }; - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem[ expando ] = doneName; - elem.sizset = i; - } + // release memory in IE + div = null; + })(); - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; + function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; break; } - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } + if ( elem.nodeType === 1 && !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } - elem = elem[dir]; + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } + } + + function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } + } + + if ( document.documentElement.contains ) { + Sizzle.contains = function ( a, b ) { + return a !== b && (a.contains ? a.contains( b ) : true); + }; + + } else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function ( a, b ) { + return !!(a.compareDocumentPosition( b ) & 16); + }; + + } else { + Sizzle.contains = function () { + return false; + }; + } + + Sizzle.isXML = function ( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; + }; + + var posProcess = function ( selector, context, seed ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); } - checkSet[i] = match; - } - } -} + selector = Expr.relative[selector] ? selector + "*" : selector; -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet, seed ); + } -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context, seed ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet, seed ); - } - - return Sizzle.filter( later, tmpSet ); -}; + return Sizzle.filter( later, tmpSet ); + }; // EXPOSE // Override sizzle attribute retrieval -Sizzle.attr = jQuery.attr; -Sizzle.selectors.attrMap = {}; -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; + Sizzle.attr = jQuery.attr; + Sizzle.selectors.attrMap = {}; + jQuery.find = Sizzle; + jQuery.expr = Sizzle.selectors; + jQuery.expr[":"] = jQuery.expr.filters; + jQuery.unique = Sizzle.uniqueSort; + jQuery.text = Sizzle.getText; + jQuery.isXMLDoc = Sizzle.isXML; + jQuery.contains = Sizzle.contains; -})(); + })(); -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, + var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.globalPOS, + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.globalPOS, // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; + guaranteedUnique = { + children : true, + contents : true, + next : true, + prev : true + }; -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; + jQuery.fn.extend( { + find : function ( selector ) { + var self = this, + i, l; - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter( function () { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice( n--, 1 ); + break; + } + } + } + } + } + + return ret; + }, + + has : function ( target ) { + var targets = jQuery( target ); + return this.filter( function () { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { return true; } } - }); - } + } ); + }, - var ret = this.pushStack( "", "find", selector ), - length, n, r; + not : function ( selector ) { + return this.pushStack( winnow( this, selector, false ), "not", selector ); + }, - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); + filter : function ( selector ) { + return this.pushStack( winnow( this, selector, true ), "filter", selector ); + }, - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); + is : function ( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + POS.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest : function ( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array (deprecated as of jQuery 1.7) + if ( jQuery.isArray( selectors ) ) { + var level = 1; + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( i = 0; i < selectors.length; i++ ) { + + if ( jQuery( cur ).is( selectors[ i ] ) ) { + ret.push( { selector : selectors[ i ], elem : cur, level : level } ); + } + } + + cur = cur.parentNode; + level++; + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index( cur ) > -1 : jQuery.find.matchesSelector( cur, selectors ) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } - } - return ret; - }, + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, + return this.pushStack( ret, "closest", selectors ); + }, - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, + // Determine the position of an element within + // the matched set of elements + index : function ( elem ) { - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - POS.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array (deprecated as of jQuery 1.7) - if ( jQuery.isArray( selectors ) ) { - var level = 1; - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( i = 0; i < selectors.length; i++ ) { - - if ( jQuery( cur ).is( selectors[ i ] ) ) { - ret.push({ selector: selectors[ i ], elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add : function ( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf : function () { + return this.add( this.prevObject ); } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); + } ); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); + function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - if ( !runtil.test( name ) ) { - selector = until; + jQuery.each( { + parent : function ( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents : function ( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil : function ( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next : function ( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev : function ( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll : function ( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll : function ( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil : function ( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil : function ( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings : function ( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children : function ( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents : function ( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); } + }, function ( name, fn ) { + jQuery.fn[ name ] = function ( until, selector ) { + var ret = jQuery.map( this, fn, until ); - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, slice.call( arguments ).join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); + if ( !runtil.test( name ) ) { + selector = until; } - cur = cur[dir]; - } - return matched; - }, - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); } - } - return cur; - }, + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); } - } - return r; - } -}); + return this.pushStack( ret, name, slice.call( arguments ).join( "," ) ); + }; + } ); + + jQuery.extend( { + filter : function ( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector( elems[0], expr ) ? [ elems[0] ] : [] : + jQuery.find.matches( expr, elems ); + }, + + dir : function ( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth : function ( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling : function ( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } + } ); // Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { + function winnow( elements, qualifier, keep ) { - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function ( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + } ); - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return ( elem === qualifier ) === keep; - }); + } else if ( qualifier.nodeType ) { + return jQuery.grep( elements, function ( elem, i ) { + return ( elem === qualifier ) === keep; + } ); - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep( elements, function ( elem ) { + return elem.nodeType === 1; + } ); - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); + if ( isSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, filtered, !keep ); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } } + + return jQuery.grep( elements, function ( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + } ); } - return jQuery.grep(elements, function( elem, i ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; - }); -} + function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); - - -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } } + return safeFrag; } - return safeFrag; -} -var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /]", "i"), + var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /]", "i" ), // checked="checked" or checked - rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /\/(java|ecma)script/i, - rcleanScript = /^\s*", "" ], - legend: [ 1, "
    ", "
    " ], - thead: [ 1, "", "
    " ], - tr: [ 2, "", "
    " ], - td: [ 3, "", "
    " ], - col: [ 2, "", "
    " ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }, - safeFragment = createSafeFragment( document ); + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /\/(java|ecma)script/i, + rcleanScript = /^\s*", "" ], + legend : [ 1, "
    ", "
    " ], + thead : [ 1, "", "
    " ], + tr : [ 2, "", "
    " ], + td : [ 3, "", "
    " ], + col : [ 2, "", "
    " ], + area : [ 1, "", "" ], + _default : [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ); -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; + wrapMap.optgroup = wrapMap.option; + wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; + wrapMap.th = wrapMap.td; // IE can't serialize and - - - -
    -

    {linked-path}

    - {files} -
    - + $( window ).on( 'content loaded', function () { + $( 'search' ).on( 'keyup', search ); + } ); + + + + + +
    +

    {linked-path}

    + {files} +
    + \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/connect/lib/public/error.html b/example/node/node_modules/express/node_modules/connect/lib/public/error.html index 34e0df5..4c1ec90 100644 --- a/example/node/node_modules/express/node_modules/connect/lib/public/error.html +++ b/example/node/node_modules/express/node_modules/connect/lib/public/error.html @@ -1,13 +1,16 @@ - - {error} - - - -
    -

    {title}

    -

    500 {error}

    -
      {stack}
    -
    - + + {error} + + + +
    +

    {title}

    + +

    500 {error}

    +
      {stack}
    +
    + \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/connect/lib/public/style.css b/example/node/node_modules/express/node_modules/connect/lib/public/style.css index 32b6507..9d68dfc 100644 --- a/example/node/node_modules/express/node_modules/connect/lib/public/style.css +++ b/example/node/node_modules/express/node_modules/connect/lib/public/style.css @@ -1,141 +1,166 @@ body { - margin: 0; - padding: 80px 100px; - font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; - background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); - background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); - background-repeat: no-repeat; - color: #555; - -webkit-font-smoothing: antialiased; + margin: 0; + padding: 80px 100px; + font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; + background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); + background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); + background-repeat: no-repeat; + color: #555; + -webkit-font-smoothing: antialiased; } + h1, h2, h3 { - margin: 0; - font-size: 22px; - color: #343434; + margin: 0; + font-size: 22px; + color: #343434; } + h1 em, h2 em { - padding: 0 5px; - font-weight: normal; + padding: 0 5px; + font-weight: normal; } + h1 { - font-size: 60px; + font-size: 60px; } + h2 { - margin-top: 10px; + margin-top: 10px; } + h3 { - margin: 5px 0 10px 0; - padding-bottom: 5px; - border-bottom: 1px solid #eee; - font-size: 18px; + margin: 5px 0 10px 0; + padding-bottom: 5px; + border-bottom: 1px solid #eee; + font-size: 18px; } + ul { - margin: 0; - padding: 0; + margin: 0; + padding: 0; } + ul li { - margin: 5px 0; - padding: 3px 8px; - list-style: none; + margin: 5px 0; + padding: 3px 8px; + list-style: none; } + ul li:hover { - cursor: pointer; - color: #2e2e2e; + cursor: pointer; + color: #2e2e2e; } + ul li .path { - padding-left: 5px; - font-weight: bold; + padding-left: 5px; + font-weight: bold; } + ul li .line { - padding-right: 5px; - font-style: italic; + padding-right: 5px; + font-style: italic; } + ul li:first-child .path { - padding-left: 0; + padding-left: 0; } + p { - line-height: 1.5; + line-height: 1.5; } + a { - color: #555; - text-decoration: none; + color: #555; + text-decoration: none; } + a:hover { - color: #303030; + color: #303030; } + #stacktrace { - margin-top: 15px; + margin-top: 15px; } + .directory h1 { - margin-bottom: 15px; - font-size: 18px; + margin-bottom: 15px; + font-size: 18px; } + ul#files { - width: 100%; - height: 500px; + width: 100%; + height: 500px; } + ul#files li { - padding: 0; + padding: 0; } + ul#files li img { - position: absolute; - top: 5px; - left: 5px; + position: absolute; + top: 5px; + left: 5px; } + ul#files li a { - position: relative; - display: block; - margin: 1px; - width: 30%; - height: 25px; - line-height: 25px; - text-indent: 8px; - float: left; - border: 1px solid transparent; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - overflow: hidden; - text-overflow: ellipsis; + position: relative; + display: block; + margin: 1px; + width: 30%; + height: 25px; + line-height: 25px; + text-indent: 8px; + float: left; + border: 1px solid transparent; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; + overflow: hidden; + text-overflow: ellipsis; } + ul#files li a.icon { - text-indent: 25px; + text-indent: 25px; } + ul#files li a:focus, ul#files li a:hover { - outline: none; - background: rgba(255,255,255,0.65); - border: 1px solid #ececec; + outline: none; + background: rgba(255, 255, 255, 0.65); + border: 1px solid #ececec; } + ul#files li a.highlight { - -webkit-transition: background .4s ease-in-out; - background: #ffff4f; - border-color: #E9DC51; + -webkit-transition: background .4s ease-in-out; + background: #ffff4f; + border-color: #E9DC51; } + #search { - display: block; - position: fixed; - top: 20px; - right: 20px; - width: 90px; - -webkit-transition: width ease 0.2s, opacity ease 0.4s; - -moz-transition: width ease 0.2s, opacity ease 0.4s; - -webkit-border-radius: 32px; - -moz-border-radius: 32px; - -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -webkit-font-smoothing: antialiased; - text-align: left; - font: 13px "Helvetica Neue", Arial, sans-serif; - padding: 4px 10px; - border: none; - background: transparent; - margin-bottom: 0; - outline: none; - opacity: 0.7; - color: #888; + display: block; + position: fixed; + top: 20px; + right: 20px; + width: 90px; + -webkit-transition: width ease 0.2s, opacity ease 0.4s; + -moz-transition: width ease 0.2s, opacity ease 0.4s; + -webkit-border-radius: 32px; + -moz-border-radius: 32px; + -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); + -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); + -webkit-font-smoothing: antialiased; + text-align: left; + font: 13px "Helvetica Neue", Arial, sans-serif; + padding: 4px 10px; + border: none; + background: transparent; + margin-bottom: 0; + outline: none; + opacity: 0.7; + color: #888; } + #search:focus { - width: 120px; - opacity: 1.0; + width: 120px; + opacity: 1.0; } diff --git a/example/node/node_modules/express/node_modules/connect/lib/utils.js b/example/node/node_modules/express/node_modules/connect/lib/utils.js index d0bc172..9ac301a 100644 --- a/example/node/node_modules/express/node_modules/connect/lib/utils.js +++ b/example/node/node_modules/express/node_modules/connect/lib/utils.js @@ -1,4 +1,3 @@ - /*! * Connect - utils * Copyright(c) 2010 Sencha Inc. @@ -10,9 +9,9 @@ * Module dependencies. */ -var crypto = require('crypto') - , Path = require('path') - , fs = require('fs'); +var crypto = require( 'crypto' ) + , Path = require( 'path' ) + , fs = require( 'fs' ); /** * Flatten the given `arr`. @@ -22,17 +21,17 @@ var crypto = require('crypto') * @api private */ -exports.flatten = function(arr, ret){ - var ret = ret || [] - , len = arr.length; - for (var i = 0; i < len; ++i) { - if (Array.isArray(arr[i])) { - exports.flatten(arr[i], ret); - } else { - ret.push(arr[i]); - } - } - return ret; +exports.flatten = function ( arr, ret ) { + var ret = ret || [] + , len = arr.length; + for ( var i = 0; i < len; ++i ) { + if ( Array.isArray( arr[i] ) ) { + exports.flatten( arr[i], ret ); + } else { + ret.push( arr[i] ); + } + } + return ret; }; /** @@ -48,11 +47,11 @@ exports.flatten = function(arr, ret){ * @api public */ -exports.md5 = function(str, encoding){ - return crypto - .createHash('md5') - .update(str) - .digest(encoding || 'hex'); +exports.md5 = function ( str, encoding ) { + return crypto + .createHash( 'md5' ) + .update( str ) + .digest( encoding || 'hex' ); }; /** @@ -60,7 +59,7 @@ exports.md5 = function(str, encoding){ * * var a = { foo: 'bar' } * , b = { bar: 'baz' }; - * + * * utils.merge(a, b); * // => { foo: 'bar', bar: 'baz' } * @@ -70,13 +69,13 @@ exports.md5 = function(str, encoding){ * @api public */ -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; +exports.merge = function ( a, b ) { + if ( a && b ) { + for ( var key in b ) { + a[key] = b[key]; + } + } + return a; }; /** @@ -87,12 +86,12 @@ exports.merge = function(a, b){ * @api public */ -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); +exports.escape = function ( html ) { + return String( html ) + .replace( /&(?!\w+;)/g, '&' ) + .replace( //g, '>' ) + .replace( /"/g, '"' ); }; @@ -107,16 +106,16 @@ exports.escape = function(html){ * @api public */ -exports.uid = function(len) { - var buf = [] - , chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' - , charlen = chars.length; +exports.uid = function ( len ) { + var buf = [] + , chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + , charlen = chars.length; - for (var i = 0; i < len; ++i) { - buf.push(chars[getRandomInt(0, charlen - 1)]); - } + for ( var i = 0; i < len; ++i ) { + buf.push( chars[getRandomInt( 0, charlen - 1 )] ); + } - return buf.join(''); + return buf.join( '' ); }; /** @@ -127,33 +126,35 @@ exports.uid = function(len) { * @api public */ -exports.parseCookie = function(str){ - var obj = {} - , pairs = str.split(/[;,] */); - for (var i = 0, len = pairs.length; i < len; ++i) { - var pair = pairs[i] - , eqlIndex = pair.indexOf('=') - , key = pair.substr(0, eqlIndex).trim().toLowerCase() - , val = pair.substr(++eqlIndex, pair.length).trim(); +exports.parseCookie = function ( str ) { + var obj = {} + , pairs = str.split( /[;,] */ ); + for ( var i = 0, len = pairs.length; i < len; ++i ) { + var pair = pairs[i] + , eqlIndex = pair.indexOf( '=' ) + , key = pair.substr( 0, eqlIndex ).trim().toLowerCase() + , val = pair.substr( ++eqlIndex, pair.length ).trim(); - // quoted values - if ('"' == val[0]) val = val.slice(1, -1); + // quoted values + if ( '"' == val[0] ) { + val = val.slice( 1, -1 ); + } - // only assign once - if (undefined == obj[key]) { - val = val.replace(/\+/g, ' '); - try { - obj[key] = decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - obj[key] = val; - } else { - throw err; - } - } - } - } - return obj; + // only assign once + if ( undefined == obj[key] ) { + val = val.replace( /\+/g, ' ' ); + try { + obj[key] = decodeURIComponent( val ); + } catch ( err ) { + if ( err instanceof URIError ) { + obj[key] = val; + } else { + throw err; + } + } + } + } + return obj; }; /** @@ -169,17 +170,27 @@ exports.parseCookie = function(str){ * @api public */ -exports.serializeCookie = function(name, val, obj){ - var pairs = [name + '=' + encodeURIComponent(val)] - , obj = obj || {}; +exports.serializeCookie = function ( name, val, obj ) { + var pairs = [name + '=' + encodeURIComponent( val )] + , obj = obj || {}; - if (obj.domain) pairs.push('domain=' + obj.domain); - if (obj.path) pairs.push('path=' + obj.path); - if (obj.expires) pairs.push('expires=' + obj.expires.toUTCString()); - if (obj.httpOnly) pairs.push('httpOnly'); - if (obj.secure) pairs.push('secure'); + if ( obj.domain ) { + pairs.push( 'domain=' + obj.domain ); + } + if ( obj.path ) { + pairs.push( 'path=' + obj.path ); + } + if ( obj.expires ) { + pairs.push( 'expires=' + obj.expires.toUTCString() ); + } + if ( obj.httpOnly ) { + pairs.push( 'httpOnly' ); + } + if ( obj.secure ) { + pairs.push( 'secure' ); + } - return pairs.join('; '); + return pairs.join( '; ' ); }; /** @@ -200,33 +211,33 @@ exports.serializeCookie = function(name, val, obj){ * @api public */ -exports.pause = function(obj){ - var onData - , onEnd - , events = []; +exports.pause = function ( obj ) { + var onData + , onEnd + , events = []; - // buffer data - obj.on('data', onData = function(data, encoding){ - events.push(['data', data, encoding]); - }); + // buffer data + obj.on( 'data', onData = function ( data, encoding ) { + events.push( ['data', data, encoding] ); + } ); - // buffer end - obj.on('end', onEnd = function(data, encoding){ - events.push(['end', data, encoding]); - }); + // buffer end + obj.on( 'end', onEnd = function ( data, encoding ) { + events.push( ['end', data, encoding] ); + } ); - return { - end: function(){ - obj.removeListener('data', onData); - obj.removeListener('end', onEnd); - }, - resume: function(){ - this.end(); - for (var i = 0, len = events.length; i < len; ++i) { - obj.emit.apply(obj, events[i]); - } - } - }; + return { + end : function () { + obj.removeListener( 'data', onData ); + obj.removeListener( 'end', onEnd ); + }, + resume : function () { + this.end(); + for ( var i = 0, len = events.length; i < len; ++i ) { + obj.emit.apply( obj, events[i] ); + } + } + }; }; /** @@ -238,31 +249,35 @@ exports.pause = function(obj){ * @api public */ -exports.modified = function(req, res, headers) { - var headers = headers || res._headers || {} - , modifiedSince = req.headers['if-modified-since'] - , lastModified = headers['last-modified'] - , noneMatch = req.headers['if-none-match'] - , etag = headers['etag']; +exports.modified = function ( req, res, headers ) { + var headers = headers || res._headers || {} + , modifiedSince = req.headers['if-modified-since'] + , lastModified = headers['last-modified'] + , noneMatch = req.headers['if-none-match'] + , etag = headers['etag']; - if (noneMatch) noneMatch = noneMatch.split(/ *, */); + if ( noneMatch ) { + noneMatch = noneMatch.split( / *, */ ); + } - // check If-None-Match - if (noneMatch && etag && ~noneMatch.indexOf(etag)) { - return false; - } + // check If-None-Match + if ( noneMatch && etag && ~noneMatch.indexOf( etag ) ) { + return false; + } - // check If-Modified-Since - if (modifiedSince && lastModified) { - modifiedSince = new Date(modifiedSince); - lastModified = new Date(lastModified); - // Ignore invalid dates - if (!isNaN(modifiedSince.getTime())) { - if (lastModified <= modifiedSince) return false; - } - } - - return true; + // check If-Modified-Since + if ( modifiedSince && lastModified ) { + modifiedSince = new Date( modifiedSince ); + lastModified = new Date( lastModified ); + // Ignore invalid dates + if ( !isNaN( modifiedSince.getTime() ) ) { + if ( lastModified <= modifiedSince ) { + return false; + } + } + } + + return true; }; /** @@ -272,12 +287,12 @@ exports.modified = function(req, res, headers) { * @api public */ -exports.removeContentHeaders = function(res){ - Object.keys(res._headers).forEach(function(field){ - if (0 == field.indexOf('content')) { - res.removeHeader(field); - } - }); +exports.removeContentHeaders = function ( res ) { + Object.keys( res._headers ).forEach( function ( field ) { + if ( 0 == field.indexOf( 'content' ) ) { + res.removeHeader( field ); + } + } ); }; /** @@ -288,9 +303,9 @@ exports.removeContentHeaders = function(res){ * @api public */ -exports.conditionalGET = function(req) { - return req.headers['if-modified-since'] - || req.headers['if-none-match']; +exports.conditionalGET = function ( req ) { + return req.headers['if-modified-since'] + || req.headers['if-none-match']; }; /** @@ -300,12 +315,12 @@ exports.conditionalGET = function(req) { * @api public */ -exports.forbidden = function(res) { - var body = 'Forbidden'; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', body.length); - res.statusCode = 403; - res.end(body); +exports.forbidden = function ( res ) { + var body = 'Forbidden'; + res.setHeader( 'Content-Type', 'text/plain' ); + res.setHeader( 'Content-Length', body.length ); + res.statusCode = 403; + res.end( body ); }; /** @@ -316,10 +331,10 @@ exports.forbidden = function(res) { * @api public */ -exports.unauthorized = function(res, realm) { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); - res.end('Unauthorized'); +exports.unauthorized = function ( res, realm ) { + res.statusCode = 401; + res.setHeader( 'WWW-Authenticate', 'Basic realm="' + realm + '"' ); + res.end( 'Unauthorized' ); }; /** @@ -329,9 +344,9 @@ exports.unauthorized = function(res, realm) { * @api public */ -exports.badRequest = function(res) { - res.statusCode = 400; - res.end('Bad Request'); +exports.badRequest = function ( res ) { + res.statusCode = 400; + res.end( 'Bad Request' ); }; /** @@ -342,10 +357,10 @@ exports.badRequest = function(res) { * @api public */ -exports.notModified = function(res) { - exports.removeContentHeaders(res); - res.statusCode = 304; - res.end(); +exports.notModified = function ( res ) { + exports.removeContentHeaders( res ); + res.statusCode = 304; + res.end(); }; /** @@ -357,8 +372,8 @@ exports.notModified = function(res) { * @api public */ -exports.etag = function(stat) { - return '"' + stat.size + '-' + Number(stat.mtime) + '"'; +exports.etag = function ( stat ) { + return '"' + stat.size + '-' + Number( stat.mtime ) + '"'; }; /** @@ -370,28 +385,30 @@ exports.etag = function(stat) { * @api public */ -exports.parseRange = function(size, str){ - var valid = true; - var arr = str.substr(6).split(',').map(function(range){ - var range = range.split('-') - , start = parseInt(range[0], 10) - , end = parseInt(range[1], 10); +exports.parseRange = function ( size, str ) { + var valid = true; + var arr = str.substr( 6 ).split( ',' ).map( function ( range ) { + var range = range.split( '-' ) + , start = parseInt( range[0], 10 ) + , end = parseInt( range[1], 10 ); - // -500 - if (isNaN(start)) { - start = size - end; - end = size - 1; - // 500- - } else if (isNaN(end)) { - end = size - 1; - } + // -500 + if ( isNaN( start ) ) { + start = size - end; + end = size - 1; + // 500- + } else if ( isNaN( end ) ) { + end = size - 1; + } - // Invalid - if (isNaN(start) || isNaN(end) || start > end) valid = false; + // Invalid + if ( isNaN( start ) || isNaN( end ) || start > end ) { + valid = false; + } - return { start: start, end: end }; - }); - return valid ? arr : undefined; + return { start : start, end : end }; + } ); + return valid ? arr : undefined; }; /** @@ -402,19 +419,19 @@ exports.parseRange = function(size, str){ * @api public */ -exports.parseCacheControl = function(str){ - var directives = str.split(',') - , obj = {}; +exports.parseCacheControl = function ( str ) { + var directives = str.split( ',' ) + , obj = {}; - for(var i = 0, len = directives.length; i < len; i++) { - var parts = directives[i].split('=') - , key = parts.shift().trim() - , val = parseInt(parts.shift(), 10); + for ( var i = 0, len = directives.length; i < len; i++ ) { + var parts = directives[i].split( '=' ) + , key = parts.shift().trim() + , val = parseInt( parts.shift(), 10 ); - obj[key] = isNaN(val) ? true : val; - } + obj[key] = isNaN( val ) ? true : val; + } - return obj; + return obj; }; @@ -428,13 +445,13 @@ exports.parseCacheControl = function(str){ * @api public */ -var toArray = exports.toArray = function(obj){ - var len = obj.length - , arr = new Array(len); - for (var i = 0; i < len; ++i) { - arr[i] = obj[i]; - } - return arr; +var toArray = exports.toArray = function ( obj ) { + var len = obj.length + , arr = new Array( len ); + for ( var i = 0; i < len; ++i ) { + arr[i] = obj[i]; + } + return arr; }; /** @@ -446,6 +463,6 @@ var toArray = exports.toArray = function(obj){ * @api private */ -function getRandomInt(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; +function getRandomInt( min, max ) { + return Math.floor( Math.random() * (max - min + 1) ) + min; } diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js index bff41f1..75b9311 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/benchmark/bench-multipart-parser.js @@ -1,70 +1,70 @@ -require('../test/common'); -var multipartParser = require('../lib/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - Buffer = require('buffer').Buffer, - boundary = '-----------------------------168072824752491622650073', - mb = 100, - buffer = createMultipartBuffer(boundary, mb * 1024 * 1024), - callbacks = - { partBegin: -1, - partEnd: -1, - headerField: -1, - headerValue: -1, - partData: -1, - end: -1, - }; +require( '../test/common' ); +var multipartParser = require( '../lib/multipart_parser' ), + MultipartParser = multipartParser.MultipartParser, + parser = new MultipartParser(), + Buffer = require( 'buffer' ).Buffer, + boundary = '-----------------------------168072824752491622650073', + mb = 100, + buffer = createMultipartBuffer( boundary, mb * 1024 * 1024 ), + callbacks = + { partBegin : -1, + partEnd : -1, + headerField : -1, + headerValue : -1, + partData : -1, + end : -1, + }; -parser.initWithBoundary(boundary); -parser.onHeaderField = function() { - callbacks.headerField++; +parser.initWithBoundary( boundary ); +parser.onHeaderField = function () { + callbacks.headerField++; }; -parser.onHeaderValue = function() { - callbacks.headerValue++; +parser.onHeaderValue = function () { + callbacks.headerValue++; }; -parser.onPartBegin = function() { - callbacks.partBegin++; +parser.onPartBegin = function () { + callbacks.partBegin++; }; -parser.onPartData = function() { - callbacks.partData++; +parser.onPartData = function () { + callbacks.partData++; }; -parser.onPartEnd = function() { - callbacks.partEnd++; +parser.onPartEnd = function () { + callbacks.partEnd++; }; -parser.onEnd = function() { - callbacks.end++; +parser.onEnd = function () { + callbacks.end++; }; var start = +new Date(), - nparsed = parser.write(buffer), - duration = +new Date - start, - mbPerSec = (mb / (duration / 1000)).toFixed(2); + nparsed = parser.write( buffer ), + duration = +new Date - start, + mbPerSec = (mb / (duration / 1000)).toFixed( 2 ); -console.log(mbPerSec+' mb/sec'); +console.log( mbPerSec + ' mb/sec' ); -assert.equal(nparsed, buffer.length); +assert.equal( nparsed, buffer.length ); -function createMultipartBuffer(boundary, size) { - var head = - '--'+boundary+'\r\n' - + 'content-disposition: form-data; name="field1"\r\n' - + '\r\n' - , tail = '\r\n--'+boundary+'--\r\n' - , buffer = new Buffer(size); +function createMultipartBuffer( boundary, size ) { + var head = + '--' + boundary + '\r\n' + + 'content-disposition: form-data; name="field1"\r\n' + + '\r\n' + , tail = '\r\n--' + boundary + '--\r\n' + , buffer = new Buffer( size ); - buffer.write(head, 'ascii', 0); - buffer.write(tail, 'ascii', buffer.length - tail.length); - return buffer; + buffer.write( head, 'ascii', 0 ); + buffer.write( tail, 'ascii', buffer.length - tail.length ); + return buffer; } -process.on('exit', function() { - for (var k in callbacks) { - assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]); - } -}); +process.on( 'exit', function () { + for ( var k in callbacks ) { + assert.equal( 0, callbacks[k], k + ' count off by ' + callbacks[k] ); + } +} ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js index f6c15a6..8c9471d 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/post.js @@ -1,43 +1,43 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; +require( '../test/common' ); +var http = require( 'http' ), + util = require( 'util' ), + formidable = require( 'formidable' ), + server; -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/post') { - var form = new formidable.IncomingForm(), - fields = []; +server = http.createServer( function ( req, res ) { + if ( req.url == '/' ) { + res.writeHead( 200, {'content-type' : 'text/html'} ); + res.end( + '
    ' + + '
    ' + + '
    ' + + '' + + '
    ' + ); + } else if ( req.url == '/post' ) { + var form = new formidable.IncomingForm(), + fields = []; - form - .on('error', function(err) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('error:\n\n'+util.inspect(err)); - }) - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('end', function() { - console.log('-> post done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('received fields:\n\n '+util.inspect(fields)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); + form + .on( 'error', function ( err ) { + res.writeHead( 200, {'content-type' : 'text/plain'} ); + res.end( 'error:\n\n' + util.inspect( err ) ); + } ) + .on( 'field', function ( field, value ) { + console.log( field, value ); + fields.push( [field, value] ); + } ) + .on( 'end', function () { + console.log( '-> post done' ); + res.writeHead( 200, {'content-type' : 'text/plain'} ); + res.end( 'received fields:\n\n ' + util.inspect( fields ) ); + } ); + form.parse( req ); + } else { + res.writeHead( 404, {'content-type' : 'text/plain'} ); + res.end( '404' ); + } +} ); +server.listen( TEST_PORT ); -console.log('listening on http://localhost:'+TEST_PORT+'/'); +console.log( 'listening on http://localhost:' + TEST_PORT + '/' ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js index 050cdd9..71141a4 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/example/upload.js @@ -1,48 +1,48 @@ -require('../test/common'); -var http = require('http'), - util = require('util'), - formidable = require('formidable'), - server; +require( '../test/common' ); +var http = require( 'http' ), + util = require( 'util' ), + formidable = require( 'formidable' ), + server; -server = http.createServer(function(req, res) { - if (req.url == '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url == '/upload') { - var form = new formidable.IncomingForm(), - files = [], - fields = []; +server = http.createServer( function ( req, res ) { + if ( req.url == '/' ) { + res.writeHead( 200, {'content-type' : 'text/html'} ); + res.end( + '
    ' + + '
    ' + + '
    ' + + '' + + '
    ' + ); + } else if ( req.url == '/upload' ) { + var form = new formidable.IncomingForm(), + files = [], + fields = []; - form.uploadDir = TEST_TMP; + form.uploadDir = TEST_TMP; - form - .on('field', function(field, value) { - console.log(field, value); - fields.push([field, value]); - }) - .on('file', function(field, file) { - console.log(field, file); - files.push([field, file]); - }) - .on('end', function() { - console.log('-> upload done'); - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received fields:\n\n '+util.inspect(fields)); - res.write('\n\n'); - res.end('received files:\n\n '+util.inspect(files)); - }); - form.parse(req); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(TEST_PORT); + form + .on( 'field', function ( field, value ) { + console.log( field, value ); + fields.push( [field, value] ); + } ) + .on( 'file', function ( field, file ) { + console.log( field, file ); + files.push( [field, file] ); + } ) + .on( 'end', function () { + console.log( '-> upload done' ); + res.writeHead( 200, {'content-type' : 'text/plain'} ); + res.write( 'received fields:\n\n ' + util.inspect( fields ) ); + res.write( '\n\n' ); + res.end( 'received files:\n\n ' + util.inspect( files ) ); + } ); + form.parse( req ); + } else { + res.writeHead( 404, {'content-type' : 'text/plain'} ); + res.end( '404' ); + } +} ); +server.listen( TEST_PORT ); -console.log('listening on http://localhost:'+TEST_PORT+'/'); +console.log( 'listening on http://localhost:' + TEST_PORT + '/' ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/index.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/index.js index be41032..9ca82c2 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/index.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/index.js @@ -1 +1 @@ -module.exports = require('./lib/formidable'); \ No newline at end of file +module.exports = require( './lib/formidable' ); \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js index 6dc8720..0c60d48 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js @@ -1,61 +1,63 @@ -if (global.GENTLY) require = GENTLY.hijack(require); +if ( global.GENTLY ) { + require = GENTLY.hijack( require ); +} -var util = require('./util'), - WriteStream = require('fs').WriteStream, - EventEmitter = require('events').EventEmitter; +var util = require( './util' ), + WriteStream = require( 'fs' ).WriteStream, + EventEmitter = require( 'events' ).EventEmitter; -function File(properties) { - EventEmitter.call(this); +function File( properties ) { + EventEmitter.call( this ); - this.size = 0; - this.path = null; - this.name = null; - this.type = null; - this.lastModifiedDate = null; + this.size = 0; + this.path = null; + this.name = null; + this.type = null; + this.lastModifiedDate = null; - this._writeStream = null; + this._writeStream = null; - for (var key in properties) { - this[key] = properties[key]; - } + for ( var key in properties ) { + this[key] = properties[key]; + } - this._backwardsCompatibility(); + this._backwardsCompatibility(); } module.exports = File; -util.inherits(File, EventEmitter); +util.inherits( File, EventEmitter ); // @todo Next release: Show error messages when accessing these -File.prototype._backwardsCompatibility = function() { - var self = this; - this.__defineGetter__('length', function() { - return self.size; - }); - this.__defineGetter__('filename', function() { - return self.name; - }); - this.__defineGetter__('mime', function() { - return self.type; - }); +File.prototype._backwardsCompatibility = function () { + var self = this; + this.__defineGetter__( 'length', function () { + return self.size; + } ); + this.__defineGetter__( 'filename', function () { + return self.name; + } ); + this.__defineGetter__( 'mime', function () { + return self.type; + } ); }; -File.prototype.open = function() { - this._writeStream = new WriteStream(this.path); +File.prototype.open = function () { + this._writeStream = new WriteStream( this.path ); }; -File.prototype.write = function(buffer, cb) { - var self = this; - this._writeStream.write(buffer, function() { - self.lastModifiedDate = new Date(); - self.size += buffer.length; - self.emit('progress', self.size); - cb(); - }); +File.prototype.write = function ( buffer, cb ) { + var self = this; + this._writeStream.write( buffer, function () { + self.lastModifiedDate = new Date(); + self.size += buffer.length; + self.emit( 'progress', self.size ); + cb(); + } ); }; -File.prototype.end = function(cb) { - var self = this; - this._writeStream.end(function() { - self.emit('end'); - cb(); - }); +File.prototype.end = function ( cb ) { + var self = this; + this._writeStream.end( function () { + self.emit( 'end' ); + cb(); + } ); }; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js index b1e2bfb..f592ac5 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js @@ -1,378 +1,388 @@ -if (global.GENTLY) require = GENTLY.hijack(require); +if ( global.GENTLY ) { + require = GENTLY.hijack( require ); +} -var fs = require('fs'); -var util = require('./util'), - path = require('path'), - File = require('./file'), - MultipartParser = require('./multipart_parser').MultipartParser, - QuerystringParser = require('./querystring_parser').QuerystringParser, - StringDecoder = require('string_decoder').StringDecoder, - EventEmitter = require('events').EventEmitter; +var fs = require( 'fs' ); +var util = require( './util' ), + path = require( 'path' ), + File = require( './file' ), + MultipartParser = require( './multipart_parser' ).MultipartParser, + QuerystringParser = require( './querystring_parser' ).QuerystringParser, + StringDecoder = require( 'string_decoder' ).StringDecoder, + EventEmitter = require( 'events' ).EventEmitter; function IncomingForm() { - if (!(this instanceof IncomingForm)) return new IncomingForm; - EventEmitter.call(this); + if ( !(this instanceof IncomingForm) ) { + return new IncomingForm; + } + EventEmitter.call( this ); - this.error = null; - this.ended = false; + this.error = null; + this.ended = false; - this.maxFieldsSize = 2 * 1024 * 1024; - this.keepExtensions = false; - this.uploadDir = IncomingForm.UPLOAD_DIR; - this.encoding = 'utf-8'; - this.headers = null; - this.type = null; + this.maxFieldsSize = 2 * 1024 * 1024; + this.keepExtensions = false; + this.uploadDir = IncomingForm.UPLOAD_DIR; + this.encoding = 'utf-8'; + this.headers = null; + this.type = null; - this.bytesReceived = null; - this.bytesExpected = null; + this.bytesReceived = null; + this.bytesExpected = null; - this._parser = null; - this._flushing = 0; - this._fieldsSize = 0; -}; -util.inherits(IncomingForm, EventEmitter); + this._parser = null; + this._flushing = 0; + this._fieldsSize = 0; +} +; +util.inherits( IncomingForm, EventEmitter ); exports.IncomingForm = IncomingForm; -IncomingForm.UPLOAD_DIR = (function() { - var dirs = [process.env.TMP, '/tmp', process.cwd()]; - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - var isDirectory = false; +IncomingForm.UPLOAD_DIR = (function () { + var dirs = [process.env.TMP, '/tmp', process.cwd()]; + for ( var i = 0; i < dirs.length; i++ ) { + var dir = dirs[i]; + var isDirectory = false; - try { - isDirectory = fs.statSync(dir).isDirectory(); - } catch (e) {} + try { + isDirectory = fs.statSync( dir ).isDirectory(); + } catch ( e ) { + } - if (isDirectory) return dir; - } + if ( isDirectory ) { + return dir; + } + } })(); -IncomingForm.prototype.parse = function(req, cb) { - this.pause = function() { - try { - req.pause(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } - return true; - }; +IncomingForm.prototype.parse = function ( req, cb ) { + this.pause = function () { + try { + req.pause(); + } catch ( err ) { + // the stream was destroyed + if ( !this.ended ) { + // before it was completed, crash & burn + this._error( err ); + } + return false; + } + return true; + }; - this.resume = function() { - try { - req.resume(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } + this.resume = function () { + try { + req.resume(); + } catch ( err ) { + // the stream was destroyed + if ( !this.ended ) { + // before it was completed, crash & burn + this._error( err ); + } + return false; + } - return true; - }; + return true; + }; - this.writeHeaders(req.headers); + this.writeHeaders( req.headers ); - var self = this; - req - .on('error', function(err) { - self._error(err); - }) - .on('aborted', function() { - self.emit('aborted'); - }) - .on('data', function(buffer) { - self.write(buffer); - }) - .on('end', function() { - if (self.error) { - return; - } + var self = this; + req + .on( 'error', function ( err ) { + self._error( err ); + } ) + .on( 'aborted', function () { + self.emit( 'aborted' ); + } ) + .on( 'data', function ( buffer ) { + self.write( buffer ); + } ) + .on( 'end', function () { + if ( self.error ) { + return; + } - var err = self._parser.end(); - if (err) { - self._error(err); - } - }); + var err = self._parser.end(); + if ( err ) { + self._error( err ); + } + } ); - if (cb) { - var fields = {}, files = {}; - this - .on('field', function(name, value) { - fields[name] = value; - }) - .on('file', function(name, file) { - files[name] = file; - }) - .on('error', function(err) { - cb(err, fields, files); - }) - .on('end', function() { - cb(null, fields, files); - }); - } + if ( cb ) { + var fields = {}, files = {}; + this + .on( 'field', function ( name, value ) { + fields[name] = value; + } ) + .on( 'file', function ( name, file ) { + files[name] = file; + } ) + .on( 'error', function ( err ) { + cb( err, fields, files ); + } ) + .on( 'end', function () { + cb( null, fields, files ); + } ); + } - return this; + return this; }; -IncomingForm.prototype.writeHeaders = function(headers) { - this.headers = headers; - this._parseContentLength(); - this._parseContentType(); +IncomingForm.prototype.writeHeaders = function ( headers ) { + this.headers = headers; + this._parseContentLength(); + this._parseContentType(); }; -IncomingForm.prototype.write = function(buffer) { - if (!this._parser) { - this._error(new Error('unintialized parser')); - return; - } +IncomingForm.prototype.write = function ( buffer ) { + if ( !this._parser ) { + this._error( new Error( 'unintialized parser' ) ); + return; + } - this.bytesReceived += buffer.length; - this.emit('progress', this.bytesReceived, this.bytesExpected); + this.bytesReceived += buffer.length; + this.emit( 'progress', this.bytesReceived, this.bytesExpected ); - var bytesParsed = this._parser.write(buffer); - if (bytesParsed !== buffer.length) { - this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); - } + var bytesParsed = this._parser.write( buffer ); + if ( bytesParsed !== buffer.length ) { + this._error( new Error( 'parser error, ' + bytesParsed + ' of ' + buffer.length + ' bytes parsed' ) ); + } - return bytesParsed; + return bytesParsed; }; -IncomingForm.prototype.pause = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; +IncomingForm.prototype.pause = function () { + // this does nothing, unless overwritten in IncomingForm.parse + return false; }; -IncomingForm.prototype.resume = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; +IncomingForm.prototype.resume = function () { + // this does nothing, unless overwritten in IncomingForm.parse + return false; }; -IncomingForm.prototype.onPart = function(part) { - // this method can be overwritten by the user - this.handlePart(part); +IncomingForm.prototype.onPart = function ( part ) { + // this method can be overwritten by the user + this.handlePart( part ); }; -IncomingForm.prototype.handlePart = function(part) { - var self = this; +IncomingForm.prototype.handlePart = function ( part ) { + var self = this; - if (part.filename === undefined) { - var value = '' - , decoder = new StringDecoder(this.encoding); + if ( part.filename === undefined ) { + var value = '' + , decoder = new StringDecoder( this.encoding ); - part.on('data', function(buffer) { - self._fieldsSize += buffer.length; - if (self._fieldsSize > self.maxFieldsSize) { - self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); - return; - } - value += decoder.write(buffer); - }); + part.on( 'data', function ( buffer ) { + self._fieldsSize += buffer.length; + if ( self._fieldsSize > self.maxFieldsSize ) { + self._error( new Error( 'maxFieldsSize exceeded, received ' + self._fieldsSize + ' bytes of field data' ) ); + return; + } + value += decoder.write( buffer ); + } ); - part.on('end', function() { - self.emit('field', part.name, value); - }); - return; - } + part.on( 'end', function () { + self.emit( 'field', part.name, value ); + } ); + return; + } - this._flushing++; + this._flushing++; - var file = new File({ - path: this._uploadPath(part.filename), - name: part.filename, - type: part.mime, - }); + var file = new File( { + path : this._uploadPath( part.filename ), + name : part.filename, + type : part.mime, + } ); - this.emit('fileBegin', part.name, file); + this.emit( 'fileBegin', part.name, file ); - file.open(); + file.open(); - part.on('data', function(buffer) { - self.pause(); - file.write(buffer, function() { - self.resume(); - }); - }); + part.on( 'data', function ( buffer ) { + self.pause(); + file.write( buffer, function () { + self.resume(); + } ); + } ); - part.on('end', function() { - file.end(function() { - self._flushing--; - self.emit('file', part.name, file); - self._maybeEnd(); - }); - }); + part.on( 'end', function () { + file.end( function () { + self._flushing--; + self.emit( 'file', part.name, file ); + self._maybeEnd(); + } ); + } ); }; -IncomingForm.prototype._parseContentType = function() { - if (!this.headers['content-type']) { - this._error(new Error('bad content-type header, no content-type')); - return; - } +IncomingForm.prototype._parseContentType = function () { + if ( !this.headers['content-type'] ) { + this._error( new Error( 'bad content-type header, no content-type' ) ); + return; + } - if (this.headers['content-type'].match(/urlencoded/i)) { - this._initUrlencoded(); - return; - } + if ( this.headers['content-type'].match( /urlencoded/i ) ) { + this._initUrlencoded(); + return; + } - if (this.headers['content-type'].match(/multipart/i)) { - var m; - if (m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i)) { - this._initMultipart(m[1] || m[2]); - } else { - this._error(new Error('bad content-type header, no multipart boundary')); - } - return; - } + if ( this.headers['content-type'].match( /multipart/i ) ) { + var m; + if ( m = this.headers['content-type'].match( /boundary=(?:"([^"]+)"|([^;]+))/i ) ) { + this._initMultipart( m[1] || m[2] ); + } else { + this._error( new Error( 'bad content-type header, no multipart boundary' ) ); + } + return; + } - this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); + this._error( new Error( 'bad content-type header, unknown content-type: ' + this.headers['content-type'] ) ); }; -IncomingForm.prototype._error = function(err) { - if (this.error) { - return; - } +IncomingForm.prototype._error = function ( err ) { + if ( this.error ) { + return; + } - this.error = err; - this.pause(); - this.emit('error', err); + this.error = err; + this.pause(); + this.emit( 'error', err ); }; -IncomingForm.prototype._parseContentLength = function() { - if (this.headers['content-length']) { - this.bytesReceived = 0; - this.bytesExpected = parseInt(this.headers['content-length'], 10); - this.emit('progress', this.bytesReceived, this.bytesExpected); - } +IncomingForm.prototype._parseContentLength = function () { + if ( this.headers['content-length'] ) { + this.bytesReceived = 0; + this.bytesExpected = parseInt( this.headers['content-length'], 10 ); + this.emit( 'progress', this.bytesReceived, this.bytesExpected ); + } }; -IncomingForm.prototype._newParser = function() { - return new MultipartParser(); +IncomingForm.prototype._newParser = function () { + return new MultipartParser(); }; -IncomingForm.prototype._initMultipart = function(boundary) { - this.type = 'multipart'; +IncomingForm.prototype._initMultipart = function ( boundary ) { + this.type = 'multipart'; - var parser = new MultipartParser(), - self = this, - headerField, - headerValue, - part; + var parser = new MultipartParser(), + self = this, + headerField, + headerValue, + part; - parser.initWithBoundary(boundary); + parser.initWithBoundary( boundary ); - parser.onPartBegin = function() { - part = new EventEmitter(); - part.headers = {}; - part.name = null; - part.filename = null; - part.mime = null; - headerField = ''; - headerValue = ''; - }; + parser.onPartBegin = function () { + part = new EventEmitter(); + part.headers = {}; + part.name = null; + part.filename = null; + part.mime = null; + headerField = ''; + headerValue = ''; + }; - parser.onHeaderField = function(b, start, end) { - headerField += b.toString(self.encoding, start, end); - }; + parser.onHeaderField = function ( b, start, end ) { + headerField += b.toString( self.encoding, start, end ); + }; - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString(self.encoding, start, end); - }; + parser.onHeaderValue = function ( b, start, end ) { + headerValue += b.toString( self.encoding, start, end ); + }; - parser.onHeaderEnd = function() { - headerField = headerField.toLowerCase(); - part.headers[headerField] = headerValue; + parser.onHeaderEnd = function () { + headerField = headerField.toLowerCase(); + part.headers[headerField] = headerValue; - var m; - if (headerField == 'content-disposition') { - if (m = headerValue.match(/name="([^"]+)"/i)) { - part.name = m[1]; - } + var m; + if ( headerField == 'content-disposition' ) { + if ( m = headerValue.match( /name="([^"]+)"/i ) ) { + part.name = m[1]; + } - part.filename = self._fileName(headerValue); - } else if (headerField == 'content-type') { - part.mime = headerValue; - } + part.filename = self._fileName( headerValue ); + } else if ( headerField == 'content-type' ) { + part.mime = headerValue; + } - headerField = ''; - headerValue = ''; - }; + headerField = ''; + headerValue = ''; + }; - parser.onHeadersEnd = function() { - self.onPart(part); - }; + parser.onHeadersEnd = function () { + self.onPart( part ); + }; - parser.onPartData = function(b, start, end) { - part.emit('data', b.slice(start, end)); - }; + parser.onPartData = function ( b, start, end ) { + part.emit( 'data', b.slice( start, end ) ); + }; - parser.onPartEnd = function() { - part.emit('end'); - }; + parser.onPartEnd = function () { + part.emit( 'end' ); + }; - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; + parser.onEnd = function () { + self.ended = true; + self._maybeEnd(); + }; - this._parser = parser; + this._parser = parser; }; -IncomingForm.prototype._fileName = function(headerValue) { - var m = headerValue.match(/filename="(.*?)"($|; )/i) - if (!m) return; +IncomingForm.prototype._fileName = function ( headerValue ) { + var m = headerValue.match( /filename="(.*?)"($|; )/i ) + if ( !m ) { + return; + } - var filename = m[1].substr(m[1].lastIndexOf('\\') + 1); - filename = filename.replace(/%22/g, '"'); - filename = filename.replace(/&#([\d]{4});/g, function(m, code) { - return String.fromCharCode(code); - }); - return filename; + var filename = m[1].substr( m[1].lastIndexOf( '\\' ) + 1 ); + filename = filename.replace( /%22/g, '"' ); + filename = filename.replace( /&#([\d]{4});/g, function ( m, code ) { + return String.fromCharCode( code ); + } ); + return filename; }; -IncomingForm.prototype._initUrlencoded = function() { - this.type = 'urlencoded'; +IncomingForm.prototype._initUrlencoded = function () { + this.type = 'urlencoded'; - var parser = new QuerystringParser() - , self = this; + var parser = new QuerystringParser() + , self = this; - parser.onField = function(key, val) { - self.emit('field', key, val); - }; + parser.onField = function ( key, val ) { + self.emit( 'field', key, val ); + }; - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; + parser.onEnd = function () { + self.ended = true; + self._maybeEnd(); + }; - this._parser = parser; + this._parser = parser; }; -IncomingForm.prototype._uploadPath = function(filename) { - var name = ''; - for (var i = 0; i < 32; i++) { - name += Math.floor(Math.random() * 16).toString(16); - } +IncomingForm.prototype._uploadPath = function ( filename ) { + var name = ''; + for ( var i = 0; i < 32; i++ ) { + name += Math.floor( Math.random() * 16 ).toString( 16 ); + } - if (this.keepExtensions) { - var ext = path.extname(filename); - ext = ext.replace(/(\.[a-z0-9]+).*/, '$1') + if ( this.keepExtensions ) { + var ext = path.extname( filename ); + ext = ext.replace( /(\.[a-z0-9]+).*/, '$1' ) - name += ext; - } + name += ext; + } - return path.join(this.uploadDir, name); + return path.join( this.uploadDir, name ); }; -IncomingForm.prototype._maybeEnd = function() { - if (!this.ended || this._flushing) { - return; - } +IncomingForm.prototype._maybeEnd = function () { + if ( !this.ended || this._flushing ) { + return; + } - this.emit('end'); + this.emit( 'end' ); }; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js index 7a6e3e1..ae19acc 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js @@ -1,3 +1,3 @@ -var IncomingForm = require('./incoming_form').IncomingForm; +var IncomingForm = require( './incoming_form' ).IncomingForm; IncomingForm.IncomingForm = IncomingForm; module.exports = IncomingForm; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js index 9ca567c..34d56ce 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js @@ -1,312 +1,315 @@ -var Buffer = require('buffer').Buffer, - s = 0, - S = - { PARSER_UNINITIALIZED: s++, - START: s++, - START_BOUNDARY: s++, - HEADER_FIELD_START: s++, - HEADER_FIELD: s++, - HEADER_VALUE_START: s++, - HEADER_VALUE: s++, - HEADER_VALUE_ALMOST_DONE: s++, - HEADERS_ALMOST_DONE: s++, - PART_DATA_START: s++, - PART_DATA: s++, - PART_END: s++, - END: s++, - }, +var Buffer = require( 'buffer' ).Buffer, + s = 0, + S = + { PARSER_UNINITIALIZED : s++, + START : s++, + START_BOUNDARY : s++, + HEADER_FIELD_START : s++, + HEADER_FIELD : s++, + HEADER_VALUE_START : s++, + HEADER_VALUE : s++, + HEADER_VALUE_ALMOST_DONE : s++, + HEADERS_ALMOST_DONE : s++, + PART_DATA_START : s++, + PART_DATA : s++, + PART_END : s++, + END : s++, + }, - f = 1, - F = - { PART_BOUNDARY: f, - LAST_BOUNDARY: f *= 2, - }, + f = 1, + F = + { PART_BOUNDARY : f, + LAST_BOUNDARY : f *= 2, + }, - LF = 10, - CR = 13, - SPACE = 32, - HYPHEN = 45, - COLON = 58, - A = 97, - Z = 122, + LF = 10, + CR = 13, + SPACE = 32, + HYPHEN = 45, + COLON = 58, + A = 97, + Z = 122, - lower = function(c) { - return c | 0x20; - }; + lower = function ( c ) { + return c | 0x20; + }; -for (var s in S) { - exports[s] = S[s]; +for ( var s in S ) { + exports[s] = S[s]; } function MultipartParser() { - this.boundary = null; - this.boundaryChars = null; - this.lookbehind = null; - this.state = S.PARSER_UNINITIALIZED; + this.boundary = null; + this.boundaryChars = null; + this.lookbehind = null; + this.state = S.PARSER_UNINITIALIZED; - this.index = null; - this.flags = 0; -}; + this.index = null; + this.flags = 0; +} +; exports.MultipartParser = MultipartParser; -MultipartParser.stateToString = function(stateNumber) { - for (var state in S) { - var number = S[state]; - if (number === stateNumber) return state; - } +MultipartParser.stateToString = function ( stateNumber ) { + for ( var state in S ) { + var number = S[state]; + if ( number === stateNumber ) { + return state; + } + } }; -MultipartParser.prototype.initWithBoundary = function(str) { - this.boundary = new Buffer(str.length+4); - this.boundary.write('\r\n--', 'ascii', 0); - this.boundary.write(str, 'ascii', 4); - this.lookbehind = new Buffer(this.boundary.length+8); - this.state = S.START; +MultipartParser.prototype.initWithBoundary = function ( str ) { + this.boundary = new Buffer( str.length + 4 ); + this.boundary.write( '\r\n--', 'ascii', 0 ); + this.boundary.write( str, 'ascii', 4 ); + this.lookbehind = new Buffer( this.boundary.length + 8 ); + this.state = S.START; - this.boundaryChars = {}; - for (var i = 0; i < this.boundary.length; i++) { - this.boundaryChars[this.boundary[i]] = true; - } + this.boundaryChars = {}; + for ( var i = 0; i < this.boundary.length; i++ ) { + this.boundaryChars[this.boundary[i]] = true; + } }; -MultipartParser.prototype.write = function(buffer) { - var self = this, - i = 0, - len = buffer.length, - prevIndex = this.index, - index = this.index, - state = this.state, - flags = this.flags, - lookbehind = this.lookbehind, - boundary = this.boundary, - boundaryChars = this.boundaryChars, - boundaryLength = this.boundary.length, - boundaryEnd = boundaryLength - 1, - bufferLength = buffer.length, - c, - cl, +MultipartParser.prototype.write = function ( buffer ) { + var self = this, + i = 0, + len = buffer.length, + prevIndex = this.index, + index = this.index, + state = this.state, + flags = this.flags, + lookbehind = this.lookbehind, + boundary = this.boundary, + boundaryChars = this.boundaryChars, + boundaryLength = this.boundary.length, + boundaryEnd = boundaryLength - 1, + bufferLength = buffer.length, + c, + cl, - mark = function(name) { - self[name+'Mark'] = i; - }, - clear = function(name) { - delete self[name+'Mark']; - }, - callback = function(name, buffer, start, end) { - if (start !== undefined && start === end) { - return; - } + mark = function ( name ) { + self[name + 'Mark'] = i; + }, + clear = function ( name ) { + delete self[name + 'Mark']; + }, + callback = function ( name, buffer, start, end ) { + if ( start !== undefined && start === end ) { + return; + } - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](buffer, start, end); - } - }, - dataCallback = function(name, clear) { - var markSymbol = name+'Mark'; - if (!(markSymbol in self)) { - return; - } + var callbackSymbol = 'on' + name.substr( 0, 1 ).toUpperCase() + name.substr( 1 ); + if ( callbackSymbol in self ) { + self[callbackSymbol]( buffer, start, end ); + } + }, + dataCallback = function ( name, clear ) { + var markSymbol = name + 'Mark'; + if ( !(markSymbol in self) ) { + return; + } - if (!clear) { - callback(name, buffer, self[markSymbol], buffer.length); - self[markSymbol] = 0; - } else { - callback(name, buffer, self[markSymbol], i); - delete self[markSymbol]; - } - }; + if ( !clear ) { + callback( name, buffer, self[markSymbol], buffer.length ); + self[markSymbol] = 0; + } else { + callback( name, buffer, self[markSymbol], i ); + delete self[markSymbol]; + } + }; - for (i = 0; i < len; i++) { - c = buffer[i]; - switch (state) { - case S.PARSER_UNINITIALIZED: - return i; - case S.START: - index = 0; - state = S.START_BOUNDARY; - case S.START_BOUNDARY: - if (index == boundary.length - 2) { - if (c != CR) { - return i; - } - index++; - break; - } else if (index - 1 == boundary.length - 2) { - if (c != LF) { - return i; - } - index = 0; - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } + for ( i = 0; i < len; i++ ) { + c = buffer[i]; + switch ( state ) { + case S.PARSER_UNINITIALIZED: + return i; + case S.START: + index = 0; + state = S.START_BOUNDARY; + case S.START_BOUNDARY: + if ( index == boundary.length - 2 ) { + if ( c != CR ) { + return i; + } + index++; + break; + } else if ( index - 1 == boundary.length - 2 ) { + if ( c != LF ) { + return i; + } + index = 0; + callback( 'partBegin' ); + state = S.HEADER_FIELD_START; + break; + } - if (c != boundary[index+2]) { - return i; - } - index++; - break; - case S.HEADER_FIELD_START: - state = S.HEADER_FIELD; - mark('headerField'); - index = 0; - case S.HEADER_FIELD: - if (c == CR) { - clear('headerField'); - state = S.HEADERS_ALMOST_DONE; - break; - } + if ( c != boundary[index + 2] ) { + return i; + } + index++; + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark( 'headerField' ); + index = 0; + case S.HEADER_FIELD: + if ( c == CR ) { + clear( 'headerField' ); + state = S.HEADERS_ALMOST_DONE; + break; + } - index++; - if (c == HYPHEN) { - break; - } + index++; + if ( c == HYPHEN ) { + break; + } - if (c == COLON) { - if (index == 1) { - // empty header field - return i; - } - dataCallback('headerField', true); - state = S.HEADER_VALUE_START; - break; - } + if ( c == COLON ) { + if ( index == 1 ) { + // empty header field + return i; + } + dataCallback( 'headerField', true ); + state = S.HEADER_VALUE_START; + break; + } - cl = lower(c); - if (cl < A || cl > Z) { - return i; - } - break; - case S.HEADER_VALUE_START: - if (c == SPACE) { - break; - } + cl = lower( c ); + if ( cl < A || cl > Z ) { + return i; + } + break; + case S.HEADER_VALUE_START: + if ( c == SPACE ) { + break; + } - mark('headerValue'); - state = S.HEADER_VALUE; - case S.HEADER_VALUE: - if (c == CR) { - dataCallback('headerValue', true); - callback('headerEnd'); - state = S.HEADER_VALUE_ALMOST_DONE; - } - break; - case S.HEADER_VALUE_ALMOST_DONE: - if (c != LF) { - return i; - } - state = S.HEADER_FIELD_START; - break; - case S.HEADERS_ALMOST_DONE: - if (c != LF) { - return i; - } + mark( 'headerValue' ); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if ( c == CR ) { + dataCallback( 'headerValue', true ); + callback( 'headerEnd' ); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if ( c != LF ) { + return i; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if ( c != LF ) { + return i; + } - callback('headersEnd'); - state = S.PART_DATA_START; - break; - case S.PART_DATA_START: - state = S.PART_DATA - mark('partData'); - case S.PART_DATA: - prevIndex = index; + callback( 'headersEnd' ); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA + mark( 'partData' ); + case S.PART_DATA: + prevIndex = index; - if (index == 0) { - // boyer-moore derrived algorithm to safely skip non-boundary data - i += boundaryEnd; - while (i < bufferLength && !(buffer[i] in boundaryChars)) { - i += boundaryLength; - } - i -= boundaryEnd; - c = buffer[i]; - } + if ( index == 0 ) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while ( i < bufferLength && !(buffer[i] in boundaryChars) ) { + i += boundaryLength; + } + i -= boundaryEnd; + c = buffer[i]; + } - if (index < boundary.length) { - if (boundary[index] == c) { - if (index == 0) { - dataCallback('partData', true); - } - index++; - } else { - index = 0; - } - } else if (index == boundary.length) { - index++; - if (c == CR) { - // CR = part boundary - flags |= F.PART_BOUNDARY; - } else if (c == HYPHEN) { - // HYPHEN = end boundary - flags |= F.LAST_BOUNDARY; - } else { - index = 0; - } - } else if (index - 1 == boundary.length) { - if (flags & F.PART_BOUNDARY) { - index = 0; - if (c == LF) { - // unset the PART_BOUNDARY flag - flags &= ~F.PART_BOUNDARY; - callback('partEnd'); - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - } else if (flags & F.LAST_BOUNDARY) { - if (c == HYPHEN) { - callback('partEnd'); - callback('end'); - state = S.END; - } else { - index = 0; - } - } else { - index = 0; - } - } + if ( index < boundary.length ) { + if ( boundary[index] == c ) { + if ( index == 0 ) { + dataCallback( 'partData', true ); + } + index++; + } else { + index = 0; + } + } else if ( index == boundary.length ) { + index++; + if ( c == CR ) { + // CR = part boundary + flags |= F.PART_BOUNDARY; + } else if ( c == HYPHEN ) { + // HYPHEN = end boundary + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if ( index - 1 == boundary.length ) { + if ( flags & F.PART_BOUNDARY ) { + index = 0; + if ( c == LF ) { + // unset the PART_BOUNDARY flag + flags &= ~F.PART_BOUNDARY; + callback( 'partEnd' ); + callback( 'partBegin' ); + state = S.HEADER_FIELD_START; + break; + } + } else if ( flags & F.LAST_BOUNDARY ) { + if ( c == HYPHEN ) { + callback( 'partEnd' ); + callback( 'end' ); + state = S.END; + } else { + index = 0; + } + } else { + index = 0; + } + } - if (index > 0) { - // when matching a possible boundary, keep a lookbehind reference - // in case it turns out to be a false lead - lookbehind[index-1] = c; - } else if (prevIndex > 0) { - // if our boundary turned out to be rubbish, the captured lookbehind - // belongs to partData - callback('partData', lookbehind, 0, prevIndex); - prevIndex = 0; - mark('partData'); + if ( index > 0 ) { + // when matching a possible boundary, keep a lookbehind reference + // in case it turns out to be a false lead + lookbehind[index - 1] = c; + } else if ( prevIndex > 0 ) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + callback( 'partData', lookbehind, 0, prevIndex ); + prevIndex = 0; + mark( 'partData' ); - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } - break; - case S.END: - break; - default: - return i; - } - } + break; + case S.END: + break; + default: + return i; + } + } - dataCallback('headerField'); - dataCallback('headerValue'); - dataCallback('partData'); + dataCallback( 'headerField' ); + dataCallback( 'headerValue' ); + dataCallback( 'partData' ); - this.index = index; - this.state = state; - this.flags = flags; + this.index = index; + this.state = state; + this.flags = flags; - return len; + return len; }; -MultipartParser.prototype.end = function() { - if (this.state != S.END) { - return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); - } +MultipartParser.prototype.end = function () { + if ( this.state != S.END ) { + return new Error( 'MultipartParser.end(): stream ended unexpectedly: ' + this.explain() ); + } }; -MultipartParser.prototype.explain = function() { - return 'state = ' + MultipartParser.stateToString(this.state); +MultipartParser.prototype.explain = function () { + return 'state = ' + MultipartParser.stateToString( this.state ); }; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js index 63f109e..08cca28 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js @@ -1,25 +1,28 @@ -if (global.GENTLY) require = GENTLY.hijack(require); +if ( global.GENTLY ) { + require = GENTLY.hijack( require ); +} // This is a buffering parser, not quite as nice as the multipart one. // If I find time I'll rewrite this to be fully streaming as well -var querystring = require('querystring'); +var querystring = require( 'querystring' ); function QuerystringParser() { - this.buffer = ''; -}; + this.buffer = ''; +} +; exports.QuerystringParser = QuerystringParser; -QuerystringParser.prototype.write = function(buffer) { - this.buffer += buffer.toString('ascii'); - return buffer.length; +QuerystringParser.prototype.write = function ( buffer ) { + this.buffer += buffer.toString( 'ascii' ); + return buffer.length; }; -QuerystringParser.prototype.end = function() { - var fields = querystring.parse(this.buffer); - for (var field in fields) { - this.onField(field, fields[field]); - } - this.buffer = ''; +QuerystringParser.prototype.end = function () { + var fields = querystring.parse( this.buffer ); + for ( var field in fields ) { + this.onField( field, fields[field] ); + } + this.buffer = ''; - this.onEnd(); + this.onEnd(); }; \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js index e9493e9..760909f 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js @@ -1,6 +1,6 @@ // Backwards compatibility ... try { - module.exports = require('util'); -} catch (e) { - module.exports = require('sys'); + module.exports = require( 'util' ); +} catch ( e ) { + module.exports = require( 'sys' ); } diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/package.json b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/package.json index 4cf5f2d..641245f 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/package.json +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/package.json @@ -1,22 +1,22 @@ { - "name": "formidable", - "version": "1.0.9", - "dependencies": {}, - "devDependencies": { - "gently": "0.8.0", - "findit": "0.1.1", - "hashish": "0.0.4", - "urun": "0.0.4", - "utest": "0.0.3" - }, - "directories": { - "lib": "./lib" - }, - "main": "./lib/index", - "scripts": { - "test": "make test" - }, - "engines": { - "node": "*" - } + "name" : "formidable", + "version" : "1.0.9", + "dependencies" : {}, + "devDependencies" : { + "gently" : "0.8.0", + "findit" : "0.1.1", + "hashish" : "0.0.4", + "urun" : "0.0.4", + "utest" : "0.0.3" + }, + "directories" : { + "lib" : "./lib" + }, + "main" : "./lib/index", + "scripts" : { + "test" : "make test" + }, + "engines" : { + "node" : "*" + } } \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js index eb432ad..e0cdc01 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/common.js @@ -1,19 +1,19 @@ -var mysql = require('..'); -var path = require('path'); +var mysql = require( '..' ); +var path = require( 'path' ); -var root = path.join(__dirname, '../'); +var root = path.join( __dirname, '../' ); exports.dir = { - root : root, - lib : root + '/lib', - fixture : root + '/test/fixture', - tmp : root + '/test/tmp', + root : root, + lib : root + '/lib', + fixture : root + '/test/fixture', + tmp : root + '/test/tmp', }; exports.port = 13532; -exports.formidable = require('..'); -exports.assert = require('assert'); +exports.formidable = require( '..' ); +exports.assert = require( 'assert' ); -exports.require = function(lib) { - return require(exports.dir.lib + '/' + lib); +exports.require = function ( lib ) { + return require( exports.dir.lib + '/' + lib ); }; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js index 0bae449..d01e902 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/no-filename.js @@ -1,3 +1,3 @@ module.exports['generic.http'] = [ - {type: 'file', name: 'upload', filename: '', fixture: 'plain.txt'}, + {type : 'file', name : 'upload', filename : '', fixture : 'plain.txt'}, ]; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js index eb76fdc..2781ab2 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/js/special-chars-in-filename.js @@ -1,21 +1,22 @@ var properFilename = 'funkyfilename.txt'; -function expect(filename) { - return [ - {type: 'field', name: 'title', value: 'Weird filename'}, - {type: 'file', name: 'upload', filename: filename, fixture: properFilename}, - ]; -}; +function expect( filename ) { + return [ + {type : 'field', name : 'title', value : 'Weird filename'}, + {type : 'file', name : 'upload', filename : filename, fixture : properFilename}, + ]; +} +; var webkit = " ? % * | \" < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; var ffOrIe = " ? % * | \" < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; module.exports = { - 'osx-chrome-13.http' : expect(webkit), - 'osx-firefox-3.6.http' : expect(ffOrIe), - 'osx-safari-5.http' : expect(webkit), - 'xp-chrome-12.http' : expect(webkit), - 'xp-ie-7.http' : expect(ffOrIe), - 'xp-ie-8.http' : expect(ffOrIe), - 'xp-safari-5.http' : expect(webkit), + 'osx-chrome-13.http' : expect( webkit ), + 'osx-firefox-3.6.http' : expect( ffOrIe ), + 'osx-safari-5.http' : expect( webkit ), + 'xp-chrome-12.http' : expect( webkit ), + 'xp-ie-7.http' : expect( ffOrIe ), + 'xp-ie-8.http' : expect( ffOrIe ), + 'xp-safari-5.http' : expect( webkit ), }; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js index a476169..5e36f7f 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/fixture/multipart.js @@ -1,72 +1,69 @@ exports['rfc1867'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; +{ boundary : 'AaB03x', + raw : '--AaB03x\r\n' + + 'content-disposition: form-data; name="field1"\r\n' + + '\r\n' + + 'Joe Blow\r\nalmost tricked you!\r\n' + + '--AaB03x\r\n' + + 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + '... contents of file1.txt ...\r\r\n' + + '--AaB03x--\r\n', + parts : [ + { headers : { + 'content-disposition' : 'form-data; name="field1"', + }, + data : 'Joe Blow\r\nalmost tricked you!', + }, + { headers : { + 'content-disposition' : 'form-data; name="pics"; filename="file1.txt"', + 'Content-Type' : 'text/plain', + }, + data : '... contents of file1.txt ...\r', + } + ] +}; exports['noTrailing\r\n'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; +{ boundary : 'AaB03x', + raw : '--AaB03x\r\n' + + 'content-disposition: form-data; name="field1"\r\n' + + '\r\n' + + 'Joe Blow\r\nalmost tricked you!\r\n' + + '--AaB03x\r\n' + + 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + '... contents of file1.txt ...\r\r\n' + + '--AaB03x--', + parts : [ + { headers : { + 'content-disposition' : 'form-data; name="field1"', + }, + data : 'Joe Blow\r\nalmost tricked you!', + }, + { headers : { + 'content-disposition' : 'form-data; name="pics"; filename="file1.txt"', + 'Content-Type' : 'text/plain', + }, + data : '... contents of file1.txt ...\r', + } + ] +}; exports['emptyHeader'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - ': foo\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - expectError: true, - }; +{ boundary : 'AaB03x', + raw : '--AaB03x\r\n' + + 'content-disposition: form-data; name="field1"\r\n' + + ': foo\r\n' + + '\r\n' + + 'Joe Blow\r\nalmost tricked you!\r\n' + + '--AaB03x\r\n' + + 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n' + + 'Content-Type: text/plain\r\n' + + '\r\n' + + '... contents of file1.txt ...\r\r\n' + + '--AaB03x--\r\n', + expectError : true, +}; diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js index 66ad259..ddbf701 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/integration/test-fixtures.js @@ -1,89 +1,97 @@ -var hashish = require('hashish'); -var fs = require('fs'); -var findit = require('findit'); -var path = require('path'); -var http = require('http'); -var net = require('net'); -var assert = require('assert'); +var hashish = require( 'hashish' ); +var fs = require( 'fs' ); +var findit = require( 'findit' ); +var path = require( 'path' ); +var http = require( 'http' ); +var net = require( 'net' ); +var assert = require( 'assert' ); -var common = require('../common'); +var common = require( '../common' ); var formidable = common.formidable; var server = http.createServer(); -server.listen(common.port, findFixtures); +server.listen( common.port, findFixtures ); function findFixtures() { - var fixtures = []; - findit - .sync(common.dir.fixture + '/js') - .forEach(function(jsPath) { - if (!/\.js$/.test(jsPath)) return; + var fixtures = []; + findit + .sync( common.dir.fixture + '/js' ) + .forEach( function ( jsPath ) { + if ( !/\.js$/.test( jsPath ) ) { + return; + } - var group = path.basename(jsPath, '.js'); - hashish.forEach(require(jsPath), function(fixture, name) { - fixtures.push({ - name : group + '/' + name, - fixture : fixture, - }); - }); - }); + var group = path.basename( jsPath, '.js' ); + hashish.forEach( require( jsPath ), function ( fixture, name ) { + fixtures.push( { + name : group + '/' + name, + fixture : fixture, + } ); + } ); + } ); - testNext(fixtures); + testNext( fixtures ); } -function testNext(fixtures) { - var fixture = fixtures.shift(); - if (!fixture) return server.close(); +function testNext( fixtures ) { + var fixture = fixtures.shift(); + if ( !fixture ) { + return server.close(); + } - var name = fixture.name; - var fixture = fixture.fixture; + var name = fixture.name; + var fixture = fixture.fixture; - uploadFixture(name, function(err, parts) { - if (err) throw err; + uploadFixture( name, function ( err, parts ) { + if ( err ) { + throw err; + } - fixture.forEach(function(expectedPart, i) { - var parsedPart = parts[i]; - assert.equal(parsedPart.type, expectedPart.type); - assert.equal(parsedPart.name, expectedPart.name); + fixture.forEach( function ( expectedPart, i ) { + var parsedPart = parts[i]; + assert.equal( parsedPart.type, expectedPart.type ); + assert.equal( parsedPart.name, expectedPart.name ); - if (parsedPart.type === 'file') { - var filename = parsedPart.value.name; - assert.equal(filename, expectedPart.filename); - } - }); + if ( parsedPart.type === 'file' ) { + var filename = parsedPart.value.name; + assert.equal( filename, expectedPart.filename ); + } + } ); - testNext(fixtures); - }); -}; - -function uploadFixture(name, cb) { - server.once('request', function(req, res) { - var form = new formidable.IncomingForm(); - form.uploadDir = common.dir.tmp; - form.parse(req); - - function callback() { - var realCallback = cb; - cb = function() {}; - realCallback.apply(null, arguments); - } - - var parts = []; - form - .on('error', callback) - .on('fileBegin', function(name, value) { - parts.push({type: 'file', name: name, value: value}); - }) - .on('field', function(name, value) { - parts.push({type: 'field', name: name, value: value}); - }) - .on('end', function() { - callback(null, parts); - }); - }); - - var socket = net.createConnection(common.port); - var file = fs.createReadStream(common.dir.fixture + '/http/' + name); - - file.pipe(socket); + testNext( fixtures ); + } ); +} +; + +function uploadFixture( name, cb ) { + server.once( 'request', function ( req, res ) { + var form = new formidable.IncomingForm(); + form.uploadDir = common.dir.tmp; + form.parse( req ); + + function callback() { + var realCallback = cb; + cb = function () { + }; + realCallback.apply( null, arguments ); + } + + var parts = []; + form + .on( 'error', callback ) + .on( 'fileBegin', function ( name, value ) { + parts.push( {type : 'file', name : name, value : value} ); + } ) + .on( 'field', function ( name, value ) { + parts.push( {type : 'field', name : name, value : value} ); + } ) + .on( 'end', function () { + callback( null, parts ); + } ); + } ); + + var socket = net.createConnection( common.port ); + var file = fs.createReadStream( common.dir.fixture + '/http/' + name ); + + file.pipe( socket ); } diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js index 2b98598..77aac77 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/common.js @@ -1,24 +1,24 @@ -var path = require('path'), - fs = require('fs'); +var path = require( 'path' ), + fs = require( 'fs' ); try { - global.Gently = require('gently'); -} catch (e) { - throw new Error('this test suite requires node-gently'); + global.Gently = require( 'gently' ); +} catch ( e ) { + throw new Error( 'this test suite requires node-gently' ); } -exports.lib = path.join(__dirname, '../../lib'); +exports.lib = path.join( __dirname, '../../lib' ); global.GENTLY = new Gently(); -global.assert = require('assert'); +global.assert = require( 'assert' ); global.TEST_PORT = 13532; -global.TEST_FIXTURES = path.join(__dirname, '../fixture'); -global.TEST_TMP = path.join(__dirname, '../tmp'); +global.TEST_FIXTURES = path.join( __dirname, '../fixture' ); +global.TEST_TMP = path.join( __dirname, '../tmp' ); // Stupid new feature in node that complains about gently attaching too many // listeners to process 'exit'. This is a workaround until I can think of a // better way to deal with this. -if (process.setMaxListeners) { - process.setMaxListeners(10000); +if ( process.setMaxListeners ) { + process.setMaxListeners( 10000 ); } diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js index 75232aa..602c228 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/integration/test-multipart-parser.js @@ -1,80 +1,80 @@ -var common = require('../common'); +var common = require( '../common' ); var CHUNK_LENGTH = 10, - multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - parser = new MultipartParser(), - fixtures = require(TEST_FIXTURES + '/multipart'), - Buffer = require('buffer').Buffer; + multipartParser = require( common.lib + '/multipart_parser' ), + MultipartParser = multipartParser.MultipartParser, + parser = new MultipartParser(), + fixtures = require( TEST_FIXTURES + '/multipart' ), + Buffer = require( 'buffer' ).Buffer; -Object.keys(fixtures).forEach(function(name) { - var fixture = fixtures[name], - buffer = new Buffer(Buffer.byteLength(fixture.raw, 'binary')), - offset = 0, - chunk, - nparsed, +Object.keys( fixtures ).forEach( function ( name ) { + var fixture = fixtures[name], + buffer = new Buffer( Buffer.byteLength( fixture.raw, 'binary' ) ), + offset = 0, + chunk, + nparsed, - parts = [], - part = null, - headerField, - headerValue, - endCalled = ''; + parts = [], + part = null, + headerField, + headerValue, + endCalled = ''; - parser.initWithBoundary(fixture.boundary); - parser.onPartBegin = function() { - part = {headers: {}, data: ''}; - parts.push(part); - headerField = ''; - headerValue = ''; - }; + parser.initWithBoundary( fixture.boundary ); + parser.onPartBegin = function () { + part = {headers : {}, data : ''}; + parts.push( part ); + headerField = ''; + headerValue = ''; + }; - parser.onHeaderField = function(b, start, end) { - headerField += b.toString('ascii', start, end); - }; + parser.onHeaderField = function ( b, start, end ) { + headerField += b.toString( 'ascii', start, end ); + }; - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString('ascii', start, end); - } + parser.onHeaderValue = function ( b, start, end ) { + headerValue += b.toString( 'ascii', start, end ); + } - parser.onHeaderEnd = function() { - part.headers[headerField] = headerValue; - headerField = ''; - headerValue = ''; - }; + parser.onHeaderEnd = function () { + part.headers[headerField] = headerValue; + headerField = ''; + headerValue = ''; + }; - parser.onPartData = function(b, start, end) { - var str = b.toString('ascii', start, end); - part.data += b.slice(start, end); - } + parser.onPartData = function ( b, start, end ) { + var str = b.toString( 'ascii', start, end ); + part.data += b.slice( start, end ); + } - parser.onEnd = function() { - endCalled = true; - } + parser.onEnd = function () { + endCalled = true; + } - buffer.write(fixture.raw, 'binary', 0); + buffer.write( fixture.raw, 'binary', 0 ); - while (offset < buffer.length) { - if (offset + CHUNK_LENGTH < buffer.length) { - chunk = buffer.slice(offset, offset+CHUNK_LENGTH); - } else { - chunk = buffer.slice(offset, buffer.length); - } - offset = offset + CHUNK_LENGTH; + while ( offset < buffer.length ) { + if ( offset + CHUNK_LENGTH < buffer.length ) { + chunk = buffer.slice( offset, offset + CHUNK_LENGTH ); + } else { + chunk = buffer.slice( offset, buffer.length ); + } + offset = offset + CHUNK_LENGTH; - nparsed = parser.write(chunk); - if (nparsed != chunk.length) { - if (fixture.expectError) { - return; - } - puts('-- ERROR --'); - p(chunk.toString('ascii')); - throw new Error(chunk.length+' bytes written, but only '+nparsed+' bytes parsed!'); - } - } + nparsed = parser.write( chunk ); + if ( nparsed != chunk.length ) { + if ( fixture.expectError ) { + return; + } + puts( '-- ERROR --' ); + p( chunk.toString( 'ascii' ) ); + throw new Error( chunk.length + ' bytes written, but only ' + nparsed + ' bytes parsed!' ); + } + } - if (fixture.expectError) { - throw new Error('expected parse error did not happen'); - } + if ( fixture.expectError ) { + throw new Error( 'expected parse error did not happen' ); + } - assert.ok(endCalled); - assert.deepEqual(parts, fixture.parts); -}); + assert.ok( endCalled ); + assert.deepEqual( parts, fixture.parts ); +} ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js index 52ceedb..49c7f91 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-file.js @@ -1,104 +1,104 @@ -var common = require('../common'); -var WriteStreamStub = GENTLY.stub('fs', 'WriteStream'); +var common = require( '../common' ); +var WriteStreamStub = GENTLY.stub( 'fs', 'WriteStream' ); -var File = require(common.lib + '/file'), - EventEmitter = require('events').EventEmitter, - file, - gently; +var File = require( common.lib + '/file' ), + EventEmitter = require( 'events' ).EventEmitter, + file, + gently; -function test(test) { - gently = new Gently(); - file = new File(); - test(); - gently.verify(test.name); +function test( test ) { + gently = new Gently(); + file = new File(); + test(); + gently.verify( test.name ); } -test(function constructor() { - assert.ok(file instanceof EventEmitter); - assert.strictEqual(file.size, 0); - assert.strictEqual(file.path, null); - assert.strictEqual(file.name, null); - assert.strictEqual(file.type, null); - assert.strictEqual(file.lastModifiedDate, null); +test( function constructor() { + assert.ok( file instanceof EventEmitter ); + assert.strictEqual( file.size, 0 ); + assert.strictEqual( file.path, null ); + assert.strictEqual( file.name, null ); + assert.strictEqual( file.type, null ); + assert.strictEqual( file.lastModifiedDate, null ); - assert.strictEqual(file._writeStream, null); + assert.strictEqual( file._writeStream, null ); - (function testSetProperties() { - var file2 = new File({foo: 'bar'}); - assert.equal(file2.foo, 'bar'); - })(); -}); + (function testSetProperties() { + var file2 = new File( {foo : 'bar'} ); + assert.equal( file2.foo, 'bar' ); + })(); +} ); -test(function open() { - var WRITE_STREAM; - file.path = '/foo'; +test( function open() { + var WRITE_STREAM; + file.path = '/foo'; - gently.expect(WriteStreamStub, 'new', function (path) { - WRITE_STREAM = this; - assert.strictEqual(path, file.path); - }); + gently.expect( WriteStreamStub, 'new', function ( path ) { + WRITE_STREAM = this; + assert.strictEqual( path, file.path ); + } ); - file.open(); - assert.strictEqual(file._writeStream, WRITE_STREAM); -}); + file.open(); + assert.strictEqual( file._writeStream, WRITE_STREAM ); +} ); -test(function write() { - var BUFFER = {length: 10}, - CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; +test( function write() { + var BUFFER = {length : 10}, + CB_STUB, + CB = function () { + CB_STUB.apply( this, arguments ); + }; - file._writeStream = {}; + file._writeStream = {}; - gently.expect(file._writeStream, 'write', function (buffer, cb) { - assert.strictEqual(buffer, BUFFER); + gently.expect( file._writeStream, 'write', function ( buffer, cb ) { + assert.strictEqual( buffer, BUFFER ); - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.ok(file.lastModifiedDate instanceof Date); - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); + gently.expect( file, 'emit', function ( event, bytesWritten ) { + assert.ok( file.lastModifiedDate instanceof Date ); + assert.equal( event, 'progress' ); + assert.equal( bytesWritten, file.size ); + } ); - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 10); - }); + CB_STUB = gently.expect( function writeCb() { + assert.equal( file.size, 10 ); + } ); - cb(); + cb(); - gently.expect(file, 'emit', function (event, bytesWritten) { - assert.equal(event, 'progress'); - assert.equal(bytesWritten, file.size); - }); + gently.expect( file, 'emit', function ( event, bytesWritten ) { + assert.equal( event, 'progress' ); + assert.equal( bytesWritten, file.size ); + } ); - CB_STUB = gently.expect(function writeCb() { - assert.equal(file.size, 20); - }); + CB_STUB = gently.expect( function writeCb() { + assert.equal( file.size, 20 ); + } ); - cb(); - }); + cb(); + } ); - file.write(BUFFER, CB); -}); + file.write( BUFFER, CB ); +} ); -test(function end() { - var CB_STUB, - CB = function() { - CB_STUB.apply(this, arguments); - }; +test( function end() { + var CB_STUB, + CB = function () { + CB_STUB.apply( this, arguments ); + }; - file._writeStream = {}; + file._writeStream = {}; - gently.expect(file._writeStream, 'end', function (cb) { - gently.expect(file, 'emit', function (event) { - assert.equal(event, 'end'); - }); + gently.expect( file._writeStream, 'end', function ( cb ) { + gently.expect( file, 'emit', function ( event ) { + assert.equal( event, 'end' ); + } ); - CB_STUB = gently.expect(function endCb() { - }); + CB_STUB = gently.expect( function endCb() { + } ); - cb(); - }); + cb(); + } ); - file.end(CB); -}); + file.end( CB ); +} ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js index b64df8b..25503d0 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-incoming-form.js @@ -1,726 +1,724 @@ -var common = require('../common'); -var MultipartParserStub = GENTLY.stub('./multipart_parser', 'MultipartParser'), - QuerystringParserStub = GENTLY.stub('./querystring_parser', 'QuerystringParser'), - EventEmitterStub = GENTLY.stub('events', 'EventEmitter'), - FileStub = GENTLY.stub('./file'); +var common = require( '../common' ); +var MultipartParserStub = GENTLY.stub( './multipart_parser', 'MultipartParser' ), + QuerystringParserStub = GENTLY.stub( './querystring_parser', 'QuerystringParser' ), + EventEmitterStub = GENTLY.stub( 'events', 'EventEmitter' ), + FileStub = GENTLY.stub( './file' ); -var formidable = require(common.lib + '/index'), - IncomingForm = formidable.IncomingForm, - events = require('events'), - fs = require('fs'), - path = require('path'), - Buffer = require('buffer').Buffer, - fixtures = require(TEST_FIXTURES + '/multipart'), - form, - gently; +var formidable = require( common.lib + '/index' ), + IncomingForm = formidable.IncomingForm, + events = require( 'events' ), + fs = require( 'fs' ), + path = require( 'path' ), + Buffer = require( 'buffer' ).Buffer, + fixtures = require( TEST_FIXTURES + '/multipart' ), + form, + gently; -function test(test) { - gently = new Gently(); - gently.expect(EventEmitterStub, 'call'); - form = new IncomingForm(); - test(); - gently.verify(test.name); +function test( test ) { + gently = new Gently(); + gently.expect( EventEmitterStub, 'call' ); + form = new IncomingForm(); + test(); + gently.verify( test.name ); } -test(function constructor() { - assert.strictEqual(form.error, null); - assert.strictEqual(form.ended, false); - assert.strictEqual(form.type, null); - assert.strictEqual(form.headers, null); - assert.strictEqual(form.keepExtensions, false); - assert.strictEqual(form.uploadDir, '/tmp'); - assert.strictEqual(form.encoding, 'utf-8'); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - assert.strictEqual(form.maxFieldsSize, 2 * 1024 * 1024); - assert.strictEqual(form._parser, null); - assert.strictEqual(form._flushing, 0); - assert.strictEqual(form._fieldsSize, 0); - assert.ok(form instanceof EventEmitterStub); - assert.equal(form.constructor.name, 'IncomingForm'); - - (function testSimpleConstructor() { - gently.expect(EventEmitterStub, 'call'); - var form = IncomingForm(); - assert.ok(form instanceof IncomingForm); - })(); - - (function testSimpleConstructorShortcut() { - gently.expect(EventEmitterStub, 'call'); - var form = formidable(); - assert.ok(form instanceof IncomingForm); - })(); -}); - -test(function parse() { - var REQ = {headers: {}} - , emit = {}; - - gently.expect(form, 'writeHeaders', function(headers) { - assert.strictEqual(headers, REQ.headers); - }); - - var events = ['error', 'aborted', 'data', 'end']; - gently.expect(REQ, 'on', events.length, function(event, fn) { - assert.equal(event, events.shift()); - emit[event] = fn; - return this; - }); - - form.parse(REQ); - - (function testPause() { - gently.expect(REQ, 'pause'); - assert.strictEqual(form.pause(), true); - })(); - - (function testPauseCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testPauseHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'pause', function() { - throw ERR; - }); - - assert.strictEqual(form.pause(), false); - })(); - - (function testResume() { - gently.expect(REQ, 'resume'); - assert.strictEqual(form.resume(), true); - })(); - - (function testResumeCriticalException() { - form.ended = false; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testResumeHarmlessException() { - form.ended = true; - - var ERR = new Error('dasdsa'); - gently.expect(REQ, 'resume', function() { - throw ERR; - }); - - assert.strictEqual(form.resume(), false); - })(); - - (function testEmitError() { - var ERR = new Error('something bad happened'); - gently.expect(form, '_error',function(err) { - assert.strictEqual(err, ERR); - }); - emit.error(ERR); - })(); - - (function testEmitAborted() { - gently.expect(form, 'emit',function(event) { - assert.equal(event, 'aborted'); - }); - - emit.aborted(); - })(); - - - (function testEmitData() { - var BUFFER = [1, 2, 3]; - gently.expect(form, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - }); - emit.data(BUFFER); - })(); - - (function testEmitEnd() { - form._parser = {}; - - (function testWithError() { - var ERR = new Error('haha'); - gently.expect(form._parser, 'end', function() { - return ERR; - }); - - gently.expect(form, '_error', function(err) { - assert.strictEqual(err, ERR); - }); - - emit.end(); - })(); - - (function testWithoutError() { - gently.expect(form._parser, 'end'); - emit.end(); - })(); - - (function testAfterError() { - form.error = true; - emit.end(); - })(); - })(); - - (function testWithCallback() { - gently.expect(EventEmitterStub, 'call'); - var form = new IncomingForm(), - REQ = {headers: {}}, - parseCalled = 0; - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - gently.expect(form, 'on', 4, function(event, fn) { - if (event == 'field') { - fn('field1', 'foo'); - fn('field1', 'bar'); - fn('field2', 'nice'); - } - - if (event == 'file') { - fn('file1', '1'); - fn('file1', '2'); - fn('file2', '3'); - } - - if (event == 'end') { - fn(); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbOk(err, fields, files) { - assert.deepEqual(fields, {field1: 'bar', field2: 'nice'}); - assert.deepEqual(files, {file1: '2', file2: '3'}); - })); - - gently.expect(form, 'writeHeaders'); - gently.expect(REQ, 'on', 4, function() { - return this; - }); - - var ERR = new Error('test'); - gently.expect(form, 'on', 3, function(event, fn) { - if (event == 'field') { - fn('foo', 'bar'); - } - - if (event == 'error') { - fn(ERR); - gently.expect(form, 'on'); - } - return this; - }); - - form.parse(REQ, gently.expect(function parseCbErr(err, fields, files) { - assert.strictEqual(err, ERR); - assert.deepEqual(fields, {foo: 'bar'}); - })); - })(); -}); - -test(function pause() { - assert.strictEqual(form.pause(), false); -}); - -test(function resume() { - assert.strictEqual(form.resume(), false); -}); - - -test(function writeHeaders() { - var HEADERS = {}; - gently.expect(form, '_parseContentLength'); - gently.expect(form, '_parseContentType'); - - form.writeHeaders(HEADERS); - assert.strictEqual(form.headers, HEADERS); -}); - -test(function write() { - var parser = {}, - BUFFER = [1, 2, 3]; - - form._parser = parser; - form.bytesExpected = 523423; - - (function testBasic() { - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, BUFFER.length); - assert.equal(bytesExpected, form.bytesExpected); - }); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length; - }); - - assert.equal(form.write(BUFFER), BUFFER.length); - assert.equal(form.bytesReceived, BUFFER.length); - })(); - - (function testParserError() { - gently.expect(form, 'emit'); - - gently.expect(parser, 'write', function(buffer) { - assert.strictEqual(buffer, BUFFER); - return buffer.length - 1; - }); - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/parser error/i)); - }); - - assert.equal(form.write(BUFFER), BUFFER.length - 1); - assert.equal(form.bytesReceived, BUFFER.length + BUFFER.length); - })(); - - (function testUninitialized() { - delete form._parser; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unintialized parser/i)); - }); - form.write(BUFFER); - })(); -}); - -test(function parseContentType() { - var HEADERS = {}; - - form.headers = {'content-type': 'application/x-www-form-urlencoded'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - // accept anything that has 'urlencoded' in it - form.headers = {'content-type': 'broken-client/urlencoded-stupid'}; - gently.expect(form, '_initUrlencoded'); - form._parseContentType(); - - var BOUNDARY = '---------------------------57814261102167618332366269'; - form.headers = {'content-type': 'multipart/form-data; boundary='+BOUNDARY}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - - (function testQuotedBoundary() { - form.headers = {'content-type': 'multipart/form-data; boundary="' + BOUNDARY + '"'}; - - gently.expect(form, '_initMultipart', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - form._parseContentType(); - })(); - - (function testNoBoundary() { - form.headers = {'content-type': 'multipart/form-data'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no multipart boundary/i)); - }); - form._parseContentType(); - })(); - - (function testNoContentType() { - form.headers = {}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/no content-type/i)); - }); - form._parseContentType(); - })(); - - (function testUnknownContentType() { - form.headers = {'content-type': 'invalid'}; - - gently.expect(form, '_error', function(err) { - assert.ok(err.message.match(/unknown content-type/i)); - }); - form._parseContentType(); - })(); -}); - -test(function parseContentLength() { - var HEADERS = {}; - - form.headers = {}; - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, null); - assert.strictEqual(form.bytesExpected, null); - - form.headers['content-length'] = '8'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesReceived, 0); - assert.strictEqual(form.bytesExpected, 8); - - // JS can be evil, lets make sure we are not - form.headers['content-length'] = '08'; - gently.expect(form, 'emit', function(event, bytesReceived, bytesExpected) { - assert.equal(event, 'progress'); - assert.equal(bytesReceived, 0); - assert.equal(bytesExpected, 8); - }); - form._parseContentLength(); - assert.strictEqual(form.bytesExpected, 8); -}); - -test(function _initMultipart() { - var BOUNDARY = '123', - PARSER; - - gently.expect(MultipartParserStub, 'new', function() { - PARSER = this; - }); - - gently.expect(MultipartParserStub.prototype, 'initWithBoundary', function(boundary) { - assert.equal(boundary, BOUNDARY); - }); - - form._initMultipart(BOUNDARY); - assert.equal(form.type, 'multipart'); - assert.strictEqual(form._parser, PARSER); - - (function testRegularField() { - var PART; - gently.expect(EventEmitterStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.strictEqual(part, PART); - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field1"' - , 'foo': 'bar' - } - ); - assert.equal(part.name, 'field1'); - - var strings = ['hello', ' world']; - gently.expect(part, 'emit', 2, function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), strings.shift()); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 10); - PARSER.onHeaderField(new Buffer('content-disposition'), 10, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 0, 14); - PARSER.onHeaderValue(new Buffer('form-data; name="field1"'), 14, 24); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('foo'), 0, 3); - PARSER.onHeaderValue(new Buffer('bar'), 0, 3); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('hello world'), 0, 5); - PARSER.onPartData(new Buffer('hello world'), 5, 11); - PARSER.onPartEnd(); - })(); - - (function testFileField() { - var PART; - gently.expect(EventEmitterStub, 'new', function() { - PART = this; - }); - - gently.expect(form, 'onPart', function(part) { - assert.deepEqual - ( part.headers - , { 'content-disposition': 'form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"' - , 'content-type': 'text/plain' - } - ); - assert.equal(part.name, 'field2'); - assert.equal(part.filename, 'Sun"et.jpg'); - assert.equal(part.mime, 'text/plain'); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'data'); - assert.equal(b.toString(), '... contents of file1.txt ...'); - }); - - gently.expect(part, 'emit', function(event, b) { - assert.equal(event, 'end'); - }); - }); - - PARSER.onPartBegin(); - PARSER.onHeaderField(new Buffer('content-disposition'), 0, 19); - PARSER.onHeaderValue(new Buffer('form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"'), 0, 85); - PARSER.onHeaderEnd(); - PARSER.onHeaderField(new Buffer('Content-Type'), 0, 12); - PARSER.onHeaderValue(new Buffer('text/plain'), 0, 10); - PARSER.onHeaderEnd(); - PARSER.onHeadersEnd(); - PARSER.onPartData(new Buffer('... contents of file1.txt ...'), 0, 29); - PARSER.onPartEnd(); - })(); - - (function testEnd() { - gently.expect(form, '_maybeEnd'); - PARSER.onEnd(); - assert.ok(form.ended); - })(); -}); - -test(function _fileName() { - // TODO - return; -}); - -test(function _initUrlencoded() { - var PARSER; - - gently.expect(QuerystringParserStub, 'new', function() { - PARSER = this; - }); - - form._initUrlencoded(); - assert.equal(form.type, 'urlencoded'); - assert.strictEqual(form._parser, PARSER); - - (function testOnField() { - var KEY = 'KEY', VAL = 'VAL'; - gently.expect(form, 'emit', function(field, key, val) { - assert.equal(field, 'field'); - assert.equal(key, KEY); - assert.equal(val, VAL); - }); - - PARSER.onField(KEY, VAL); - })(); - - (function testOnEnd() { - gently.expect(form, '_maybeEnd'); - - PARSER.onEnd(); - assert.equal(form.ended, true); - })(); -}); - -test(function _error() { - var ERR = new Error('bla'); - - gently.expect(form, 'pause'); - gently.expect(form, 'emit', function(event, err) { - assert.equal(event, 'error'); - assert.strictEqual(err, ERR); - }); - - form._error(ERR); - assert.strictEqual(form.error, ERR); - - // make sure _error only does its thing once - form._error(ERR); -}); - -test(function onPart() { - var PART = {}; - gently.expect(form, 'handlePart', function(part) { - assert.strictEqual(part, PART); - }); - - form.onPart(PART); -}); - -test(function handlePart() { - (function testUtf8Field() { - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field'); - assert.equal(value, 'hello world: €'); - }); - - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testBinaryField() { - var PART = new events.EventEmitter(); - PART.name = 'my_field2'; - - gently.expect(form, 'emit', function(event, field, value) { - assert.equal(event, 'field'); - assert.equal(field, 'my_field2'); - assert.equal(value, 'hello world: '+new Buffer([0xE2, 0x82, 0xAC]).toString('binary')); - }); - - form.encoding = 'binary'; - form.handlePart(PART); - PART.emit('data', new Buffer('hello')); - PART.emit('data', new Buffer(' world: ')); - PART.emit('data', new Buffer([0xE2])); - PART.emit('data', new Buffer([0x82, 0xAC])); - PART.emit('end'); - })(); - - (function testFieldSize() { - form.maxFieldsSize = 8; - var PART = new events.EventEmitter(); - PART.name = 'my_field'; - - gently.expect(form, '_error', function(err) { - assert.equal(err.message, 'maxFieldsSize exceeded, received 9 bytes of field data'); - }); - - form.handlePart(PART); - form._fieldsSize = 1; - PART.emit('data', new Buffer(7)); - PART.emit('data', new Buffer(1)); - })(); - - (function testFilePart() { - var PART = new events.EventEmitter(), - FILE = new events.EventEmitter(), - PATH = '/foo/bar'; - - PART.name = 'my_file'; - PART.filename = 'sweet.txt'; - PART.mime = 'sweet.txt'; - - gently.expect(form, '_uploadPath', function(filename) { - assert.equal(filename, PART.filename); - return PATH; - }); - - gently.expect(FileStub, 'new', function(properties) { - assert.equal(properties.path, PATH); - assert.equal(properties.name, PART.filename); - assert.equal(properties.type, PART.mime); - FILE = this; - - gently.expect(form, 'emit', function (event, field, file) { - assert.equal(event, 'fileBegin'); - assert.strictEqual(field, PART.name); - assert.strictEqual(file, FILE); - }); - - gently.expect(FILE, 'open'); - }); - - form.handlePart(PART); - assert.equal(form._flushing, 1); - - var BUFFER; - gently.expect(form, 'pause'); - gently.expect(FILE, 'write', function(buffer, cb) { - assert.strictEqual(buffer, BUFFER); - gently.expect(form, 'resume'); - // @todo handle cb(new Err) - cb(); - }); - - PART.emit('data', BUFFER = new Buffer('test')); - - gently.expect(FILE, 'end', function(cb) { - gently.expect(form, 'emit', function(event, field, file) { - assert.equal(event, 'file'); - assert.strictEqual(file, FILE); - }); - - gently.expect(form, '_maybeEnd'); - - cb(); - assert.equal(form._flushing, 0); - }); - - PART.emit('end'); - })(); -}); - -test(function _uploadPath() { - (function testUniqueId() { - var UUID_A, UUID_B; - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - assert.equal(uploadDir, form.uploadDir); - UUID_A = uuid; - }); - form._uploadPath(); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, uuid) { - UUID_B = uuid; - }); - form._uploadPath(); - - assert.notEqual(UUID_A, UUID_B); - })(); - - (function testFileExtension() { - form.keepExtensions = true; - var FILENAME = 'foo.jpg', - EXT = '.bar'; - - gently.expect(GENTLY.hijacked.path, 'extname', function(filename) { - assert.equal(filename, FILENAME); - gently.restore(path, 'extname'); - - return EXT; - }); - - gently.expect(GENTLY.hijacked.path, 'join', function(uploadDir, name) { - assert.equal(path.extname(name), EXT); - }); - form._uploadPath(FILENAME); - })(); -}); - -test(function _maybeEnd() { - gently.expect(form, 'emit', 0); - form._maybeEnd(); - - form.ended = true; - form._flushing = 1; - form._maybeEnd(); - - gently.expect(form, 'emit', function(event) { - assert.equal(event, 'end'); - }); - - form.ended = true; - form._flushing = 0; - form._maybeEnd(); -}); +test( function constructor() { + assert.strictEqual( form.error, null ); + assert.strictEqual( form.ended, false ); + assert.strictEqual( form.type, null ); + assert.strictEqual( form.headers, null ); + assert.strictEqual( form.keepExtensions, false ); + assert.strictEqual( form.uploadDir, '/tmp' ); + assert.strictEqual( form.encoding, 'utf-8' ); + assert.strictEqual( form.bytesReceived, null ); + assert.strictEqual( form.bytesExpected, null ); + assert.strictEqual( form.maxFieldsSize, 2 * 1024 * 1024 ); + assert.strictEqual( form._parser, null ); + assert.strictEqual( form._flushing, 0 ); + assert.strictEqual( form._fieldsSize, 0 ); + assert.ok( form instanceof EventEmitterStub ); + assert.equal( form.constructor.name, 'IncomingForm' ); + + (function testSimpleConstructor() { + gently.expect( EventEmitterStub, 'call' ); + var form = IncomingForm(); + assert.ok( form instanceof IncomingForm ); + })(); + + (function testSimpleConstructorShortcut() { + gently.expect( EventEmitterStub, 'call' ); + var form = formidable(); + assert.ok( form instanceof IncomingForm ); + })(); +} ); + +test( function parse() { + var REQ = {headers : {}} + , emit = {}; + + gently.expect( form, 'writeHeaders', function ( headers ) { + assert.strictEqual( headers, REQ.headers ); + } ); + + var events = ['error', 'aborted', 'data', 'end']; + gently.expect( REQ, 'on', events.length, function ( event, fn ) { + assert.equal( event, events.shift() ); + emit[event] = fn; + return this; + } ); + + form.parse( REQ ); + + (function testPause() { + gently.expect( REQ, 'pause' ); + assert.strictEqual( form.pause(), true ); + })(); + + (function testPauseCriticalException() { + form.ended = false; + + var ERR = new Error( 'dasdsa' ); + gently.expect( REQ, 'pause', function () { + throw ERR; + } ); + + gently.expect( form, '_error', function ( err ) { + assert.strictEqual( err, ERR ); + } ); + + assert.strictEqual( form.pause(), false ); + })(); + + (function testPauseHarmlessException() { + form.ended = true; + + var ERR = new Error( 'dasdsa' ); + gently.expect( REQ, 'pause', function () { + throw ERR; + } ); + + assert.strictEqual( form.pause(), false ); + })(); + + (function testResume() { + gently.expect( REQ, 'resume' ); + assert.strictEqual( form.resume(), true ); + })(); + + (function testResumeCriticalException() { + form.ended = false; + + var ERR = new Error( 'dasdsa' ); + gently.expect( REQ, 'resume', function () { + throw ERR; + } ); + + gently.expect( form, '_error', function ( err ) { + assert.strictEqual( err, ERR ); + } ); + + assert.strictEqual( form.resume(), false ); + })(); + + (function testResumeHarmlessException() { + form.ended = true; + + var ERR = new Error( 'dasdsa' ); + gently.expect( REQ, 'resume', function () { + throw ERR; + } ); + + assert.strictEqual( form.resume(), false ); + })(); + + (function testEmitError() { + var ERR = new Error( 'something bad happened' ); + gently.expect( form, '_error', function ( err ) { + assert.strictEqual( err, ERR ); + } ); + emit.error( ERR ); + })(); + + (function testEmitAborted() { + gently.expect( form, 'emit', function ( event ) { + assert.equal( event, 'aborted' ); + } ); + + emit.aborted(); + })(); + + + (function testEmitData() { + var BUFFER = [1, 2, 3]; + gently.expect( form, 'write', function ( buffer ) { + assert.strictEqual( buffer, BUFFER ); + } ); + emit.data( BUFFER ); + })(); + + (function testEmitEnd() { + form._parser = {}; + + (function testWithError() { + var ERR = new Error( 'haha' ); + gently.expect( form._parser, 'end', function () { + return ERR; + } ); + + gently.expect( form, '_error', function ( err ) { + assert.strictEqual( err, ERR ); + } ); + + emit.end(); + })(); + + (function testWithoutError() { + gently.expect( form._parser, 'end' ); + emit.end(); + })(); + + (function testAfterError() { + form.error = true; + emit.end(); + })(); + })(); + + (function testWithCallback() { + gently.expect( EventEmitterStub, 'call' ); + var form = new IncomingForm(), + REQ = {headers : {}}, + parseCalled = 0; + + gently.expect( form, 'writeHeaders' ); + gently.expect( REQ, 'on', 4, function () { + return this; + } ); + + gently.expect( form, 'on', 4, function ( event, fn ) { + if ( event == 'field' ) { + fn( 'field1', 'foo' ); + fn( 'field1', 'bar' ); + fn( 'field2', 'nice' ); + } + + if ( event == 'file' ) { + fn( 'file1', '1' ); + fn( 'file1', '2' ); + fn( 'file2', '3' ); + } + + if ( event == 'end' ) { + fn(); + } + return this; + } ); + + form.parse( REQ, gently.expect( function parseCbOk( err, fields, files ) { + assert.deepEqual( fields, {field1 : 'bar', field2 : 'nice'} ); + assert.deepEqual( files, {file1 : '2', file2 : '3'} ); + } ) ); + + gently.expect( form, 'writeHeaders' ); + gently.expect( REQ, 'on', 4, function () { + return this; + } ); + + var ERR = new Error( 'test' ); + gently.expect( form, 'on', 3, function ( event, fn ) { + if ( event == 'field' ) { + fn( 'foo', 'bar' ); + } + + if ( event == 'error' ) { + fn( ERR ); + gently.expect( form, 'on' ); + } + return this; + } ); + + form.parse( REQ, gently.expect( function parseCbErr( err, fields, files ) { + assert.strictEqual( err, ERR ); + assert.deepEqual( fields, {foo : 'bar'} ); + } ) ); + })(); +} ); + +test( function pause() { + assert.strictEqual( form.pause(), false ); +} ); + +test( function resume() { + assert.strictEqual( form.resume(), false ); +} ); + + +test( function writeHeaders() { + var HEADERS = {}; + gently.expect( form, '_parseContentLength' ); + gently.expect( form, '_parseContentType' ); + + form.writeHeaders( HEADERS ); + assert.strictEqual( form.headers, HEADERS ); +} ); + +test( function write() { + var parser = {}, + BUFFER = [1, 2, 3]; + + form._parser = parser; + form.bytesExpected = 523423; + + (function testBasic() { + gently.expect( form, 'emit', function ( event, bytesReceived, bytesExpected ) { + assert.equal( event, 'progress' ); + assert.equal( bytesReceived, BUFFER.length ); + assert.equal( bytesExpected, form.bytesExpected ); + } ); + + gently.expect( parser, 'write', function ( buffer ) { + assert.strictEqual( buffer, BUFFER ); + return buffer.length; + } ); + + assert.equal( form.write( BUFFER ), BUFFER.length ); + assert.equal( form.bytesReceived, BUFFER.length ); + })(); + + (function testParserError() { + gently.expect( form, 'emit' ); + + gently.expect( parser, 'write', function ( buffer ) { + assert.strictEqual( buffer, BUFFER ); + return buffer.length - 1; + } ); + + gently.expect( form, '_error', function ( err ) { + assert.ok( err.message.match( /parser error/i ) ); + } ); + + assert.equal( form.write( BUFFER ), BUFFER.length - 1 ); + assert.equal( form.bytesReceived, BUFFER.length + BUFFER.length ); + })(); + + (function testUninitialized() { + delete form._parser; + + gently.expect( form, '_error', function ( err ) { + assert.ok( err.message.match( /unintialized parser/i ) ); + } ); + form.write( BUFFER ); + })(); +} ); + +test( function parseContentType() { + var HEADERS = {}; + + form.headers = {'content-type' : 'application/x-www-form-urlencoded'}; + gently.expect( form, '_initUrlencoded' ); + form._parseContentType(); + + // accept anything that has 'urlencoded' in it + form.headers = {'content-type' : 'broken-client/urlencoded-stupid'}; + gently.expect( form, '_initUrlencoded' ); + form._parseContentType(); + + var BOUNDARY = '---------------------------57814261102167618332366269'; + form.headers = {'content-type' : 'multipart/form-data; boundary=' + BOUNDARY}; + + gently.expect( form, '_initMultipart', function ( boundary ) { + assert.equal( boundary, BOUNDARY ); + } ); + form._parseContentType(); + + (function testQuotedBoundary() { + form.headers = {'content-type' : 'multipart/form-data; boundary="' + BOUNDARY + '"'}; + + gently.expect( form, '_initMultipart', function ( boundary ) { + assert.equal( boundary, BOUNDARY ); + } ); + form._parseContentType(); + })(); + + (function testNoBoundary() { + form.headers = {'content-type' : 'multipart/form-data'}; + + gently.expect( form, '_error', function ( err ) { + assert.ok( err.message.match( /no multipart boundary/i ) ); + } ); + form._parseContentType(); + })(); + + (function testNoContentType() { + form.headers = {}; + + gently.expect( form, '_error', function ( err ) { + assert.ok( err.message.match( /no content-type/i ) ); + } ); + form._parseContentType(); + })(); + + (function testUnknownContentType() { + form.headers = {'content-type' : 'invalid'}; + + gently.expect( form, '_error', function ( err ) { + assert.ok( err.message.match( /unknown content-type/i ) ); + } ); + form._parseContentType(); + })(); +} ); + +test( function parseContentLength() { + var HEADERS = {}; + + form.headers = {}; + form._parseContentLength(); + assert.strictEqual( form.bytesReceived, null ); + assert.strictEqual( form.bytesExpected, null ); + + form.headers['content-length'] = '8'; + gently.expect( form, 'emit', function ( event, bytesReceived, bytesExpected ) { + assert.equal( event, 'progress' ); + assert.equal( bytesReceived, 0 ); + assert.equal( bytesExpected, 8 ); + } ); + form._parseContentLength(); + assert.strictEqual( form.bytesReceived, 0 ); + assert.strictEqual( form.bytesExpected, 8 ); + + // JS can be evil, lets make sure we are not + form.headers['content-length'] = '08'; + gently.expect( form, 'emit', function ( event, bytesReceived, bytesExpected ) { + assert.equal( event, 'progress' ); + assert.equal( bytesReceived, 0 ); + assert.equal( bytesExpected, 8 ); + } ); + form._parseContentLength(); + assert.strictEqual( form.bytesExpected, 8 ); +} ); + +test( function _initMultipart() { + var BOUNDARY = '123', + PARSER; + + gently.expect( MultipartParserStub, 'new', function () { + PARSER = this; + } ); + + gently.expect( MultipartParserStub.prototype, 'initWithBoundary', function ( boundary ) { + assert.equal( boundary, BOUNDARY ); + } ); + + form._initMultipart( BOUNDARY ); + assert.equal( form.type, 'multipart' ); + assert.strictEqual( form._parser, PARSER ); + + (function testRegularField() { + var PART; + gently.expect( EventEmitterStub, 'new', function () { + PART = this; + } ); + + gently.expect( form, 'onPart', function ( part ) { + assert.strictEqual( part, PART ); + assert.deepEqual + ( part.headers + , { 'content-disposition' : 'form-data; name="field1"', 'foo' : 'bar' + } + ); + assert.equal( part.name, 'field1' ); + + var strings = ['hello', ' world']; + gently.expect( part, 'emit', 2, function ( event, b ) { + assert.equal( event, 'data' ); + assert.equal( b.toString(), strings.shift() ); + } ); + + gently.expect( part, 'emit', function ( event, b ) { + assert.equal( event, 'end' ); + } ); + } ); + + PARSER.onPartBegin(); + PARSER.onHeaderField( new Buffer( 'content-disposition' ), 0, 10 ); + PARSER.onHeaderField( new Buffer( 'content-disposition' ), 10, 19 ); + PARSER.onHeaderValue( new Buffer( 'form-data; name="field1"' ), 0, 14 ); + PARSER.onHeaderValue( new Buffer( 'form-data; name="field1"' ), 14, 24 ); + PARSER.onHeaderEnd(); + PARSER.onHeaderField( new Buffer( 'foo' ), 0, 3 ); + PARSER.onHeaderValue( new Buffer( 'bar' ), 0, 3 ); + PARSER.onHeaderEnd(); + PARSER.onHeadersEnd(); + PARSER.onPartData( new Buffer( 'hello world' ), 0, 5 ); + PARSER.onPartData( new Buffer( 'hello world' ), 5, 11 ); + PARSER.onPartEnd(); + })(); + + (function testFileField() { + var PART; + gently.expect( EventEmitterStub, 'new', function () { + PART = this; + } ); + + gently.expect( form, 'onPart', function ( part ) { + assert.deepEqual + ( part.headers + , { 'content-disposition' : 'form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"', 'content-type' : 'text/plain' + } + ); + assert.equal( part.name, 'field2' ); + assert.equal( part.filename, 'Sun"et.jpg' ); + assert.equal( part.mime, 'text/plain' ); + + gently.expect( part, 'emit', function ( event, b ) { + assert.equal( event, 'data' ); + assert.equal( b.toString(), '... contents of file1.txt ...' ); + } ); + + gently.expect( part, 'emit', function ( event, b ) { + assert.equal( event, 'end' ); + } ); + } ); + + PARSER.onPartBegin(); + PARSER.onHeaderField( new Buffer( 'content-disposition' ), 0, 19 ); + PARSER.onHeaderValue( new Buffer( 'form-data; name="field2"; filename="C:\\Documents and Settings\\IE\\Must\\Die\\Sun"et.jpg"' ), 0, 85 ); + PARSER.onHeaderEnd(); + PARSER.onHeaderField( new Buffer( 'Content-Type' ), 0, 12 ); + PARSER.onHeaderValue( new Buffer( 'text/plain' ), 0, 10 ); + PARSER.onHeaderEnd(); + PARSER.onHeadersEnd(); + PARSER.onPartData( new Buffer( '... contents of file1.txt ...' ), 0, 29 ); + PARSER.onPartEnd(); + })(); + + (function testEnd() { + gently.expect( form, '_maybeEnd' ); + PARSER.onEnd(); + assert.ok( form.ended ); + })(); +} ); + +test( function _fileName() { + // TODO + return; +} ); + +test( function _initUrlencoded() { + var PARSER; + + gently.expect( QuerystringParserStub, 'new', function () { + PARSER = this; + } ); + + form._initUrlencoded(); + assert.equal( form.type, 'urlencoded' ); + assert.strictEqual( form._parser, PARSER ); + + (function testOnField() { + var KEY = 'KEY', VAL = 'VAL'; + gently.expect( form, 'emit', function ( field, key, val ) { + assert.equal( field, 'field' ); + assert.equal( key, KEY ); + assert.equal( val, VAL ); + } ); + + PARSER.onField( KEY, VAL ); + })(); + + (function testOnEnd() { + gently.expect( form, '_maybeEnd' ); + + PARSER.onEnd(); + assert.equal( form.ended, true ); + })(); +} ); + +test( function _error() { + var ERR = new Error( 'bla' ); + + gently.expect( form, 'pause' ); + gently.expect( form, 'emit', function ( event, err ) { + assert.equal( event, 'error' ); + assert.strictEqual( err, ERR ); + } ); + + form._error( ERR ); + assert.strictEqual( form.error, ERR ); + + // make sure _error only does its thing once + form._error( ERR ); +} ); + +test( function onPart() { + var PART = {}; + gently.expect( form, 'handlePart', function ( part ) { + assert.strictEqual( part, PART ); + } ); + + form.onPart( PART ); +} ); + +test( function handlePart() { + (function testUtf8Field() { + var PART = new events.EventEmitter(); + PART.name = 'my_field'; + + gently.expect( form, 'emit', function ( event, field, value ) { + assert.equal( event, 'field' ); + assert.equal( field, 'my_field' ); + assert.equal( value, 'hello world: €' ); + } ); + + form.handlePart( PART ); + PART.emit( 'data', new Buffer( 'hello' ) ); + PART.emit( 'data', new Buffer( ' world: ' ) ); + PART.emit( 'data', new Buffer( [0xE2] ) ); + PART.emit( 'data', new Buffer( [0x82, 0xAC] ) ); + PART.emit( 'end' ); + })(); + + (function testBinaryField() { + var PART = new events.EventEmitter(); + PART.name = 'my_field2'; + + gently.expect( form, 'emit', function ( event, field, value ) { + assert.equal( event, 'field' ); + assert.equal( field, 'my_field2' ); + assert.equal( value, 'hello world: ' + new Buffer( [0xE2, 0x82, 0xAC] ).toString( 'binary' ) ); + } ); + + form.encoding = 'binary'; + form.handlePart( PART ); + PART.emit( 'data', new Buffer( 'hello' ) ); + PART.emit( 'data', new Buffer( ' world: ' ) ); + PART.emit( 'data', new Buffer( [0xE2] ) ); + PART.emit( 'data', new Buffer( [0x82, 0xAC] ) ); + PART.emit( 'end' ); + })(); + + (function testFieldSize() { + form.maxFieldsSize = 8; + var PART = new events.EventEmitter(); + PART.name = 'my_field'; + + gently.expect( form, '_error', function ( err ) { + assert.equal( err.message, 'maxFieldsSize exceeded, received 9 bytes of field data' ); + } ); + + form.handlePart( PART ); + form._fieldsSize = 1; + PART.emit( 'data', new Buffer( 7 ) ); + PART.emit( 'data', new Buffer( 1 ) ); + })(); + + (function testFilePart() { + var PART = new events.EventEmitter(), + FILE = new events.EventEmitter(), + PATH = '/foo/bar'; + + PART.name = 'my_file'; + PART.filename = 'sweet.txt'; + PART.mime = 'sweet.txt'; + + gently.expect( form, '_uploadPath', function ( filename ) { + assert.equal( filename, PART.filename ); + return PATH; + } ); + + gently.expect( FileStub, 'new', function ( properties ) { + assert.equal( properties.path, PATH ); + assert.equal( properties.name, PART.filename ); + assert.equal( properties.type, PART.mime ); + FILE = this; + + gently.expect( form, 'emit', function ( event, field, file ) { + assert.equal( event, 'fileBegin' ); + assert.strictEqual( field, PART.name ); + assert.strictEqual( file, FILE ); + } ); + + gently.expect( FILE, 'open' ); + } ); + + form.handlePart( PART ); + assert.equal( form._flushing, 1 ); + + var BUFFER; + gently.expect( form, 'pause' ); + gently.expect( FILE, 'write', function ( buffer, cb ) { + assert.strictEqual( buffer, BUFFER ); + gently.expect( form, 'resume' ); + // @todo handle cb(new Err) + cb(); + } ); + + PART.emit( 'data', BUFFER = new Buffer( 'test' ) ); + + gently.expect( FILE, 'end', function ( cb ) { + gently.expect( form, 'emit', function ( event, field, file ) { + assert.equal( event, 'file' ); + assert.strictEqual( file, FILE ); + } ); + + gently.expect( form, '_maybeEnd' ); + + cb(); + assert.equal( form._flushing, 0 ); + } ); + + PART.emit( 'end' ); + })(); +} ); + +test( function _uploadPath() { + (function testUniqueId() { + var UUID_A, UUID_B; + gently.expect( GENTLY.hijacked.path, 'join', function ( uploadDir, uuid ) { + assert.equal( uploadDir, form.uploadDir ); + UUID_A = uuid; + } ); + form._uploadPath(); + + gently.expect( GENTLY.hijacked.path, 'join', function ( uploadDir, uuid ) { + UUID_B = uuid; + } ); + form._uploadPath(); + + assert.notEqual( UUID_A, UUID_B ); + })(); + + (function testFileExtension() { + form.keepExtensions = true; + var FILENAME = 'foo.jpg', + EXT = '.bar'; + + gently.expect( GENTLY.hijacked.path, 'extname', function ( filename ) { + assert.equal( filename, FILENAME ); + gently.restore( path, 'extname' ); + + return EXT; + } ); + + gently.expect( GENTLY.hijacked.path, 'join', function ( uploadDir, name ) { + assert.equal( path.extname( name ), EXT ); + } ); + form._uploadPath( FILENAME ); + })(); +} ); + +test( function _maybeEnd() { + gently.expect( form, 'emit', 0 ); + form._maybeEnd(); + + form.ended = true; + form._flushing = 1; + form._maybeEnd(); + + gently.expect( form, 'emit', function ( event ) { + assert.equal( event, 'end' ); + } ); + + form.ended = true; + form._flushing = 0; + form._maybeEnd(); +} ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js index d8dc968..6b9644b 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-multipart-parser.js @@ -1,50 +1,50 @@ -var common = require('../common'); -var multipartParser = require(common.lib + '/multipart_parser'), - MultipartParser = multipartParser.MultipartParser, - events = require('events'), - Buffer = require('buffer').Buffer, - parser; +var common = require( '../common' ); +var multipartParser = require( common.lib + '/multipart_parser' ), + MultipartParser = multipartParser.MultipartParser, + events = require( 'events' ), + Buffer = require( 'buffer' ).Buffer, + parser; -function test(test) { - parser = new MultipartParser(); - test(); +function test( test ) { + parser = new MultipartParser(); + test(); } -test(function constructor() { - assert.equal(parser.boundary, null); - assert.equal(parser.state, 0); - assert.equal(parser.flags, 0); - assert.equal(parser.boundaryChars, null); - assert.equal(parser.index, null); - assert.equal(parser.lookbehind, null); - assert.equal(parser.constructor.name, 'MultipartParser'); -}); +test( function constructor() { + assert.equal( parser.boundary, null ); + assert.equal( parser.state, 0 ); + assert.equal( parser.flags, 0 ); + assert.equal( parser.boundaryChars, null ); + assert.equal( parser.index, null ); + assert.equal( parser.lookbehind, null ); + assert.equal( parser.constructor.name, 'MultipartParser' ); +} ); -test(function initWithBoundary() { - var boundary = 'abc'; - parser.initWithBoundary(boundary); - assert.deepEqual(Array.prototype.slice.call(parser.boundary), [13, 10, 45, 45, 97, 98, 99]); - assert.equal(parser.state, multipartParser.START); +test( function initWithBoundary() { + var boundary = 'abc'; + parser.initWithBoundary( boundary ); + assert.deepEqual( Array.prototype.slice.call( parser.boundary ), [13, 10, 45, 45, 97, 98, 99] ); + assert.equal( parser.state, multipartParser.START ); - assert.deepEqual(parser.boundaryChars, {10: true, 13: true, 45: true, 97: true, 98: true, 99: true}); -}); + assert.deepEqual( parser.boundaryChars, {10 : true, 13 : true, 45 : true, 97 : true, 98 : true, 99 : true} ); +} ); -test(function parserError() { - var boundary = 'abc', - buffer = new Buffer(5); +test( function parserError() { + var boundary = 'abc', + buffer = new Buffer( 5 ); - parser.initWithBoundary(boundary); - buffer.write('--ad', 'ascii', 0); - assert.equal(parser.write(buffer), 3); -}); + parser.initWithBoundary( boundary ); + buffer.write( '--ad', 'ascii', 0 ); + assert.equal( parser.write( buffer ), 3 ); +} ); -test(function end() { - (function testError() { - assert.equal(parser.end().message, 'MultipartParser.end(): stream ended unexpectedly: ' + parser.explain()); - })(); +test( function end() { + (function testError() { + assert.equal( parser.end().message, 'MultipartParser.end(): stream ended unexpectedly: ' + parser.explain() ); + })(); - (function testRegular() { - parser.state = multipartParser.END; - assert.strictEqual(parser.end(), undefined); - })(); -}); + (function testRegular() { + parser.state = multipartParser.END; + assert.strictEqual( parser.end(), undefined ); + })(); +} ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js index 54d3e2d..5d043d2 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/simple/test-querystring-parser.js @@ -1,45 +1,45 @@ -var common = require('../common'); -var QuerystringParser = require(common.lib + '/querystring_parser').QuerystringParser, - Buffer = require('buffer').Buffer, - gently, - parser; +var common = require( '../common' ); +var QuerystringParser = require( common.lib + '/querystring_parser' ).QuerystringParser, + Buffer = require( 'buffer' ).Buffer, + gently, + parser; -function test(test) { - gently = new Gently(); - parser = new QuerystringParser(); - test(); - gently.verify(test.name); +function test( test ) { + gently = new Gently(); + parser = new QuerystringParser(); + test(); + gently.verify( test.name ); } -test(function constructor() { - assert.equal(parser.buffer, ''); - assert.equal(parser.constructor.name, 'QuerystringParser'); -}); +test( function constructor() { + assert.equal( parser.buffer, '' ); + assert.equal( parser.constructor.name, 'QuerystringParser' ); +} ); -test(function write() { - var a = new Buffer('a=1'); - assert.equal(parser.write(a), a.length); +test( function write() { + var a = new Buffer( 'a=1' ); + assert.equal( parser.write( a ), a.length ); - var b = new Buffer('&b=2'); - parser.write(b); - assert.equal(parser.buffer, a + b); -}); + var b = new Buffer( '&b=2' ); + parser.write( b ); + assert.equal( parser.buffer, a + b ); +} ); -test(function end() { - var FIELDS = {a: ['b', {c: 'd'}], e: 'f'}; +test( function end() { + var FIELDS = {a : ['b', {c : 'd'}], e : 'f'}; - gently.expect(GENTLY.hijacked.querystring, 'parse', function(str) { - assert.equal(str, parser.buffer); - return FIELDS; - }); + gently.expect( GENTLY.hijacked.querystring, 'parse', function ( str ) { + assert.equal( str, parser.buffer ); + return FIELDS; + } ); - gently.expect(parser, 'onField', Object.keys(FIELDS).length, function(key, val) { - assert.deepEqual(FIELDS[key], val); - }); + gently.expect( parser, 'onField', Object.keys( FIELDS ).length, function ( key, val ) { + assert.deepEqual( FIELDS[key], val ); + } ); - gently.expect(parser, 'onEnd'); + gently.expect( parser, 'onEnd' ); - parser.buffer = 'my buffer'; - parser.end(); - assert.equal(parser.buffer, ''); -}); + parser.buffer = 'my buffer'; + parser.end(); + assert.equal( parser.buffer, '' ); +} ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js index fcfdb94..6753c63 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/legacy/system/test-multi-video-upload.js @@ -1,72 +1,72 @@ -var common = require('../common'); +var common = require( '../common' ); var BOUNDARY = '---------------------------10102754414578508781458777923', - FIXTURE = TEST_FIXTURES+'/multi_video.upload', - fs = require('fs'), - util = require(common.lib + '/util'), - http = require('http'), - formidable = require(common.lib + '/index'), - server = http.createServer(); + FIXTURE = TEST_FIXTURES + '/multi_video.upload', + fs = require( 'fs' ), + util = require( common.lib + '/util' ), + http = require( 'http' ), + formidable = require( common.lib + '/index' ), + server = http.createServer(); -server.on('request', function(req, res) { - var form = new formidable.IncomingForm(), - uploads = {}; +server.on( 'request', function ( req, res ) { + var form = new formidable.IncomingForm(), + uploads = {}; - form.uploadDir = TEST_TMP; - form.parse(req); + form.uploadDir = TEST_TMP; + form.parse( req ); - form - .on('fileBegin', function(field, file) { - assert.equal(field, 'upload'); + form + .on( 'fileBegin', function ( field, file ) { + assert.equal( field, 'upload' ); - var tracker = {file: file, progress: [], ended: false}; - uploads[file.filename] = tracker; - file - .on('progress', function(bytesReceived) { - tracker.progress.push(bytesReceived); - assert.equal(bytesReceived, file.length); - }) - .on('end', function() { - tracker.ended = true; - }); - }) - .on('field', function(field, value) { - assert.equal(field, 'title'); - assert.equal(value, ''); - }) - .on('file', function(field, file) { - assert.equal(field, 'upload'); - assert.strictEqual(uploads[file.filename].file, file); - }) - .on('end', function() { - assert.ok(uploads['shortest_video.flv']); - assert.ok(uploads['shortest_video.flv'].ended); - assert.ok(uploads['shortest_video.flv'].progress.length > 3); - assert.equal(uploads['shortest_video.flv'].progress.slice(-1), uploads['shortest_video.flv'].file.length); - assert.ok(uploads['shortest_video.mp4']); - assert.ok(uploads['shortest_video.mp4'].ended); - assert.ok(uploads['shortest_video.mp4'].progress.length > 3); + var tracker = {file : file, progress : [], ended : false}; + uploads[file.filename] = tracker; + file + .on( 'progress', function ( bytesReceived ) { + tracker.progress.push( bytesReceived ); + assert.equal( bytesReceived, file.length ); + } ) + .on( 'end', function () { + tracker.ended = true; + } ); + } ) + .on( 'field', function ( field, value ) { + assert.equal( field, 'title' ); + assert.equal( value, '' ); + } ) + .on( 'file', function ( field, file ) { + assert.equal( field, 'upload' ); + assert.strictEqual( uploads[file.filename].file, file ); + } ) + .on( 'end', function () { + assert.ok( uploads['shortest_video.flv'] ); + assert.ok( uploads['shortest_video.flv'].ended ); + assert.ok( uploads['shortest_video.flv'].progress.length > 3 ); + assert.equal( uploads['shortest_video.flv'].progress.slice( -1 ), uploads['shortest_video.flv'].file.length ); + assert.ok( uploads['shortest_video.mp4'] ); + assert.ok( uploads['shortest_video.mp4'].ended ); + assert.ok( uploads['shortest_video.mp4'].progress.length > 3 ); - server.close(); - res.writeHead(200); - res.end('good'); - }); -}); + server.close(); + res.writeHead( 200 ); + res.end( 'good' ); + } ); +} ); -server.listen(TEST_PORT, function() { - var client = http.createClient(TEST_PORT), - stat = fs.statSync(FIXTURE), - headers = { - 'content-type': 'multipart/form-data; boundary='+BOUNDARY, - 'content-length': stat.size, - } - request = client.request('POST', '/', headers), - fixture = new fs.ReadStream(FIXTURE); +server.listen( TEST_PORT, function () { + var client = http.createClient( TEST_PORT ), + stat = fs.statSync( FIXTURE ), + headers = { + 'content-type' : 'multipart/form-data; boundary=' + BOUNDARY, + 'content-length' : stat.size, + } + request = client.request( 'POST', '/', headers ), + fixture = new fs.ReadStream( FIXTURE ); - fixture - .on('data', function(b) { - request.write(b); - }) - .on('end', function() { - request.end(); - }); -}); + fixture + .on( 'data', function ( b ) { + request.write( b ); + } ) + .on( 'end', function () { + request.end(); + } ); +} ); diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js index 50b2361..591cbf9 100755 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/run.js @@ -1,2 +1,5 @@ -#!/usr/bin/env node -require('urun')(__dirname) +# +!/usr/ +bin / env +node +require( 'urun' )( __dirname ) diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js index bcf61d7..da29143 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/test/unit/test-incoming-form.js @@ -1,63 +1,63 @@ -var common = require('../common'); -var test = require('utest'); -var assert = common.assert; -var IncomingForm = common.require('incoming_form').IncomingForm; -var path = require('path'); +var common = require( '../common' ); +var test = require( 'utest' ); +var assert = common.assert; +var IncomingForm = common.require( 'incoming_form' ).IncomingForm; +var path = require( 'path' ); var from; -test('IncomingForm', { - before: function() { - form = new IncomingForm(); - }, +test( 'IncomingForm', { + before : function () { + form = new IncomingForm(); + }, - '#_fileName with regular characters': function() { - var filename = 'foo.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'foo.txt'); - }, + '#_fileName with regular characters' : function () { + var filename = 'foo.txt'; + assert.equal( form._fileName( makeHeader( filename ) ), 'foo.txt' ); + }, - '#_fileName with unescaped quote': function() { - var filename = 'my".txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, + '#_fileName with unescaped quote' : function () { + var filename = 'my".txt'; + assert.equal( form._fileName( makeHeader( filename ) ), 'my".txt' ); + }, - '#_fileName with escaped quote': function() { - var filename = 'my%22.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my".txt'); - }, + '#_fileName with escaped quote' : function () { + var filename = 'my%22.txt'; + assert.equal( form._fileName( makeHeader( filename ) ), 'my".txt' ); + }, - '#_fileName with bad quote and additional sub-header': function() { - var filename = 'my".txt'; - var header = makeHeader(filename) + '; foo="bar"'; - assert.equal(form._fileName(header), filename); - }, + '#_fileName with bad quote and additional sub-header' : function () { + var filename = 'my".txt'; + var header = makeHeader( filename ) + '; foo="bar"'; + assert.equal( form._fileName( header ), filename ); + }, - '#_fileName with semicolon': function() { - var filename = 'my;.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my;.txt'); - }, + '#_fileName with semicolon' : function () { + var filename = 'my;.txt'; + assert.equal( form._fileName( makeHeader( filename ) ), 'my;.txt' ); + }, - '#_fileName with utf8 character': function() { - var filename = 'my☃.txt'; - assert.equal(form._fileName(makeHeader(filename)), 'my☃.txt'); - }, + '#_fileName with utf8 character' : function () { + var filename = 'my☃.txt'; + assert.equal( form._fileName( makeHeader( filename ) ), 'my☃.txt' ); + }, - '#_uploadPath strips harmful characters from extension when keepExtensions': function() { - form.keepExtensions = true; + '#_uploadPath strips harmful characters from extension when keepExtensions' : function () { + form.keepExtensions = true; - var ext = path.extname(form._uploadPath('fine.jpg?foo=bar')); - assert.equal(ext, '.jpg'); + var ext = path.extname( form._uploadPath( 'fine.jpg?foo=bar' ) ); + assert.equal( ext, '.jpg' ); - var ext = path.extname(form._uploadPath('fine?foo=bar')); - assert.equal(ext, ''); + var ext = path.extname( form._uploadPath( 'fine?foo=bar' ) ); + assert.equal( ext, '' ); - var ext = path.extname(form._uploadPath('super.cr2+dsad')); - assert.equal(ext, '.cr2'); + var ext = path.extname( form._uploadPath( 'super.cr2+dsad' ) ); + assert.equal( ext, '.cr2' ); - var ext = path.extname(form._uploadPath('super.bar')); - assert.equal(ext, '.bar'); - }, -}); + var ext = path.extname( form._uploadPath( 'super.bar' ) ); + assert.equal( ext, '.bar' ); + }, +} ); -function makeHeader(filename) { - return 'Content-Disposition: form-data; name="upload"; filename="' + filename + '"'; +function makeHeader( filename ) { + return 'Content-Disposition: form-data; name="upload"; filename="' + filename + '"'; } diff --git a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js index 9f1cef8..425bb82 100644 --- a/example/node/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js +++ b/example/node/node_modules/express/node_modules/connect/node_modules/formidable/tool/record.js @@ -1,47 +1,47 @@ -var http = require('http'); -var fs = require('fs'); +var http = require( 'http' ); +var fs = require( 'fs' ); var connections = 0; -var server = http.createServer(function(req, res) { - var socket = req.socket; - console.log('Request: %s %s -> %s', req.method, req.url, socket.filename); +var server = http.createServer( function ( req, res ) { + var socket = req.socket; + console.log( 'Request: %s %s -> %s', req.method, req.url, socket.filename ); - req.on('end', function() { - if (req.url !== '/') { - res.end(JSON.stringify({ - method: req.method, - url: req.url, - filename: socket.filename, - })); - return; - } + req.on( 'end', function () { + if ( req.url !== '/' ) { + res.end( JSON.stringify( { + method : req.method, + url : req.url, + filename : socket.filename, + } ) ); + return; + } - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }); -}); + res.writeHead( 200, {'content-type' : 'text/html'} ); + res.end( + '
    ' + + '
    ' + + '
    ' + + '' + + '
    ' + ); + } ); +} ); -server.on('connection', function(socket) { - connections++; +server.on( 'connection', function ( socket ) { + connections++; - socket.id = connections; - socket.filename = 'connection-' + socket.id + '.http'; - socket.file = fs.createWriteStream(socket.filename); - socket.pipe(socket.file); + socket.id = connections; + socket.filename = 'connection-' + socket.id + '.http'; + socket.file = fs.createWriteStream( socket.filename ); + socket.pipe( socket.file ); - console.log('--> %s', socket.filename); - socket.on('close', function() { - console.log('<-- %s', socket.filename); - }); -}); + console.log( '--> %s', socket.filename ); + socket.on( 'close', function () { + console.log( '<-- %s', socket.filename ); + } ); +} ); var port = process.env.PORT || 8080; -server.listen(port, function() { - console.log('Recording connections on port %s', port); -}); +server.listen( port, function () { + console.log( 'Recording connections on port %s', port ); +} ); diff --git a/example/node/node_modules/express/node_modules/connect/package.json b/example/node/node_modules/express/node_modules/connect/package.json index 2b35a78..40895bb 100644 --- a/example/node/node_modules/express/node_modules/connect/package.json +++ b/example/node/node_modules/express/node_modules/connect/package.json @@ -1,25 +1,27 @@ { - "name": "connect", - "version": "1.8.6", - "description": "High performance middleware framework", - "keywords": ["framework", "web", "middleware", "connect", "rack"], - "repository": "git://github.com/senchalabs/connect.git", - "author": "TJ Holowaychuk (http://tjholowaychuk.com)", - "repository": "git://github.com/senchalabs/connect", - "dependencies": { - "qs": ">= 0.4.0", - "mime": ">= 0.0.1", - "formidable": "1.0.x" - }, - "devDependencies": { - "expresso": "0.9.2", - "koala": "0.1.2", - "less": "1.1.1", - "sass": "0.5.0", - "markdown": "0.2.1", - "ejs": "0.4.3", - "should": "0.3.2" - }, - "main": "index", - "engines": { "node": ">= 0.4.1 < 0.7.0" } + "name" : "connect", + "version" : "1.8.6", + "description" : "High performance middleware framework", + "keywords" : ["framework", "web", "middleware", "connect", "rack"], + "repository" : "git://github.com/senchalabs/connect.git", + "author" : "TJ Holowaychuk (http://tjholowaychuk.com)", + "repository" : "git://github.com/senchalabs/connect", + "dependencies" : { + "qs" : ">= 0.4.0", + "mime" : ">= 0.0.1", + "formidable" : "1.0.x" + }, + "devDependencies" : { + "expresso" : "0.9.2", + "koala" : "0.1.2", + "less" : "1.1.1", + "sass" : "0.5.0", + "markdown" : "0.2.1", + "ejs" : "0.4.3", + "should" : "0.3.2" + }, + "main" : "index", + "engines" : { + "node" : ">= 0.4.1 < 0.7.0" + } } \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/mime/mime.js b/example/node/node_modules/express/node_modules/mime/mime.js index 5fac753..80863cb 100644 --- a/example/node/node_modules/express/node_modules/mime/mime.js +++ b/example/node/node_modules/express/node_modules/mime/mime.js @@ -1,92 +1,92 @@ -var path = require('path'), - fs = require('fs'); +var path = require( 'path' ), + fs = require( 'fs' ); var mime = module.exports = { - /** Map of extension to mime type */ - types: {}, + /** Map of extension to mime type */ + types : {}, - /** Map of mime type to extension */ - extensions :{}, + /** Map of mime type to extension */ + extensions : {}, - /** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ - define: function(map) { - for (var type in map) { - var exts = map[type]; + /** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ + define : function ( map ) { + for ( var type in map ) { + var exts = map[type]; - for (var i = 0; i < exts.length; i++) { - mime.types[exts[i]] = type; - } + for ( var i = 0; i < exts.length; i++ ) { + mime.types[exts[i]] = type; + } - // Default extension is the first one we encounter - if (!mime.extensions[type]) { - mime.extensions[type] = exts[0]; - } - } - }, + // Default extension is the first one we encounter + if ( !mime.extensions[type] ) { + mime.extensions[type] = exts[0]; + } + } + }, - /** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ - load: function(file) { - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); + /** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ + load : function ( file ) { + // Read file and split into lines + var map = {}, + content = fs.readFileSync( file, 'ascii' ), + lines = content.split( /[\r\n]+/ ); - lines.forEach(function(line, lineno) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); + lines.forEach( function ( line, lineno ) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace( /\s*#.*|^\s*|\s*$/g, '' ).split( /\s+/ ); + map[fields.shift()] = fields; + } ); - mime.define(map); - }, + mime.define( map ); + }, - /** - * Lookup a mime type based on extension - */ - lookup: function(path, fallback) { - var ext = path.replace(/.*[\.\/]/, '').toLowerCase(); - return mime.types[ext] || fallback || mime.default_type; - }, + /** + * Lookup a mime type based on extension + */ + lookup : function ( path, fallback ) { + var ext = path.replace( /.*[\.\/]/, '' ).toLowerCase(); + return mime.types[ext] || fallback || mime.default_type; + }, - /** - * Return file extension associated with a mime type - */ - extension: function(mimeType) { - return mime.extensions[mimeType]; - }, + /** + * Return file extension associated with a mime type + */ + extension : function ( mimeType ) { + return mime.extensions[mimeType]; + }, - /** - * Lookup a charset based on mime type. - */ - charsets: { - lookup: function (mimeType, fallback) { - // Assume text types are utf8. Modify mime logic as needed. - return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; - } - } + /** + * Lookup a charset based on mime type. + */ + charsets : { + lookup : function ( mimeType, fallback ) { + // Assume text types are utf8. Modify mime logic as needed. + return (/^text\//).test( mimeType ) ? 'UTF-8' : fallback; + } + } }; // Load our local copy of // http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -mime.load(path.join(__dirname, 'types/mime.types')); +mime.load( path.join( __dirname, 'types/mime.types' ) ); // Overlay enhancements submitted by the node.js community -mime.load(path.join(__dirname, 'types/node.types')); +mime.load( path.join( __dirname, 'types/node.types' ) ); // Set the default type mime.default_type = mime.types.bin; diff --git a/example/node/node_modules/express/node_modules/mime/package.json b/example/node/node_modules/express/node_modules/mime/package.json index 85277b0..c1f6543 100644 --- a/example/node/node_modules/express/node_modules/mime/package.json +++ b/example/node/node_modules/express/node_modules/mime/package.json @@ -1,22 +1,27 @@ { - "author": { - "name": "Robert Kieffer", - "url": "http://github.com/broofa", - "email": "robert@broofa.com" - }, - "contributors": [ - { - "name": "Benjamin Thomas", - "url": "http://github.com/bentomas", - "email": "benjamin@benjaminthomas.org" - } - ], - "dependencies": {}, - "description": "A comprehensive library for mime-type mapping", - "devDependencies": {"async_testing": ""}, - "keywords": ["util", "mime"], - "main": "mime.js", - "name": "mime", - "repository": {"url": "http://github.com/bentomas/node-mime", "type": "git"}, - "version": "1.2.4" + "author" : { + "name" : "Robert Kieffer", + "url" : "http://github.com/broofa", + "email" : "robert@broofa.com" + }, + "contributors" : [ + { + "name" : "Benjamin Thomas", + "url" : "http://github.com/bentomas", + "email" : "benjamin@benjaminthomas.org" + } + ], + "dependencies" : {}, + "description" : "A comprehensive library for mime-type mapping", + "devDependencies" : { + "async_testing" : "" + }, + "keywords" : ["util", "mime"], + "main" : "mime.js", + "name" : "mime", + "repository" : { + "url" : "http://github.com/bentomas/node-mime", + "type" : "git" + }, + "version" : "1.2.4" } diff --git a/example/node/node_modules/express/node_modules/mime/test.js b/example/node/node_modules/express/node_modules/mime/test.js index b904895..8c455e9 100644 --- a/example/node/node_modules/express/node_modules/mime/test.js +++ b/example/node/node_modules/express/node_modules/mime/test.js @@ -3,77 +3,77 @@ * * Usage: node test.js */ -var mime = require('./mime'); -exports["test mime lookup"] = function(test) { - // easy - test.equal('text/plain', mime.lookup('text.txt')); +var mime = require( './mime' ); +exports["test mime lookup"] = function ( test ) { + // easy + test.equal( 'text/plain', mime.lookup( 'text.txt' ) ); - // hidden file or multiple periods - test.equal('text/plain', mime.lookup('.text.txt')); + // hidden file or multiple periods + test.equal( 'text/plain', mime.lookup( '.text.txt' ) ); - // just an extension - test.equal('text/plain', mime.lookup('.txt')); + // just an extension + test.equal( 'text/plain', mime.lookup( '.txt' ) ); - // just an extension without a dot - test.equal('text/plain', mime.lookup('txt')); + // just an extension without a dot + test.equal( 'text/plain', mime.lookup( 'txt' ) ); - // default - test.equal('application/octet-stream', mime.lookup('text.nope')); + // default + test.equal( 'application/octet-stream', mime.lookup( 'text.nope' ) ); - // fallback - test.equal('fallback', mime.lookup('text.fallback', 'fallback')); + // fallback + test.equal( 'fallback', mime.lookup( 'text.fallback', 'fallback' ) ); - test.finish(); + test.finish(); }; -exports["test extension lookup"] = function(test) { - // easy - test.equal('txt', mime.extension(mime.types.text)); - test.equal('html', mime.extension(mime.types.htm)); - test.equal('bin', mime.extension('application/octet-stream')); +exports["test extension lookup"] = function ( test ) { + // easy + test.equal( 'txt', mime.extension( mime.types.text ) ); + test.equal( 'html', mime.extension( mime.types.htm ) ); + test.equal( 'bin', mime.extension( 'application/octet-stream' ) ); - test.finish(); + test.finish(); }; -exports["test mime lookup uppercase"] = function(test) { - // easy - test.equal('text/plain', mime.lookup('TEXT.TXT')); +exports["test mime lookup uppercase"] = function ( test ) { + // easy + test.equal( 'text/plain', mime.lookup( 'TEXT.TXT' ) ); - // just an extension - test.equal('text/plain', mime.lookup('.TXT')); + // just an extension + test.equal( 'text/plain', mime.lookup( '.TXT' ) ); - // just an extension without a dot - test.equal('text/plain', mime.lookup('TXT')); + // just an extension without a dot + test.equal( 'text/plain', mime.lookup( 'TXT' ) ); - // default - test.equal('application/octet-stream', mime.lookup('TEXT.NOPE')); + // default + test.equal( 'application/octet-stream', mime.lookup( 'TEXT.NOPE' ) ); - // fallback - test.equal('fallback', mime.lookup('TEXT.FALLBACK', 'fallback')); + // fallback + test.equal( 'fallback', mime.lookup( 'TEXT.FALLBACK', 'fallback' ) ); - test.finish(); + test.finish(); }; -exports["test custom types"] = function(test) { - test.equal('application/octet-stream', mime.lookup('file.buffer')); - test.equal('audio/mp4', mime.lookup('file.m4a')); +exports["test custom types"] = function ( test ) { + test.equal( 'application/octet-stream', mime.lookup( 'file.buffer' ) ); + test.equal( 'audio/mp4', mime.lookup( 'file.m4a' ) ); - test.finish(); + test.finish(); }; -exports["test charset lookup"] = function(test) { - // easy - test.equal('UTF-8', mime.charsets.lookup('text/plain')); +exports["test charset lookup"] = function ( test ) { + // easy + test.equal( 'UTF-8', mime.charsets.lookup( 'text/plain' ) ); - // none - test.ok(typeof mime.charsets.lookup(mime.types.js) == 'undefined'); + // none + test.ok( typeof mime.charsets.lookup( mime.types.js ) == 'undefined' ); - // fallback - test.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + // fallback + test.equal( 'fallback', mime.charsets.lookup( 'application/octet-stream', 'fallback' ) ); - test.finish(); + test.finish(); }; -if (module == require.main) { - require('async_testing').run(__filename, process.ARGV); +if ( module == require.main ) { + require( 'async_testing' ).run( __filename, process.ARGV ); } diff --git a/example/node/node_modules/express/node_modules/mkdirp/examples/pow.js b/example/node/node_modules/express/node_modules/mkdirp/examples/pow.js index e692421..15b77c1 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/examples/pow.js +++ b/example/node/node_modules/express/node_modules/mkdirp/examples/pow.js @@ -1,6 +1,10 @@ -var mkdirp = require('mkdirp'); +var mkdirp = require( 'mkdirp' ); -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); +mkdirp( '/tmp/foo/bar/baz', function ( err ) { + if ( err ) { + console.error( err ) + } + else { + console.log( 'pow!' ) + } +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/index.js b/example/node/node_modules/express/node_modules/mkdirp/index.js index 25f43ad..71a61b9 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/index.js +++ b/example/node/node_modules/express/node_modules/mkdirp/index.js @@ -1,79 +1,102 @@ -var path = require('path'); -var fs = require('fs'); +var path = require( 'path' ); +var fs = require( 'fs' ); module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; -function mkdirP (p, mode, f) { - if (typeof mode === 'function' || mode === undefined) { - f = mode; - mode = 0777 & (~process.umask()); - } - - var cb = f || function () {}; - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); +function mkdirP( p, mode, f ) { + if ( typeof mode === 'function' || mode === undefined ) { + f = mode; + mode = 0777 & (~process.umask()); + } - fs.mkdir(p, mode, function (er) { - if (!er) return cb(); - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), mode, function (er) { - if (er) cb(er); - else mkdirP(p, mode, cb); - }); - break; + var cb = f || function () { + }; + if ( typeof mode === 'string' ) { + mode = parseInt( mode, 8 ); + } + p = path.resolve( p ); - case 'EEXIST': - fs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original EEXIST be the failure reason. - if (er2 || !stat.isDirectory()) cb(er) - else cb(); - }); - break; + fs.mkdir( p, mode, function ( er ) { + if ( !er ) { + return cb(); + } + switch ( er.code ) { + case 'ENOENT': + mkdirP( path.dirname( p ), mode, function ( er ) { + if ( er ) { + cb( er ); + } + else { + mkdirP( p, mode, cb ); + } + } ); + break; - default: - cb(er); - break; - } - }); + case 'EEXIST': + fs.stat( p, function ( er2, stat ) { + // if the stat fails, then that's super weird. + // let the original EEXIST be the failure reason. + if ( er2 || !stat.isDirectory() ) { + cb( er ) + } + else { + cb(); + } + } ); + break; + + default: + cb( er ); + break; + } + } ); } -mkdirP.sync = function sync (p, mode) { - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - try { - fs.mkdirSync(p, mode) - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - var err1 = sync(path.dirname(p), mode) - if (err1) throw err1; - else return sync(p, mode); - break; - - case 'EEXIST' : - var stat; - try { - stat = fs.statSync(p); - } - catch (err1) { - throw err0 - } - if (!stat.isDirectory()) throw err0; - else return null; - break; - default : - throw err0 - break; - } - } - - return null; +mkdirP.sync = function sync( p, mode ) { + if ( mode === undefined ) { + mode = 0777 & (~process.umask()); + } + + if ( typeof mode === 'string' ) { + mode = parseInt( mode, 8 ); + } + p = path.resolve( p ); + + try { + fs.mkdirSync( p, mode ) + } + catch ( err0 ) { + switch ( err0.code ) { + case 'ENOENT' : + var err1 = sync( path.dirname( p ), mode ) + if ( err1 ) { + throw err1; + } + else { + return sync( p, mode ); + } + break; + + case 'EEXIST' : + var stat; + try { + stat = fs.statSync( p ); + } + catch ( err1 ) { + throw err0 + } + if ( !stat.isDirectory() ) { + throw err0; + } + else { + return null; + } + break; + default : + throw err0 + break; + } + } + + return null; }; diff --git a/example/node/node_modules/express/node_modules/mkdirp/package.json b/example/node/node_modules/express/node_modules/mkdirp/package.json index 1bf9ac7..2d02711 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/package.json +++ b/example/node/node_modules/express/node_modules/mkdirp/package.json @@ -1,23 +1,25 @@ { - "name" : "mkdirp", - "description" : "Recursively mkdir, like `mkdir -p`", - "version" : "0.3.0", - "author" : "James Halliday (http://substack.net)", - "main" : "./index", - "keywords" : [ - "mkdir", - "directory" - ], - "repository" : { - "type" : "git", - "url" : "http://github.com/substack/node-mkdirp.git" - }, - "scripts" : { - "test" : "tap test/*.js" - }, - "devDependencies" : { - "tap" : "0.0.x" - }, - "license" : "MIT/X11", - "engines": { "node": "*" } + "name" : "mkdirp", + "description" : "Recursively mkdir, like `mkdir -p`", + "version" : "0.3.0", + "author" : "James Halliday (http://substack.net)", + "main" : "./index", + "keywords" : [ + "mkdir", + "directory" + ], + "repository" : { + "type" : "git", + "url" : "http://github.com/substack/node-mkdirp.git" + }, + "scripts" : { + "test" : "tap test/*.js" + }, + "devDependencies" : { + "tap" : "0.0.x" + }, + "license" : "MIT/X11", + "engines" : { + "node" : "*" + } } diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/chmod.js b/example/node/node_modules/express/node_modules/mkdirp/test/chmod.js index 520dcb8..25cb0e1 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/chmod.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/chmod.js @@ -1,38 +1,38 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ).mkdirp; +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; var ps = [ '', 'tmp' ]; -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); +for ( var i = 0; i < 25; i++ ) { + var dir = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + ps.push( dir ); } -var file = ps.join('/'); +var file = ps.join( '/' ); -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); +test( 'chmod-pre', function ( t ) { + var mode = 0744 + mkdirp( file, mode, function ( er ) { + t.ifError( er, 'should not error' ); + fs.stat( file, function ( er, stat ) { + t.ifError( er, 'should exist' ); + t.ok( stat && stat.isDirectory(), 'should be directory' ); + t.equal( stat && stat.mode & 0777, mode, 'should be 0744' ); + t.end(); + } ); + } ); +} ); -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); +test( 'chmod', function ( t ) { + var mode = 0755 + mkdirp( file, mode, function ( er ) { + t.ifError( er, 'should not error' ); + fs.stat( file, function ( er, stat ) { + t.ifError( er, 'should exist' ); + t.ok( stat && stat.isDirectory(), 'should be directory' ); + t.end(); + } ); + } ); +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/clobber.js b/example/node/node_modules/express/node_modules/mkdirp/test/clobber.js index 0eb7099..463cd81 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/clobber.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/clobber.js @@ -1,37 +1,37 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ).mkdirp; +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; var ps = [ '', 'tmp' ]; -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); +for ( var i = 0; i < 25; i++ ) { + var dir = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + ps.push( dir ); } -var file = ps.join('/'); +var file = ps.join( '/' ); // a file in the way -var itw = ps.slice(0, 3).join('/'); +var itw = ps.slice( 0, 3 ).join( '/' ); -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); +test( 'clobber-pre', function ( t ) { + console.error( "about to write to " + itw ) + fs.writeFileSync( itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.' ); - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) + fs.stat( itw, function ( er, stat ) { + t.ifError( er ) + t.ok( stat && stat.isFile(), 'should be file' ) + t.end() + } ) +} ) -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); +test( 'clobber', function ( t ) { + t.plan( 2 ); + mkdirp( file, 0755, function ( err ) { + t.ok( err ); + t.equal( err.code, 'ENOTDIR' ); + t.end(); + } ); +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/mkdirp.js b/example/node/node_modules/express/node_modules/mkdirp/test/mkdirp.js index b07cd70..079b8b3 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/mkdirp.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/mkdirp.js @@ -1,28 +1,38 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ); +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); +test( 'woo', function ( t ) { + t.plan( 2 ); + var x = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var y = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var z = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + + var file = '/tmp/' + [x, y, z].join( '/' ); + + mkdirp( file, 0755, function ( err ) { + if ( err ) { + t.fail( err ); + } + else { + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.equal( stat.mode & 0777, 0755 ); + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ) + } + } ); +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/perm.js b/example/node/node_modules/express/node_modules/mkdirp/test/perm.js index 23a7abb..7ed7b98 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/perm.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/perm.js @@ -1,32 +1,44 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ); +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('async perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); +test( 'async perm', function ( t ) { + t.plan( 2 ); + var file = '/tmp/' + (Math.random() * (1 << 30)).toString( 16 ); -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); + mkdirp( file, 0755, function ( err ) { + if ( err ) { + t.fail( err ); + } + else { + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.equal( stat.mode & 0777, 0755 ); + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ) + } + } ); +} ); + +test( 'async root perm', function ( t ) { + mkdirp( '/tmp', 0755, function ( err ) { + if ( err ) { + t.fail( err ); + } + t.end(); + } ); + t.end(); +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/perm_sync.js b/example/node/node_modules/express/node_modules/mkdirp/test/perm_sync.js index f685f60..deb3e60 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/perm_sync.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/perm_sync.js @@ -1,39 +1,51 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ); +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('sync perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); +test( 'sync perm', function ( t ) { + t.plan( 2 ); + var file = '/tmp/' + (Math.random() * (1 << 30)).toString( 16 ) + '.json'; -test('sync root perm', function (t) { - t.plan(1); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); + mkdirp.sync( file, 0755 ); + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.equal( stat.mode & 0777, 0755 ); + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ); +} ); + +test( 'sync root perm', function ( t ) { + t.plan( 1 ); + + var file = '/tmp'; + mkdirp.sync( file, 0755 ); + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ); +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/race.js b/example/node/node_modules/express/node_modules/mkdirp/test/race.js index 96a0447..5ab6f8c 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/race.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/race.js @@ -1,41 +1,57 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ).mkdirp; +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); +test( 'race', function ( t ) { + t.plan( 4 ); + var ps = [ '', 'tmp' ]; + + for ( var i = 0; i < 25; i++ ) { + var dir = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + ps.push( dir ); + } + var file = ps.join( '/' ); + + var res = 2; + mk( file, function () { + if ( --res === 0 ) { + t.end(); + } + } ); + + mk( file, function () { + if ( --res === 0 ) { + t.end(); + } + } ); + + function mk( file, cb ) { + mkdirp( file, 0755, function ( err ) { + if ( err ) { + t.fail( err ); + } + else { + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.equal( stat.mode & 0777, 0755 ); + t.ok( stat.isDirectory(), 'target not a directory' ); + if ( cb ) { + cb(); + } + } + } ) + } + } ) + } + } ); + } +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/rel.js b/example/node/node_modules/express/node_modules/mkdirp/test/rel.js index 7985824..b5ae1e4 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/rel.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/rel.js @@ -1,32 +1,42 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ); +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); +test( 'rel', function ( t ) { + t.plan( 2 ); + var x = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var y = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var z = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + + var cwd = process.cwd(); + process.chdir( '/tmp' ); + + var file = [x, y, z].join( '/' ); + + mkdirp( file, 0755, function ( err ) { + if ( err ) { + t.fail( err ); + } + else { + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + process.chdir( cwd ); + t.equal( stat.mode & 0777, 0755 ); + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ) + } + } ); +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/sync.js b/example/node/node_modules/express/node_modules/mkdirp/test/sync.js index e0e389d..891b280 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/sync.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/sync.js @@ -1,27 +1,37 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ); +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('sync', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - var err = mkdirp.sync(file, 0755); - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) -}); +test( 'sync', function ( t ) { + t.plan( 2 ); + var x = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var y = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var z = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + + var file = '/tmp/' + [x, y, z].join( '/' ); + + var err = mkdirp.sync( file, 0755 ); + if ( err ) { + t.fail( err ); + } + else { + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.equal( stat.mode & 0777, 0755 ); + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ) + } +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/umask.js b/example/node/node_modules/express/node_modules/mkdirp/test/umask.js index 64ccafe..e11f75b 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/umask.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/umask.js @@ -1,28 +1,38 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ); +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('implicit mode from umask', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); +test( 'implicit mode from umask', function ( t ) { + t.plan( 2 ); + var x = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var y = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var z = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + + var file = '/tmp/' + [x, y, z].join( '/' ); + + mkdirp( file, function ( err ) { + if ( err ) { + t.fail( err ); + } + else { + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.equal( stat.mode & 0777, 0777 & (~process.umask()) ); + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ) + } + } ); +} ); diff --git a/example/node/node_modules/express/node_modules/mkdirp/test/umask_sync.js b/example/node/node_modules/express/node_modules/mkdirp/test/umask_sync.js index 83cba56..7726874 100644 --- a/example/node/node_modules/express/node_modules/mkdirp/test/umask_sync.js +++ b/example/node/node_modules/express/node_modules/mkdirp/test/umask_sync.js @@ -1,27 +1,37 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; +var mkdirp = require( '../' ); +var path = require( 'path' ); +var fs = require( 'fs' ); +var test = require( 'tap' ).test; -test('umask sync modes', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - var err = mkdirp.sync(file); - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, (0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) -}); +test( 'umask sync modes', function ( t ) { + t.plan( 2 ); + var x = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var y = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + var z = Math.floor( Math.random() * Math.pow( 16, 4 ) ).toString( 16 ); + + var file = '/tmp/' + [x, y, z].join( '/' ); + + var err = mkdirp.sync( file ); + if ( err ) { + t.fail( err ); + } + else { + path.exists( file, function ( ex ) { + if ( !ex ) { + t.fail( 'file not created' ) + } + else { + fs.stat( file, function ( err, stat ) { + if ( err ) { + t.fail( err ) + } + else { + t.equal( stat.mode & 0777, (0777 & (~process.umask())) ); + t.ok( stat.isDirectory(), 'target not a directory' ); + t.end(); + } + } ) + } + } ) + } +} ); diff --git a/example/node/node_modules/express/node_modules/qs/benchmark.js b/example/node/node_modules/express/node_modules/qs/benchmark.js index 97e2c93..3811973 100644 --- a/example/node/node_modules/express/node_modules/qs/benchmark.js +++ b/example/node/node_modules/express/node_modules/qs/benchmark.js @@ -1,17 +1,20 @@ - -var qs = require('./'); +var qs = require( './' ); var times = 100000 - , start = new Date - , n = times; + , start = new Date + , n = times; -console.log('times: %d', times); +console.log( 'times: %d', times ); -while (n--) qs.parse('foo=bar'); -console.log('simple: %dms', new Date - start); +while ( n-- ) { + qs.parse( 'foo=bar' ); +} +console.log( 'simple: %dms', new Date - start ); var start = new Date - , n = times; + , n = times; -while (n--) qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log('nested: %dms', new Date - start); \ No newline at end of file +while ( n-- ) { + qs.parse( 'user[name][first]=tj&user[name][last]=holowaychuk' ); +} +console.log( 'nested: %dms', new Date - start ); \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/qs/examples.js b/example/node/node_modules/express/node_modules/qs/examples.js index 27617b7..d02c13a 100644 --- a/example/node/node_modules/express/node_modules/qs/examples.js +++ b/example/node/node_modules/express/node_modules/qs/examples.js @@ -1,51 +1,50 @@ - /** * Module dependencies. */ -var qs = require('./'); +var qs = require( './' ); -var obj = qs.parse('foo'); -console.log(obj) +var obj = qs.parse( 'foo' ); +console.log( obj ) -var obj = qs.parse('foo=bar=baz'); -console.log(obj) +var obj = qs.parse( 'foo=bar=baz' ); +console.log( obj ) -var obj = qs.parse('users[]'); -console.log(obj) +var obj = qs.parse( 'users[]' ); +console.log( obj ) -var obj = qs.parse('name=tj&email=tj@vision-media.ca'); -console.log(obj) +var obj = qs.parse( 'name=tj&email=tj@vision-media.ca' ); +console.log( obj ) -var obj = qs.parse('users[]=tj&users[]=tobi&users[]=jane'); -console.log(obj) +var obj = qs.parse( 'users[]=tj&users[]=tobi&users[]=jane' ); +console.log( obj ) -var obj = qs.parse('user[name][first]=tj&user[name][last]=holowaychuk'); -console.log(obj) +var obj = qs.parse( 'user[name][first]=tj&user[name][last]=holowaychuk' ); +console.log( obj ) -var obj = qs.parse('users[][name][first]=tj&users[][name][last]=holowaychuk'); -console.log(obj) +var obj = qs.parse( 'users[][name][first]=tj&users[][name][last]=holowaychuk' ); +console.log( obj ) -var obj = qs.parse('a=a&a=b&a=c'); -console.log(obj) +var obj = qs.parse( 'a=a&a=b&a=c' ); +console.log( obj ) -var obj = qs.parse('user[tj]=tj&user[tj]=TJ'); -console.log(obj) +var obj = qs.parse( 'user[tj]=tj&user[tj]=TJ' ); +console.log( obj ) -var obj = qs.parse('user[names]=tj&user[names]=TJ&user[names]=Tyler'); -console.log(obj) +var obj = qs.parse( 'user[names]=tj&user[names]=TJ&user[names]=Tyler' ); +console.log( obj ) -var obj = qs.parse('user[name][first]=tj&user[name][first]=TJ'); -console.log(obj) +var obj = qs.parse( 'user[name][first]=tj&user[name][first]=TJ' ); +console.log( obj ) -var obj = qs.parse('user[0]=tj&user[1]=TJ'); -console.log(obj) +var obj = qs.parse( 'user[0]=tj&user[1]=TJ' ); +console.log( obj ) -var obj = qs.parse('user[0]=tj&user[]=TJ'); -console.log(obj) +var obj = qs.parse( 'user[0]=tj&user[]=TJ' ); +console.log( obj ) -var obj = qs.parse('user[0]=tj&user[foo]=TJ'); -console.log(obj) +var obj = qs.parse( 'user[0]=tj&user[foo]=TJ' ); +console.log( obj ) -var str = qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}); -console.log(str); \ No newline at end of file +var str = qs.stringify( { user : { name : 'Tobi', email : 'tobi@learnboost.com' }} ); +console.log( str ); \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/qs/index.js b/example/node/node_modules/express/node_modules/qs/index.js index d177d20..179860d 100644 --- a/example/node/node_modules/express/node_modules/qs/index.js +++ b/example/node/node_modules/express/node_modules/qs/index.js @@ -1,2 +1 @@ - -module.exports = require('./lib/querystring'); \ No newline at end of file +module.exports = require( './lib/querystring' ); \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/qs/lib/querystring.js b/example/node/node_modules/express/node_modules/qs/lib/querystring.js index 6c72712..26406cd 100644 --- a/example/node/node_modules/express/node_modules/qs/lib/querystring.js +++ b/example/node/node_modules/express/node_modules/qs/lib/querystring.js @@ -1,4 +1,3 @@ - /*! * querystring * Copyright(c) 2010 TJ Holowaychuk @@ -23,111 +22,126 @@ var toString = Object.prototype.toString; var isint = /^[0-9]+$/; -function promote(parent, key) { - if (parent[key].length == 0) return parent[key] = {}; - var t = {}; - for (var i in parent[key]) t[i] = parent[key][i]; - parent[key] = t; - return t; +function promote( parent, key ) { + if ( parent[key].length == 0 ) { + return parent[key] = {}; + } + var t = {}; + for ( var i in parent[key] ) { + t[i] = parent[key][i]; + } + parent[key] = t; + return t; } -function parse(parts, parent, key, val) { - var part = parts.shift(); - // end - if (!part) { - if (Array.isArray(parent[key])) { - parent[key].push(val); - } else if ('object' == typeof parent[key]) { - parent[key] = val; - } else if ('undefined' == typeof parent[key]) { - parent[key] = val; - } else { - parent[key] = [parent[key], val]; - } - // array - } else { - var obj = parent[key] = parent[key] || []; - if (']' == part) { - if (Array.isArray(obj)) { - if ('' != val) obj.push(val); - } else if ('object' == typeof obj) { - obj[Object.keys(obj).length] = val; - } else { - obj = parent[key] = [parent[key], val]; - } - // prop - } else if (~part.indexOf(']')) { - part = part.substr(0, part.length - 1); - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - // key - } else { - if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - } - } +function parse( parts, parent, key, val ) { + var part = parts.shift(); + // end + if ( !part ) { + if ( Array.isArray( parent[key] ) ) { + parent[key].push( val ); + } else if ( 'object' == typeof parent[key] ) { + parent[key] = val; + } else if ( 'undefined' == typeof parent[key] ) { + parent[key] = val; + } else { + parent[key] = [parent[key], val]; + } + // array + } else { + var obj = parent[key] = parent[key] || []; + if ( ']' == part ) { + if ( Array.isArray( obj ) ) { + if ( '' != val ) { + obj.push( val ); + } + } else if ( 'object' == typeof obj ) { + obj[Object.keys( obj ).length] = val; + } else { + obj = parent[key] = [parent[key], val]; + } + // prop + } else if ( ~part.indexOf( ']' ) ) { + part = part.substr( 0, part.length - 1 ); + if ( !isint.test( part ) && Array.isArray( obj ) ) { + obj = promote( parent, key ); + } + parse( parts, obj, part, val ); + // key + } else { + if ( !isint.test( part ) && Array.isArray( obj ) ) { + obj = promote( parent, key ); + } + parse( parts, obj, part, val ); + } + } } /** * Merge parent key/val pair. */ -function merge(parent, key, val){ - if (~key.indexOf(']')) { - var parts = key.split('[') - , len = parts.length - , last = len - 1; - parse(parts, parent, 'base', val); - // optimize - } else { - if (!isint.test(key) && Array.isArray(parent.base)) { - var t = {}; - for (var k in parent.base) t[k] = parent.base[k]; - parent.base = t; - } - set(parent.base, key, val); - } +function merge( parent, key, val ) { + if ( ~key.indexOf( ']' ) ) { + var parts = key.split( '[' ) + , len = parts.length + , last = len - 1; + parse( parts, parent, 'base', val ); + // optimize + } else { + if ( !isint.test( key ) && Array.isArray( parent.base ) ) { + var t = {}; + for ( var k in parent.base ) { + t[k] = parent.base[k]; + } + parent.base = t; + } + set( parent.base, key, val ); + } - return parent; + return parent; } /** * Parse the given obj. */ -function parseObject(obj){ - var ret = { base: {} }; - Object.keys(obj).forEach(function(name){ - merge(ret, name, obj[name]); - }); - return ret.base; +function parseObject( obj ) { + var ret = { base : {} }; + Object.keys( obj ).forEach( function ( name ) { + merge( ret, name, obj[name] ); + } ); + return ret.base; } /** * Parse the given str. */ -function parseString(str){ - return String(str) - .split('&') - .reduce(function(ret, pair){ - try{ - pair = decodeURIComponent(pair.replace(/\+/g, ' ')); - } catch(e) { - // ignore - } +function parseString( str ) { + return String( str ) + .split( '&' ) + .reduce( + function ( ret, pair ) { + try { + pair = decodeURIComponent( pair.replace( /\+/g, ' ' ) ); + } catch ( e ) { + // ignore + } - var eql = pair.indexOf('=') - , brace = lastBraceInKey(pair) - , key = pair.substr(0, brace || eql) - , val = pair.substr(brace || eql, pair.length) - , val = val.substr(val.indexOf('=') + 1, val.length); + var eql = pair.indexOf( '=' ) + , brace = lastBraceInKey( pair ) + , key = pair.substr( 0, brace || eql ) + , val = pair.substr( brace || eql, pair.length ) + , val = val.substr( val.indexOf( '=' ) + 1, val.length ); - // ?foo - if ('' == key) key = pair, val = ''; + // ?foo + if ( '' == key ) { + key = pair, val = ''; + } - return merge(ret, key, val); - }, { base: {} }).base; + return merge( ret, key, val ); + }, { base : {} } ).base; } /** @@ -138,11 +152,13 @@ function parseString(str){ * @api public */ -exports.parse = function(str){ - if (null == str || '' == str) return {}; - return 'object' == typeof str - ? parseObject(str) - : parseString(str); +exports.parse = function ( str ) { + if ( null == str || '' == str ) { + return {}; + } + return 'object' == typeof str + ? parseObject( str ) + : parseString( str ); }; /** @@ -153,16 +169,16 @@ exports.parse = function(str){ * @api public */ -var stringify = exports.stringify = function(obj, prefix) { - if (Array.isArray(obj)) { - return stringifyArray(obj, prefix); - } else if ('[object Object]' == toString.call(obj)) { - return stringifyObject(obj, prefix); - } else if ('string' == typeof obj) { - return stringifyString(obj, prefix); - } else { - return prefix + '=' + obj; - } +var stringify = exports.stringify = function ( obj, prefix ) { + if ( Array.isArray( obj ) ) { + return stringifyArray( obj, prefix ); + } else if ( '[object Object]' == toString.call( obj ) ) { + return stringifyObject( obj, prefix ); + } else if ( 'string' == typeof obj ) { + return stringifyString( obj, prefix ); + } else { + return prefix + '=' + obj; + } }; /** @@ -174,9 +190,11 @@ var stringify = exports.stringify = function(obj, prefix) { * @api private */ -function stringifyString(str, prefix) { - if (!prefix) throw new TypeError('stringify expects an object'); - return prefix + '=' + encodeURIComponent(str); +function stringifyString( str, prefix ) { + if ( !prefix ) { + throw new TypeError( 'stringify expects an object' ); + } + return prefix + '=' + encodeURIComponent( str ); } /** @@ -188,13 +206,15 @@ function stringifyString(str, prefix) { * @api private */ -function stringifyArray(arr, prefix) { - var ret = []; - if (!prefix) throw new TypeError('stringify expects an object'); - for (var i = 0; i < arr.length; i++) { - ret.push(stringify(arr[i], prefix + '[]')); - } - return ret.join('&'); +function stringifyArray( arr, prefix ) { + var ret = []; + if ( !prefix ) { + throw new TypeError( 'stringify expects an object' ); + } + for ( var i = 0; i < arr.length; i++ ) { + ret.push( stringify( arr[i], prefix + '[]' ) ); + } + return ret.join( '&' ); } /** @@ -206,19 +226,19 @@ function stringifyArray(arr, prefix) { * @api private */ -function stringifyObject(obj, prefix) { - var ret = [] - , keys = Object.keys(obj) - , key; +function stringifyObject( obj, prefix ) { + var ret = [] + , keys = Object.keys( obj ) + , key; - for (var i = 0, len = keys.length; i < len; ++i) { - key = keys[i]; - ret.push(stringify(obj[key], prefix - ? prefix + '[' + encodeURIComponent(key) + ']' - : encodeURIComponent(key))); - } + for ( var i = 0, len = keys.length; i < len; ++i ) { + key = keys[i]; + ret.push( stringify( obj[key], prefix + ? prefix + '[' + encodeURIComponent( key ) + ']' + : encodeURIComponent( key ) ) ); + } - return ret.join('&'); + return ret.join( '&' ); } /** @@ -232,15 +252,15 @@ function stringifyObject(obj, prefix) { * @api private */ -function set(obj, key, val) { - var v = obj[key]; - if (undefined === v) { - obj[key] = val; - } else if (Array.isArray(v)) { - v.push(val); - } else { - obj[key] = [v, val]; - } +function set( obj, key, val ) { + var v = obj[key]; + if ( undefined === v ) { + obj[key] = val; + } else if ( Array.isArray( v ) ) { + v.push( val ); + } else { + obj[key] = [v, val]; + } } /** @@ -251,14 +271,20 @@ function set(obj, key, val) { * @api private */ -function lastBraceInKey(str) { - var len = str.length - , brace - , c; - for (var i = 0; i < len; ++i) { - c = str[i]; - if (']' == c) brace = false; - if ('[' == c) brace = true; - if ('=' == c && !brace) return i; - } +function lastBraceInKey( str ) { + var len = str.length + , brace + , c; + for ( var i = 0; i < len; ++i ) { + c = str[i]; + if ( ']' == c ) { + brace = false; + } + if ( '[' == c ) { + brace = true; + } + if ( '=' == c && !brace ) { + return i; + } + } } diff --git a/example/node/node_modules/express/node_modules/qs/package.json b/example/node/node_modules/express/node_modules/qs/package.json index 68dd5a6..a02e623 100644 --- a/example/node/node_modules/express/node_modules/qs/package.json +++ b/example/node/node_modules/express/node_modules/qs/package.json @@ -1,16 +1,18 @@ { - "name": "qs", - "description": "querystring parser", - "version": "0.4.2", - "repository": { - "type" : "git", - "url" : "git://github.com/visionmedia/node-querystring.git" - }, - "devDependencies": { - "mocha": "*" - , "should": "*" - }, - "author": "TJ Holowaychuk (http://tjholowaychuk.com)", - "main": "index", - "engines": { "node": "*" } + "name" : "qs", + "description" : "querystring parser", + "version" : "0.4.2", + "repository" : { + "type" : "git", + "url" : "git://github.com/visionmedia/node-querystring.git" + }, + "devDependencies" : { + "mocha" : "*", + "should" : "*" + }, + "author" : "TJ Holowaychuk (http://tjholowaychuk.com)", + "main" : "index", + "engines" : { + "node" : "*" + } } \ No newline at end of file diff --git a/example/node/node_modules/express/node_modules/qs/test/parse.js b/example/node/node_modules/express/node_modules/qs/test/parse.js index f219e27..b912754 100644 --- a/example/node/node_modules/express/node_modules/qs/test/parse.js +++ b/example/node/node_modules/express/node_modules/qs/test/parse.js @@ -1,167 +1,164 @@ - /** * Module dependencies. */ -var qs = require('../'); +var qs = require( '../' ); module.exports = { - 'test basics': function(){ - qs.parse('0=foo').should.eql({ '0': 'foo' }); + 'test basics' : function () { + qs.parse( '0=foo' ).should.eql( { '0' : 'foo' } ); - qs.parse('foo=c++') - .should.eql({ foo: 'c ' }); + qs.parse( 'foo=c++' ) + .should.eql( { foo : 'c ' } ); - qs.parse('a[>=]=23') - .should.eql({ a: { '>=': '23' }}); + qs.parse( 'a[>=]=23' ) + .should.eql( { a : { '>=' : '23' }} ); - qs.parse('a[<=>]==23') - .should.eql({ a: { '<=>': '=23' }}); + qs.parse( 'a[<=>]==23' ) + .should.eql( { a : { '<=>' : '=23' }} ); - qs.parse('a[==]=23') - .should.eql({ a: { '==': '23' }}); + qs.parse( 'a[==]=23' ) + .should.eql( { a : { '==' : '23' }} ); - qs.parse('foo') - .should.eql({ foo: '' }); + qs.parse( 'foo' ) + .should.eql( { foo : '' } ); - qs.parse('foo=bar') - .should.eql({ foo: 'bar' }); + qs.parse( 'foo=bar' ) + .should.eql( { foo : 'bar' } ); - qs.parse('foo%3Dbar=baz') - .should.eql({ foo: 'bar=baz' }); + qs.parse( 'foo%3Dbar=baz' ) + .should.eql( { foo : 'bar=baz' } ); - qs.parse(' foo = bar = baz ') - .should.eql({ ' foo ': ' bar = baz ' }); + qs.parse( ' foo = bar = baz ' ) + .should.eql( { ' foo ' : ' bar = baz ' } ); - qs.parse('foo=bar=baz') - .should.eql({ foo: 'bar=baz' }); + qs.parse( 'foo=bar=baz' ) + .should.eql( { foo : 'bar=baz' } ); - qs.parse('foo=bar&bar=baz') - .should.eql({ foo: 'bar', bar: 'baz' }); + qs.parse( 'foo=bar&bar=baz' ) + .should.eql( { foo : 'bar', bar : 'baz' } ); - qs.parse('foo=bar&baz') - .should.eql({ foo: 'bar', baz: '' }); + qs.parse( 'foo=bar&baz' ) + .should.eql( { foo : 'bar', baz : '' } ); - qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World') - .should.eql({ - cht: 'p3' - , chd: 't:60,40' - , chs: '250x100' - , chl: 'Hello|World' - }); - }, - - 'test nesting': function(){ - qs.parse('ops[>=]=25') - .should.eql({ ops: { '>=': '25' }}); + qs.parse( 'cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World' ) + .should.eql( { + cht : 'p3', chd : 't:60,40', chs : '250x100', chl : 'Hello|World' + } ); + }, - qs.parse('user[name]=tj') - .should.eql({ user: { name: 'tj' }}); + 'test nesting' : function () { + qs.parse( 'ops[>=]=25' ) + .should.eql( { ops : { '>=' : '25' }} ); - qs.parse('user[name][first]=tj&user[name][last]=holowaychuk') - .should.eql({ user: { name: { first: 'tj', last: 'holowaychuk' }}}); - }, - - 'test escaping': function(){ - qs.parse('foo=foo%20bar') - .should.eql({ foo: 'foo bar' }); - }, - - 'test arrays': function(){ - qs.parse('images[]') - .should.eql({ images: [] }); + qs.parse( 'user[name]=tj' ) + .should.eql( { user : { name : 'tj' }} ); - qs.parse('user[]=tj') - .should.eql({ user: ['tj'] }); + qs.parse( 'user[name][first]=tj&user[name][last]=holowaychuk' ) + .should.eql( { user : { name : { first : 'tj', last : 'holowaychuk' }}} ); + }, - qs.parse('user[]=tj&user[]=tobi&user[]=jane') - .should.eql({ user: ['tj', 'tobi', 'jane'] }); + 'test escaping' : function () { + qs.parse( 'foo=foo%20bar' ) + .should.eql( { foo : 'foo bar' } ); + }, - qs.parse('user[names][]=tj&user[names][]=tyler') - .should.eql({ user: { names: ['tj', 'tyler'] }}); + 'test arrays' : function () { + qs.parse( 'images[]' ) + .should.eql( { images : [] } ); - qs.parse('user[names][]=tj&user[names][]=tyler&user[email]=tj@vision-media.ca') - .should.eql({ user: { names: ['tj', 'tyler'], email: 'tj@vision-media.ca' }}); + qs.parse( 'user[]=tj' ) + .should.eql( { user : ['tj'] } ); - qs.parse('items=a&items=b') - .should.eql({ items: ['a', 'b'] }); + qs.parse( 'user[]=tj&user[]=tobi&user[]=jane' ) + .should.eql( { user : ['tj', 'tobi', 'jane'] } ); - qs.parse('user[names]=tj&user[names]=holowaychuk&user[names]=TJ') - .should.eql({ user: { names: ['tj', 'holowaychuk', 'TJ'] }}); + qs.parse( 'user[names][]=tj&user[names][]=tyler' ) + .should.eql( { user : { names : ['tj', 'tyler'] }} ); - qs.parse('user[name][first]=tj&user[name][first]=TJ') - .should.eql({ user: { name: { first: ['tj', 'TJ'] }}}); + qs.parse( 'user[names][]=tj&user[names][]=tyler&user[email]=tj@vision-media.ca' ) + .should.eql( { user : { names : ['tj', 'tyler'], email : 'tj@vision-media.ca' }} ); - var o = qs.parse('existing[fcbaebfecc][name][last]=tj') - o.should.eql({ existing: { 'fcbaebfecc': { name: { last: 'tj' }}}}) - Array.isArray(o.existing).should.be.false; - }, + qs.parse( 'items=a&items=b' ) + .should.eql( { items : ['a', 'b'] } ); - 'test right-hand brackets': function(){ - qs.parse('pets=["tobi"]') - .should.eql({ pets: '["tobi"]' }); + qs.parse( 'user[names]=tj&user[names]=holowaychuk&user[names]=TJ' ) + .should.eql( { user : { names : ['tj', 'holowaychuk', 'TJ'] }} ); - qs.parse('operators=[">=", "<="]') - .should.eql({ operators: '[">=", "<="]' }); + qs.parse( 'user[name][first]=tj&user[name][first]=TJ' ) + .should.eql( { user : { name : { first : ['tj', 'TJ'] }}} ); - qs.parse('op[>=]=[1,2,3]') - .should.eql({ op: { '>=': '[1,2,3]' }}); + var o = qs.parse( 'existing[fcbaebfecc][name][last]=tj' ) + o.should.eql( { existing : { 'fcbaebfecc' : { name : { last : 'tj' }}}} ) + Array.isArray( o.existing ).should.be.false; + }, - qs.parse('op[>=]=[1,2,3]&op[=]=[[[[1]]]]') - .should.eql({ op: { '>=': '[1,2,3]', '=': '[[[[1]]]]' }}); - }, - - 'test duplicates': function(){ - qs.parse('items=bar&items=baz&items=raz') - .should.eql({ items: ['bar', 'baz', 'raz'] }); - }, + 'test right-hand brackets' : function () { + qs.parse( 'pets=["tobi"]' ) + .should.eql( { pets : '["tobi"]' } ); - 'test empty': function(){ - qs.parse('').should.eql({}); - qs.parse(undefined).should.eql({}); - qs.parse(null).should.eql({}); - }, + qs.parse( 'operators=[">=", "<="]' ) + .should.eql( { operators : '[">=", "<="]' } ); - 'test arrays with indexes': function(){ - qs.parse('foo[0]=bar&foo[1]=baz').should.eql({ foo: ['bar', 'baz'] }); - qs.parse('foo[1]=bar&foo[0]=baz').should.eql({ foo: ['baz', 'bar'] }); - qs.parse('foo[base64]=RAWR').should.eql({ foo: { base64: 'RAWR' }}); - qs.parse('foo[64base]=RAWR').should.eql({ foo: { '64base': 'RAWR' }}); - }, + qs.parse( 'op[>=]=[1,2,3]' ) + .should.eql( { op : { '>=' : '[1,2,3]' }} ); - 'test arrays becoming objects': function(){ - qs.parse('foo[0]=bar&foo[bad]=baz').should.eql({ foo: { 0: "bar", bad: "baz" }}); - qs.parse('foo[bad]=baz&foo[0]=bar').should.eql({ foo: { 0: "bar", bad: "baz" }}); - }, + qs.parse( 'op[>=]=[1,2,3]&op[=]=[[[[1]]]]' ) + .should.eql( { op : { '>=' : '[1,2,3]', '=' : '[[[[1]]]]' }} ); + }, - 'test bleed-through of Array native properties/methods': function(){ - Array.prototype.protoProperty = true; - Array.prototype.protoFunction = function () {}; - qs.parse('foo=bar').should.eql({ foo: 'bar' }); - }, + 'test duplicates' : function () { + qs.parse( 'items=bar&items=baz&items=raz' ) + .should.eql( { items : ['bar', 'baz', 'raz'] } ); + }, - 'test malformed uri': function(){ - qs.parse('{%:%}').should.eql({ '{%:%}': '' }); - qs.parse('foo=%:%}').should.eql({ 'foo': '%:%}' }); - }, + 'test empty' : function () { + qs.parse( '' ).should.eql( {} ); + qs.parse( undefined ).should.eql( {} ); + qs.parse( null ).should.eql( {} ); + }, - 'test semi-parsed': function(){ - qs.parse({ 'user[name]': 'tobi' }) - .should.eql({ user: { name: 'tobi' }}); + 'test arrays with indexes' : function () { + qs.parse( 'foo[0]=bar&foo[1]=baz' ).should.eql( { foo : ['bar', 'baz'] } ); + qs.parse( 'foo[1]=bar&foo[0]=baz' ).should.eql( { foo : ['baz', 'bar'] } ); + qs.parse( 'foo[base64]=RAWR' ).should.eql( { foo : { base64 : 'RAWR' }} ); + qs.parse( 'foo[64base]=RAWR' ).should.eql( { foo : { '64base' : 'RAWR' }} ); + }, - qs.parse({ 'user[name]': 'tobi', 'user[email][main]': 'tobi@lb.com' }) - .should.eql({ user: { name: 'tobi', email: { main: 'tobi@lb.com' } }}); - } - - // 'test complex': function(){ - // qs.parse('users[][name][first]=tj&users[foo]=bar') - // .should.eql({ - // users: [ { name: 'tj' }, { name: 'tobi' }, { foo: 'bar' }] - // }); - // - // qs.parse('users[][name][first]=tj&users[][name][first]=tobi') - // .should.eql({ - // users: [ { name: 'tj' }, { name: 'tobi' }] - // }); - // } + 'test arrays becoming objects' : function () { + qs.parse( 'foo[0]=bar&foo[bad]=baz' ).should.eql( { foo : { 0 : "bar", bad : "baz" }} ); + qs.parse( 'foo[bad]=baz&foo[0]=bar' ).should.eql( { foo : { 0 : "bar", bad : "baz" }} ); + }, + + 'test bleed-through of Array native properties/methods' : function () { + Array.prototype.protoProperty = true; + Array.prototype.protoFunction = function () { + }; + qs.parse( 'foo=bar' ).should.eql( { foo : 'bar' } ); + }, + + 'test malformed uri' : function () { + qs.parse( '{%:%}' ).should.eql( { '{%:%}' : '' } ); + qs.parse( 'foo=%:%}' ).should.eql( { 'foo' : '%:%}' } ); + }, + + 'test semi-parsed' : function () { + qs.parse( { 'user[name]' : 'tobi' } ) + .should.eql( { user : { name : 'tobi' }} ); + + qs.parse( { 'user[name]' : 'tobi', 'user[email][main]' : 'tobi@lb.com' } ) + .should.eql( { user : { name : 'tobi', email : { main : 'tobi@lb.com' } }} ); + } + + // 'test complex': function(){ + // qs.parse('users[][name][first]=tj&users[foo]=bar') + // .should.eql({ + // users: [ { name: 'tj' }, { name: 'tobi' }, { foo: 'bar' }] + // }); + // + // qs.parse('users[][name][first]=tj&users[][name][first]=tobi') + // .should.eql({ + // users: [ { name: 'tj' }, { name: 'tobi' }] + // }); + // } }; diff --git a/example/node/node_modules/express/node_modules/qs/test/stringify.js b/example/node/node_modules/express/node_modules/qs/test/stringify.js index c2195cb..aa9a12d 100644 --- a/example/node/node_modules/express/node_modules/qs/test/stringify.js +++ b/example/node/node_modules/express/node_modules/qs/test/stringify.js @@ -1,103 +1,117 @@ - /** * Module dependencies. */ -var qs = require('../') - , should = require('should') - , str_identities = { - 'basics': [ - { str: 'foo=bar', obj: {'foo' : 'bar'}}, - { str: 'foo=%22bar%22', obj: {'foo' : '\"bar\"'}}, - { str: 'foo=', obj: {'foo': ''}}, - { str: 'foo=1&bar=2', obj: {'foo' : '1', 'bar' : '2'}}, - { str: 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', obj: {'my weird field': "q1!2\"'w$5&7/z8)?"}}, - { str: 'foo%3Dbaz=bar', obj: {'foo=baz': 'bar'}}, - { str: 'foo=bar&bar=baz', obj: {foo: 'bar', bar: 'baz'}} - ], - 'escaping': [ - { str: 'foo=foo%20bar', obj: {foo: 'foo bar'}}, - { str: 'cht=p3&chd=t%3A60%2C40&chs=250x100&chl=Hello%7CWorld', obj: { - cht: 'p3' - , chd: 't:60,40' - , chs: '250x100' - , chl: 'Hello|World' - }} - ], - 'nested': [ - { str: 'foo[]=bar&foo[]=quux', obj: {'foo' : ['bar', 'quux']}}, - { str: 'foo[]=bar', obj: {foo: ['bar']}}, - { str: 'foo[]=1&foo[]=2', obj: {'foo' : ['1', '2']}}, - { str: 'foo=bar&baz[]=1&baz[]=2&baz[]=3', obj: {'foo' : 'bar', 'baz' : ['1', '2', '3']}}, - { str: 'foo[]=bar&baz[]=1&baz[]=2&baz[]=3', obj: {'foo' : ['bar'], 'baz' : ['1', '2', '3']}}, - { str: 'x[y][z]=1', obj: {'x' : {'y' : {'z' : '1'}}}}, - { str: 'x[y][z][]=1', obj: {'x' : {'y' : {'z' : ['1']}}}}, - { str: 'x[y][z]=2', obj: {'x' : {'y' : {'z' : '2'}}}}, - { str: 'x[y][z][]=1&x[y][z][]=2', obj: {'x' : {'y' : {'z' : ['1', '2']}}}}, - { str: 'x[y][][z]=1', obj: {'x' : {'y' : [{'z' : '1'}]}}}, - { str: 'x[y][][z][]=1', obj: {'x' : {'y' : [{'z' : ['1']}]}}}, - { str: 'x[y][][z]=1&x[y][][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'w' : '2'}]}}}, - { str: 'x[y][][v][w]=1', obj: {'x' : {'y' : [{'v' : {'w' : '1'}}]}}}, - { str: 'x[y][][z]=1&x[y][][v][w]=2', obj: {'x' : {'y' : [{'z' : '1', 'v' : {'w' : '2'}}]}}}, - { str: 'x[y][][z]=1&x[y][][z]=2', obj: {'x' : {'y' : [{'z' : '1'}, {'z' : '2'}]}}}, - { str: 'x[y][][z]=1&x[y][][w]=a&x[y][][z]=2&x[y][][w]=3', obj: {'x' : {'y' : [{'z' : '1', 'w' : 'a'}, {'z' : '2', 'w' : '3'}]}}}, - { str: 'user[name][first]=tj&user[name][last]=holowaychuk', obj: { user: { name: { first: 'tj', last: 'holowaychuk' }}}} - ], - 'errors': [ - { obj: 'foo=bar', message: 'stringify expects an object' }, - { obj: ['foo', 'bar'], message: 'stringify expects an object' } - ], - 'numbers': [ - { str: 'limit[]=1&limit[]=2&limit[]=3', obj: { limit: [1, 2, '3'] }}, - { str: 'limit=1', obj: { limit: 1 }} - ] - }; - +var qs = require( '../' ) + , should = require( 'should' ) + , str_identities = { + 'basics' : [ + { str : 'foo=bar', obj : {'foo' : 'bar'}}, + { str : 'foo=%22bar%22', obj : {'foo' : '\"bar\"'}}, + { str : 'foo=', obj : {'foo' : ''}}, + { str : 'foo=1&bar=2', obj : {'foo' : '1', 'bar' : '2'}}, + { str : 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', obj : {'my weird field' : "q1!2\"'w$5&7/z8)?"}}, + { str : 'foo%3Dbaz=bar', obj : {'foo=baz' : 'bar'}}, + { str : 'foo=bar&bar=baz', obj : {foo : 'bar', bar : 'baz'}} + ], + 'escaping' : [ + { str : 'foo=foo%20bar', obj : {foo : 'foo bar'}}, + { str : 'cht=p3&chd=t%3A60%2C40&chs=250x100&chl=Hello%7CWorld', obj : { + cht : 'p3', chd : 't:60,40', chs : '250x100', chl : 'Hello|World' + }} + ], + 'nested' : [ + { str : 'foo[]=bar&foo[]=quux', obj : {'foo' : ['bar', 'quux']}}, + { str : 'foo[]=bar', obj : {foo : ['bar']}}, + { str : 'foo[]=1&foo[]=2', obj : {'foo' : ['1', '2']}}, + { str : 'foo=bar&baz[]=1&baz[]=2&baz[]=3', obj : {'foo' : 'bar', 'baz' : ['1', '2', '3']}}, + { str : 'foo[]=bar&baz[]=1&baz[]=2&baz[]=3', obj : {'foo' : ['bar'], 'baz' : ['1', '2', '3']}}, + { str : 'x[y][z]=1', obj : {'x' : {'y' : {'z' : '1'}}}}, + { str : 'x[y][z][]=1', obj : {'x' : {'y' : {'z' : ['1']}}}}, + { str : 'x[y][z]=2', obj : {'x' : {'y' : {'z' : '2'}}}}, + { str : 'x[y][z][]=1&x[y][z][]=2', obj : {'x' : {'y' : {'z' : ['1', '2']}}}}, + { str : 'x[y][][z]=1', obj : {'x' : {'y' : [ + {'z' : '1'} + ]}}}, + { str : 'x[y][][z][]=1', obj : {'x' : {'y' : [ + {'z' : ['1']} + ]}}}, + { str : 'x[y][][z]=1&x[y][][w]=2', obj : {'x' : {'y' : [ + {'z' : '1', 'w' : '2'} + ]}}}, + { str : 'x[y][][v][w]=1', obj : {'x' : {'y' : [ + {'v' : {'w' : '1'}} + ]}}}, + { str : 'x[y][][z]=1&x[y][][v][w]=2', obj : {'x' : {'y' : [ + {'z' : '1', 'v' : {'w' : '2'}} + ]}}}, + { str : 'x[y][][z]=1&x[y][][z]=2', obj : {'x' : {'y' : [ + {'z' : '1'}, + {'z' : '2'} + ]}}}, + { str : 'x[y][][z]=1&x[y][][w]=a&x[y][][z]=2&x[y][][w]=3', obj : {'x' : {'y' : [ + {'z' : '1', 'w' : 'a'}, + {'z' : '2', 'w' : '3'} + ]}}}, + { str : 'user[name][first]=tj&user[name][last]=holowaychuk', obj : { user : { name : { first : 'tj', last : 'holowaychuk' }}}} + ], + 'errors' : [ + { obj : 'foo=bar', message : 'stringify expects an object' }, + { obj : ['foo', 'bar'], message : 'stringify expects an object' } + ], + 'numbers' : [ + { str : 'limit[]=1&limit[]=2&limit[]=3', obj : { limit : [1, 2, '3'] }}, + { str : 'limit=1', obj : { limit : 1 }} + ] + }; + // Assert error -function err(fn, msg){ - var err; - try { - fn(); - } catch (e) { - should.equal(e.message, msg); - return; - } - throw new Error('no exception thrown, expected "' + msg + '"'); +function err( fn, msg ) { + var err; + try { + fn(); + } catch ( e ) { + should.equal( e.message, msg ); + return; + } + throw new Error( 'no exception thrown, expected "' + msg + '"' ); } -function test(type) { - var str, obj; - for (var i = 0; i < str_identities[type].length; i++) { - str = str_identities[type][i].str; - obj = str_identities[type][i].obj; - qs.stringify(obj).should.eql(str); - } +function test( type ) { + var str, obj; + for ( var i = 0; i < str_identities[type].length; i++ ) { + str = str_identities[type][i].str; + obj = str_identities[type][i].obj; + qs.stringify( obj ).should.eql( str ); + } } module.exports = { - 'test basics': function() { - test('basics'); - }, + 'test basics' : function () { + test( 'basics' ); + }, - 'test escaping': function() { - test('escaping'); - }, + 'test escaping' : function () { + test( 'escaping' ); + }, - 'test nested': function() { - test('nested'); - }, - - 'test numbers': function(){ - test('numbers'); - }, + 'test nested' : function () { + test( 'nested' ); + }, - 'test errors': function() { - var obj, message; - for (var i = 0; i < str_identities['errors'].length; i++) { - message = str_identities['errors'][i].message; - obj = str_identities['errors'][i].obj; - err(function(){ qs.stringify(obj) }, message); - } - } + 'test numbers' : function () { + test( 'numbers' ); + }, + + 'test errors' : function () { + var obj, message; + for ( var i = 0; i < str_identities['errors'].length; i++ ) { + message = str_identities['errors'][i].message; + obj = str_identities['errors'][i].obj; + err( function () { + qs.stringify( obj ) + }, message ); + } + } }; \ No newline at end of file diff --git a/example/node/node_modules/express/package.json b/example/node/node_modules/express/package.json index 6675674..97f6627 100644 --- a/example/node/node_modules/express/package.json +++ b/example/node/node_modules/express/package.json @@ -1,39 +1,55 @@ { - "name": "express", - "description": "Sinatra inspired web development framework", - "version": "2.5.8", - "author": "TJ Holowaychuk ", - "contributors": [ - { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, - { "name": "Aaron Heckmann", "email": "aaron.heckmann+github@gmail.com" }, - { "name": "Ciaran Jessup", "email": "ciaranj@gmail.com" }, - { "name": "Guillermo Rauch", "email": "rauchg@gmail.com" } - ], - "dependencies": { - "connect": "1.x", - "mime": "1.2.4", - "qs": "0.4.x", - "mkdirp": "0.3.0" - }, - "devDependencies": { - "connect-form": "0.2.1", - "ejs": "0.4.2", - "expresso": "0.9.2", - "hamljs": "0.6.x", - "jade": "0.16.2", - "stylus": "0.13.0", - "should": "0.3.2", - "express-messages": "0.0.2", - "node-markdown": ">= 0.0.1", - "connect-redis": ">= 0.0.1" - }, - "keywords": ["framework", "sinatra", "web", "rest", "restful"], - "repository": "git://github.com/visionmedia/express", - "main": "index", - "bin": { "express": "./bin/express" }, - "scripts": { - "test": "make test", - "prepublish" : "npm prune" - }, - "engines": { "node": ">= 0.4.1 < 0.7.0" } + "name" : "express", + "description" : "Sinatra inspired web development framework", + "version" : "2.5.8", + "author" : "TJ Holowaychuk ", + "contributors" : [ + { + "name" : "TJ Holowaychuk", + "email" : "tj@vision-media.ca" + }, + { + "name" : "Aaron Heckmann", + "email" : "aaron.heckmann+github@gmail.com" + }, + { + "name" : "Ciaran Jessup", + "email" : "ciaranj@gmail.com" + }, + { + "name" : "Guillermo Rauch", + "email" : "rauchg@gmail.com" + } + ], + "dependencies" : { + "connect" : "1.x", + "mime" : "1.2.4", + "qs" : "0.4.x", + "mkdirp" : "0.3.0" + }, + "devDependencies" : { + "connect-form" : "0.2.1", + "ejs" : "0.4.2", + "expresso" : "0.9.2", + "hamljs" : "0.6.x", + "jade" : "0.16.2", + "stylus" : "0.13.0", + "should" : "0.3.2", + "express-messages" : "0.0.2", + "node-markdown" : ">= 0.0.1", + "connect-redis" : ">= 0.0.1" + }, + "keywords" : ["framework", "sinatra", "web", "rest", "restful"], + "repository" : "git://github.com/visionmedia/express", + "main" : "index", + "bin" : { + "express" : "./bin/express" + }, + "scripts" : { + "test" : "make test", + "prepublish" : "npm prune" + }, + "engines" : { + "node" : ">= 0.4.1 < 0.7.0" + } } \ No newline at end of file diff --git a/example/node/node_modules/express/testing/foo/app.js b/example/node/node_modules/express/testing/foo/app.js index 7574676..c935bc1 100644 --- a/example/node/node_modules/express/testing/foo/app.js +++ b/example/node/node_modules/express/testing/foo/app.js @@ -1,35 +1,34 @@ - /** * Module dependencies. */ -var express = require('express') - , routes = require('./routes') +var express = require( 'express' ) + , routes = require( './routes' ) var app = module.exports = express.createServer(); // Configuration -app.configure(function(){ - app.set('views', __dirname + '/views'); - app.set('view engine', 'jade'); - app.use(express.bodyParser()); - app.use(express.methodOverride()); - app.use(app.router); - app.use(express.static(__dirname + '/public')); -}); +app.configure( function () { + app.set( 'views', __dirname + '/views' ); + app.set( 'view engine', 'jade' ); + app.use( express.bodyParser() ); + app.use( express.methodOverride() ); + app.use( app.router ); + app.use( express.static( __dirname + '/public' ) ); +} ); -app.configure('development', function(){ - app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); -}); +app.configure( 'development', function () { + app.use( express.errorHandler( { dumpExceptions : true, showStack : true } ) ); +} ); -app.configure('production', function(){ - app.use(express.errorHandler()); -}); +app.configure( 'production', function () { + app.use( express.errorHandler() ); +} ); // Routes -app.get('/', routes.index); +app.get( '/', routes.index ); -app.listen(3000); -console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); +app.listen( 3000 ); +console.log( "Express server listening on port %d in %s mode", app.address().port, app.settings.env ); diff --git a/example/node/node_modules/express/testing/foo/package.json b/example/node/node_modules/express/testing/foo/package.json index dd54123..1450568 100644 --- a/example/node/node_modules/express/testing/foo/package.json +++ b/example/node/node_modules/express/testing/foo/package.json @@ -1,9 +1,6 @@ { - "name": "application-name" - , "version": "0.0.1" - , "private": true - , "dependencies": { - "express": "2.5.0" - , "jade": ">= 0.0.1" - } + "name" : "application-name", "version" : "0.0.1", "private" : true, "dependencies" : { + "express" : "2.5.0", + "jade" : ">= 0.0.1" +} } \ No newline at end of file diff --git a/example/node/node_modules/express/testing/foo/public/stylesheets/style.css b/example/node/node_modules/express/testing/foo/public/stylesheets/style.css index 30e047d..a0d2848 100644 --- a/example/node/node_modules/express/testing/foo/public/stylesheets/style.css +++ b/example/node/node_modules/express/testing/foo/public/stylesheets/style.css @@ -1,8 +1,8 @@ body { - padding: 50px; - font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; } a { - color: #00B7FF; + color: #00B7FF; } \ No newline at end of file diff --git a/example/node/node_modules/express/testing/foo/routes/index.js b/example/node/node_modules/express/testing/foo/routes/index.js index 0b2205c..8f16368 100644 --- a/example/node/node_modules/express/testing/foo/routes/index.js +++ b/example/node/node_modules/express/testing/foo/routes/index.js @@ -1,10 +1,9 @@ - /* * GET home page. */ -exports.index = function(req, res){ - res.writeHead(200); - req.doesnotexist(); - // res.render('index', { title: 'Express' }) +exports.index = function ( req, res ) { + res.writeHead( 200 ); + req.doesnotexist(); + // res.render('index', { title: 'Express' }) }; \ No newline at end of file diff --git a/example/node/node_modules/express/testing/index.js b/example/node/node_modules/express/testing/index.js index 3c5185d..073f9e1 100644 --- a/example/node/node_modules/express/testing/index.js +++ b/example/node/node_modules/express/testing/index.js @@ -1,18 +1,17 @@ - /** * Module dependencies. */ -var express = require('../') - , http = require('http') - , connect = require('connect'); +var express = require( '../' ) + , http = require( 'http' ) + , connect = require( 'connect' ); var app = express.createServer(); -app.get('/', function(req, res){ - req.foo(); - res.send('test'); -}); +app.get( '/', function ( req, res ) { + req.foo(); + res.send( 'test' ); +} ); // app.set('views', __dirname + '/views'); // app.set('view engine', 'jade'); @@ -39,5 +38,5 @@ app.get('/', function(req, res){ // next(); // }); -app.listen(3000); -console.log('listening on port 3000'); \ No newline at end of file +app.listen( 3000 ); +console.log( 'listening on port 3000' ); \ No newline at end of file diff --git a/example/node/node_modules/socket.io/benchmarks/decode.bench.js b/example/node/node_modules/socket.io/benchmarks/decode.bench.js index 4855d80..63c26cf 100644 --- a/example/node/node_modules/socket.io/benchmarks/decode.bench.js +++ b/example/node/node_modules/socket.io/benchmarks/decode.bench.js @@ -1,64 +1,63 @@ - /** * Module dependencies. */ -var benchmark = require('benchmark') - , colors = require('colors') - , io = require('../') - , parser = io.parser - , suite = new benchmark.Suite('Decode packet'); +var benchmark = require( 'benchmark' ) + , colors = require( 'colors' ) + , io = require( '../' ) + , parser = io.parser + , suite = new benchmark.Suite( 'Decode packet' ); -suite.add('string', function () { - parser.decodePacket('4:::"2"'); -}); +suite.add( 'string', function () { + parser.decodePacket( '4:::"2"' ); +} ); -suite.add('event', function () { - parser.decodePacket('5:::{"name":"woot"}'); -}); +suite.add( 'event', function () { + parser.decodePacket( '5:::{"name":"woot"}' ); +} ); -suite.add('event+ack', function () { - parser.decodePacket('5:1+::{"name":"tobi"}'); -}); +suite.add( 'event+ack', function () { + parser.decodePacket( '5:1+::{"name":"tobi"}' ); +} ); -suite.add('event+data', function () { - parser.decodePacket('5:::{"name":"edwald","args":[{"a": "b"},2,"3"]}'); -}); +suite.add( 'event+data', function () { + parser.decodePacket( '5:::{"name":"edwald","args":[{"a": "b"},2,"3"]}' ); +} ); -suite.add('heartbeat', function () { - parser.decodePacket('2:::'); -}); +suite.add( 'heartbeat', function () { + parser.decodePacket( '2:::' ); +} ); -suite.add('error', function () { - parser.decodePacket('7:::2+0'); -}); +suite.add( 'error', function () { + parser.decodePacket( '7:::2+0' ); +} ); -var payload = parser.encodePayload([ - parser.encodePacket({ type: 'message', data: '5', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: '53d', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobarbazfoobarbaz', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' }) -]); +var payload = parser.encodePayload( [ + parser.encodePacket( { type : 'message', data : '5', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : '53d', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobar', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobarbaz', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobarbazfoobarbaz', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobarbaz', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobar', endpoint : '' } ) +] ); -suite.add('payload', function () { - parser.decodePayload(payload); -}); +suite.add( 'payload', function () { + parser.decodePayload( payload ); +} ); -suite.on('cycle', function (bench, details) { - console.log('\n' + suite.name.grey, details.name.white.bold); - console.log([ - details.hz.toFixed(2).cyan + ' ops/sec'.grey - , details.count.toString().white + ' times executed'.grey - , 'benchmark took '.grey + details.times.elapsed.toString().white + ' sec.'.grey - , - ].join(', '.grey)); -}); +suite.on( 'cycle', function ( bench, details ) { + console.log( '\n' + suite.name.grey, details.name.white.bold ); + console.log( [ + details.hz.toFixed( 2 ).cyan + ' ops/sec'.grey + , details.count.toString().white + ' times executed'.grey + , 'benchmark took '.grey + details.times.elapsed.toString().white + ' sec.'.grey + , + ].join( ', '.grey ) ); +} ); -if (!module.parent) { - suite.run(); +if ( !module.parent ) { + suite.run(); } else { - module.exports = suite; + module.exports = suite; } diff --git a/example/node/node_modules/socket.io/benchmarks/encode.bench.js b/example/node/node_modules/socket.io/benchmarks/encode.bench.js index 5037702..b459df0 100644 --- a/example/node/node_modules/socket.io/benchmarks/encode.bench.js +++ b/example/node/node_modules/socket.io/benchmarks/encode.bench.js @@ -1,90 +1,77 @@ - /** * Module dependencies. */ -var benchmark = require('benchmark') - , colors = require('colors') - , io = require('../') - , parser = io.parser - , suite = new benchmark.Suite('Encode packet'); +var benchmark = require( 'benchmark' ) + , colors = require( 'colors' ) + , io = require( '../' ) + , parser = io.parser + , suite = new benchmark.Suite( 'Encode packet' ); -suite.add('string', function () { - parser.encodePacket({ - type: 'json' - , endpoint: '' - , data: '2' - }); -}); +suite.add( 'string', function () { + parser.encodePacket( { + type : 'json', endpoint : '', data : '2' + } ); +} ); -suite.add('event', function () { - parser.encodePacket({ - type: 'event' - , name: 'woot' - , endpoint: '' - , args: [] - }); -}); +suite.add( 'event', function () { + parser.encodePacket( { + type : 'event', name : 'woot', endpoint : '', args : [] + } ); +} ); -suite.add('event+ack', function () { - parser.encodePacket({ - type: 'json' - , id: 1 - , ack: 'data' - , endpoint: '' - , data: { a: 'b' } - }); -}); +suite.add( 'event+ack', function () { + parser.encodePacket( { + type : 'json', id : 1, ack : 'data', endpoint : '', data : { a : 'b' } + } ); +} ); -suite.add('event+data', function () { - parser.encodePacket({ - type: 'event' - , name: 'edwald' - , endpoint: '' - , args: [{a: 'b'}, 2, '3'] - }); -}); +suite.add( 'event+data', function () { + parser.encodePacket( { + type : 'event', name : 'edwald', endpoint : '', args : [ + {a : 'b'}, + 2, + '3' + ] + } ); +} ); -suite.add('heartbeat', function () { - parser.encodePacket({ - type: 'heartbeat' - , endpoint: '' - }) -}); +suite.add( 'heartbeat', function () { + parser.encodePacket( { + type : 'heartbeat', endpoint : '' + } ) +} ); -suite.add('error', function () { - parser.encodePacket({ - type: 'error' - , reason: 'unauthorized' - , advice: 'reconnect' - , endpoint: '' - }) -}) +suite.add( 'error', function () { + parser.encodePacket( { + type : 'error', reason : 'unauthorized', advice : 'reconnect', endpoint : '' + } ) +} ) -suite.add('payload', function () { - parser.encodePayload([ - parser.encodePacket({ type: 'message', data: '5', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: '53d', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobarbazfoobarbaz', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' }) - , parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' }) - ]); -}); +suite.add( 'payload', function () { + parser.encodePayload( [ + parser.encodePacket( { type : 'message', data : '5', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : '53d', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobar', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobarbaz', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobarbazfoobarbaz', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobarbaz', endpoint : '' } ) + , parser.encodePacket( { type : 'message', data : 'foobar', endpoint : '' } ) + ] ); +} ); -suite.on('cycle', function (bench, details) { - console.log('\n' + suite.name.grey, details.name.white.bold); - console.log([ - details.hz.toFixed(2).cyan + ' ops/sec'.grey - , details.count.toString().white + ' times executed'.grey - , 'benchmark took '.grey + details.times.elapsed.toString().white + ' sec.'.grey - , - ].join(', '.grey)); -}); +suite.on( 'cycle', function ( bench, details ) { + console.log( '\n' + suite.name.grey, details.name.white.bold ); + console.log( [ + details.hz.toFixed( 2 ).cyan + ' ops/sec'.grey + , details.count.toString().white + ' times executed'.grey + , 'benchmark took '.grey + details.times.elapsed.toString().white + ' sec.'.grey + , + ].join( ', '.grey ) ); +} ); -if (!module.parent) { - suite.run(); +if ( !module.parent ) { + suite.run(); } else { - module.exports = suite; + module.exports = suite; } diff --git a/example/node/node_modules/socket.io/benchmarks/runner.js b/example/node/node_modules/socket.io/benchmarks/runner.js index 81e55ca..80af7ed 100644 --- a/example/node/node_modules/socket.io/benchmarks/runner.js +++ b/example/node/node_modules/socket.io/benchmarks/runner.js @@ -2,54 +2,54 @@ * Benchmark runner dependencies */ -var colors = require('colors') - , path = require('path'); +var colors = require( 'colors' ) + , path = require( 'path' ); /** * Find all the benchmarks */ -var benchmarks_files = process.env.BENCHMARKS.split(' ') - , all = [].concat(benchmarks_files) - , first = all.shift() - , benchmarks = {}; +var benchmarks_files = process.env.BENCHMARKS.split( ' ' ) + , all = [].concat( benchmarks_files ) + , first = all.shift() + , benchmarks = {}; // find the benchmarks and load them all in our obj -benchmarks_files.forEach(function (file) { - benchmarks[file] = require(path.join(__dirname, '..', file)); -}); +benchmarks_files.forEach( function ( file ) { + benchmarks[file] = require( path.join( __dirname, '..', file ) ); +} ); // setup the complete listeners -benchmarks_files.forEach(function (file) { - var benchmark = benchmarks[file] - , next_file = all.shift() - , next = benchmarks[next_file]; +benchmarks_files.forEach( function ( file ) { + var benchmark = benchmarks[file] + , next_file = all.shift() + , next = benchmarks[next_file]; - /** - * Generate a oncomplete function for the tests, either we are done or we - * have more benchmarks to process. - */ + /** + * Generate a oncomplete function for the tests, either we are done or we + * have more benchmarks to process. + */ - function complete () { - if (!next) { - console.log( - '\n\nBenchmark completed in'.grey - , (Date.now() - start).toString().green + ' ms'.grey - ); - } else { - console.log('\nStarting benchmark '.grey + next_file.yellow); - next.run(); - } - } + function complete() { + if ( !next ) { + console.log( + '\n\nBenchmark completed in'.grey + , (Date.now() - start).toString().green + ' ms'.grey + ); + } else { + console.log( '\nStarting benchmark '.grey + next_file.yellow ); + next.run(); + } + } - // attach the listener - benchmark.on('complete', complete); -}); + // attach the listener + benchmark.on( 'complete', complete ); +} ); /** * Start the benchmark */ var start = Date.now(); -console.log('Starting benchmark '.grey + first.yellow); +console.log( 'Starting benchmark '.grey + first.yellow ); benchmarks[first].run(); diff --git a/example/node/node_modules/socket.io/examples/chat/app.js b/example/node/node_modules/socket.io/examples/chat/app.js index bdfad2a..610d028 100644 --- a/example/node/node_modules/socket.io/examples/chat/app.js +++ b/example/node/node_modules/socket.io/examples/chat/app.js @@ -2,10 +2,10 @@ * Module dependencies. */ -var express = require('express') - , stylus = require('stylus') - , nib = require('nib') - , sio = require('../../lib/socket.io'); +var express = require( 'express' ) + , stylus = require( 'stylus' ) + , nib = require( 'nib' ) + , sio = require( '../../lib/socket.io' ); /** * App. @@ -17,64 +17,68 @@ var app = express.createServer(); * App configuration. */ -app.configure(function () { - app.use(stylus.middleware({ src: __dirname + '/public', compile: compile })); - app.use(express.static(__dirname + '/public')); - app.set('views', __dirname); - app.set('view engine', 'jade'); +app.configure( function () { + app.use( stylus.middleware( { src : __dirname + '/public', compile : compile } ) ); + app.use( express.static( __dirname + '/public' ) ); + app.set( 'views', __dirname ); + app.set( 'view engine', 'jade' ); - function compile (str, path) { - return stylus(str) - .set('filename', path) - .use(nib()); - }; -}); + function compile( str, path ) { + return stylus( str ) + .set( 'filename', path ) + .use( nib() ); + } + + ; +} ); /** * App routes. */ -app.get('/', function (req, res) { - res.render('index', { layout: false }); -}); +app.get( '/', function ( req, res ) { + res.render( 'index', { layout : false } ); +} ); /** * App listen. */ -app.listen(3000, function () { - var addr = app.address(); - console.log(' app listening on http://' + addr.address + ':' + addr.port); -}); +app.listen( 3000, function () { + var addr = app.address(); + console.log( ' app listening on http://' + addr.address + ':' + addr.port ); +} ); /** * Socket.IO server (single process only) */ -var io = sio.listen(app) - , nicknames = {}; +var io = sio.listen( app ) + , nicknames = {}; -io.sockets.on('connection', function (socket) { - socket.on('user message', function (msg) { - socket.broadcast.emit('user message', socket.nickname, msg); - }); +io.sockets.on( 'connection', function ( socket ) { + socket.on( 'user message', function ( msg ) { + socket.broadcast.emit( 'user message', socket.nickname, msg ); + } ); - socket.on('nickname', function (nick, fn) { - if (nicknames[nick]) { - fn(true); - } else { - fn(false); - nicknames[nick] = socket.nickname = nick; - socket.broadcast.emit('announcement', nick + ' connected'); - io.sockets.emit('nicknames', nicknames); - } - }); + socket.on( 'nickname', function ( nick, fn ) { + if ( nicknames[nick] ) { + fn( true ); + } else { + fn( false ); + nicknames[nick] = socket.nickname = nick; + socket.broadcast.emit( 'announcement', nick + ' connected' ); + io.sockets.emit( 'nicknames', nicknames ); + } + } ); - socket.on('disconnect', function () { - if (!socket.nickname) return; + socket.on( 'disconnect', function () { + if ( !socket.nickname ) { + return; + } - delete nicknames[socket.nickname]; - socket.broadcast.emit('announcement', socket.nickname + ' disconnected'); - socket.broadcast.emit('nicknames', nicknames); - }); -}); + delete nicknames[socket.nickname]; + socket.broadcast.emit( 'announcement', socket.nickname + ' disconnected' ); + socket.broadcast.emit( 'nicknames', nicknames ); + } ); +} ); diff --git a/example/node/node_modules/socket.io/examples/chat/package.json b/example/node/node_modules/socket.io/examples/chat/package.json index 6b375b0..b611dc0 100644 --- a/example/node/node_modules/socket.io/examples/chat/package.json +++ b/example/node/node_modules/socket.io/examples/chat/package.json @@ -1,11 +1,8 @@ { - "name": "chat.io" - , "description": "example chat application with socket.io" - , "version": "0.0.1" - , "dependencies": { - "express": "2.5.5" - , "jade": "0.16.4" - , "stylus": "0.19.0" - , "nib": "0.2.0" - } + "name" : "chat.io", "description" : "example chat application with socket.io", "version" : "0.0.1", "dependencies" : { + "express" : "2.5.5", + "jade" : "0.16.4", + "stylus" : "0.19.0", + "nib" : "0.2.0" +} } diff --git a/example/node/node_modules/socket.io/examples/chat/public/stylesheets/style.css b/example/node/node_modules/socket.io/examples/chat/public/stylesheets/style.css index 42cf98f..61897d9 100644 --- a/example/node/node_modules/socket.io/examples/chat/public/stylesheets/style.css +++ b/example/node/node_modules/socket.io/examples/chat/public/stylesheets/style.css @@ -1,188 +1,219 @@ #chat, #nickname, #messages { - width: 600px; + width: 600px; } + #chat { - position: relative; - border: 1px solid #ccc; + position: relative; + border: 1px solid #ccc; } + #nickname, #connecting { - position: absolute; - height: 410px; - z-index: 100; - left: 0; - top: 0; - background: #fff; - text-align: center; - width: 600px; - font: 15px Georgia; - color: #666; - display: block; + position: absolute; + height: 410px; + z-index: 100; + left: 0; + top: 0; + background: #fff; + text-align: center; + width: 600px; + font: 15px Georgia; + color: #666; + display: block; } + #nickname .wrap, #connecting .wrap { - padding-top: 150px; + padding-top: 150px; } + #nickname input { - border: 1px solid #ccc; - padding: 10px; + border: 1px solid #ccc; + padding: 10px; } + #nickname input:focus { - border-color: #999; - outline: 0; + border-color: #999; + outline: 0; } + #nickname #nickname-err { - color: #8b0000; - font-size: 12px; - visibility: hidden; + color: #8b0000; + font-size: 12px; + visibility: hidden; } + .connected #connecting { - display: none; + display: none; } + .nickname-set #nickname { - display: none; + display: none; } + #messages { - height: 380px; - background: #eee; + height: 380px; + background: #eee; } + #messages em { - text-shadow: 0 1px 0 #fff; - color: #999; + text-shadow: 0 1px 0 #fff; + color: #999; } + #messages p { - padding: 0; - margin: 0; - font: 12px Helvetica, Arial; - padding: 5px 10px; + padding: 0; + margin: 0; + font: 12px Helvetica, Arial; + padding: 5px 10px; } + #messages p b { - display: inline-block; - padding-right: 10px; + display: inline-block; + padding-right: 10px; } + #messages p:nth-child(even) { - background: #fafafa; + background: #fafafa; } + #messages #nicknames { - background: #ccc; - padding: 2px 4px 4px; - font: 11px Helvetica; + background: #ccc; + padding: 2px 4px 4px; + font: 11px Helvetica; } + #messages #nicknames span { - color: #000; + color: #000; } + #messages #nicknames b { - display: inline-block; - color: #fff; - background: #999; - padding: 3px 6px; - margin-right: 5px; - -webkit-border-radius: 10px; - -moz-border-radius: 10px; - border-radius: 10px; - text-shadow: 0 1px 0 #666; + display: inline-block; + color: #fff; + background: #999; + padding: 3px 6px; + margin-right: 5px; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border-radius: 10px; + text-shadow: 0 1px 0 #666; } + #messages #lines { - height: 355px; - overflow: auto; - overflow-x: hidden; - overflow-y: auto; + height: 355px; + overflow: auto; + overflow-x: hidden; + overflow-y: auto; } + #messages #lines::-webkit-scrollbar { - width: 6px; - height: 6px; + width: 6px; + height: 6px; } + #messages #lines::-webkit-scrollbar-button:start:decrement, #messages #lines ::-webkit-scrollbar-button:end:increment { - display: block; - height: 10px; + display: block; + height: 10px; } + #messages #lines::-webkit-scrollbar-button:vertical:increment { - background-color: #fff; + background-color: #fff; } + #messages #lines::-webkit-scrollbar-track-piece { - background-color: #fff; - -webkit-border-radius: 3px; + background-color: #fff; + -webkit-border-radius: 3px; } + #messages #lines::-webkit-scrollbar-thumb:vertical { - height: 50px; - background-color: #ccc; - -webkit-border-radius: 3px; + height: 50px; + background-color: #ccc; + -webkit-border-radius: 3px; } + #messages #lines::-webkit-scrollbar-thumb:horizontal { - width: 50px; - background-color: #fff; - -webkit-border-radius: 3px; + width: 50px; + background-color: #fff; + -webkit-border-radius: 3px; } + #send-message { - background: #fff; - position: relative; + background: #fff; + position: relative; } + #send-message input { - border: none; - height: 30px; - padding: 0 10px; - line-height: 30px; - vertical-align: middle; - width: 580px; + border: none; + height: 30px; + padding: 0 10px; + line-height: 30px; + vertical-align: middle; + width: 580px; } + #send-message input:focus { - outline: 0; + outline: 0; } + #send-message button { - position: absolute; - top: 5px; - right: 5px; + position: absolute; + top: 5px; + right: 5px; } + button { - margin: 0; - -webkit-user-select: none; - -moz-user-select: none; - user-select: none; - display: inline-block; - text-decoration: none; - background: #43a1f7; - background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #377ad0)); - background: -webkit-linear-gradient(top, #43a1f7 0%, #377ad0 100%); - background: -moz-linear-gradient(top, #43a1f7 0%, #377ad0 100%); - background: linear-gradient(top, #43a1f7 0%, #377ad0 100%); - border: 1px solid #2e70c4; - -webkit-border-radius: 16px; - -moz-border-radius: 16px; - border-radius: 16px; - color: #fff; - font-family: "lucida grande", sans-serif; - font-size: 11px; - font-weight: normal; - line-height: 1; - padding: 3px 10px 5px 10px; - text-align: center; - text-shadow: 0 -1px 1px #2d6dc0; + margin: 0; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + display: inline-block; + text-decoration: none; + background: #43a1f7; + background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #377ad0)); + background: -webkit-linear-gradient(top, #43a1f7 0%, #377ad0 100%); + background: -moz-linear-gradient(top, #43a1f7 0%, #377ad0 100%); + background: linear-gradient(top, #43a1f7 0%, #377ad0 100%); + border: 1px solid #2e70c4; + -webkit-border-radius: 16px; + -moz-border-radius: 16px; + border-radius: 16px; + color: #fff; + font-family: "lucida grande", sans-serif; + font-size: 11px; + font-weight: normal; + line-height: 1; + padding: 3px 10px 5px 10px; + text-align: center; + text-shadow: 0 -1px 1px #2d6dc0; } + button:hover, button.hover { - background: darker; - background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #2e70c4)); - background: -webkit-linear-gradient(top, #43a1f7 0%, #2e70c4 100%); - background: -moz-linear-gradient(top, #43a1f7 0%, #2e70c4 100%); - background: linear-gradient(top, #43a1f7 0%, #2e70c4 100%); - border: 1px solid #2e70c4; - cursor: pointer; - text-shadow: 0 -1px 1px #2c6bbb; + background: darker; + background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #43a1f7), color-stop(1, #2e70c4)); + background: -webkit-linear-gradient(top, #43a1f7 0%, #2e70c4 100%); + background: -moz-linear-gradient(top, #43a1f7 0%, #2e70c4 100%); + background: linear-gradient(top, #43a1f7 0%, #2e70c4 100%); + border: 1px solid #2e70c4; + cursor: pointer; + text-shadow: 0 -1px 1px #2c6bbb; } + button:active, button.active { - background: #2e70c4; - border: 1px solid #2e70c4; - border-bottom: 1px solid #2861aa; - text-shadow: 0 -1px 1px #2b67b5; + background: #2e70c4; + border: 1px solid #2e70c4; + border-bottom: 1px solid #2861aa; + text-shadow: 0 -1px 1px #2b67b5; } + button:focus, button.focus { - outline: none; - -webkit-box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0; - -moz-box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0; - box-shadow: 0 1px 0 0 rgba(255,255,255,0.4), 0 0 4px 0 #377ad0; + outline: none; + -webkit-box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.4), 0 0 4px 0 #377ad0; + -moz-box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.4), 0 0 4px 0 #377ad0; + box-shadow: 0 1px 0 0 rgba(255, 255, 255, 0.4), 0 0 4px 0 #377ad0; } diff --git a/example/node/node_modules/socket.io/examples/irc-output/app.js b/example/node/node_modules/socket.io/examples/irc-output/app.js index 784886a..9d114b3 100644 --- a/example/node/node_modules/socket.io/examples/irc-output/app.js +++ b/example/node/node_modules/socket.io/examples/irc-output/app.js @@ -2,11 +2,11 @@ * Module dependencies. */ -var express = require('express') - , stylus = require('stylus') - , nib = require('nib') - , sio = require('../../lib/socket.io') - , irc = require('./irc'); +var express = require( 'express' ) + , stylus = require( 'stylus' ) + , nib = require( 'nib' ) + , sio = require( '../../lib/socket.io' ) + , irc = require( './irc' ); /** * App. @@ -18,57 +18,59 @@ var app = express.createServer(); * App configuration. */ -app.configure(function () { - app.use(stylus.middleware({ src: __dirname + '/public', compile: compile })) - app.use(express.static(__dirname + '/public')); - app.set('views', __dirname); - app.set('view engine', 'jade'); +app.configure( function () { + app.use( stylus.middleware( { src : __dirname + '/public', compile : compile } ) ) + app.use( express.static( __dirname + '/public' ) ); + app.set( 'views', __dirname ); + app.set( 'view engine', 'jade' ); - function compile (str, path) { - return stylus(str) - .set('filename', path) - .use(nib()); - }; -}); + function compile( str, path ) { + return stylus( str ) + .set( 'filename', path ) + .use( nib() ); + } + + ; +} ); /** * App routes. */ -app.get('/', function (req, res) { - res.render('index', { layout: false }); -}); +app.get( '/', function ( req, res ) { + res.render( 'index', { layout : false } ); +} ); /** * App listen. */ -app.listen(3000, function () { - var addr = app.address(); - console.log(' app listening on http://' + addr.address + ':' + addr.port); -}); +app.listen( 3000, function () { + var addr = app.address(); + console.log( ' app listening on http://' + addr.address + ':' + addr.port ); +} ); /** * Socket.IO server */ -var io = sio.listen(app) +var io = sio.listen( app ) /** * Connect to IRC. */ -var client = new irc.Client('irc.freenode.net', 6667); -client.connect('socketio\\test\\' + String(Math.random()).substr(-3)); -client.on('001', function () { - this.send('JOIN', '#node.js'); -}); -client.on('PART', function (prefix) { - io.sockets.emit('announcement', irc.user(prefix) + ' left the channel'); -}); -client.on('JOIN', function (prefix) { - io.sockets.emit('announcement', irc.user(prefix) + ' joined the channel'); -}); -client.on('PRIVMSG', function (prefix, channel, text) { - io.sockets.emit('irc message', irc.user(prefix), text); -}); +var client = new irc.Client( 'irc.freenode.net', 6667 ); +client.connect( 'socketio\\test\\' + String( Math.random() ).substr( -3 ) ); +client.on( '001', function () { + this.send( 'JOIN', '#node.js' ); +} ); +client.on( 'PART', function ( prefix ) { + io.sockets.emit( 'announcement', irc.user( prefix ) + ' left the channel' ); +} ); +client.on( 'JOIN', function ( prefix ) { + io.sockets.emit( 'announcement', irc.user( prefix ) + ' joined the channel' ); +} ); +client.on( 'PRIVMSG', function ( prefix, channel, text ) { + io.sockets.emit( 'irc message', irc.user( prefix ), text ); +} ); diff --git a/example/node/node_modules/socket.io/examples/irc-output/irc.js b/example/node/node_modules/socket.io/examples/irc-output/irc.js index cc679d5..4f19460 100644 --- a/example/node/node_modules/socket.io/examples/irc-output/irc.js +++ b/example/node/node_modules/socket.io/examples/irc-output/irc.js @@ -2,163 +2,163 @@ * From https://github.com/felixge/nodelog/ */ -var sys = require('util'); -var tcp = require('net'); +var sys = require( 'util' ); +var tcp = require( 'net' ); var irc = exports; -function bind(fn, scope) { - var bindArgs = Array.prototype.slice.call(arguments); - bindArgs.shift(); - bindArgs.shift(); +function bind( fn, scope ) { + var bindArgs = Array.prototype.slice.call( arguments ); + bindArgs.shift(); + bindArgs.shift(); - return function() { - var args = Array.prototype.slice.call(arguments); - fn.apply(scope, bindArgs.concat(args)); - }; + return function () { + var args = Array.prototype.slice.call( arguments ); + fn.apply( scope, bindArgs.concat( args ) ); + }; } -function each(set, iterator) { - for (var i = 0; i < set.length; i++) { - var r = iterator(set[i], i); - if (r === false) { - return; - } - } +function each( set, iterator ) { + for ( var i = 0; i < set.length; i++ ) { + var r = iterator( set[i], i ); + if ( r === false ) { + return; + } + } } -var Client = irc.Client = function(host, port) { - this.host = host || 'localhost'; - this.port = port || 6667; +var Client = irc.Client = function ( host, port ) { + this.host = host || 'localhost'; + this.port = port || 6667; - this.connection = null; - this.buffer = ''; - this.encoding = 'utf8'; - this.timeout = 10 * 60 * 60 * 1000; + this.connection = null; + this.buffer = ''; + this.encoding = 'utf8'; + this.timeout = 10 * 60 * 60 * 1000; - this.nick = null; - this.user = null; - this.real = null; + this.nick = null; + this.user = null; + this.real = null; } -sys.inherits(Client, process.EventEmitter); +sys.inherits( Client, process.EventEmitter ); -Client.prototype.connect = function(nick, user, real) { - var connection = tcp.createConnection(this.port, this.host); - connection.setEncoding(this.encoding); - connection.setTimeout(this.timeout); - connection.addListener('connect', bind(this.onConnect, this)); - connection.addListener('data', bind(this.onReceive, this)); - connection.addListener('end', bind(this.onEof, this)); - connection.addListener('timeout', bind(this.onTimeout, this)); - connection.addListener('close', bind(this.onClose, this)); +Client.prototype.connect = function ( nick, user, real ) { + var connection = tcp.createConnection( this.port, this.host ); + connection.setEncoding( this.encoding ); + connection.setTimeout( this.timeout ); + connection.addListener( 'connect', bind( this.onConnect, this ) ); + connection.addListener( 'data', bind( this.onReceive, this ) ); + connection.addListener( 'end', bind( this.onEof, this ) ); + connection.addListener( 'timeout', bind( this.onTimeout, this ) ); + connection.addListener( 'close', bind( this.onClose, this ) ); - this.nick = nick; - this.user = user || 'guest'; - this.real = real || 'Guest'; + this.nick = nick; + this.user = user || 'guest'; + this.real = real || 'Guest'; - this.connection = connection; + this.connection = connection; }; -Client.prototype.disconnect = function(why) { - if (this.connection.readyState !== 'closed') { - this.connection.close(); - sys.puts('disconnected (reason: '+why+')'); - this.emit('DISCONNECT', why); - } +Client.prototype.disconnect = function ( why ) { + if ( this.connection.readyState !== 'closed' ) { + this.connection.close(); + sys.puts( 'disconnected (reason: ' + why + ')' ); + this.emit( 'DISCONNECT', why ); + } }; -Client.prototype.send = function(arg1) { - if (this.connection.readyState !== 'open') { - return this.disconnect('cannot send with readyState: '+this.connection.readyState); - } +Client.prototype.send = function ( arg1 ) { + if ( this.connection.readyState !== 'open' ) { + return this.disconnect( 'cannot send with readyState: ' + this.connection.readyState ); + } - var message = []; - for (var i = 0; i< arguments.length; i++) { - if (arguments[i]) { - message.push(arguments[i]); - } - } - message = message.join(' '); + var message = []; + for ( var i = 0; i < arguments.length; i++ ) { + if ( arguments[i] ) { + message.push( arguments[i] ); + } + } + message = message.join( ' ' ); - sys.puts('> '+message); - message = message + "\r\n"; - this.connection.write(message, this.encoding); + sys.puts( '> ' + message ); + message = message + "\r\n"; + this.connection.write( message, this.encoding ); }; -Client.prototype.parse = function(message) { - var match = message.match(/(?:(:[^\s]+) )?([^\s]+) (.+)/); - var parsed = { - prefix: match[1], - command: match[2] - }; +Client.prototype.parse = function ( message ) { + var match = message.match( /(?:(:[^\s]+) )?([^\s]+) (.+)/ ); + var parsed = { + prefix : match[1], + command : match[2] + }; - var params = match[3].match(/(.*?) ?:(.*)/); - if (params) { - // Params before : - params[1] = (params[1]) - ? params[1].split(' ') - : []; - // Rest after : - params[2] = params[2] - ? [params[2]] - : []; + var params = match[3].match( /(.*?) ?:(.*)/ ); + if ( params ) { + // Params before : + params[1] = (params[1]) + ? params[1].split( ' ' ) + : []; + // Rest after : + params[2] = params[2] + ? [params[2]] + : []; - params = params[1].concat(params[2]); - } else { - params = match[3].split(' '); - } + params = params[1].concat( params[2] ); + } else { + params = match[3].split( ' ' ); + } - parsed.params = params; - return parsed; + parsed.params = params; + return parsed; }; -Client.prototype.onConnect = function() { - this.send('NICK', this.nick); - this.send('USER', this.user, '0', '*', ':'+this.real); +Client.prototype.onConnect = function () { + this.send( 'NICK', this.nick ); + this.send( 'USER', this.user, '0', '*', ':' + this.real ); }; -Client.prototype.onReceive = function(chunk) { - this.buffer = this.buffer + chunk; - - while (this.buffer) { - var offset = this.buffer.indexOf("\r\n"); - if (offset < 0) { - return; - } - - var message = this.buffer.substr(0, offset); - this.buffer = this.buffer.substr(offset + 2); - sys.puts('< '+message); +Client.prototype.onReceive = function ( chunk ) { + this.buffer = this.buffer + chunk; - message = this.parse(message); + while ( this.buffer ) { + var offset = this.buffer.indexOf( "\r\n" ); + if ( offset < 0 ) { + return; + } - this.emit.apply(this, [message.command, message.prefix].concat(message.params)); + var message = this.buffer.substr( 0, offset ); + this.buffer = this.buffer.substr( offset + 2 ); + sys.puts( '< ' + message ); - if (message !== false) { - this.onMessage(message); - } - } -}; + message = this.parse( message ); -Client.prototype.onMessage = function(message) { - switch (message.command) { - case 'PING': - this.send('PONG', ':'+message.params[0]); - break; - } + this.emit.apply( this, [message.command, message.prefix].concat( message.params ) ); + + if ( message !== false ) { + this.onMessage( message ); + } + } }; -Client.prototype.onEof = function() { - this.disconnect('eof'); +Client.prototype.onMessage = function ( message ) { + switch ( message.command ) { + case 'PING': + this.send( 'PONG', ':' + message.params[0] ); + break; + } }; -Client.prototype.onTimeout = function() { - this.disconnect('timeout'); +Client.prototype.onEof = function () { + this.disconnect( 'eof' ); }; -Client.prototype.onClose = function() { - this.disconnect('close'); +Client.prototype.onTimeout = function () { + this.disconnect( 'timeout' ); }; -exports.user = function(prefix) { - return prefix.match(/:([^!]+)!/)[1] +Client.prototype.onClose = function () { + this.disconnect( 'close' ); +}; + +exports.user = function ( prefix ) { + return prefix.match( /:([^!]+)!/ )[1] }; diff --git a/example/node/node_modules/socket.io/examples/irc-output/package.json b/example/node/node_modules/socket.io/examples/irc-output/package.json index 665ee33..f47ae92 100644 --- a/example/node/node_modules/socket.io/examples/irc-output/package.json +++ b/example/node/node_modules/socket.io/examples/irc-output/package.json @@ -1,10 +1,8 @@ { - "name": "socket.io-irc" - , "version": "0.0.1" - , "dependencies": { - "express": "2.5.5" - , "jade": "0.16.4" - , "stylus": "0.19.0" - , "nib": "0.2.0" - } + "name" : "socket.io-irc", "version" : "0.0.1", "dependencies" : { + "express" : "2.5.5", + "jade" : "0.16.4", + "stylus" : "0.19.0", + "nib" : "0.2.0" +} } diff --git a/example/node/node_modules/socket.io/index.js b/example/node/node_modules/socket.io/index.js index cc00c10..a802606 100644 --- a/example/node/node_modules/socket.io/index.js +++ b/example/node/node_modules/socket.io/index.js @@ -1,8 +1,7 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost * MIT Licensed */ -module.exports = require('./lib/socket.io'); +module.exports = require( './lib/socket.io' ); diff --git a/example/node/node_modules/socket.io/lib/client.js b/example/node/node_modules/socket.io/lib/client.js index d80067b..ce160c6 100644 --- a/example/node/node_modules/socket.io/lib/client.js +++ b/example/node/node_modules/socket.io/lib/client.js @@ -1,10 +1,9 @@ - /** * Module dependencies. */ -var parser = require('socket.io-client').parser - , EventEmitter = require('events').EventEmitter +var parser = require( 'socket.io-client' ).parser + , EventEmitter = require( 'events' ).EventEmitter /** * Client constructor. @@ -12,20 +11,20 @@ var parser = require('socket.io-client').parser * @api public */ -function Client (id, server) { - this.id = id; - this.acks = {}; - this.store = server.store; +function Client( id, server ) { + this.id = id; + this.acks = {}; + this.store = server.store; - var self = this; + var self = this; - store.subscribe(id, function (packet) { - - }); + store.subscribe( id, function ( packet ) { - store.subscribe(id + '.disconect', function () { - self.onDisconnect(); - }); + } ); + + store.subscribe( id + '.disconect', function () { + self.onDisconnect(); + } ); } /** @@ -48,9 +47,9 @@ Client.prototype._emit = Client.prototype.emit; * @api public */ -Client.prototype.__defineGetter__('broadcast', function () { - this.flags.broadcast = true; -}); +Client.prototype.__defineGetter__( 'broadcast', function () { + this.flags.broadcast = true; +} ); /** * JSON flag (deprecated) @@ -58,9 +57,9 @@ Client.prototype.__defineGetter__('broadcast', function () { * @api public */ -Client.prototype.__defineGetter__('json', function () { - this.flags.broadcast = true; -}); +Client.prototype.__defineGetter__( 'json', function () { + this.flags.broadcast = true; +} ); /** * Joins a group. @@ -70,18 +69,18 @@ Client.prototype.__defineGetter__('json', function () { * @api public */ -Client.prototype.join = function (group, fn) { - if (!~this.subscriptions.indexOf(group)) { - var self = this; - this.subscriptions.push(group); - this.store.addToGroup(group, this.sid, function (ev, args) { - self.onGroupEvent(ev, args); - }, fn); - } else { - fn && fn(); - } +Client.prototype.join = function ( group, fn ) { + if ( !~this.subscriptions.indexOf( group ) ) { + var self = this; + this.subscriptions.push( group ); + this.store.addToGroup( group, this.sid, function ( ev, args ) { + self.onGroupEvent( ev, args ); + }, fn ); + } else { + fn && fn(); + } - return this; + return this; }; /** @@ -91,20 +90,20 @@ Client.prototype.join = function (group, fn) { * @api public */ -Client.prototype.leave = function (group) { - var index = this.subscriptions.indexOf(group); - if (~index) { - this.subscriptions.splice(index, 1); - } - return this; +Client.prototype.leave = function ( group ) { + var index = this.subscriptions.indexOf( group ); + if ( ~index ) { + this.subscriptions.splice( index, 1 ); + } + return this; }; Client.prototype.disconnect = function () { - if (this.socket) { - this.socket.disconnect(); - } else { - this.publish('disconnect'); - } + if ( this.socket ) { + this.socket.disconnect(); + } else { + this.publish( 'disconnect' ); + } } /** @@ -114,17 +113,17 @@ Client.prototype.disconnect = function () { */ Client.prototype.onDisconnect = function () { - for (var i = 0, l = this.subscriptions; i < l; i++) { - this.store.removeFromGroup(id, group, fn); - } + for ( var i = 0, l = this.subscriptions; i < l; i++ ) { + this.store.removeFromGroup( id, group, fn ); + } }; /** * Registers ACK. */ -Client.prototype.ack = function (fn, callback) { - this.subscribe('ack'); +Client.prototype.ack = function ( fn, callback ) { + this.subscribe( 'ack' ); }; /** @@ -132,36 +131,36 @@ Client.prototype.ack = function (fn, callback) { */ Client.prototype.emit = function () { - var args = toArray(arguments), fn; + var args = toArray( arguments ), fn; - if ('function' == typeof args[args.length - 1]) { - fn = args.pop(); - } + if ( 'function' == typeof args[args.length - 1] ) { + fn = args.pop(); + } - var data = args.shift(); - if (args.length) { - data += '\n' + JSON.stringify(args); - } + var data = args.shift(); + if ( args.length ) { + data += '\n' + JSON.stringify( args ); + } - if (fn) { - this.ack(fn, function (id) { - self.sendPacket('event', data, id); - }); - } else { - this.sendPacket('event', data); - } + if ( fn ) { + this.ack( fn, function ( id ) { + self.sendPacket( 'event', data, id ); + } ); + } else { + this.sendPacket( 'event', data ); + } - return this; + return this; }; /** * Sends a packet. */ -Client.prototype.sendPacket = function (type, data, id) { - var data = parser.encode({ type: type, data: data, id: id }); +Client.prototype.sendPacket = function ( type, data, id ) { + var data = parser.encode( { type : type, data : data, id : id } ); - if (this.server.sockets[id]) { - this.server.sockets[id].write(data); - } + if ( this.server.sockets[id] ) { + this.server.sockets[id].write( data ); + } }; diff --git a/example/node/node_modules/socket.io/lib/logger.js b/example/node/node_modules/socket.io/lib/logger.js index 49d02c9..96a3efa 100644 --- a/example/node/node_modules/socket.io/lib/logger.js +++ b/example/node/node_modules/socket.io/lib/logger.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,18 +8,18 @@ * Module dependencies. */ -var util = require('./util') - , toArray = util.toArray; +var util = require( './util' ) + , toArray = util.toArray; /** * Log levels. */ var levels = [ - 'error' - , 'warn' - , 'info' - , 'debug' + 'error' + , 'warn' + , 'info' + , 'debug' ]; /** @@ -28,27 +27,30 @@ var levels = [ */ var colors = [ - 31 - , 33 - , 36 - , 90 + 31 + , 33 + , 36 + , 90 ]; /** * Pads the nice output to the longest log level. */ -function pad (str) { - var max = 0; +function pad( str ) { + var max = 0; - for (var i = 0, l = levels.length; i < l; i++) - max = Math.max(max, levels[i].length); + for ( var i = 0, l = levels.length; i < l; i++ ) { + max = Math.max( max, levels[i].length ); + } - if (str.length < max) - return str + new Array(max - str.length + 1).join(' '); + if ( str.length < max ) { + return str + new Array( max - str.length + 1 ).join( ' ' ); + } - return str; -}; + return str; +} +; /** * Logger (console). @@ -56,11 +58,11 @@ function pad (str) { * @api public */ -var Logger = module.exports = function (opts) { - opts = opts || {} - this.colors = false !== opts.colors; - this.level = 3; - this.enabled = true; +var Logger = module.exports = function ( opts ) { + opts = opts || {} + this.colors = false !== opts.colors; + this.level = 3; + this.enabled = true; }; /** @@ -69,29 +71,30 @@ var Logger = module.exports = function (opts) { * @api public */ -Logger.prototype.log = function (type) { - var index = levels.indexOf(type); +Logger.prototype.log = function ( type ) { + var index = levels.indexOf( type ); - if (index > this.level || !this.enabled) - return this; + if ( index > this.level || !this.enabled ) { + return this; + } - console.log.apply( - console - , [this.colors - ? ' \033[' + colors[index] + 'm' + pad(type) + ' -\033[39m' - : type + ':' - ].concat(toArray(arguments).slice(1)) - ); + console.log.apply( + console + , [this.colors + ? ' \033[' + colors[index] + 'm' + pad( type ) + ' -\033[39m' + : type + ':' + ].concat( toArray( arguments ).slice( 1 ) ) + ); - return this; + return this; }; /** * Generate methods. */ -levels.forEach(function (name) { - Logger.prototype[name] = function () { - this.log.apply(this, [name].concat(toArray(arguments))); - }; -}); +levels.forEach( function ( name ) { + Logger.prototype[name] = function () { + this.log.apply( this, [name].concat( toArray( arguments ) ) ); + }; +} ); diff --git a/example/node/node_modules/socket.io/lib/manager.js b/example/node/node_modules/socket.io/lib/manager.js index d136a90..7aefdbd 100644 --- a/example/node/node_modules/socket.io/lib/manager.js +++ b/example/node/node_modules/socket.io/lib/manager.js @@ -8,19 +8,19 @@ * Module dependencies. */ -var fs = require('fs') - , url = require('url') - , tty = require('tty') - , util = require('./util') - , store = require('./store') - , client = require('socket.io-client') - , transports = require('./transports') - , Logger = require('./logger') - , Socket = require('./socket') - , MemoryStore = require('./stores/memory') - , SocketNamespace = require('./namespace') - , Static = require('./static') - , EventEmitter = process.EventEmitter; +var fs = require( 'fs' ) + , url = require( 'url' ) + , tty = require( 'tty' ) + , util = require( './util' ) + , store = require( './store' ) + , client = require( 'socket.io-client' ) + , transports = require( './transports' ) + , Logger = require( './logger' ) + , Socket = require( './socket' ) + , MemoryStore = require( './stores/memory' ) + , SocketNamespace = require( './namespace' ) + , Static = require( './static' ) + , EventEmitter = process.EventEmitter; /** * Export the constructor. @@ -33,10 +33,10 @@ exports = module.exports = Manager; */ var defaultTransports = exports.defaultTransports = [ - 'websocket' - , 'htmlfile' - , 'xhr-polling' - , 'jsonp-polling' + 'websocket' + , 'htmlfile' + , 'xhr-polling' + , 'jsonp-polling' ]; /** @@ -44,7 +44,7 @@ var defaultTransports = exports.defaultTransports = [ */ var parent = module.parent.exports - , protocol = parent.protocol; + , protocol = parent.protocol; /** * Manager constructor. @@ -54,93 +54,66 @@ var parent = module.parent.exports * @api public */ -function Manager (server, options) { - this.server = server; - this.namespaces = {}; - this.sockets = this.of(''); - this.settings = { - origins: '*:*' - , log: true - , store: new MemoryStore - , logger: new Logger - , static: new Static(this) - , heartbeats: true - , resource: '/socket.io' - , transports: defaultTransports - , authorization: false - , blacklist: ['disconnect'] - , 'log level': 3 - , 'log colors': tty.isatty(process.stdout.fd) - , 'close timeout': 60 - , 'heartbeat interval': 25 - , 'heartbeat timeout': 60 - , 'polling duration': 20 - , 'flash policy server': true - , 'flash policy port': 10843 - , 'destroy upgrade': true - , 'destroy buffer size': 10E7 - , 'browser client': true - , 'browser client cache': true - , 'browser client minification': false - , 'browser client etag': false - , 'browser client expires': 315360000 - , 'browser client gzip': false - , 'browser client handler': false - , 'client store expiration': 15 - , 'match origin protocol': false - }; +function Manager( server, options ) { + this.server = server; + this.namespaces = {}; + this.sockets = this.of( '' ); + this.settings = { + origins : '*:*', log : true, store : new MemoryStore, logger : new Logger, static : new Static( this ), heartbeats : true, resource : '/socket.io', transports : defaultTransports, authorization : false, blacklist : ['disconnect'], 'log level' : 3, 'log colors' : tty.isatty( process.stdout.fd ), 'close timeout' : 60, 'heartbeat interval' : 25, 'heartbeat timeout' : 60, 'polling duration' : 20, 'flash policy server' : true, 'flash policy port' : 10843, 'destroy upgrade' : true, 'destroy buffer size' : 10E7, 'browser client' : true, 'browser client cache' : true, 'browser client minification' : false, 'browser client etag' : false, 'browser client expires' : 315360000, 'browser client gzip' : false, 'browser client handler' : false, 'client store expiration' : 15, 'match origin protocol' : false + }; - for (var i in options) { - this.settings[i] = options[i]; - } + for ( var i in options ) { + this.settings[i] = options[i]; + } - var self = this; + var self = this; - // default error handler - server.on('error', function(err) { - self.log.warn('error raised: ' + err); - }); + // default error handler + server.on( 'error', function ( err ) { + self.log.warn( 'error raised: ' + err ); + } ); - this.initStore(); + this.initStore(); - this.on('set:store', function() { - self.initStore(); - }); + this.on( 'set:store', function () { + self.initStore(); + } ); - // reset listeners - this.oldListeners = server.listeners('request'); - server.removeAllListeners('request'); + // reset listeners + this.oldListeners = server.listeners( 'request' ); + server.removeAllListeners( 'request' ); - server.on('request', function (req, res) { - self.handleRequest(req, res); - }); + server.on( 'request', function ( req, res ) { + self.handleRequest( req, res ); + } ); - server.on('upgrade', function (req, socket, head) { - self.handleUpgrade(req, socket, head); - }); + server.on( 'upgrade', function ( req, socket, head ) { + self.handleUpgrade( req, socket, head ); + } ); - server.on('close', function () { - clearInterval(self.gc); - }); + server.on( 'close', function () { + clearInterval( self.gc ); + } ); - server.once('listening', function () { - self.gc = setInterval(self.garbageCollection.bind(self), 10000); - }); + server.once( 'listening', function () { + self.gc = setInterval( self.garbageCollection.bind( self ), 10000 ); + } ); - for (var i in transports) { - if (transports[i].init) { - transports[i].init(this); - } - } + for ( var i in transports ) { + if ( transports[i].init ) { + transports[i].init( this ); + } + } - // forward-compatibility with 1.0 - var self = this; - this.sockets.on('connection', function (conn) { - self.emit('connection', conn); - }); + // forward-compatibility with 1.0 + var self = this; + this.sockets.on( 'connection', function ( conn ) { + self.emit( 'connection', conn ); + } ); - this.log.info('socket.io started'); -}; + this.log.info( 'socket.io started' ); +} +; Manager.prototype.__proto__ = EventEmitter.prototype @@ -150,11 +123,11 @@ Manager.prototype.__proto__ = EventEmitter.prototype * @api public */ -Manager.prototype.__defineGetter__('store', function () { - var store = this.get('store'); - store.manager = this; - return store; -}); +Manager.prototype.__defineGetter__( 'store', function () { + var store = this.get( 'store' ); + store.manager = this; + return store; +} ); /** * Logger accessor. @@ -162,15 +135,15 @@ Manager.prototype.__defineGetter__('store', function () { * @api public */ -Manager.prototype.__defineGetter__('log', function () { - var logger = this.get('logger'); +Manager.prototype.__defineGetter__( 'log', function () { + var logger = this.get( 'logger' ); - logger.level = this.get('log level') || -1; - logger.colors = this.get('log colors'); - logger.enabled = this.enabled('log'); + logger.level = this.get( 'log level' ) || -1; + logger.colors = this.get( 'log colors' ); + logger.enabled = this.enabled( 'log' ); - return logger; -}); + return logger; +} ); /** * Static accessor. @@ -178,9 +151,9 @@ Manager.prototype.__defineGetter__('log', function () { * @api public */ -Manager.prototype.__defineGetter__('static', function () { - return this.get('static'); -}); +Manager.prototype.__defineGetter__( 'static', function () { + return this.get( 'static' ); +} ); /** * Get settings. @@ -188,8 +161,8 @@ Manager.prototype.__defineGetter__('static', function () { * @api public */ -Manager.prototype.get = function (key) { - return this.settings[key]; +Manager.prototype.get = function ( key ) { + return this.settings[key]; }; /** @@ -198,11 +171,13 @@ Manager.prototype.get = function (key) { * @api public */ -Manager.prototype.set = function (key, value) { - if (arguments.length == 1) return this.get(key); - this.settings[key] = value; - this.emit('set:' + key, this.settings[key], key); - return this; +Manager.prototype.set = function ( key, value ) { + if ( arguments.length == 1 ) { + return this.get( key ); + } + this.settings[key] = value; + this.emit( 'set:' + key, this.settings[key], key ); + return this; }; /** @@ -211,10 +186,10 @@ Manager.prototype.set = function (key, value) { * @api public */ -Manager.prototype.enable = function (key) { - this.settings[key] = true; - this.emit('set:' + key, this.settings[key], key); - return this; +Manager.prototype.enable = function ( key ) { + this.settings[key] = true; + this.emit( 'set:' + key, this.settings[key], key ); + return this; }; /** @@ -223,10 +198,10 @@ Manager.prototype.enable = function (key) { * @api public */ -Manager.prototype.disable = function (key) { - this.settings[key] = false; - this.emit('set:' + key, this.settings[key], key); - return this; +Manager.prototype.disable = function ( key ) { + this.settings[key] = false; + this.emit( 'set:' + key, this.settings[key], key ); + return this; }; /** @@ -235,8 +210,8 @@ Manager.prototype.disable = function (key) { * @api public */ -Manager.prototype.enabled = function (key) { - return !!this.settings[key]; +Manager.prototype.enabled = function ( key ) { + return !!this.settings[key]; }; /** @@ -245,8 +220,8 @@ Manager.prototype.enabled = function (key) { * @api public */ -Manager.prototype.disabled = function (key) { - return !this.settings[key]; +Manager.prototype.disabled = function ( key ) { + return !this.settings[key]; }; /** @@ -255,14 +230,14 @@ Manager.prototype.disabled = function (key) { * @api public */ -Manager.prototype.configure = function (env, fn) { - if ('function' == typeof env) { - env.call(this); - } else if (env == (process.env.NODE_ENV || 'development')) { - fn.call(this); - } +Manager.prototype.configure = function ( env, fn ) { + if ( 'function' == typeof env ) { + env.call( this ); + } else if ( env == (process.env.NODE_ENV || 'development') ) { + fn.call( this ); + } - return this; + return this; }; /** @@ -272,46 +247,46 @@ Manager.prototype.configure = function (env, fn) { */ Manager.prototype.initStore = function () { - this.handshaken = {}; - this.connected = {}; - this.open = {}; - this.closed = {}; - this.rooms = {}; - this.roomClients = {}; + this.handshaken = {}; + this.connected = {}; + this.open = {}; + this.closed = {}; + this.rooms = {}; + this.roomClients = {}; - var self = this; + var self = this; - this.store.subscribe('handshake', function (id, data) { - self.onHandshake(id, data); - }); + this.store.subscribe( 'handshake', function ( id, data ) { + self.onHandshake( id, data ); + } ); - this.store.subscribe('connect', function (id) { - self.onConnect(id); - }); + this.store.subscribe( 'connect', function ( id ) { + self.onConnect( id ); + } ); - this.store.subscribe('open', function (id) { - self.onOpen(id); - }); + this.store.subscribe( 'open', function ( id ) { + self.onOpen( id ); + } ); - this.store.subscribe('join', function (id, room) { - self.onJoin(id, room); - }); + this.store.subscribe( 'join', function ( id, room ) { + self.onJoin( id, room ); + } ); - this.store.subscribe('leave', function (id, room) { - self.onLeave(id, room); - }); + this.store.subscribe( 'leave', function ( id, room ) { + self.onLeave( id, room ); + } ); - this.store.subscribe('close', function (id) { - self.onClose(id); - }); + this.store.subscribe( 'close', function ( id ) { + self.onClose( id ); + } ); - this.store.subscribe('dispatch', function (room, packet, volatile, exceptions) { - self.onDispatch(room, packet, volatile, exceptions); - }); + this.store.subscribe( 'dispatch', function ( room, packet, volatile, exceptions ) { + self.onDispatch( room, packet, volatile, exceptions ); + } ); - this.store.subscribe('disconnect', function (id) { - self.onDisconnect(id); - }); + this.store.subscribe( 'disconnect', function ( id ) { + self.onDisconnect( id ); + } ); }; /** @@ -320,8 +295,8 @@ Manager.prototype.initStore = function () { * @param text */ -Manager.prototype.onHandshake = function (id, data) { - this.handshaken[id] = data; +Manager.prototype.onHandshake = function ( id, data ) { + this.handshaken[id] = data; }; /** @@ -330,8 +305,8 @@ Manager.prototype.onHandshake = function (id, data) { * @api private */ -Manager.prototype.onConnect = function (id) { - this.connected[id] = true; +Manager.prototype.onConnect = function ( id ) { + this.connected[id] = true; }; /** @@ -340,23 +315,23 @@ Manager.prototype.onConnect = function (id) { * @api private */ -Manager.prototype.onOpen = function (id) { - this.open[id] = true; +Manager.prototype.onOpen = function ( id ) { + this.open[id] = true; - // if we were buffering messages for the client, clear them - if (this.closed[id]) { - var self = this; + // if we were buffering messages for the client, clear them + if ( this.closed[id] ) { + var self = this; - this.store.unsubscribe('dispatch:' + id, function () { - delete self.closed[id]; - }); - } + this.store.unsubscribe( 'dispatch:' + id, function () { + delete self.closed[id]; + } ); + } - // clear the current transport - if (this.transports[id]) { - this.transports[id].discard(); - this.transports[id] = null; - } + // clear the current transport + if ( this.transports[id] ) { + this.transports[id].discard(); + this.transports[id] = null; + } }; /** @@ -365,20 +340,20 @@ Manager.prototype.onOpen = function (id) { * @api private */ -Manager.prototype.onDispatch = function (room, packet, volatile, exceptions) { - if (this.rooms[room]) { - for (var i = 0, l = this.rooms[room].length; i < l; i++) { - var id = this.rooms[room][i]; +Manager.prototype.onDispatch = function ( room, packet, volatile, exceptions ) { + if ( this.rooms[room] ) { + for ( var i = 0, l = this.rooms[room].length; i < l; i++ ) { + var id = this.rooms[room][i]; - if (!~exceptions.indexOf(id)) { - if (this.transports[id] && this.transports[id].open) { - this.transports[id].onDispatch(packet, volatile); - } else if (!volatile) { - this.onClientDispatch(id, packet); - } - } - } - } + if ( !~exceptions.indexOf( id ) ) { + if ( this.transports[id] && this.transports[id].open ) { + this.transports[id].onDispatch( packet, volatile ); + } else if ( !volatile ) { + this.onClientDispatch( id, packet ); + } + } + } + } }; /** @@ -387,19 +362,19 @@ Manager.prototype.onDispatch = function (room, packet, volatile, exceptions) { * @api private */ -Manager.prototype.onJoin = function (id, name) { - if (!this.roomClients[id]) { - this.roomClients[id] = {}; - } +Manager.prototype.onJoin = function ( id, name ) { + if ( !this.roomClients[id] ) { + this.roomClients[id] = {}; + } - if (!this.rooms[name]) { - this.rooms[name] = []; - } + if ( !this.rooms[name] ) { + this.rooms[name] = []; + } - if (!~this.rooms[name].indexOf(id)) { - this.rooms[name].push(id); - this.roomClients[id][name] = true; - } + if ( !~this.rooms[name].indexOf( id ) ) { + this.rooms[name].push( id ); + this.roomClients[id][name] = true; + } }; /** @@ -408,19 +383,19 @@ Manager.prototype.onJoin = function (id, name) { * @param private */ -Manager.prototype.onLeave = function (id, room) { - if (this.rooms[room]) { - var index = this.rooms[room].indexOf(id); +Manager.prototype.onLeave = function ( id, room ) { + if ( this.rooms[room] ) { + var index = this.rooms[room].indexOf( id ); - if (index >= 0) { - this.rooms[room].splice(index, 1); - } + if ( index >= 0 ) { + this.rooms[room].splice( index, 1 ); + } - if (!this.rooms[room].length) { - delete this.rooms[room]; - } - delete this.roomClients[id][room]; - } + if ( !this.rooms[room].length ) { + delete this.rooms[room]; + } + delete this.roomClients[id][room]; + } }; /** @@ -429,20 +404,20 @@ Manager.prototype.onLeave = function (id, room) { * @api private */ -Manager.prototype.onClose = function (id) { - if (this.open[id]) { - delete this.open[id]; - } +Manager.prototype.onClose = function ( id ) { + if ( this.open[id] ) { + delete this.open[id]; + } - this.closed[id] = []; + this.closed[id] = []; - var self = this; + var self = this; - this.store.subscribe('dispatch:' + id, function (packet, volatile) { - if (!volatile) { - self.onClientDispatch(id, packet); - } - }); + this.store.subscribe( 'dispatch:' + id, function ( packet, volatile ) { + if ( !volatile ) { + self.onClientDispatch( id, packet ); + } + } ); }; /** @@ -451,10 +426,10 @@ Manager.prototype.onClose = function (id) { * @api private */ -Manager.prototype.onClientDispatch = function (id, packet) { - if (this.closed[id]) { - this.closed[id].push(packet); - } +Manager.prototype.onClientDispatch = function ( id, packet ) { + if ( this.closed[id] ) { + this.closed[id].push( packet ); + } }; /** @@ -463,10 +438,10 @@ Manager.prototype.onClientDispatch = function (id, packet) { * @api private */ -Manager.prototype.onClientMessage = function (id, packet) { - if (this.namespaces[packet.endpoint]) { - this.namespaces[packet.endpoint].handlePacket(id, packet); - } +Manager.prototype.onClientMessage = function ( id, packet ) { + if ( this.namespaces[packet.endpoint] ) { + this.namespaces[packet.endpoint].handlePacket( id, packet ); + } }; /** @@ -475,13 +450,13 @@ Manager.prototype.onClientMessage = function (id, packet) { * @api private */ -Manager.prototype.onClientDisconnect = function (id, reason) { - for (var name in this.namespaces) { - this.namespaces[name].handleDisconnect(id, reason, typeof this.roomClients[id] !== 'undefined' && - typeof this.roomClients[id][name] !== 'undefined'); - } +Manager.prototype.onClientDisconnect = function ( id, reason ) { + for ( var name in this.namespaces ) { + this.namespaces[name].handleDisconnect( id, reason, typeof this.roomClients[id] !== 'undefined' && + typeof this.roomClients[id][name] !== 'undefined' ); + } - this.onDisconnect(id); + this.onDisconnect( id ); }; /** @@ -490,41 +465,41 @@ Manager.prototype.onClientDisconnect = function (id, reason) { * @param text */ -Manager.prototype.onDisconnect = function (id, local) { - delete this.handshaken[id]; +Manager.prototype.onDisconnect = function ( id, local ) { + delete this.handshaken[id]; - if (this.open[id]) { - delete this.open[id]; - } + if ( this.open[id] ) { + delete this.open[id]; + } - if (this.connected[id]) { - delete this.connected[id]; - } + if ( this.connected[id] ) { + delete this.connected[id]; + } - if (this.transports[id]) { - this.transports[id].discard(); - delete this.transports[id]; - } + if ( this.transports[id] ) { + this.transports[id].discard(); + delete this.transports[id]; + } - if (this.closed[id]) { - delete this.closed[id]; - } + if ( this.closed[id] ) { + delete this.closed[id]; + } - if (this.roomClients[id]) { - for (var room in this.roomClients[id]) { - this.onLeave(id, room); - } - delete this.roomClients[id] - } + if ( this.roomClients[id] ) { + for ( var room in this.roomClients[id] ) { + this.onLeave( id, room ); + } + delete this.roomClients[id] + } - this.store.destroyClient(id, this.get('client store expiration')); + this.store.destroyClient( id, this.get( 'client store expiration' ) ); - this.store.unsubscribe('dispatch:' + id); + this.store.unsubscribe( 'dispatch:' + id ); - if (local) { - this.store.unsubscribe('message:' + id); - this.store.unsubscribe('disconnect:' + id); - } + if ( local ) { + this.store.unsubscribe( 'message:' + id ); + this.store.unsubscribe( 'disconnect:' + id ); + } }; /** @@ -533,42 +508,42 @@ Manager.prototype.onDisconnect = function (id, local) { * @api private */ -Manager.prototype.handleRequest = function (req, res) { - var data = this.checkRequest(req); +Manager.prototype.handleRequest = function ( req, res ) { + var data = this.checkRequest( req ); - if (!data) { - for (var i = 0, l = this.oldListeners.length; i < l; i++) { - this.oldListeners[i].call(this.server, req, res); - } + if ( !data ) { + for ( var i = 0, l = this.oldListeners.length; i < l; i++ ) { + this.oldListeners[i].call( this.server, req, res ); + } - return; - } + return; + } - if (data.static || !data.transport && !data.protocol) { - if (data.static && this.enabled('browser client')) { - this.static.write(data.path, req, res); - } else { - res.writeHead(200); - res.end('Welcome to socket.io.'); + if ( data.static || !data.transport && !data.protocol ) { + if ( data.static && this.enabled( 'browser client' ) ) { + this.static.write( data.path, req, res ); + } else { + res.writeHead( 200 ); + res.end( 'Welcome to socket.io.' ); - this.log.info('unhandled socket.io url'); - } + this.log.info( 'unhandled socket.io url' ); + } - return; - } + return; + } - if (data.protocol != protocol) { - res.writeHead(500); - res.end('Protocol version not supported.'); + if ( data.protocol != protocol ) { + res.writeHead( 500 ); + res.end( 'Protocol version not supported.' ); - this.log.info('client protocol version unsupported'); - } else { - if (data.id) { - this.handleHTTPRequest(data, req, res); - } else { - this.handleHandshake(data, req, res); - } - } + this.log.info( 'client protocol version unsupported' ); + } else { + if ( data.id ) { + this.handleHTTPRequest( data, req, res ); + } else { + this.handleHandshake( data, req, res ); + } + } }; /** @@ -577,21 +552,21 @@ Manager.prototype.handleRequest = function (req, res) { * @api private */ -Manager.prototype.handleUpgrade = function (req, socket, head) { - var data = this.checkRequest(req) - , self = this; +Manager.prototype.handleUpgrade = function ( req, socket, head ) { + var data = this.checkRequest( req ) + , self = this; - if (!data) { - if (this.enabled('destroy upgrade')) { - socket.end(); - this.log.debug('destroying non-socket.io upgrade'); - } + if ( !data ) { + if ( this.enabled( 'destroy upgrade' ) ) { + socket.end(); + this.log.debug( 'destroying non-socket.io upgrade' ); + } - return; - } + return; + } - req.head = head; - this.handleClient(data, req); + req.head = head; + this.handleClient( data, req ); }; /** @@ -600,9 +575,9 @@ Manager.prototype.handleUpgrade = function (req, socket, head) { * @api private */ -Manager.prototype.handleHTTPRequest = function (data, req, res) { - req.res = res; - this.handleClient(data, req); +Manager.prototype.handleHTTPRequest = function ( data, req, res ) { + req.res = res; + this.handleClient( data, req ); }; /** @@ -611,80 +586,80 @@ Manager.prototype.handleHTTPRequest = function (data, req, res) { * @api private */ -Manager.prototype.handleClient = function (data, req) { - var socket = req.socket - , store = this.store - , self = this; +Manager.prototype.handleClient = function ( data, req ) { + var socket = req.socket + , store = this.store + , self = this; - if (undefined != data.query.disconnect) { - if (this.transports[data.id] && this.transports[data.id].open) { - this.transports[data.id].onForcedDisconnect(); - } else { - this.store.publish('disconnect-force:' + data.id); - } - return; - } + if ( undefined != data.query.disconnect ) { + if ( this.transports[data.id] && this.transports[data.id].open ) { + this.transports[data.id].onForcedDisconnect(); + } else { + this.store.publish( 'disconnect-force:' + data.id ); + } + return; + } - if (!~this.get('transports').indexOf(data.transport)) { - this.log.warn('unknown transport: "' + data.transport + '"'); - req.connection.end(); - return; - } + if ( !~this.get( 'transports' ).indexOf( data.transport ) ) { + this.log.warn( 'unknown transport: "' + data.transport + '"' ); + req.connection.end(); + return; + } - var transport = new transports[data.transport](this, data, req) - , handshaken = this.handshaken[data.id]; + var transport = new transports[data.transport]( this, data, req ) + , handshaken = this.handshaken[data.id]; - if (transport.disconnected) { - // failed during transport setup - req.connection.end(); - return; - } - if (handshaken) { - if (transport.open) { - if (this.closed[data.id] && this.closed[data.id].length) { - transport.payload(this.closed[data.id]); - this.closed[data.id] = []; - } + if ( transport.disconnected ) { + // failed during transport setup + req.connection.end(); + return; + } + if ( handshaken ) { + if ( transport.open ) { + if ( this.closed[data.id] && this.closed[data.id].length ) { + transport.payload( this.closed[data.id] ); + this.closed[data.id] = []; + } - this.onOpen(data.id); - this.store.publish('open', data.id); - this.transports[data.id] = transport; - } + this.onOpen( data.id ); + this.store.publish( 'open', data.id ); + this.transports[data.id] = transport; + } - if (!this.connected[data.id]) { - this.onConnect(data.id); - this.store.publish('connect', data.id); + if ( !this.connected[data.id] ) { + this.onConnect( data.id ); + this.store.publish( 'connect', data.id ); - // flag as used - delete handshaken.issued; - this.onHandshake(data.id, handshaken); - this.store.publish('handshake', data.id, handshaken); + // flag as used + delete handshaken.issued; + this.onHandshake( data.id, handshaken ); + this.store.publish( 'handshake', data.id, handshaken ); - // initialize the socket for all namespaces - for (var i in this.namespaces) { - var socket = this.namespaces[i].socket(data.id, true); + // initialize the socket for all namespaces + for ( var i in this.namespaces ) { + var socket = this.namespaces[i].socket( data.id, true ); - // echo back connect packet and fire connection event - if (i === '') { - this.namespaces[i].handlePacket(data.id, { type: 'connect' }); - } - } + // echo back connect packet and fire connection event + if ( i === '' ) { + this.namespaces[i].handlePacket( data.id, { type : 'connect' } ); + } + } - this.store.subscribe('message:' + data.id, function (packet) { - self.onClientMessage(data.id, packet); - }); + this.store.subscribe( 'message:' + data.id, function ( packet ) { + self.onClientMessage( data.id, packet ); + } ); - this.store.subscribe('disconnect:' + data.id, function (reason) { - self.onClientDisconnect(data.id, reason); - }); - } - } else { - if (transport.open) { - transport.error('client not handshaken', 'reconnect'); - } + this.store.subscribe( 'disconnect:' + data.id, function ( reason ) { + self.onClientDisconnect( data.id, reason ); + } ); + } + } else { + if ( transport.open ) { + transport.error( 'client not handshaken', 'reconnect' ); + } - transport.discard(); - } + transport.discard(); + } }; /** @@ -694,8 +669,8 @@ Manager.prototype.handleClient = function (data, req) { */ Manager.prototype.generateId = function () { - return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString() - + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString(); + return Math.abs( Math.random() * Math.random() * Date.now() | 0 ).toString() + + Math.abs( Math.random() * Math.random() * Date.now() | 0 ).toString(); }; /** @@ -704,71 +679,77 @@ Manager.prototype.generateId = function () { * @api private */ -Manager.prototype.handleHandshake = function (data, req, res) { - var self = this - , origin = req.headers.origin - , headers = { - 'Content-Type': 'text/plain' - }; +Manager.prototype.handleHandshake = function ( data, req, res ) { + var self = this + , origin = req.headers.origin + , headers = { + 'Content-Type' : 'text/plain' + }; - function writeErr (status, message) { - if (data.query.jsonp) { - res.writeHead(200, { 'Content-Type': 'application/javascript' }); - res.end('io.j[' + data.query.jsonp + '](new Error("' + message + '"));'); - } else { - res.writeHead(status, headers); - res.end(message); - } - }; + function writeErr( status, message ) { + if ( data.query.jsonp ) { + res.writeHead( 200, { 'Content-Type' : 'application/javascript' } ); + res.end( 'io.j[' + data.query.jsonp + '](new Error("' + message + '"));' ); + } else { + res.writeHead( status, headers ); + res.end( message ); + } + } - function error (err) { - writeErr(500, 'handshake error'); - self.log.warn('handshake error ' + err); - }; + ; - if (!this.verifyOrigin(req)) { - writeErr(403, 'handshake bad origin'); - return; - } + function error( err ) { + writeErr( 500, 'handshake error' ); + self.log.warn( 'handshake error ' + err ); + } - var handshakeData = this.handshakeData(data); + ; - if (origin) { - // https://developer.mozilla.org/En/HTTP_Access_Control - headers['Access-Control-Allow-Origin'] = origin; - headers['Access-Control-Allow-Credentials'] = 'true'; - } + if ( !this.verifyOrigin( req ) ) { + writeErr( 403, 'handshake bad origin' ); + return; + } - this.authorize(handshakeData, function (err, authorized, newData) { - if (err) return error(err); + var handshakeData = this.handshakeData( data ); - if (authorized) { - var id = self.generateId() - , hs = [ - id - , self.enabled('heartbeats') ? self.get('heartbeat timeout') || '' : '' - , self.get('close timeout') || '' - , self.transports(data).join(',') - ].join(':'); + if ( origin ) { + // https://developer.mozilla.org/En/HTTP_Access_Control + headers['Access-Control-Allow-Origin'] = origin; + headers['Access-Control-Allow-Credentials'] = 'true'; + } - if (data.query.jsonp) { - hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify(hs) + ');'; - res.writeHead(200, { 'Content-Type': 'application/javascript' }); - } else { - res.writeHead(200, headers); - } + this.authorize( handshakeData, function ( err, authorized, newData ) { + if ( err ) { + return error( err ); + } - res.end(hs); + if ( authorized ) { + var id = self.generateId() + , hs = [ + id + , self.enabled( 'heartbeats' ) ? self.get( 'heartbeat timeout' ) || '' : '' + , self.get( 'close timeout' ) || '' + , self.transports( data ).join( ',' ) + ].join( ':' ); - self.onHandshake(id, newData || handshakeData); - self.store.publish('handshake', id, newData || handshakeData); + if ( data.query.jsonp ) { + hs = 'io.j[' + data.query.jsonp + '](' + JSON.stringify( hs ) + ');'; + res.writeHead( 200, { 'Content-Type' : 'application/javascript' } ); + } else { + res.writeHead( 200, headers ); + } - self.log.info('handshake authorized', id); - } else { - writeErr(403, 'handshake unauthorized'); - self.log.info('handshake unauthorized'); - } - }) + res.end( hs ); + + self.onHandshake( id, newData || handshakeData ); + self.store.publish( 'handshake', id, newData || handshakeData ); + + self.log.info( 'handshake authorized', id ); + } else { + writeErr( 403, 'handshake unauthorized' ); + self.log.info( 'handshake unauthorized' ); + } + } ) }; /** @@ -777,33 +758,24 @@ Manager.prototype.handleHandshake = function (data, req, res) { * @api private */ -Manager.prototype.handshakeData = function (data) { - var connection = data.request.connection - , connectionAddress - , date = new Date; +Manager.prototype.handshakeData = function ( data ) { + var connection = data.request.connection + , connectionAddress + , date = new Date; - if (connection.remoteAddress) { - connectionAddress = { - address: connection.remoteAddress - , port: connection.remotePort - }; - } else if (connection.socket && connection.socket.remoteAddress) { - connectionAddress = { - address: connection.socket.remoteAddress - , port: connection.socket.remotePort - }; - } + if ( connection.remoteAddress ) { + connectionAddress = { + address : connection.remoteAddress, port : connection.remotePort + }; + } else if ( connection.socket && connection.socket.remoteAddress ) { + connectionAddress = { + address : connection.socket.remoteAddress, port : connection.socket.remotePort + }; + } - return { - headers: data.headers - , address: connectionAddress - , time: date.toString() - , query: data.query - , url: data.request.url - , xdomain: !!data.request.headers.origin - , secure: data.request.connection.secure - , issued: +date - }; + return { + headers : data.headers, address : connectionAddress, time : date.toString(), query : data.query, url : data.request.url, xdomain : !!data.request.headers.origin, secure : data.request.connection.secure, issued : +date + }; }; /** @@ -812,34 +784,38 @@ Manager.prototype.handshakeData = function (data) { * @api private */ -Manager.prototype.verifyOrigin = function (request) { - var origin = request.headers.origin || request.headers.referer - , origins = this.get('origins'); +Manager.prototype.verifyOrigin = function ( request ) { + var origin = request.headers.origin || request.headers.referer + , origins = this.get( 'origins' ); - if (origin === 'null') origin = '*'; + if ( origin === 'null' ) { + origin = '*'; + } - if (origins.indexOf('*:*') !== -1) { - return true; - } + if ( origins.indexOf( '*:*' ) !== -1 ) { + return true; + } - if (origin) { - try { - var parts = url.parse(origin); - parts.port = parts.port || 80; - var ok = - ~origins.indexOf(parts.hostname + ':' + parts.port) || - ~origins.indexOf(parts.hostname + ':*') || - ~origins.indexOf('*:' + parts.port); - if (!ok) this.log.warn('illegal origin: ' + origin); - return ok; - } catch (ex) { - this.log.warn('error parsing origin'); - } - } - else { - this.log.warn('origin missing from handshake, yet required by config'); - } - return false; + if ( origin ) { + try { + var parts = url.parse( origin ); + parts.port = parts.port || 80; + var ok = + ~origins.indexOf( parts.hostname + ':' + parts.port ) || + ~origins.indexOf( parts.hostname + ':*' ) || + ~origins.indexOf( '*:' + parts.port ); + if ( !ok ) { + this.log.warn( 'illegal origin: ' + origin ); + } + return ok; + } catch ( ex ) { + this.log.warn( 'error parsing origin' ); + } + } + else { + this.log.warn( 'origin missing from handshake, yet required by config' ); + } + return false; }; /** @@ -848,8 +824,8 @@ Manager.prototype.verifyOrigin = function (request) { * @api private */ -Manager.prototype.handlePacket = function (sessid, packet) { - this.of(packet.endpoint || '').handlePacket(sessid, packet); +Manager.prototype.handlePacket = function ( sessid, packet ) { + this.of( packet.endpoint || '' ).handlePacket( sessid, packet ); }; /** @@ -859,20 +835,20 @@ Manager.prototype.handlePacket = function (sessid, packet) { * @api private */ -Manager.prototype.authorize = function (data, fn) { - if (this.get('authorization')) { - var self = this; +Manager.prototype.authorize = function ( data, fn ) { + if ( this.get( 'authorization' ) ) { + var self = this; - this.get('authorization').call(this, data, function (err, authorized) { - self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized'); - fn(err, authorized); - }); - } else { - this.log.debug('client authorized'); - fn(null, true); - } + this.get( 'authorization' ).call( this, data, function ( err, authorized ) { + self.log.debug( 'client ' + authorized ? 'authorized' : 'unauthorized' ); + fn( err, authorized ); + } ); + } else { + this.log.debug( 'client authorized' ); + fn( null, true ); + } - return this; + return this; }; /** @@ -881,21 +857,21 @@ Manager.prototype.authorize = function (data, fn) { * @api private */ -Manager.prototype.transports = function (data) { - var transp = this.get('transports') - , ret = []; +Manager.prototype.transports = function ( data ) { + var transp = this.get( 'transports' ) + , ret = []; - for (var i = 0, l = transp.length; i < l; i++) { - var transport = transp[i]; + for ( var i = 0, l = transp.length; i < l; i++ ) { + var transport = transp[i]; - if (transport) { - if (!transport.checkClient || transport.checkClient(data)) { - ret.push(transport); - } - } - } + if ( transport ) { + if ( !transport.checkClient || transport.checkClient( data ) ) { + ret.push( transport ); + } + } + } - return ret; + return ret; }; /** @@ -907,42 +883,44 @@ Manager.prototype.transports = function (data) { var regexp = /^\/([^\/]+)\/?([^\/]+)?\/?([^\/]+)?\/?$/ -Manager.prototype.checkRequest = function (req) { - var resource = this.get('resource'); +Manager.prototype.checkRequest = function ( req ) { + var resource = this.get( 'resource' ); - var match; - if (typeof resource === 'string') { - match = req.url.substr(0, resource.length); - if (match !== resource) match = null; - } else { - match = resource.exec(req.url); - if (match) match = match[0]; - } + var match; + if ( typeof resource === 'string' ) { + match = req.url.substr( 0, resource.length ); + if ( match !== resource ) { + match = null; + } + } else { + match = resource.exec( req.url ); + if ( match ) { + match = match[0]; + } + } - if (match) { - var uri = url.parse(req.url.substr(match.length), true) - , path = uri.pathname || '' - , pieces = path.match(regexp); + if ( match ) { + var uri = url.parse( req.url.substr( match.length ), true ) + , path = uri.pathname || '' + , pieces = path.match( regexp ); - // client request data - var data = { - query: uri.query || {} - , headers: req.headers - , request: req - , path: path - }; + // client request data + var data = { + query : uri.query || {}, headers : req.headers, request : req, path : path + }; - if (pieces) { - data.protocol = Number(pieces[1]); - data.transport = pieces[2]; - data.id = pieces[3]; - data.static = !!this.static.has(path); - }; + if ( pieces ) { + data.protocol = Number( pieces[1] ); + data.transport = pieces[2]; + data.id = pieces[3]; + data.static = !!this.static.has( path ); + } + ; - return data; - } + return data; + } - return false; + return false; }; /** @@ -951,12 +929,12 @@ Manager.prototype.checkRequest = function (req) { * @api public */ -Manager.prototype.of = function (nsp) { - if (this.namespaces[nsp]) { - return this.namespaces[nsp]; - } +Manager.prototype.of = function ( nsp ) { + if ( this.namespaces[nsp] ) { + return this.namespaces[nsp]; + } - return this.namespaces[nsp] = new SocketNamespace(this, nsp); + return this.namespaces[nsp] = new SocketNamespace( this, nsp ); }; /** @@ -967,17 +945,17 @@ Manager.prototype.of = function (nsp) { */ Manager.prototype.garbageCollection = function () { - // clean up unused handshakes - var ids = Object.keys(this.handshaken) - , i = ids.length - , now = Date.now() - , handshake; + // clean up unused handshakes + var ids = Object.keys( this.handshaken ) + , i = ids.length + , now = Date.now() + , handshake; - while (i--) { - handshake = this.handshaken[ids[i]]; + while ( i-- ) { + handshake = this.handshaken[ids[i]]; - if ('issued' in handshake && (now - handshake.issued) >= 3E4) { - this.onDisconnect(ids[i]); - } - } + if ( 'issued' in handshake && (now - handshake.issued) >= 3E4 ) { + this.onDisconnect( ids[i] ); + } + } }; diff --git a/example/node/node_modules/socket.io/lib/namespace.js b/example/node/node_modules/socket.io/lib/namespace.js index 6e1e1c9..8c9f866 100644 --- a/example/node/node_modules/socket.io/lib/namespace.js +++ b/example/node/node_modules/socket.io/lib/namespace.js @@ -2,10 +2,10 @@ * Module dependencies. */ -var Socket = require('./socket') - , EventEmitter = process.EventEmitter - , parser = require('./parser') - , util = require('./util'); +var Socket = require( './socket' ) + , EventEmitter = process.EventEmitter + , parser = require( './parser' ) + , util = require( './util' ); /** * Exports the constructor. @@ -19,13 +19,14 @@ exports = module.exports = SocketNamespace; * @api public. */ -function SocketNamespace (mgr, name) { - this.manager = mgr; - this.name = name || ''; - this.sockets = {}; - this.auth = false; - this.setFlags(); -}; +function SocketNamespace( mgr, name ) { + this.manager = mgr; + this.name = name || ''; + this.sockets = {}; + this.auth = false; + this.setFlags(); +} +; /** * Inherits from EventEmitter. @@ -47,17 +48,17 @@ SocketNamespace.prototype.$emit = EventEmitter.prototype.emit; * @api public */ -SocketNamespace.prototype.clients = function (room) { - var room = this.name + (room !== undefined ? - '/' + room : ''); +SocketNamespace.prototype.clients = function ( room ) { + var room = this.name + (room !== undefined ? + '/' + room : ''); - if (!this.manager.rooms[room]) { - return []; - } + if ( !this.manager.rooms[room] ) { + return []; + } - return this.manager.rooms[room].map(function (id) { - return this.socket(id); - }, this); + return this.manager.rooms[room].map( function ( id ) { + return this.socket( id ); + }, this ); }; /** @@ -66,9 +67,9 @@ SocketNamespace.prototype.clients = function (room) { * @api public */ -SocketNamespace.prototype.__defineGetter__('log', function () { - return this.manager.log; -}); +SocketNamespace.prototype.__defineGetter__( 'log', function () { + return this.manager.log; +} ); /** * Access store. @@ -76,9 +77,9 @@ SocketNamespace.prototype.__defineGetter__('log', function () { * @api public */ -SocketNamespace.prototype.__defineGetter__('store', function () { - return this.manager.store; -}); +SocketNamespace.prototype.__defineGetter__( 'store', function () { + return this.manager.store; +} ); /** * JSON message flag. @@ -86,10 +87,10 @@ SocketNamespace.prototype.__defineGetter__('store', function () { * @api public */ -SocketNamespace.prototype.__defineGetter__('json', function () { - this.flags.json = true; - return this; -}); +SocketNamespace.prototype.__defineGetter__( 'json', function () { + this.flags.json = true; + return this; +} ); /** * Volatile message flag. @@ -97,10 +98,10 @@ SocketNamespace.prototype.__defineGetter__('json', function () { * @api public */ -SocketNamespace.prototype.__defineGetter__('volatile', function () { - this.flags.volatile = true; - return this; -}); +SocketNamespace.prototype.__defineGetter__( 'volatile', function () { + this.flags.volatile = true; + return this; +} ); /** * Overrides the room to relay messages to (flag). @@ -108,9 +109,9 @@ SocketNamespace.prototype.__defineGetter__('volatile', function () { * @api public */ -SocketNamespace.prototype.in = SocketNamespace.prototype.to = function (room) { - this.flags.endpoint = this.name + (room ? '/' + room : ''); - return this; +SocketNamespace.prototype.in = SocketNamespace.prototype.to = function ( room ) { + this.flags.endpoint = this.name + (room ? '/' + room : ''); + return this; }; /** @@ -119,9 +120,9 @@ SocketNamespace.prototype.in = SocketNamespace.prototype.to = function (room) { * @api public */ -SocketNamespace.prototype.except = function (id) { - this.flags.exceptions.push(id); - return this; +SocketNamespace.prototype.except = function ( id ) { + this.flags.exceptions.push( id ); + return this; }; /** @@ -131,11 +132,10 @@ SocketNamespace.prototype.except = function (id) { */ SocketNamespace.prototype.setFlags = function () { - this.flags = { - endpoint: this.name - , exceptions: [] - }; - return this; + this.flags = { + endpoint : this.name, exceptions : [] + }; + return this; }; /** @@ -144,21 +144,21 @@ SocketNamespace.prototype.setFlags = function () { * @api private */ -SocketNamespace.prototype.packet = function (packet) { - packet.endpoint = this.name; +SocketNamespace.prototype.packet = function ( packet ) { + packet.endpoint = this.name; - var store = this.store - , log = this.log - , volatile = this.flags.volatile - , exceptions = this.flags.exceptions - , packet = parser.encodePacket(packet); + var store = this.store + , log = this.log + , volatile = this.flags.volatile + , exceptions = this.flags.exceptions + , packet = parser.encodePacket( packet ); - this.manager.onDispatch(this.flags.endpoint, packet, volatile, exceptions); - this.store.publish('dispatch', this.flags.endpoint, packet, volatile, exceptions); + this.manager.onDispatch( this.flags.endpoint, packet, volatile, exceptions ); + this.store.publish( 'dispatch', this.flags.endpoint, packet, volatile, exceptions ); - this.setFlags(); + this.setFlags(); - return this; + return this; }; /** @@ -167,11 +167,10 @@ SocketNamespace.prototype.packet = function (packet) { * @api public */ -SocketNamespace.prototype.send = function (data) { - return this.packet({ - type: this.flags.json ? 'json' : 'message' - , data: data - }); +SocketNamespace.prototype.send = function ( data ) { + return this.packet( { + type : this.flags.json ? 'json' : 'message', data : data + } ); }; /** @@ -180,16 +179,14 @@ SocketNamespace.prototype.send = function (data) { * @api public */ -SocketNamespace.prototype.emit = function (name) { - if (name == 'newListener') { - return this.$emit.apply(this, arguments); - } +SocketNamespace.prototype.emit = function ( name ) { + if ( name == 'newListener' ) { + return this.$emit.apply( this, arguments ); + } - return this.packet({ - type: 'event' - , name: name - , args: util.toArray(arguments).slice(1) - }); + return this.packet( { + type : 'event', name : name, args : util.toArray( arguments ).slice( 1 ) + } ); }; /** @@ -199,12 +196,12 @@ SocketNamespace.prototype.emit = function (name) { * @api public */ -SocketNamespace.prototype.socket = function (sid, readable) { - if (!this.sockets[sid]) { - this.sockets[sid] = new Socket(this.manager, sid, this, readable); - } +SocketNamespace.prototype.socket = function ( sid, readable ) { + if ( !this.sockets[sid] ) { + this.sockets[sid] = new Socket( this.manager, sid, this, readable ); + } - return this.sockets[sid]; + return this.sockets[sid]; }; /** @@ -213,9 +210,9 @@ SocketNamespace.prototype.socket = function (sid, readable) { * @api public */ -SocketNamespace.prototype.authorization = function (fn) { - this.auth = fn; - return this; +SocketNamespace.prototype.authorization = function ( fn ) { + this.auth = fn; + return this; }; /** @@ -224,11 +221,13 @@ SocketNamespace.prototype.authorization = function (fn) { * @api private */ -SocketNamespace.prototype.handleDisconnect = function (sid, reason, raiseOnDisconnect) { - if (this.sockets[sid] && this.sockets[sid].readable) { - if (raiseOnDisconnect) this.sockets[sid].onDisconnect(reason); - delete this.sockets[sid]; - } +SocketNamespace.prototype.handleDisconnect = function ( sid, reason, raiseOnDisconnect ) { + if ( this.sockets[sid] && this.sockets[sid].readable ) { + if ( raiseOnDisconnect ) { + this.sockets[sid].onDisconnect( reason ); + } + delete this.sockets[sid]; + } }; /** @@ -238,21 +237,21 @@ SocketNamespace.prototype.handleDisconnect = function (sid, reason, raiseOnDisco * @api private */ -SocketNamespace.prototype.authorize = function (data, fn) { - if (this.auth) { - var self = this; +SocketNamespace.prototype.authorize = function ( data, fn ) { + if ( this.auth ) { + var self = this; - this.auth.call(this, data, function (err, authorized) { - self.log.debug('client ' + - (authorized ? '' : 'un') + 'authorized for ' + self.name); - fn(err, authorized); - }); - } else { - this.log.debug('client authorized for ' + this.name); - fn(null, true); - } + this.auth.call( this, data, function ( err, authorized ) { + self.log.debug( 'client ' + + (authorized ? '' : 'un') + 'authorized for ' + self.name ); + fn( err, authorized ); + } ); + } else { + this.log.debug( 'client authorized for ' + this.name ); + fn( null, true ); + } - return this; + return this; }; /** @@ -261,95 +260,103 @@ SocketNamespace.prototype.authorize = function (data, fn) { * @api private */ -SocketNamespace.prototype.handlePacket = function (sessid, packet) { - var socket = this.socket(sessid) - , dataAck = packet.ack == 'data' - , manager = this.manager - , self = this; +SocketNamespace.prototype.handlePacket = function ( sessid, packet ) { + var socket = this.socket( sessid ) + , dataAck = packet.ack == 'data' + , manager = this.manager + , self = this; - function ack () { - self.log.debug('sending data ack packet'); - socket.packet({ - type: 'ack' - , args: util.toArray(arguments) - , ackId: packet.id - }); - }; + function ack() { + self.log.debug( 'sending data ack packet' ); + socket.packet( { + type : 'ack', args : util.toArray( arguments ), ackId : packet.id + } ); + } - function error (err) { - self.log.warn('handshake error ' + err + ' for ' + self.name); - socket.packet({ type: 'error', reason: err }); - }; + ; - function connect () { - self.manager.onJoin(sessid, self.name); - self.store.publish('join', sessid, self.name); + function error( err ) { + self.log.warn( 'handshake error ' + err + ' for ' + self.name ); + socket.packet( { type : 'error', reason : err } ); + } - // packet echo - socket.packet({ type: 'connect' }); + ; - // emit connection event - self.$emit('connection', socket); - }; + function connect() { + self.manager.onJoin( sessid, self.name ); + self.store.publish( 'join', sessid, self.name ); - switch (packet.type) { - case 'connect': - if (packet.endpoint == '') { - connect(); - } else { - var handshakeData = manager.handshaken[sessid]; + // packet echo + socket.packet( { type : 'connect' } ); - this.authorize(handshakeData, function (err, authorized, newData) { - if (err) return error(err); + // emit connection event + self.$emit( 'connection', socket ); + } - if (authorized) { - manager.onHandshake(sessid, newData || handshakeData); - self.store.publish('handshake', sessid, newData || handshakeData); - connect(); - } else { - error('unauthorized'); - } - }); - } - break; + ; - case 'ack': - if (socket.acks[packet.ackId]) { - socket.acks[packet.ackId].apply(socket, packet.args); - } else { - this.log.info('unknown ack packet'); - } - break; + switch ( packet.type ) { + case 'connect': + if ( packet.endpoint == '' ) { + connect(); + } else { + var handshakeData = manager.handshaken[sessid]; - case 'event': - // check if the emitted event is not blacklisted - if (-~manager.get('blacklist').indexOf(packet.name)) { - this.log.debug('ignoring blacklisted event `' + packet.name + '`'); - } else { - var params = [packet.name].concat(packet.args); + this.authorize( handshakeData, function ( err, authorized, newData ) { + if ( err ) { + return error( err ); + } - if (dataAck) { - params.push(ack); - } + if ( authorized ) { + manager.onHandshake( sessid, newData || handshakeData ); + self.store.publish( 'handshake', sessid, newData || handshakeData ); + connect(); + } else { + error( 'unauthorized' ); + } + } ); + } + break; - socket.$emit.apply(socket, params); - } - break; + case 'ack': + if ( socket.acks[packet.ackId] ) { + socket.acks[packet.ackId].apply( socket, packet.args ); + } else { + this.log.info( 'unknown ack packet' ); + } + break; - case 'disconnect': - this.manager.onLeave(sessid, this.name); - this.store.publish('leave', sessid, this.name); + case 'event': + // check if the emitted event is not blacklisted + if ( -~manager.get( 'blacklist' ).indexOf( packet.name ) ) { + this.log.debug( 'ignoring blacklisted event `' + packet.name + '`' ); + } else { + var params = [packet.name].concat( packet.args ); - socket.$emit('disconnect', packet.reason || 'packet'); - break; + if ( dataAck ) { + params.push( ack ); + } - case 'json': - case 'message': - var params = ['message', packet.data]; + socket.$emit.apply( socket, params ); + } + break; - if (dataAck) - params.push(ack); + case 'disconnect': + this.manager.onLeave( sessid, this.name ); + this.store.publish( 'leave', sessid, this.name ); - socket.$emit.apply(socket, params); - }; + socket.$emit( 'disconnect', packet.reason || 'packet' ); + break; + + case 'json': + case 'message': + var params = ['message', packet.data]; + + if ( dataAck ) { + params.push( ack ); + } + + socket.$emit.apply( socket, params ); + } + ; }; diff --git a/example/node/node_modules/socket.io/lib/parser.js b/example/node/node_modules/socket.io/lib/parser.js index d56b550..ffbb6bc 100644 --- a/example/node/node_modules/socket.io/lib/parser.js +++ b/example/node/node_modules/socket.io/lib/parser.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -14,37 +13,27 @@ */ var packets = exports.packets = { - 'disconnect': 0 - , 'connect': 1 - , 'heartbeat': 2 - , 'message': 3 - , 'json': 4 - , 'event': 5 - , 'ack': 6 - , 'error': 7 - , 'noop': 8 - } - , packetslist = Object.keys(packets); + 'disconnect' : 0, 'connect' : 1, 'heartbeat' : 2, 'message' : 3, 'json' : 4, 'event' : 5, 'ack' : 6, 'error' : 7, 'noop' : 8 + } + , packetslist = Object.keys( packets ); /** * Errors reasons. */ var reasons = exports.reasons = { - 'transport not supported': 0 - , 'client not handshaken': 1 - , 'unauthorized': 2 - } - , reasonslist = Object.keys(reasons); + 'transport not supported' : 0, 'client not handshaken' : 1, 'unauthorized' : 2 + } + , reasonslist = Object.keys( reasons ); /** * Errors advice. */ var advice = exports.advice = { - 'reconnect': 0 - } - , advicelist = Object.keys(advice); + 'reconnect' : 0 + } + , advicelist = Object.keys( advice ); /** * Encodes a packet. @@ -52,62 +41,66 @@ var advice = exports.advice = { * @api private */ -exports.encodePacket = function (packet) { - var type = packets[packet.type] - , id = packet.id || '' - , endpoint = packet.endpoint || '' - , ack = packet.ack - , data = null; +exports.encodePacket = function ( packet ) { + var type = packets[packet.type] + , id = packet.id || '' + , endpoint = packet.endpoint || '' + , ack = packet.ack + , data = null; - switch (packet.type) { - case 'message': - if (packet.data !== '') - data = packet.data; - break; + switch ( packet.type ) { + case 'message': + if ( packet.data !== '' ) { + data = packet.data; + } + break; - case 'event': - var ev = { name: packet.name }; + case 'event': + var ev = { name : packet.name }; - if (packet.args && packet.args.length) { - ev.args = packet.args; - } + if ( packet.args && packet.args.length ) { + ev.args = packet.args; + } - data = JSON.stringify(ev); - break; + data = JSON.stringify( ev ); + break; - case 'json': - data = JSON.stringify(packet.data); - break; + case 'json': + data = JSON.stringify( packet.data ); + break; - case 'ack': - data = packet.ackId - + (packet.args && packet.args.length - ? '+' + JSON.stringify(packet.args) : ''); - break; + case 'ack': + data = packet.ackId + + (packet.args && packet.args.length + ? '+' + JSON.stringify( packet.args ) : ''); + break; - case 'connect': - if (packet.qs) - data = packet.qs; - break; + case 'connect': + if ( packet.qs ) { + data = packet.qs; + } + break; - case 'error': - var reason = packet.reason ? reasons[packet.reason] : '' - , adv = packet.advice ? advice[packet.advice] : '' + case 'error': + var reason = packet.reason ? reasons[packet.reason] : '' + , adv = packet.advice ? advice[packet.advice] : '' - if (reason !== '' || adv !== '') - data = reason + (adv !== '' ? ('+' + adv) : '') + if ( reason !== '' || adv !== '' ) { + data = reason + (adv !== '' ? ('+' + adv) : '') + } - break; - } + break; + } - // construct packet with required fragments - var encoded = type + ':' + id + (ack == 'data' ? '+' : '') + ':' + endpoint; + // construct packet with required fragments + var encoded = type + ':' + id + (ack == 'data' ? '+' : '') + ':' + endpoint; - // data fragment is optional - if (data !== null && data !== undefined) - encoded += ':' + data; + // data fragment is optional + if ( data !== null && data !== undefined ) { + encoded += ':' + data; + } - return encoded; + return encoded; }; /** @@ -117,18 +110,19 @@ exports.encodePacket = function (packet) { * @api private */ -exports.encodePayload = function (packets) { - var decoded = ''; +exports.encodePayload = function ( packets ) { + var decoded = ''; - if (packets.length == 1) - return packets[0]; + if ( packets.length == 1 ) { + return packets[0]; + } - for (var i = 0, l = packets.length; i < l; i++) { - var packet = packets[i]; - decoded += '\ufffd' + packet.length + '\ufffd' + packets[i] - } + for ( var i = 0, l = packets.length; i < l; i++ ) { + var packet = packets[i]; + decoded += '\ufffd' + packet.length + '\ufffd' + packets[i] + } - return decoded; + return decoded; }; /** @@ -146,75 +140,82 @@ var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/; * @api private */ -function parse (data) { - try { return JSON.parse(data) } - catch (e) { return false } +function parse( data ) { + try { + return JSON.parse( data ) + } + catch ( e ) { + return false + } } -exports.decodePacket = function (data) { - var pieces = data.match(regexp); +exports.decodePacket = function ( data ) { + var pieces = data.match( regexp ); - if (!pieces) return {}; + if ( !pieces ) { + return {}; + } - var id = pieces[2] || '' - , data = pieces[5] || '' - , packet = { - type: packetslist[pieces[1]] - , endpoint: pieces[4] || '' - }; + var id = pieces[2] || '' + , data = pieces[5] || '' + , packet = { + type : packetslist[pieces[1]], endpoint : pieces[4] || '' + }; - // whether we need to acknowledge the packet - if (id) { - packet.id = id; - if (pieces[3]) - packet.ack = 'data'; - else - packet.ack = true; - } + // whether we need to acknowledge the packet + if ( id ) { + packet.id = id; + if ( pieces[3] ) { + packet.ack = 'data'; + } + else { + packet.ack = true; + } + } - // handle different packet types - switch (packet.type) { - case 'message': - packet.data = data || ''; - break; + // handle different packet types + switch ( packet.type ) { + case 'message': + packet.data = data || ''; + break; - case 'event': - pieces = parse(data); - if (pieces) { - packet.name = pieces.name; - packet.args = pieces.args; - } + case 'event': + pieces = parse( data ); + if ( pieces ) { + packet.name = pieces.name; + packet.args = pieces.args; + } - packet.args = packet.args || []; - break; + packet.args = packet.args || []; + break; - case 'json': - packet.data = parse(data); - break; + case 'json': + packet.data = parse( data ); + break; - case 'connect': - packet.qs = data || ''; - break; + case 'connect': + packet.qs = data || ''; + break; - case 'ack': - pieces = data.match(/^([0-9]+)(\+)?(.*)/); - if (pieces) { - packet.ackId = pieces[1]; - packet.args = []; + case 'ack': + pieces = data.match( /^([0-9]+)(\+)?(.*)/ ); + if ( pieces ) { + packet.ackId = pieces[1]; + packet.args = []; - if (pieces[3]) { - packet.args = parse(pieces[3]) || []; - } - } - break; + if ( pieces[3] ) { + packet.args = parse( pieces[3] ) || []; + } + } + break; - case 'error': - pieces = data.split('+'); - packet.reason = reasonslist[pieces[0]] || ''; - packet.advice = advicelist[pieces[1]] || ''; - } + case 'error': + pieces = data.split( '+' ); + packet.reason = reasonslist[pieces[0]] || ''; + packet.advice = advicelist[pieces[1]] || ''; + } - return packet; + return packet; }; /** @@ -224,26 +225,26 @@ exports.decodePacket = function (data) { * @api public */ -exports.decodePayload = function (data) { - if (undefined == data || null == data) { - return []; - } +exports.decodePayload = function ( data ) { + if ( undefined == data || null == data ) { + return []; + } - if (data[0] == '\ufffd') { - var ret = []; + if ( data[0] == '\ufffd' ) { + var ret = []; - for (var i = 1, length = ''; i < data.length; i++) { - if (data[i] == '\ufffd') { - ret.push(exports.decodePacket(data.substr(i + 1, length))); - i += Number(length) + 1; - length = ''; - } else { - length += data[i]; - } - } + for ( var i = 1, length = ''; i < data.length; i++ ) { + if ( data[i] == '\ufffd' ) { + ret.push( exports.decodePacket( data.substr( i + 1, length ) ) ); + i += Number( length ) + 1; + length = ''; + } else { + length += data[i]; + } + } - return ret; - } else { - return [exports.decodePacket(data)]; - } + return ret; + } else { + return [exports.decodePacket( data )]; + } }; diff --git a/example/node/node_modules/socket.io/lib/socket.io.js b/example/node/node_modules/socket.io/lib/socket.io.js index 824f6e8..45b7f4f 100644 --- a/example/node/node_modules/socket.io/lib/socket.io.js +++ b/example/node/node_modules/socket.io/lib/socket.io.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,7 +8,7 @@ * Module dependencies. */ -var client = require('socket.io-client'); +var client = require( 'socket.io-client' ); /** * Version. @@ -38,37 +37,39 @@ exports.clientVersion = client.version; * @api public */ -exports.listen = function (server, options, fn) { - if ('function' == typeof options) { - fn = options; - options = {}; - } +exports.listen = function ( server, options, fn ) { + if ( 'function' == typeof options ) { + fn = options; + options = {}; + } - if ('undefined' == typeof server) { - // create a server that listens on port 80 - server = 80; - } + if ( 'undefined' == typeof server ) { + // create a server that listens on port 80 + server = 80; + } - if ('number' == typeof server) { - // if a port number is passed - var port = server; + if ( 'number' == typeof server ) { + // if a port number is passed + var port = server; - if (options && options.key) - server = require('https').createServer(options); - else - server = require('http').createServer(); + if ( options && options.key ) { + server = require( 'https' ).createServer( options ); + } + else { + server = require( 'http' ).createServer(); + } - // default response - server.on('request', function (req, res) { - res.writeHead(200); - res.end('Welcome to socket.io.'); - }); + // default response + server.on( 'request', function ( req, res ) { + res.writeHead( 200 ); + res.end( 'Welcome to socket.io.' ); + } ); - server.listen(port, fn); - } + server.listen( port, fn ); + } - // otherwise assume a http/s server - return new exports.Manager(server, options); + // otherwise assume a http/s server + return new exports.Manager( server, options ); }; /** @@ -77,7 +78,7 @@ exports.listen = function (server, options, fn) { * @api public */ -exports.Manager = require('./manager'); +exports.Manager = require( './manager' ); /** * Transport constructor. @@ -85,7 +86,7 @@ exports.Manager = require('./manager'); * @api public */ -exports.Transport = require('./transport'); +exports.Transport = require( './transport' ); /** * Socket constructor. @@ -93,7 +94,7 @@ exports.Transport = require('./transport'); * @api public */ -exports.Socket = require('./socket'); +exports.Socket = require( './socket' ); /** * Static constructor. @@ -101,7 +102,7 @@ exports.Socket = require('./socket'); * @api public */ -exports.Static = require('./static'); +exports.Static = require( './static' ); /** * Store constructor. @@ -109,7 +110,7 @@ exports.Static = require('./static'); * @api public */ -exports.Store = require('./store'); +exports.Store = require( './store' ); /** * Memory Store constructor. @@ -117,7 +118,7 @@ exports.Store = require('./store'); * @api public */ -exports.MemoryStore = require('./stores/memory'); +exports.MemoryStore = require( './stores/memory' ); /** * Redis Store constructor. @@ -125,7 +126,7 @@ exports.MemoryStore = require('./stores/memory'); * @api public */ -exports.RedisStore = require('./stores/redis'); +exports.RedisStore = require( './stores/redis' ); /** * Parser. @@ -133,4 +134,4 @@ exports.RedisStore = require('./stores/redis'); * @api public */ -exports.parser = require('./parser'); +exports.parser = require( './parser' ); diff --git a/example/node/node_modules/socket.io/lib/socket.js b/example/node/node_modules/socket.io/lib/socket.js index 38542f4..2479c45 100644 --- a/example/node/node_modules/socket.io/lib/socket.js +++ b/example/node/node_modules/socket.io/lib/socket.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,9 +8,9 @@ * Module dependencies. */ -var parser = require('./parser') - , util = require('./util') - , EventEmitter = process.EventEmitter +var parser = require( './parser' ) + , util = require( './util' ) + , EventEmitter = process.EventEmitter /** * Export the constructor. @@ -23,7 +22,8 @@ exports = module.exports = Socket; * Default error event listener to prevent uncaught exceptions. */ -var defaultError = function () {}; +var defaultError = function () { +}; /** * Socket constructor. @@ -31,22 +31,23 @@ var defaultError = function () {}; * @param {Manager} manager instance * @param {String} session id * @param {Namespace} namespace the socket belongs to - * @param {Boolean} whether the + * @param {Boolean} whether the * @api public */ -function Socket (manager, id, nsp, readable) { - this.id = id; - this.namespace = nsp; - this.manager = manager; - this.disconnected = false; - this.ackPackets = 0; - this.acks = {}; - this.setFlags(); - this.readable = readable; - this.store = this.manager.store.client(this.id); - this.on('error', defaultError); -}; +function Socket( manager, id, nsp, readable ) { + this.id = id; + this.namespace = nsp; + this.manager = manager; + this.disconnected = false; + this.ackPackets = 0; + this.acks = {}; + this.setFlags(); + this.readable = readable; + this.store = this.manager.store.client( this.id ); + this.on( 'error', defaultError ); +} +; /** * Inherits from EventEmitter. @@ -60,9 +61,9 @@ Socket.prototype.__proto__ = EventEmitter.prototype; * @api private */ -Socket.prototype.__defineGetter__('handshake', function () { - return this.manager.handshaken[this.id]; -}); +Socket.prototype.__defineGetter__( 'handshake', function () { + return this.manager.handshaken[this.id]; +} ); /** * Accessor shortcut for the transport type @@ -70,9 +71,9 @@ Socket.prototype.__defineGetter__('handshake', function () { * @api private */ -Socket.prototype.__defineGetter__('transport', function () { - return this.manager.transports[this.id].name; -}); +Socket.prototype.__defineGetter__( 'transport', function () { + return this.manager.transports[this.id].name; +} ); /** * Accessor shortcut for the logger. @@ -80,9 +81,9 @@ Socket.prototype.__defineGetter__('transport', function () { * @api private */ -Socket.prototype.__defineGetter__('log', function () { - return this.manager.log; -}); +Socket.prototype.__defineGetter__( 'log', function () { + return this.manager.log; +} ); /** * JSON message flag. @@ -90,10 +91,10 @@ Socket.prototype.__defineGetter__('log', function () { * @api public */ -Socket.prototype.__defineGetter__('json', function () { - this.flags.json = true; - return this; -}); +Socket.prototype.__defineGetter__( 'json', function () { + this.flags.json = true; + return this; +} ); /** * Volatile message flag. @@ -101,10 +102,10 @@ Socket.prototype.__defineGetter__('json', function () { * @api public */ -Socket.prototype.__defineGetter__('volatile', function () { - this.flags.volatile = true; - return this; -}); +Socket.prototype.__defineGetter__( 'volatile', function () { + this.flags.volatile = true; + return this; +} ); /** * Broadcast message flag. @@ -112,10 +113,10 @@ Socket.prototype.__defineGetter__('volatile', function () { * @api public */ -Socket.prototype.__defineGetter__('broadcast', function () { - this.flags.broadcast = true; - return this; -}); +Socket.prototype.__defineGetter__( 'broadcast', function () { + this.flags.broadcast = true; + return this; +} ); /** * Overrides the room to broadcast messages to (flag) @@ -123,9 +124,9 @@ Socket.prototype.__defineGetter__('broadcast', function () { * @api public */ -Socket.prototype.to = Socket.prototype.in = function (room) { - this.flags.room = room; - return this; +Socket.prototype.to = Socket.prototype.in = function ( room ) { + this.flags.room = room; + return this; }; /** @@ -135,11 +136,10 @@ Socket.prototype.to = Socket.prototype.in = function (room) { */ Socket.prototype.setFlags = function () { - this.flags = { - endpoint: this.namespace.name - , room: '' - }; - return this; + this.flags = { + endpoint : this.namespace.name, room : '' + }; + return this; }; /** @@ -148,11 +148,11 @@ Socket.prototype.setFlags = function () { * @api private */ -Socket.prototype.onDisconnect = function (reason) { - if (!this.disconnected) { - this.$emit('disconnect', reason); - this.disconnected = true; - } +Socket.prototype.onDisconnect = function ( reason ) { + if ( !this.disconnected ) { + this.$emit( 'disconnect', reason ); + this.disconnected = true; + } }; /** @@ -161,19 +161,19 @@ Socket.prototype.onDisconnect = function (reason) { * @api public */ -Socket.prototype.join = function (name, fn) { - var nsp = this.namespace.name - , name = (nsp + '/') + name; +Socket.prototype.join = function ( name, fn ) { + var nsp = this.namespace.name + , name = (nsp + '/') + name; - this.manager.onJoin(this.id, name); - this.manager.store.publish('join', this.id, name); + this.manager.onJoin( this.id, name ); + this.manager.store.publish( 'join', this.id, name ); - if (fn) { - this.log.warn('Client#join callback is deprecated'); - fn(); - } + if ( fn ) { + this.log.warn( 'Client#join callback is deprecated' ); + fn(); + } - return this; + return this; }; /** @@ -182,19 +182,19 @@ Socket.prototype.join = function (name, fn) { * @api public */ -Socket.prototype.leave = function (name, fn) { - var nsp = this.namespace.name - , name = (nsp + '/') + name; +Socket.prototype.leave = function ( name, fn ) { + var nsp = this.namespace.name + , name = (nsp + '/') + name; - this.manager.onLeave(this.id, name); - this.manager.store.publish('leave', this.id, name); + this.manager.onLeave( this.id, name ); + this.manager.store.publish( 'leave', this.id, name ); - if (fn) { - this.log.warn('Client#leave callback is deprecated'); - fn(); - } + if ( fn ) { + this.log.warn( 'Client#leave callback is deprecated' ); + fn(); + } - return this; + return this; }; /** @@ -203,20 +203,20 @@ Socket.prototype.leave = function (name, fn) { * @api private */ -Socket.prototype.packet = function (packet) { - if (this.flags.broadcast) { - this.log.debug('broadcasting packet'); - this.namespace.in(this.flags.room).except(this.id).packet(packet); - } else { - packet.endpoint = this.flags.endpoint; - packet = parser.encodePacket(packet); +Socket.prototype.packet = function ( packet ) { + if ( this.flags.broadcast ) { + this.log.debug( 'broadcasting packet' ); + this.namespace.in( this.flags.room ).except( this.id ).packet( packet ); + } else { + packet.endpoint = this.flags.endpoint; + packet = parser.encodePacket( packet ); - this.dispatch(packet, this.flags.volatile); - } + this.dispatch( packet, this.flags.volatile ); + } - this.setFlags(); + this.setFlags(); - return this; + return this; }; /** @@ -225,16 +225,16 @@ Socket.prototype.packet = function (packet) { * @api private */ -Socket.prototype.dispatch = function (packet, volatile) { - if (this.manager.transports[this.id] && this.manager.transports[this.id].open) { - this.manager.transports[this.id].onDispatch(packet, volatile); - } else { - if (!volatile) { - this.manager.onClientDispatch(this.id, packet, volatile); - } +Socket.prototype.dispatch = function ( packet, volatile ) { + if ( this.manager.transports[this.id] && this.manager.transports[this.id].open ) { + this.manager.transports[this.id].onDispatch( packet, volatile ); + } else { + if ( !volatile ) { + this.manager.onClientDispatch( this.id, packet, volatile ); + } - this.manager.store.publish('dispatch:' + this.id, packet, volatile); - } + this.manager.store.publish( 'dispatch:' + this.id, packet, volatile ); + } }; /** @@ -243,9 +243,9 @@ Socket.prototype.dispatch = function (packet, volatile) { * @api public */ -Socket.prototype.set = function (key, value, fn) { - this.store.set(key, value, fn); - return this; +Socket.prototype.set = function ( key, value, fn ) { + this.store.set( key, value, fn ); + return this; }; /** @@ -254,9 +254,9 @@ Socket.prototype.set = function (key, value, fn) { * @api public */ -Socket.prototype.get = function (key, fn) { - this.store.get(key, fn); - return this; +Socket.prototype.get = function ( key, fn ) { + this.store.get( key, fn ); + return this; }; /** @@ -265,9 +265,9 @@ Socket.prototype.get = function (key, fn) { * @api public */ -Socket.prototype.has = function (key, fn) { - this.store.has(key, fn); - return this; +Socket.prototype.has = function ( key, fn ) { + this.store.has( key, fn ); + return this; }; /** @@ -276,9 +276,9 @@ Socket.prototype.has = function (key, fn) { * @api public */ -Socket.prototype.del = function (key, fn) { - this.store.del(key, fn); - return this; +Socket.prototype.del = function ( key, fn ) { + this.store.del( key, fn ); + return this; }; /** @@ -288,18 +288,18 @@ Socket.prototype.del = function (key, fn) { */ Socket.prototype.disconnect = function () { - if (!this.disconnected) { - this.log.info('booting client'); + if ( !this.disconnected ) { + this.log.info( 'booting client' ); - if (this.manager.transports[this.id] && this.manager.transports[this.id].open) { - this.manager.transports[this.id].onForcedDisconnect(); - } else { - this.manager.onClientDisconnect(this.id); - this.manager.store.publish('disconnect:' + this.id); - } - } + if ( this.manager.transports[this.id] && this.manager.transports[this.id].open ) { + this.manager.transports[this.id].onForcedDisconnect(); + } else { + this.manager.onClientDisconnect( this.id ); + this.manager.store.publish( 'disconnect:' + this.id ); + } + } - return this; + return this; }; /** @@ -308,19 +308,18 @@ Socket.prototype.disconnect = function () { * @api public */ -Socket.prototype.send = function (data, fn) { - var packet = { - type: this.flags.json ? 'json' : 'message' - , data: data - }; +Socket.prototype.send = function ( data, fn ) { + var packet = { + type : this.flags.json ? 'json' : 'message', data : data + }; - if (fn) { - packet.id = ++this.ackPackets; - packet.ack = true; - this.acks[packet.id] = fn; - } + if ( fn ) { + packet.id = ++this.ackPackets; + packet.ack = true; + this.acks[packet.id] = fn; + } - return this.packet(packet); + return this.packet( packet ); }; /** @@ -337,26 +336,25 @@ Socket.prototype.$emit = EventEmitter.prototype.emit; * @api public */ -Socket.prototype.emit = function (ev) { - if (ev == 'newListener') { - return this.$emit.apply(this, arguments); - } +Socket.prototype.emit = function ( ev ) { + if ( ev == 'newListener' ) { + return this.$emit.apply( this, arguments ); + } - var args = util.toArray(arguments).slice(1) - , lastArg = args[args.length - 1] - , packet = { - type: 'event' - , name: ev - }; + var args = util.toArray( arguments ).slice( 1 ) + , lastArg = args[args.length - 1] + , packet = { + type : 'event', name : ev + }; - if ('function' == typeof lastArg) { - packet.id = ++this.ackPackets; - packet.ack = lastArg.length ? 'data' : true; - this.acks[packet.id] = lastArg; - args = args.slice(0, args.length - 1); - } + if ( 'function' == typeof lastArg ) { + packet.id = ++this.ackPackets; + packet.ack = lastArg.length ? 'data' : true; + this.acks[packet.id] = lastArg; + args = args.slice( 0, args.length - 1 ); + } - packet.args = args; + packet.args = args; - return this.packet(packet); + return this.packet( packet ); }; diff --git a/example/node/node_modules/socket.io/lib/static.js b/example/node/node_modules/socket.io/lib/static.js index e3117ed..5df9ce4 100644 --- a/example/node/node_modules/socket.io/lib/static.js +++ b/example/node/node_modules/socket.io/lib/static.js @@ -1,18 +1,17 @@ - /*! -* socket.io-node -* Copyright(c) 2011 LearnBoost -* MIT Licensed -*/ + * socket.io-node + * Copyright(c) 2011 LearnBoost + * MIT Licensed + */ /** * Module dependencies. */ -var client = require('socket.io-client') - , cp = require('child_process') - , fs = require('fs') - , util = require('./util'); +var client = require( 'socket.io-client' ) + , cp = require( 'child_process' ) + , fs = require( 'fs' ) + , util = require( './util' ); /** * File type details. @@ -21,16 +20,11 @@ var client = require('socket.io-client') */ var mime = { - js: { - type: 'application/javascript' - , encoding: 'utf8' - , gzip: true - } - , swf: { - type: 'application/x-shockwave-flash' - , encoding: 'binary' - , gzip: false - } + js : { + type : 'application/javascript', encoding : 'utf8', gzip : true + }, swf : { + type : 'application/x-shockwave-flash', encoding : 'binary', gzip : false + } }; /** @@ -43,7 +37,7 @@ var mime = { */ var bundle = /\+((?:\+)?[\w\-]+)*(?:\.v\d+\.\d+\.\d+)?(?:\.js)$/ - , versioning = /\.v\d+\.\d+\.\d+(?:\.js)$/; + , versioning = /\.v\d+\.\d+\.\d+(?:\.js)$/; /** * Export the constructor @@ -57,12 +51,12 @@ exports = module.exports = Static; * @api public */ -function Static (manager) { - this.manager = manager; - this.cache = {}; - this.paths = {}; +function Static( manager ) { + this.manager = manager; + this.cache = {}; + this.paths = {}; - this.init(); + this.init(); } /** @@ -72,87 +66,92 @@ function Static (manager) { */ Static.prototype.init = function () { - /** - * Generates a unique id based the supplied transports array - * - * @param {Array} transports The array with transport types - * @api private - */ - function id (transports) { - var id = transports.join('').split('').map(function (char) { - return ('' + char.charCodeAt(0)).split('').pop(); - }).reduce(function (char, id) { - return char +id; - }); + /** + * Generates a unique id based the supplied transports array + * + * @param {Array} transports The array with transport types + * @api private + */ + function id( transports ) { + var id = transports.join( '' ).split( '' ).map( + function ( char ) { + return ('' + char.charCodeAt( 0 )).split( '' ).pop(); + } ).reduce( function ( char, id ) { + return char + id; + } ); - return client.version + ':' + id; - } + return client.version + ':' + id; + } - /** - * Generates a socket.io-client file based on the supplied transports. - * - * @param {Array} transports The array with transport types - * @param {Function} callback Callback for the static.write - * @api private - */ + /** + * Generates a socket.io-client file based on the supplied transports. + * + * @param {Array} transports The array with transport types + * @param {Function} callback Callback for the static.write + * @api private + */ - function build (transports, callback) { - client.builder(transports, { - minify: self.manager.enabled('browser client minification') - }, function (err, content) { - callback(err, content ? new Buffer(content) : null, id(transports)); - } - ); - } + function build( transports, callback ) { + client.builder( transports, { + minify : self.manager.enabled( 'browser client minification' ) + }, function ( err, content ) { + callback( err, content ? new Buffer( content ) : null, id( transports ) ); + } + ); + } - var self = this; + var self = this; - // add our default static files - this.add('/static/flashsocket/WebSocketMain.swf', { - file: client.dist + '/WebSocketMain.swf' - }); + // add our default static files + this.add( '/static/flashsocket/WebSocketMain.swf', { + file : client.dist + '/WebSocketMain.swf' + } ); - this.add('/static/flashsocket/WebSocketMainInsecure.swf', { - file: client.dist + '/WebSocketMainInsecure.swf' - }); + this.add( '/static/flashsocket/WebSocketMainInsecure.swf', { + file : client.dist + '/WebSocketMainInsecure.swf' + } ); - // generates dedicated build based on the available transports - this.add('/socket.io.js', function (path, callback) { - build(self.manager.get('transports'), callback); - }); + // generates dedicated build based on the available transports + this.add( '/socket.io.js', function ( path, callback ) { + build( self.manager.get( 'transports' ), callback ); + } ); - this.add('/socket.io.v', { mime: mime.js }, function (path, callback) { - build(self.manager.get('transports'), callback); - }); + this.add( '/socket.io.v', { mime : mime.js }, function ( path, callback ) { + build( self.manager.get( 'transports' ), callback ); + } ); - // allow custom builds based on url paths - this.add('/socket.io+', { mime: mime.js }, function (path, callback) { - var available = self.manager.get('transports') - , matches = path.match(bundle) - , transports = []; + // allow custom builds based on url paths + this.add( '/socket.io+', { mime : mime.js }, function ( path, callback ) { + var available = self.manager.get( 'transports' ) + , matches = path.match( bundle ) + , transports = []; - if (!matches) return callback('No valid transports'); + if ( !matches ) { + return callback( 'No valid transports' ); + } - // make sure they valid transports - matches[0].split('.')[0].split('+').slice(1).forEach(function (transport) { - if (!!~available.indexOf(transport)) { - transports.push(transport); - } - }); + // make sure they valid transports + matches[0].split( '.' )[0].split( '+' ).slice( 1 ).forEach( function ( transport ) { + if ( !!~available.indexOf( transport ) ) { + transports.push( transport ); + } + } ); - if (!transports.length) return callback('No valid transports'); - build(transports, callback); - }); + if ( !transports.length ) { + return callback( 'No valid transports' ); + } + build( transports, callback ); + } ); - // clear cache when transports change - this.manager.on('set:transports', function (key, value) { - delete self.cache['/socket.io.js']; - Object.keys(self.cache).forEach(function (key) { - if (bundle.test(key)) { - delete self.cache[key]; - } - }); - }); + // clear cache when transports change + this.manager.on( 'set:transports', function ( key, value ) { + delete self.cache['/socket.io.js']; + Object.keys( self.cache ).forEach( function ( key ) { + if ( bundle.test( key ) ) { + delete self.cache[key]; + } + } ); + } ); }; /** @@ -163,48 +162,50 @@ Static.prototype.init = function () { * @api public */ -Static.prototype.gzip = function (data, callback) { - var gzip = cp.spawn('gzip', ['-9', '-c', '-f', '-n']) - , encoding = Buffer.isBuffer(data) ? 'binary' : 'utf8' - , buffer = [] - , err; +Static.prototype.gzip = function ( data, callback ) { + var gzip = cp.spawn( 'gzip', ['-9', '-c', '-f', '-n'] ) + , encoding = Buffer.isBuffer( data ) ? 'binary' : 'utf8' + , buffer = [] + , err; - gzip.stdout.on('data', function (data) { - buffer.push(data); - }); + gzip.stdout.on( 'data', function ( data ) { + buffer.push( data ); + } ); - gzip.stderr.on('data', function (data) { - err = data +''; - buffer.length = 0; - }); + gzip.stderr.on( 'data', function ( data ) { + err = data + ''; + buffer.length = 0; + } ); - gzip.on('exit', function () { - if (err) return callback(err); + gzip.on( 'exit', function () { + if ( err ) { + return callback( err ); + } - var size = 0 - , index = 0 - , i = buffer.length - , content; + var size = 0 + , index = 0 + , i = buffer.length + , content; - while (i--) { - size += buffer[i].length; - } + while ( i-- ) { + size += buffer[i].length; + } - content = new Buffer(size); - i = buffer.length; + content = new Buffer( size ); + i = buffer.length; - buffer.forEach(function (buffer) { - var length = buffer.length; + buffer.forEach( function ( buffer ) { + var length = buffer.length; - buffer.copy(content, index, 0, length); - index += length; - }); + buffer.copy( content, index, 0, length ); + index += length; + } ); - buffer.length = 0; - callback(null, content); - }); + buffer.length = 0; + callback( null, content ); + } ); - gzip.stdin.end(data, encoding); + gzip.stdin.end( data, encoding ); }; /** @@ -214,18 +215,22 @@ Static.prototype.gzip = function (data, callback) { * @api public */ -Static.prototype.has = function (path) { - // fast case - if (this.paths[path]) return this.paths[path]; +Static.prototype.has = function ( path ) { + // fast case + if ( this.paths[path] ) { + return this.paths[path]; + } - var keys = Object.keys(this.paths) - , i = keys.length; - - while (i--) { - if (-~path.indexOf(keys[i])) return this.paths[keys[i]]; - } + var keys = Object.keys( this.paths ) + , i = keys.length; - return false; + while ( i-- ) { + if ( -~path.indexOf( keys[i] ) ) { + return this.paths[keys[i]]; + } + } + + return false; }; /** @@ -238,22 +243,26 @@ Static.prototype.has = function (path) { * @api public */ -Static.prototype.add = function (path, options, callback) { - var extension = /(?:\.(\w{1,4}))$/.exec(path); +Static.prototype.add = function ( path, options, callback ) { + var extension = /(?:\.(\w{1,4}))$/.exec( path ); - if (!callback && typeof options == 'function') { - callback = options; - options = {}; - } + if ( !callback && typeof options == 'function' ) { + callback = options; + options = {}; + } - options.mime = options.mime || (extension ? mime[extension[1]] : false); + options.mime = options.mime || (extension ? mime[extension[1]] : false); - if (callback) options.callback = callback; - if (!(options.file || options.callback) || !options.mime) return false; + if ( callback ) { + options.callback = callback; + } + if ( !(options.file || options.callback) || !options.mime ) { + return false; + } - this.paths[path] = options; + this.paths[path] = options; - return true; + return true; }; /** @@ -265,131 +274,127 @@ Static.prototype.add = function (path, options, callback) { * @api public */ -Static.prototype.write = function (path, req, res) { - /** - * Write a response without throwing errors because can throw error if the - * response is no longer writable etc. - * - * @api private - */ +Static.prototype.write = function ( path, req, res ) { + /** + * Write a response without throwing errors because can throw error if the + * response is no longer writable etc. + * + * @api private + */ - function write (status, headers, content, encoding) { - try { - res.writeHead(status, headers || undefined); + function write( status, headers, content, encoding ) { + try { + res.writeHead( status, headers || undefined ); - // only write content if it's not a HEAD request and we actually have - // some content to write (304's doesn't have content). - res.end( - req.method !== 'HEAD' && content ? content : '' - , encoding || undefined - ); - } catch (e) {} - } + // only write content if it's not a HEAD request and we actually have + // some content to write (304's doesn't have content). + res.end( + req.method !== 'HEAD' && content ? content : '' + , encoding || undefined + ); + } catch ( e ) { + } + } - /** - * Answers requests depending on the request properties and the reply object. - * - * @param {Object} reply The details and content to reply the response with - * @api private - */ + /** + * Answers requests depending on the request properties and the reply object. + * + * @param {Object} reply The details and content to reply the response with + * @api private + */ - function answer (reply) { - var cached = req.headers['if-none-match'] === reply.etag; - if (cached && self.manager.enabled('browser client etag')) { - return write(304); - } + function answer( reply ) { + var cached = req.headers['if-none-match'] === reply.etag; + if ( cached && self.manager.enabled( 'browser client etag' ) ) { + return write( 304 ); + } - var accept = req.headers['accept-encoding'] || '' - , gzip = !!~accept.toLowerCase().indexOf('gzip') - , mime = reply.mime - , versioned = reply.versioned - , headers = { - 'Content-Type': mime.type - }; + var accept = req.headers['accept-encoding'] || '' + , gzip = !!~accept.toLowerCase().indexOf( 'gzip' ) + , mime = reply.mime + , versioned = reply.versioned + , headers = { + 'Content-Type' : mime.type + }; - // check if we can add a etag - if (self.manager.enabled('browser client etag') && reply.etag && !versioned) { - headers['Etag'] = reply.etag; - } + // check if we can add a etag + if ( self.manager.enabled( 'browser client etag' ) && reply.etag && !versioned ) { + headers['Etag'] = reply.etag; + } - // see if we need to set Expire headers because the path is versioned - if (versioned) { - var expires = self.manager.get('browser client expires'); - headers['Cache-Control'] = 'private, x-gzip-ok="", max-age=' + expires; - headers['Date'] = new Date().toUTCString(); - headers['Expires'] = new Date(Date.now() + (expires * 1000)).toUTCString(); - } + // see if we need to set Expire headers because the path is versioned + if ( versioned ) { + var expires = self.manager.get( 'browser client expires' ); + headers['Cache-Control'] = 'private, x-gzip-ok="", max-age=' + expires; + headers['Date'] = new Date().toUTCString(); + headers['Expires'] = new Date( Date.now() + (expires * 1000) ).toUTCString(); + } - if (gzip && reply.gzip) { - headers['Content-Length'] = reply.gzip.length; - headers['Content-Encoding'] = 'gzip'; - headers['Vary'] = 'Accept-Encoding'; - write(200, headers, reply.gzip.content, mime.encoding); - } else { - headers['Content-Length'] = reply.length; - write(200, headers, reply.content, mime.encoding); - } + if ( gzip && reply.gzip ) { + headers['Content-Length'] = reply.gzip.length; + headers['Content-Encoding'] = 'gzip'; + headers['Vary'] = 'Accept-Encoding'; + write( 200, headers, reply.gzip.content, mime.encoding ); + } else { + headers['Content-Length'] = reply.length; + write( 200, headers, reply.content, mime.encoding ); + } - self.manager.log.debug('served static content ' + path); - } + self.manager.log.debug( 'served static content ' + path ); + } - var self = this - , details; + var self = this + , details; - // most common case first - if (this.manager.enabled('browser client cache') && this.cache[path]) { - return answer(this.cache[path]); - } else if (this.manager.get('browser client handler')) { - return this.manager.get('browser client handler').call(this, req, res); - } else if ((details = this.has(path))) { - /** - * A small helper function that will let us deal with fs and dynamic files - * - * @param {Object} err Optional error - * @param {Buffer} content The data - * @api private - */ + // most common case first + if ( this.manager.enabled( 'browser client cache' ) && this.cache[path] ) { + return answer( this.cache[path] ); + } else if ( this.manager.get( 'browser client handler' ) ) { + return this.manager.get( 'browser client handler' ).call( this, req, res ); + } else if ( (details = this.has( path )) ) { + /** + * A small helper function that will let us deal with fs and dynamic files + * + * @param {Object} err Optional error + * @param {Buffer} content The data + * @api private + */ - function ready (err, content, etag) { - if (err) { - self.manager.log.warn('Unable to serve file. ' + (err.message || err)); - return write(500, null, 'Error serving static ' + path); - } + function ready( err, content, etag ) { + if ( err ) { + self.manager.log.warn( 'Unable to serve file. ' + (err.message || err) ); + return write( 500, null, 'Error serving static ' + path ); + } - // store the result in the cache - var reply = self.cache[path] = { - content: content - , length: content.length - , mime: details.mime - , etag: etag || client.version - , versioned: versioning.test(path) - }; + // store the result in the cache + var reply = self.cache[path] = { + content : content, length : content.length, mime : details.mime, etag : etag || client.version, versioned : versioning.test( path ) + }; - // check if gzip is enabled - if (details.mime.gzip && self.manager.enabled('browser client gzip')) { - self.gzip(content, function (err, content) { - if (!err) { - reply.gzip = { - content: content - , length: content.length - } - } + // check if gzip is enabled + if ( details.mime.gzip && self.manager.enabled( 'browser client gzip' ) ) { + self.gzip( content, function ( err, content ) { + if ( !err ) { + reply.gzip = { + content : content, length : content.length + } + } - answer(reply); - }); - } else { - answer(reply); - } - } + answer( reply ); + } ); + } else { + answer( reply ); + } + } - if (details.file) { - fs.readFile(details.file, ready); - } else if(details.callback) { - details.callback.call(this, path, ready); - } else { - write(404, null, 'File handle not found'); - } - } else { - write(404, null, 'File not found'); - } + if ( details.file ) { + fs.readFile( details.file, ready ); + } else if ( details.callback ) { + details.callback.call( this, path, ready ); + } else { + write( 404, null, 'File handle not found' ); + } + } else { + write( 404, null, 'File not found' ); + } }; diff --git a/example/node/node_modules/socket.io/lib/store.js b/example/node/node_modules/socket.io/lib/store.js index 06c0389..e5451dd 100644 --- a/example/node/node_modules/socket.io/lib/store.js +++ b/example/node/node_modules/socket.io/lib/store.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -23,10 +22,11 @@ var EventEmitter = process.EventEmitter; * @api public */ -function Store (options) { - this.options = options; - this.clients = {}; -}; +function Store( options ) { + this.options = options; + this.clients = {}; +} +; /** * Inherit from EventEmitter. @@ -41,12 +41,12 @@ Store.prototype.__proto__ = EventEmitter.prototype; * @api public */ -Store.prototype.client = function (id) { - if (!this.clients[id]) { - this.clients[id] = new (this.constructor.Client)(this, id); - } +Store.prototype.client = function ( id ) { + if ( !this.clients[id] ) { + this.clients[id] = new (this.constructor.Client)( this, id ); + } - return this.clients[id]; + return this.clients[id]; }; /** @@ -57,13 +57,13 @@ Store.prototype.client = function (id) { * @api private */ -Store.prototype.destroyClient = function (id, expiration) { - if (this.clients[id]) { - this.clients[id].destroy(expiration); - delete this.clients[id]; - } +Store.prototype.destroyClient = function ( id, expiration ) { + if ( this.clients[id] ) { + this.clients[id].destroy( expiration ); + delete this.clients[id]; + } - return this; + return this; }; /** @@ -73,17 +73,17 @@ Store.prototype.destroyClient = function (id, expiration) { * @api private */ -Store.prototype.destroy = function (clientExpiration) { - var keys = Object.keys(this.clients) - , count = keys.length; +Store.prototype.destroy = function ( clientExpiration ) { + var keys = Object.keys( this.clients ) + , count = keys.length; - for (var i = 0, l = count; i < l; i++) { - this.destroyClient(keys[i], clientExpiration); - } + for ( var i = 0, l = count; i < l; i++ ) { + this.destroyClient( keys[i], clientExpiration ); + } - this.clients = {}; + this.clients = {}; - return this; + return this; }; /** @@ -92,7 +92,7 @@ Store.prototype.destroy = function (clientExpiration) { * @api public */ -Store.Client = function (store, id) { - this.store = store; - this.id = id; +Store.Client = function ( store, id ) { + this.store = store; + this.id = id; }; diff --git a/example/node/node_modules/socket.io/lib/stores/memory.js b/example/node/node_modules/socket.io/lib/stores/memory.js index 8b731a7..acc700a 100644 --- a/example/node/node_modules/socket.io/lib/stores/memory.js +++ b/example/node/node_modules/socket.io/lib/stores/memory.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,8 +8,8 @@ * Module dependencies. */ -var crypto = require('crypto') - , Store = require('../store'); +var crypto = require( 'crypto' ) + , Store = require( '../store' ); /** * Exports the constructor. @@ -25,9 +24,10 @@ Memory.Client = Client; * @api public */ -function Memory (opts) { - Store.call(this, opts); -}; +function Memory( opts ) { + Store.call( this, opts ); +} +; /** * Inherits from Store. @@ -41,7 +41,8 @@ Memory.prototype.__proto__ = Store.prototype; * @api private */ -Memory.prototype.publish = function () { }; +Memory.prototype.publish = function () { +}; /** * Subscribes to a channel @@ -49,7 +50,8 @@ Memory.prototype.publish = function () { }; * @api private */ -Memory.prototype.subscribe = function () { }; +Memory.prototype.subscribe = function () { +}; /** * Unsubscribes @@ -57,7 +59,8 @@ Memory.prototype.subscribe = function () { }; * @api private */ -Memory.prototype.unsubscribe = function () { }; +Memory.prototype.unsubscribe = function () { +}; /** * Client constructor @@ -65,10 +68,11 @@ Memory.prototype.unsubscribe = function () { }; * @api private */ -function Client () { - Store.Client.apply(this, arguments); - this.data = {}; -}; +function Client() { + Store.Client.apply( this, arguments ); + this.data = {}; +} +; /** * Inherits from Store.Client @@ -82,9 +86,9 @@ Client.prototype.__proto__ = Store.Client; * @api public */ -Client.prototype.get = function (key, fn) { - fn(null, this.data[key] === undefined ? null : this.data[key]); - return this; +Client.prototype.get = function ( key, fn ) { + fn( null, this.data[key] === undefined ? null : this.data[key] ); + return this; }; /** @@ -93,10 +97,10 @@ Client.prototype.get = function (key, fn) { * @api public */ -Client.prototype.set = function (key, value, fn) { - this.data[key] = value; - fn && fn(null); - return this; +Client.prototype.set = function ( key, value, fn ) { + this.data[key] = value; + fn && fn( null ); + return this; }; /** @@ -105,8 +109,8 @@ Client.prototype.set = function (key, value, fn) { * @api public */ -Client.prototype.has = function (key, fn) { - fn(null, key in this.data); +Client.prototype.has = function ( key, fn ) { + fn( null, key in this.data ); }; /** @@ -115,10 +119,10 @@ Client.prototype.has = function (key, fn) { * @api public */ -Client.prototype.del = function (key, fn) { - delete this.data[key]; - fn && fn(null); - return this; +Client.prototype.del = function ( key, fn ) { + delete this.data[key]; + fn && fn( null ); + return this; }; /** @@ -128,16 +132,16 @@ Client.prototype.del = function (key, fn) { * @api private */ -Client.prototype.destroy = function (expiration) { - if ('number' != typeof expiration) { - this.data = {}; - } else { - var self = this; +Client.prototype.destroy = function ( expiration ) { + if ( 'number' != typeof expiration ) { + this.data = {}; + } else { + var self = this; - setTimeout(function () { - self.data = {}; - }, expiration * 1000); - } + setTimeout( function () { + self.data = {}; + }, expiration * 1000 ); + } - return this; + return this; }; diff --git a/example/node/node_modules/socket.io/lib/stores/redis.js b/example/node/node_modules/socket.io/lib/stores/redis.js index 8fea235..1e36759 100644 --- a/example/node/node_modules/socket.io/lib/stores/redis.js +++ b/example/node/node_modules/socket.io/lib/stores/redis.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,9 +8,9 @@ * Module dependencies. */ -var crypto = require('crypto') - , Store = require('../store') - , assert = require('assert'); +var crypto = require( 'crypto' ) + , Store = require( '../store' ) + , assert = require( 'assert' ); /** * Exports the constructor. @@ -34,60 +33,61 @@ Redis.Client = Client; * @api public */ -function Redis (opts) { - opts = opts || {}; +function Redis( opts ) { + opts = opts || {}; - // node id to uniquely identify this node - var nodeId = opts.nodeId || function () { - // by default, we generate a random id - return Math.abs(Math.random() * Math.random() * Date.now() | 0); - }; + // node id to uniquely identify this node + var nodeId = opts.nodeId || function () { + // by default, we generate a random id + return Math.abs( Math.random() * Math.random() * Date.now() | 0 ); + }; - this.nodeId = nodeId(); + this.nodeId = nodeId(); - // packing / unpacking mechanism - if (opts.pack) { - this.pack = opts.pack; - this.unpack = opts.unpack; - } else { - try { - var msgpack = require('msgpack'); - this.pack = msgpack.pack; - this.unpack = msgpack.unpack; - } catch (e) { - this.pack = JSON.stringify; - this.unpack = JSON.parse; - } - } + // packing / unpacking mechanism + if ( opts.pack ) { + this.pack = opts.pack; + this.unpack = opts.unpack; + } else { + try { + var msgpack = require( 'msgpack' ); + this.pack = msgpack.pack; + this.unpack = msgpack.unpack; + } catch ( e ) { + this.pack = JSON.stringify; + this.unpack = JSON.parse; + } + } - var redis = opts.redis || require('redis') - , RedisClient = redis.RedisClient; + var redis = opts.redis || require( 'redis' ) + , RedisClient = redis.RedisClient; - // initialize a pubsub client and a regular client - if (opts.redisPub instanceof RedisClient) { - this.pub = opts.redisPub; - } else { - opts.redisPub || (opts.redisPub = {}); - this.pub = redis.createClient(opts.redisPub.port, opts.redisPub.host, opts.redisPub); - } - if (opts.redisSub instanceof RedisClient) { - this.sub = opts.redisSub; - } else { - opts.redisSub || (opts.redisSub = {}); - this.sub = redis.createClient(opts.redisSub.port, opts.redisSub.host, opts.redisSub); - } - if (opts.redisClient instanceof RedisClient) { - this.cmd = opts.redisClient; - } else { - opts.redisClient || (opts.redisClient = {}); - this.cmd = redis.createClient(opts.redisClient.port, opts.redisClient.host, opts.redisClient); - } + // initialize a pubsub client and a regular client + if ( opts.redisPub instanceof RedisClient ) { + this.pub = opts.redisPub; + } else { + opts.redisPub || (opts.redisPub = {}); + this.pub = redis.createClient( opts.redisPub.port, opts.redisPub.host, opts.redisPub ); + } + if ( opts.redisSub instanceof RedisClient ) { + this.sub = opts.redisSub; + } else { + opts.redisSub || (opts.redisSub = {}); + this.sub = redis.createClient( opts.redisSub.port, opts.redisSub.host, opts.redisSub ); + } + if ( opts.redisClient instanceof RedisClient ) { + this.cmd = opts.redisClient; + } else { + opts.redisClient || (opts.redisClient = {}); + this.cmd = redis.createClient( opts.redisClient.port, opts.redisClient.host, opts.redisClient ); + } - Store.call(this, opts); + Store.call( this, opts ); - this.sub.setMaxListeners(0); - this.setMaxListeners(0); -}; + this.sub.setMaxListeners( 0 ); + this.setMaxListeners( 0 ); +} +; /** * Inherits from Store. @@ -101,10 +101,10 @@ Redis.prototype.__proto__ = Store.prototype; * @api private */ -Redis.prototype.publish = function (name) { - var args = Array.prototype.slice.call(arguments, 1); - this.pub.publish(name, this.pack({ nodeId: this.nodeId, args: args })); - this.emit.apply(this, ['publish', name].concat(args)); +Redis.prototype.publish = function ( name ) { + var args = Array.prototype.slice.call( arguments, 1 ); + this.pub.publish( name, this.pack( { nodeId : this.nodeId, args : args } ) ); + this.emit.apply( this, ['publish', name].concat( args ) ); }; /** @@ -113,42 +113,44 @@ Redis.prototype.publish = function (name) { * @api private */ -Redis.prototype.subscribe = function (name, consumer, fn) { - this.sub.subscribe(name); +Redis.prototype.subscribe = function ( name, consumer, fn ) { + this.sub.subscribe( name ); - if (consumer || fn) { - var self = this; + if ( consumer || fn ) { + var self = this; - self.sub.on('subscribe', function subscribe (ch) { - if (name == ch) { - function message (ch, msg) { - if (name == ch) { - msg = self.unpack(msg); + self.sub.on( 'subscribe', function subscribe( ch ) { + if ( name == ch ) { + function message( ch, msg ) { + if ( name == ch ) { + msg = self.unpack( msg ); - // we check that the message consumed wasnt emitted by this node - if (self.nodeId != msg.nodeId) { - consumer.apply(null, msg.args); - } - } - }; + // we check that the message consumed wasnt emitted by this node + if ( self.nodeId != msg.nodeId ) { + consumer.apply( null, msg.args ); + } + } + } - self.sub.on('message', message); + ; - self.on('unsubscribe', function unsubscribe (ch) { - if (name == ch) { - self.sub.removeListener('message', message); - self.removeListener('unsubscribe', unsubscribe); - } - }); + self.sub.on( 'message', message ); - self.sub.removeListener('subscribe', subscribe); + self.on( 'unsubscribe', function unsubscribe( ch ) { + if ( name == ch ) { + self.sub.removeListener( 'message', message ); + self.removeListener( 'unsubscribe', unsubscribe ); + } + } ); - fn && fn(); - } - }); - } + self.sub.removeListener( 'subscribe', subscribe ); - this.emit('subscribe', name, consumer, fn); + fn && fn(); + } + } ); + } + + this.emit( 'subscribe', name, consumer, fn ); }; /** @@ -157,21 +159,21 @@ Redis.prototype.subscribe = function (name, consumer, fn) { * @api private */ -Redis.prototype.unsubscribe = function (name, fn) { - this.sub.unsubscribe(name); +Redis.prototype.unsubscribe = function ( name, fn ) { + this.sub.unsubscribe( name ); - if (fn) { - var client = this.sub; + if ( fn ) { + var client = this.sub; - client.on('unsubscribe', function unsubscribe (ch) { - if (name == ch) { - fn(); - client.removeListener('unsubscribe', unsubscribe); - } - }); - } + client.on( 'unsubscribe', function unsubscribe( ch ) { + if ( name == ch ) { + fn(); + client.removeListener( 'unsubscribe', unsubscribe ); + } + } ); + } - this.emit('unsubscribe', name, fn); + this.emit( 'unsubscribe', name, fn ); }; /** @@ -181,11 +183,11 @@ Redis.prototype.unsubscribe = function (name, fn) { */ Redis.prototype.destroy = function () { - Store.prototype.destroy.call(this); + Store.prototype.destroy.call( this ); - this.pub.end(); - this.sub.end(); - this.cmd.end(); + this.pub.end(); + this.sub.end(); + this.cmd.end(); }; /** @@ -194,9 +196,10 @@ Redis.prototype.destroy = function () { * @api private */ -function Client (store, id) { - Store.Client.call(this, store, id); -}; +function Client( store, id ) { + Store.Client.call( this, store, id ); +} +; /** * Inherits from Store.Client @@ -210,9 +213,9 @@ Client.prototype.__proto__ = Store.Client; * @api private */ -Client.prototype.get = function (key, fn) { - this.store.cmd.hget(this.id, key, fn); - return this; +Client.prototype.get = function ( key, fn ) { + this.store.cmd.hget( this.id, key, fn ); + return this; }; /** @@ -221,9 +224,9 @@ Client.prototype.get = function (key, fn) { * @api private */ -Client.prototype.set = function (key, value, fn) { - this.store.cmd.hset(this.id, key, value, fn); - return this; +Client.prototype.set = function ( key, value, fn ) { + this.store.cmd.hset( this.id, key, value, fn ); + return this; }; /** @@ -232,9 +235,9 @@ Client.prototype.set = function (key, value, fn) { * @api private */ -Client.prototype.del = function (key, fn) { - this.store.cmd.hdel(this.id, key, fn); - return this; +Client.prototype.del = function ( key, fn ) { + this.store.cmd.hdel( this.id, key, fn ); + return this; }; /** @@ -243,12 +246,14 @@ Client.prototype.del = function (key, fn) { * @api private */ -Client.prototype.has = function (key, fn) { - this.store.cmd.hexists(this.id, key, function (err, has) { - if (err) return fn(err); - fn(null, !!has); - }); - return this; +Client.prototype.has = function ( key, fn ) { + this.store.cmd.hexists( this.id, key, function ( err, has ) { + if ( err ) { + return fn( err ); + } + fn( null, !!has ); + } ); + return this; }; /** @@ -258,12 +263,12 @@ Client.prototype.has = function (key, fn) { * @api private */ -Client.prototype.destroy = function (expiration) { - if ('number' != typeof expiration) { - this.store.cmd.del(this.id); - } else { - this.store.cmd.expire(this.id, expiration); - } +Client.prototype.destroy = function ( expiration ) { + if ( 'number' != typeof expiration ) { + this.store.cmd.del( this.id ); + } else { + this.store.cmd.expire( this.id, expiration ); + } - return this; + return this; }; diff --git a/example/node/node_modules/socket.io/lib/transport.js b/example/node/node_modules/socket.io/lib/transport.js index 61f456f..e1c185d 100644 --- a/example/node/node_modules/socket.io/lib/transport.js +++ b/example/node/node_modules/socket.io/lib/transport.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,7 +8,7 @@ * Module dependencies. */ -var parser = require('./parser'); +var parser = require( './parser' ); /** * Expose the constructor. @@ -23,13 +22,14 @@ exports = module.exports = Transport; * @api public */ -function Transport (mng, data, req) { - this.manager = mng; - this.id = data.id; - this.disconnected = false; - this.drained = true; - this.handleRequest(req); -}; +function Transport( mng, data, req ) { + this.manager = mng; + this.id = data.id; + this.disconnected = false; + this.drained = true; + this.handleRequest( req ); +} +; /** * Access the logger. @@ -37,9 +37,9 @@ function Transport (mng, data, req) { * @api public */ -Transport.prototype.__defineGetter__('log', function () { - return this.manager.log; -}); +Transport.prototype.__defineGetter__( 'log', function () { + return this.manager.log; +} ); /** * Access the store. @@ -47,9 +47,9 @@ Transport.prototype.__defineGetter__('log', function () { * @api public */ -Transport.prototype.__defineGetter__('store', function () { - return this.manager.store; -}); +Transport.prototype.__defineGetter__( 'store', function () { + return this.manager.store; +} ); /** * Handles a request when it's set. @@ -57,19 +57,19 @@ Transport.prototype.__defineGetter__('store', function () { * @api private */ -Transport.prototype.handleRequest = function (req) { - this.log.debug('setting request', req.method, req.url); - this.req = req; +Transport.prototype.handleRequest = function ( req ) { + this.log.debug( 'setting request', req.method, req.url ); + this.req = req; - if (req.method == 'GET') { - this.socket = req.socket; - this.open = true; - this.drained = true; - this.setHeartbeatInterval(); + if ( req.method == 'GET' ) { + this.socket = req.socket; + this.open = true; + this.drained = true; + this.setHeartbeatInterval(); - this.setHandlers(); - this.onSocketConnect(); - } + this.setHandlers(); + this.onSocketConnect(); + } }; /** @@ -78,7 +78,8 @@ Transport.prototype.handleRequest = function (req) { * @api private */ -Transport.prototype.onSocketConnect = function () { }; +Transport.prototype.onSocketConnect = function () { +}; /** * Sets transport handlers @@ -87,35 +88,32 @@ Transport.prototype.onSocketConnect = function () { }; */ Transport.prototype.setHandlers = function () { - var self = this; + var self = this; - // we need to do this in a pub/sub way since the client can POST the message - // over a different socket (ie: different Transport instance) - this.store.subscribe('heartbeat-clear:' + this.id, function () { - self.onHeartbeatClear(); - }); + // we need to do this in a pub/sub way since the client can POST the message + // over a different socket (ie: different Transport instance) + this.store.subscribe( 'heartbeat-clear:' + this.id, function () { + self.onHeartbeatClear(); + } ); - this.store.subscribe('disconnect-force:' + this.id, function () { - self.onForcedDisconnect(); - }); + this.store.subscribe( 'disconnect-force:' + this.id, function () { + self.onForcedDisconnect(); + } ); - this.store.subscribe('dispatch:' + this.id, function (packet, volatile) { - self.onDispatch(packet, volatile); - }); + this.store.subscribe( 'dispatch:' + this.id, function ( packet, volatile ) { + self.onDispatch( packet, volatile ); + } ); - this.bound = { - end: this.onSocketEnd.bind(this) - , close: this.onSocketClose.bind(this) - , error: this.onSocketError.bind(this) - , drain: this.onSocketDrain.bind(this) - }; + this.bound = { + end : this.onSocketEnd.bind( this ), close : this.onSocketClose.bind( this ), error : this.onSocketError.bind( this ), drain : this.onSocketDrain.bind( this ) + }; - this.socket.on('end', this.bound.end); - this.socket.on('close', this.bound.close); - this.socket.on('error', this.bound.error); - this.socket.on('drain', this.bound.drain); + this.socket.on( 'end', this.bound.end ); + this.socket.on( 'close', this.bound.close ); + this.socket.on( 'error', this.bound.error ); + this.socket.on( 'drain', this.bound.drain ); - this.handlersSet = true; + this.handlersSet = true; }; /** @@ -125,16 +123,16 @@ Transport.prototype.setHandlers = function () { */ Transport.prototype.clearHandlers = function () { - if (this.handlersSet) { - this.store.unsubscribe('disconnect-force:' + this.id); - this.store.unsubscribe('heartbeat-clear:' + this.id); - this.store.unsubscribe('dispatch:' + this.id); + if ( this.handlersSet ) { + this.store.unsubscribe( 'disconnect-force:' + this.id ); + this.store.unsubscribe( 'heartbeat-clear:' + this.id ); + this.store.unsubscribe( 'dispatch:' + this.id ); - this.socket.removeListener('end', this.bound.end); - this.socket.removeListener('close', this.bound.close); - this.socket.removeListener('error', this.bound.error); - this.socket.removeListener('drain', this.bound.drain); - } + this.socket.removeListener( 'end', this.bound.end ); + this.socket.removeListener( 'close', this.bound.close ); + this.socket.removeListener( 'error', this.bound.error ); + this.socket.removeListener( 'drain', this.bound.drain ); + } }; /** @@ -144,7 +142,7 @@ Transport.prototype.clearHandlers = function () { */ Transport.prototype.onSocketEnd = function () { - this.end('socket end'); + this.end( 'socket end' ); }; /** @@ -153,8 +151,8 @@ Transport.prototype.onSocketEnd = function () { * @api private */ -Transport.prototype.onSocketClose = function (error) { - this.end(error ? 'socket error' : 'socket close'); +Transport.prototype.onSocketClose = function ( error ) { + this.end( error ? 'socket error' : 'socket close' ); }; /** @@ -163,13 +161,13 @@ Transport.prototype.onSocketClose = function (error) { * @api private */ -Transport.prototype.onSocketError = function (err) { - if (this.open) { - this.socket.destroy(); - this.onClose(); - } +Transport.prototype.onSocketError = function ( err ) { + if ( this.open ) { + this.socket.destroy(); + this.onClose(); + } - this.log.info('socket error ' + err.stack); + this.log.info( 'socket error ' + err.stack ); }; /** @@ -179,7 +177,7 @@ Transport.prototype.onSocketError = function (err) { */ Transport.prototype.onSocketDrain = function () { - this.drained = true; + this.drained = true; }; /** @@ -189,8 +187,8 @@ Transport.prototype.onSocketDrain = function () { */ Transport.prototype.onHeartbeatClear = function () { - this.clearHeartbeatTimeout(); - this.setHeartbeatInterval(); + this.clearHeartbeatTimeout(); + this.setHeartbeatInterval(); }; /** @@ -200,13 +198,13 @@ Transport.prototype.onHeartbeatClear = function () { */ Transport.prototype.onForcedDisconnect = function () { - if (!this.disconnected) { - this.log.info('transport end by forced client disconnection'); - if (this.open) { - this.packet({ type: 'disconnect' }); - } - this.end('booted'); - } + if ( !this.disconnected ) { + this.log.info( 'transport end by forced client disconnection' ); + if ( this.open ) { + this.packet( { type : 'disconnect' } ); + } + this.end( 'booted' ); + } }; /** @@ -215,12 +213,12 @@ Transport.prototype.onForcedDisconnect = function () { * @api private */ -Transport.prototype.onDispatch = function (packet, volatile) { - if (volatile) { - this.writeVolatile(packet); - } else { - this.write(packet); - } +Transport.prototype.onDispatch = function ( packet, volatile ) { + if ( volatile ) { + this.writeVolatile( packet ); + } else { + this.write( packet ); + } }; /** @@ -228,17 +226,17 @@ Transport.prototype.onDispatch = function (packet, volatile) { */ Transport.prototype.setCloseTimeout = function () { - if (!this.closeTimeout) { - var self = this; + if ( !this.closeTimeout ) { + var self = this; - this.closeTimeout = setTimeout(function () { - self.log.debug('fired close timeout for client', self.id); - self.closeTimeout = null; - self.end('close timeout'); - }, this.manager.get('close timeout') * 1000); + this.closeTimeout = setTimeout( function () { + self.log.debug( 'fired close timeout for client', self.id ); + self.closeTimeout = null; + self.end( 'close timeout' ); + }, this.manager.get( 'close timeout' ) * 1000 ); - this.log.debug('set close timeout for client', this.id); - } + this.log.debug( 'set close timeout for client', this.id ); + } }; /** @@ -246,12 +244,12 @@ Transport.prototype.setCloseTimeout = function () { */ Transport.prototype.clearCloseTimeout = function () { - if (this.closeTimeout) { - clearTimeout(this.closeTimeout); - this.closeTimeout = null; + if ( this.closeTimeout ) { + clearTimeout( this.closeTimeout ); + this.closeTimeout = null; - this.log.debug('cleared close timeout for client', this.id); - } + this.log.debug( 'cleared close timeout for client', this.id ); + } }; /** @@ -259,17 +257,17 @@ Transport.prototype.clearCloseTimeout = function () { */ Transport.prototype.setHeartbeatTimeout = function () { - if (!this.heartbeatTimeout && this.manager.enabled('heartbeats')) { - var self = this; + if ( !this.heartbeatTimeout && this.manager.enabled( 'heartbeats' ) ) { + var self = this; - this.heartbeatTimeout = setTimeout(function () { - self.log.debug('fired heartbeat timeout for client', self.id); - self.heartbeatTimeout = null; - self.end('heartbeat timeout'); - }, this.manager.get('heartbeat timeout') * 1000); + this.heartbeatTimeout = setTimeout( function () { + self.log.debug( 'fired heartbeat timeout for client', self.id ); + self.heartbeatTimeout = null; + self.end( 'heartbeat timeout' ); + }, this.manager.get( 'heartbeat timeout' ) * 1000 ); - this.log.debug('set heartbeat timeout for client', this.id); - } + this.log.debug( 'set heartbeat timeout for client', this.id ); + } }; /** @@ -279,11 +277,11 @@ Transport.prototype.setHeartbeatTimeout = function () { */ Transport.prototype.clearHeartbeatTimeout = function () { - if (this.heartbeatTimeout && this.manager.enabled('heartbeats')) { - clearTimeout(this.heartbeatTimeout); - this.heartbeatTimeout = null; - this.log.debug('cleared heartbeat timeout for client', this.id); - } + if ( this.heartbeatTimeout && this.manager.enabled( 'heartbeats' ) ) { + clearTimeout( this.heartbeatTimeout ); + this.heartbeatTimeout = null; + this.log.debug( 'cleared heartbeat timeout for client', this.id ); + } }; /** @@ -294,16 +292,16 @@ Transport.prototype.clearHeartbeatTimeout = function () { */ Transport.prototype.setHeartbeatInterval = function () { - if (!this.heartbeatInterval && this.manager.enabled('heartbeats')) { - var self = this; + if ( !this.heartbeatInterval && this.manager.enabled( 'heartbeats' ) ) { + var self = this; - this.heartbeatInterval = setTimeout(function () { - self.heartbeat(); - self.heartbeatInterval = null; - }, this.manager.get('heartbeat interval') * 1000); + this.heartbeatInterval = setTimeout( function () { + self.heartbeat(); + self.heartbeatInterval = null; + }, this.manager.get( 'heartbeat interval' ) * 1000 ); - this.log.debug('set heartbeat interval for client', this.id); - } + this.log.debug( 'set heartbeat interval for client', this.id ); + } }; /** @@ -313,9 +311,9 @@ Transport.prototype.setHeartbeatInterval = function () { */ Transport.prototype.clearTimeouts = function () { - this.clearCloseTimeout(); - this.clearHeartbeatTimeout(); - this.clearHeartbeatInterval(); + this.clearCloseTimeout(); + this.clearHeartbeatTimeout(); + this.clearHeartbeatInterval(); }; /** @@ -325,13 +323,13 @@ Transport.prototype.clearTimeouts = function () { */ Transport.prototype.heartbeat = function () { - if (this.open) { - this.log.debug('emitting heartbeat for client', this.id); - this.packet({ type: 'heartbeat' }); - this.setHeartbeatTimeout(); - } + if ( this.open ) { + this.log.debug( 'emitting heartbeat for client', this.id ); + this.packet( { type : 'heartbeat' } ); + this.setHeartbeatTimeout(); + } - return this; + return this; }; /** @@ -341,54 +339,52 @@ Transport.prototype.heartbeat = function () { * @api private */ -Transport.prototype.onMessage = function (packet) { - var current = this.manager.transports[this.id]; +Transport.prototype.onMessage = function ( packet ) { + var current = this.manager.transports[this.id]; - if ('heartbeat' == packet.type) { - this.log.debug('got heartbeat packet'); + if ( 'heartbeat' == packet.type ) { + this.log.debug( 'got heartbeat packet' ); - if (current && current.open) { - current.onHeartbeatClear(); - } else { - this.store.publish('heartbeat-clear:' + this.id); - } - } else { - if ('disconnect' == packet.type && packet.endpoint == '') { - this.log.debug('got disconnection packet'); + if ( current && current.open ) { + current.onHeartbeatClear(); + } else { + this.store.publish( 'heartbeat-clear:' + this.id ); + } + } else { + if ( 'disconnect' == packet.type && packet.endpoint == '' ) { + this.log.debug( 'got disconnection packet' ); - if (current) { - current.onForcedDisconnect(); - } else { - this.store.publish('disconnect-force:' + this.id); - } + if ( current ) { + current.onForcedDisconnect(); + } else { + this.store.publish( 'disconnect-force:' + this.id ); + } - return; - } + return; + } - if (packet.id && packet.ack != 'data') { - this.log.debug('acknowledging packet automatically'); + if ( packet.id && packet.ack != 'data' ) { + this.log.debug( 'acknowledging packet automatically' ); - var ack = parser.encodePacket({ - type: 'ack' - , ackId: packet.id - , endpoint: packet.endpoint || '' - }); + var ack = parser.encodePacket( { + type : 'ack', ackId : packet.id, endpoint : packet.endpoint || '' + } ); - if (current && current.open) { - current.onDispatch(ack); - } else { - this.manager.onClientDispatch(this.id, ack); - this.store.publish('dispatch:' + this.id, ack); - } - } + if ( current && current.open ) { + current.onDispatch( ack ); + } else { + this.manager.onClientDispatch( this.id, ack ); + this.store.publish( 'dispatch:' + this.id, ack ); + } + } - // handle packet locally or publish it - if (current) { - this.manager.onClientMessage(this.id, packet); - } else { - this.store.publish('message:' + this.id, packet); - } - } + // handle packet locally or publish it + if ( current ) { + this.manager.onClientMessage( this.id, packet ); + } else { + this.store.publish( 'message:' + this.id, packet ); + } + } }; /** @@ -398,11 +394,11 @@ Transport.prototype.onMessage = function (packet) { */ Transport.prototype.clearHeartbeatInterval = function () { - if (this.heartbeatInterval && this.manager.enabled('heartbeats')) { - clearTimeout(this.heartbeatInterval); - this.heartbeatInterval = null; - this.log.debug('cleared heartbeat interval for client', this.id); - } + if ( this.heartbeatInterval && this.manager.enabled( 'heartbeats' ) ) { + clearTimeout( this.heartbeatInterval ); + this.heartbeatInterval = null; + this.log.debug( 'cleared heartbeat interval for client', this.id ); + } }; /** @@ -411,11 +407,11 @@ Transport.prototype.clearHeartbeatInterval = function () { * @api private */ -Transport.prototype.disconnect = function (reason) { - this.packet({ type: 'disconnect' }); - this.end(reason); +Transport.prototype.disconnect = function ( reason ) { + this.packet( { type : 'disconnect' } ); + this.end( reason ); - return this; + return this; }; /** @@ -425,10 +421,10 @@ Transport.prototype.disconnect = function (reason) { */ Transport.prototype.close = function () { - if (this.open) { - this.doClose(); - this.onClose(); - } + if ( this.open ) { + this.doClose(); + this.onClose(); + } }; /** @@ -438,13 +434,13 @@ Transport.prototype.close = function () { */ Transport.prototype.onClose = function () { - if (this.open) { - this.setCloseTimeout(); - this.clearHandlers(); - this.open = false; - this.manager.onClose(this.id); - this.store.publish('close', this.id); - } + if ( this.open ) { + this.setCloseTimeout(); + this.clearHandlers(); + this.open = false; + this.manager.onClose( this.id ); + this.store.publish( 'close', this.id ); + } }; /** @@ -453,22 +449,22 @@ Transport.prototype.onClose = function () { * @api private */ -Transport.prototype.end = function (reason) { - if (!this.disconnected) { - this.log.info('transport end'); +Transport.prototype.end = function ( reason ) { + if ( !this.disconnected ) { + this.log.info( 'transport end' ); - var local = this.manager.transports[this.id]; + var local = this.manager.transports[this.id]; - this.close(); - this.clearTimeouts(); - this.disconnected = true; + this.close(); + this.clearTimeouts(); + this.disconnected = true; - if (local) { - this.manager.onClientDisconnect(this.id, reason, true); - } else { - this.store.publish('disconnect:' + this.id, reason); - } - } + if ( local ) { + this.manager.onClientDisconnect( this.id, reason, true ); + } else { + this.store.publish( 'disconnect:' + this.id, reason ); + } + } }; /** @@ -478,12 +474,12 @@ Transport.prototype.end = function (reason) { */ Transport.prototype.discard = function () { - this.log.debug('discarding transport'); - this.discarded = true; - this.clearTimeouts(); - this.clearHandlers(); + this.log.debug( 'discarding transport' ); + this.discarded = true; + this.clearTimeouts(); + this.clearHandlers(); - return this; + return this; }; /** @@ -494,15 +490,13 @@ Transport.prototype.discard = function () { * @api public */ -Transport.prototype.error = function (reason, advice) { - this.packet({ - type: 'error' - , reason: reason - , advice: advice - }); +Transport.prototype.error = function ( reason, advice ) { + this.packet( { + type : 'error', reason : reason, advice : advice + } ); - this.log.warn(reason, advice ? ('client should ' + advice) : ''); - this.end('error'); + this.log.warn( reason, advice ? ('client should ' + advice) : '' ); + this.end( 'error' ); }; /** @@ -511,8 +505,8 @@ Transport.prototype.error = function (reason, advice) { * @api public */ -Transport.prototype.packet = function (obj) { - return this.write(parser.encodePacket(obj)); +Transport.prototype.packet = function ( obj ) { + return this.write( parser.encodePacket( obj ) ); }; /** @@ -521,14 +515,14 @@ Transport.prototype.packet = function (obj) { * @api private */ -Transport.prototype.writeVolatile = function (msg) { - if (this.open) { - if (this.drained) { - this.write(msg); - } else { - this.log.debug('ignoring volatile packet, buffer not drained'); - } - } else { - this.log.debug('ignoring volatile packet, transport not open'); - } +Transport.prototype.writeVolatile = function ( msg ) { + if ( this.open ) { + if ( this.drained ) { + this.write( msg ); + } else { + this.log.debug( 'ignoring volatile packet, buffer not drained' ); + } + } else { + this.log.debug( 'ignoring volatile packet, transport not open' ); + } }; diff --git a/example/node/node_modules/socket.io/lib/transports/flashsocket.js b/example/node/node_modules/socket.io/lib/transports/flashsocket.js index d79363d..b32925b 100644 --- a/example/node/node_modules/socket.io/lib/transports/flashsocket.js +++ b/example/node/node_modules/socket.io/lib/transports/flashsocket.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -8,7 +7,7 @@ /** * Module requirements. */ -var WebSocket = require('./websocket'); +var WebSocket = require( './websocket' ); /** * Export the constructor. @@ -22,9 +21,9 @@ exports = module.exports = FlashSocket; * * @api public */ - -function FlashSocket (mng, data, req) { - return WebSocket.call(this, mng, data, req); + +function FlashSocket( mng, data, req ) { + return WebSocket.call( this, mng, data, req ); } /** @@ -50,57 +49,63 @@ FlashSocket.prototype.name = 'flashsocket'; */ -FlashSocket.init = function (manager) { - var server; - function create () { - server = require('policyfile').createServer({ - log: function(msg){ - manager.log.info(msg.toLowerCase()); - } - }, manager.get('origins')); +FlashSocket.init = function ( manager ) { + var server; - server.on('close', function (e) { - server = null; - }); + function create() { + server = require( 'policyfile' ).createServer( { + log : function ( msg ) { + manager.log.info( msg.toLowerCase() ); + } + }, manager.get( 'origins' ) ); - server.listen(manager.get('flash policy port'), manager.server); + server.on( 'close', function ( e ) { + server = null; + } ); - manager.flashPolicyServer = server; - } + server.listen( manager.get( 'flash policy port' ), manager.server ); - // listen for origin changes, so we can update the server - manager.on('set:origins', function (value, key) { - if (!server) return; + manager.flashPolicyServer = server; + } - // update the origins and compile a new response buffer - server.origins = Array.isArray(value) ? value : [value]; - server.compile(); - }); + // listen for origin changes, so we can update the server + manager.on( 'set:origins', function ( value, key ) { + if ( !server ) { + return; + } - // destory the server and create a new server - manager.on('set:flash policy port', function (value, key) { - var transports = manager.get('transports'); - if (~transports.indexOf('flashsocket')) { - if (server) { - if (server.port === value) return; - // destroy the server and rebuild it on a new port - try { - server.close(); - } - catch (e) { /* ignore exception. could e.g. be that the server isn't started yet */ } - } - create(); - } - }); + // update the origins and compile a new response buffer + server.origins = Array.isArray( value ) ? value : [value]; + server.compile(); + } ); - // only start the server - manager.on('set:transports', function (value, key){ - if (!server && ~manager.get('transports').indexOf('flashsocket')) { - create(); - } - }); - // check if we need to initialize at start - if (~manager.get('transports').indexOf('flashsocket')){ - create(); - } + // destory the server and create a new server + manager.on( 'set:flash policy port', function ( value, key ) { + var transports = manager.get( 'transports' ); + if ( ~transports.indexOf( 'flashsocket' ) ) { + if ( server ) { + if ( server.port === value ) { + return; + } + // destroy the server and rebuild it on a new port + try { + server.close(); + } + catch ( e ) { /* ignore exception. could e.g. be that the server isn't started yet */ + } + } + create(); + } + } ); + + // only start the server + manager.on( 'set:transports', function ( value, key ) { + if ( !server && ~manager.get( 'transports' ).indexOf( 'flashsocket' ) ) { + create(); + } + } ); + // check if we need to initialize at start + if ( ~manager.get( 'transports' ).indexOf( 'flashsocket' ) ) { + create(); + } }; diff --git a/example/node/node_modules/socket.io/lib/transports/htmlfile.js b/example/node/node_modules/socket.io/lib/transports/htmlfile.js index e8709a3..2a98d2c 100644 --- a/example/node/node_modules/socket.io/lib/transports/htmlfile.js +++ b/example/node/node_modules/socket.io/lib/transports/htmlfile.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,7 +8,7 @@ * Module requirements. */ -var HTTPTransport = require('./http'); +var HTTPTransport = require( './http' ); /** * Export the constructor. @@ -23,9 +22,10 @@ exports = module.exports = HTMLFile; * @api public */ -function HTMLFile (mng, data, req) { - HTTPTransport.call(this, mng, data, req); -}; +function HTMLFile( mng, data, req ) { + HTTPTransport.call( this, mng, data, req ); +} +; /** * Inherits from Transport. @@ -47,22 +47,20 @@ HTMLFile.prototype.name = 'htmlfile'; * @api private */ -HTMLFile.prototype.handleRequest = function (req) { - HTTPTransport.prototype.handleRequest.call(this, req); +HTMLFile.prototype.handleRequest = function ( req ) { + HTTPTransport.prototype.handleRequest.call( this, req ); - if (req.method == 'GET') { - req.res.writeHead(200, { - 'Content-Type': 'text/html; charset=UTF-8' - , 'Connection': 'keep-alive' - , 'Transfer-Encoding': 'chunked' - }); + if ( req.method == 'GET' ) { + req.res.writeHead( 200, { + 'Content-Type' : 'text/html; charset=UTF-8', 'Connection' : 'keep-alive', 'Transfer-Encoding' : 'chunked' + } ); - req.res.write( - '' - + '' - + new Array(174).join(' ') - ); - } + req.res.write( + '' + + '' + + new Array( 174 ).join( ' ' ) + ); + } }; /** @@ -71,12 +69,12 @@ HTMLFile.prototype.handleRequest = function (req) { * @api private */ -HTMLFile.prototype.write = function (data) { - data = ''; +HTMLFile.prototype.write = function ( data ) { + data = ''; - if (this.response.write(data)) { - this.drained = true; - } + if ( this.response.write( data ) ) { + this.drained = true; + } - this.log.debug(this.name + ' writing', data); + this.log.debug( this.name + ' writing', data ); }; diff --git a/example/node/node_modules/socket.io/lib/transports/http-polling.js b/example/node/node_modules/socket.io/lib/transports/http-polling.js index c71fc9c..e8cebe6 100644 --- a/example/node/node_modules/socket.io/lib/transports/http-polling.js +++ b/example/node/node_modules/socket.io/lib/transports/http-polling.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,7 +8,7 @@ * Module requirements. */ -var HTTPTransport = require('./http'); +var HTTPTransport = require( './http' ); /** * Exports the constructor. @@ -23,9 +22,10 @@ exports = module.exports = HTTPPolling; * @api public. */ -function HTTPPolling (mng, data, req) { - HTTPTransport.call(this, mng, data, req); -}; +function HTTPPolling( mng, data, req ) { + HTTPTransport.call( this, mng, data, req ); +} +; /** * Inherits from HTTPTransport. @@ -48,7 +48,7 @@ HTTPPolling.prototype.name = 'httppolling'; */ HTTPPolling.prototype.setHeartbeatInterval = function () { - return this; + return this; }; /** @@ -57,19 +57,19 @@ HTTPPolling.prototype.setHeartbeatInterval = function () { * @api private */ -HTTPPolling.prototype.handleRequest = function (req) { - HTTPTransport.prototype.handleRequest.call(this, req); +HTTPPolling.prototype.handleRequest = function ( req ) { + HTTPTransport.prototype.handleRequest.call( this, req ); - if (req.method == 'GET') { - var self = this; + if ( req.method == 'GET' ) { + var self = this; - this.pollTimeout = setTimeout(function () { - self.packet({ type: 'noop' }); - self.log.debug(self.name + ' closed due to exceeded duration'); - }, this.manager.get('polling duration') * 1000); + this.pollTimeout = setTimeout( function () { + self.packet( { type : 'noop' } ); + self.log.debug( self.name + ' closed due to exceeded duration' ); + }, this.manager.get( 'polling duration' ) * 1000 ); - this.log.debug('setting poll timeout'); - } + this.log.debug( 'setting poll timeout' ); + } }; /** @@ -79,13 +79,13 @@ HTTPPolling.prototype.handleRequest = function (req) { */ HTTPPolling.prototype.clearPollTimeout = function () { - if (this.pollTimeout) { - clearTimeout(this.pollTimeout); - this.pollTimeout = null; - this.log.debug('clearing poll timeout'); - } + if ( this.pollTimeout ) { + clearTimeout( this.pollTimeout ); + this.pollTimeout = null; + this.log.debug( 'clearing poll timeout' ); + } - return this; + return this; }; /** @@ -95,9 +95,9 @@ HTTPPolling.prototype.clearPollTimeout = function () { */ HTTPPolling.prototype.clearTimeouts = function () { - HTTPTransport.prototype.clearTimeouts.call(this); + HTTPTransport.prototype.clearTimeouts.call( this ); - this.clearPollTimeout(); + this.clearPollTimeout(); }; /** @@ -107,7 +107,7 @@ HTTPPolling.prototype.clearTimeouts = function () { */ HTTPPolling.prototype.doWrite = function () { - this.clearPollTimeout(); + this.clearPollTimeout(); }; /** @@ -116,10 +116,10 @@ HTTPPolling.prototype.doWrite = function () { * @api private. */ -HTTPPolling.prototype.write = function (data, close) { - this.doWrite(data); - this.response.end(); - this.onClose(); +HTTPPolling.prototype.write = function ( data, close ) { + this.doWrite( data ); + this.response.end(); + this.onClose(); }; /** @@ -129,7 +129,7 @@ HTTPPolling.prototype.write = function (data, close) { */ HTTPPolling.prototype.end = function () { - this.clearPollTimeout(); - return HTTPTransport.prototype.end.call(this); + this.clearPollTimeout(); + return HTTPTransport.prototype.end.call( this ); }; diff --git a/example/node/node_modules/socket.io/lib/transports/http.js b/example/node/node_modules/socket.io/lib/transports/http.js index 5144db8..eebba25 100644 --- a/example/node/node_modules/socket.io/lib/transports/http.js +++ b/example/node/node_modules/socket.io/lib/transports/http.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,9 +8,9 @@ * Module requirements. */ -var Transport = require('../transport') - , parser = require('../parser') - , qs = require('querystring'); +var Transport = require( '../transport' ) + , parser = require( '../parser' ) + , qs = require( 'querystring' ); /** * Export the constructor. @@ -25,9 +24,10 @@ exports = module.exports = HTTPTransport; * @api public */ -function HTTPTransport (mng, data, req) { - Transport.call(this, mng, data, req); -}; +function HTTPTransport( mng, data, req ) { + Transport.call( this, mng, data, req ); +} +; /** * Inherits from Transport. @@ -41,45 +41,45 @@ HTTPTransport.prototype.__proto__ = Transport.prototype; * @api private */ -HTTPTransport.prototype.handleRequest = function (req) { - if (req.method == 'POST') { - var buffer = '' - , res = req.res - , origin = req.headers.origin - , headers = { 'Content-Length': 1, 'Content-Type': 'text/plain; charset=UTF-8' } - , self = this; +HTTPTransport.prototype.handleRequest = function ( req ) { + if ( req.method == 'POST' ) { + var buffer = '' + , res = req.res + , origin = req.headers.origin + , headers = { 'Content-Length' : 1, 'Content-Type' : 'text/plain; charset=UTF-8' } + , self = this; - req.on('data', function (data) { - buffer += data; + req.on( 'data', function ( data ) { + buffer += data; - if (Buffer.byteLength(buffer) >= self.manager.get('destroy buffer size')) { - buffer = ''; - req.connection.destroy(); - } - }); + if ( Buffer.byteLength( buffer ) >= self.manager.get( 'destroy buffer size' ) ) { + buffer = ''; + req.connection.destroy(); + } + } ); - req.on('end', function () { - res.writeHead(200, headers); - res.end('1'); + req.on( 'end', function () { + res.writeHead( 200, headers ); + res.end( '1' ); - self.onData(self.postEncoded ? qs.parse(buffer).d : buffer); - }); + self.onData( self.postEncoded ? qs.parse( buffer ).d : buffer ); + } ); - // prevent memory leaks for uncompleted requests - req.on('close', function () { - buffer = ''; - }); + // prevent memory leaks for uncompleted requests + req.on( 'close', function () { + buffer = ''; + } ); - if (origin) { - // https://developer.mozilla.org/En/HTTP_Access_Control - headers['Access-Control-Allow-Origin'] = origin; - headers['Access-Control-Allow-Credentials'] = 'true'; - } - } else { - this.response = req.res; + if ( origin ) { + // https://developer.mozilla.org/En/HTTP_Access_Control + headers['Access-Control-Allow-Origin'] = origin; + headers['Access-Control-Allow-Credentials'] = 'true'; + } + } else { + this.response = req.res; - Transport.prototype.handleRequest.call(this, req); - } + Transport.prototype.handleRequest.call( this, req ); + } }; /** @@ -88,13 +88,13 @@ HTTPTransport.prototype.handleRequest = function (req) { * @api private */ -HTTPTransport.prototype.onData = function (data) { - var messages = parser.decodePayload(data); - this.log.debug(this.name + ' received data packet', data); +HTTPTransport.prototype.onData = function ( data ) { + var messages = parser.decodePayload( data ); + this.log.debug( this.name + ' received data packet', data ); - for (var i = 0, l = messages.length; i < l; i++) { - this.onMessage(messages[i]); - } + for ( var i = 0, l = messages.length; i < l; i++ ) { + this.onMessage( messages[i] ); + } }; /** @@ -104,7 +104,7 @@ HTTPTransport.prototype.onData = function (data) { */ HTTPTransport.prototype.doClose = function () { - this.response.end(); + this.response.end(); }; /** @@ -113,6 +113,6 @@ HTTPTransport.prototype.doClose = function () { * @api private */ -HTTPTransport.prototype.payload = function (msgs) { - this.write(parser.encodePayload(msgs)); +HTTPTransport.prototype.payload = function ( msgs ) { + this.write( parser.encodePayload( msgs ) ); }; diff --git a/example/node/node_modules/socket.io/lib/transports/index.js b/example/node/node_modules/socket.io/lib/transports/index.js index b865559..a100fd6 100644 --- a/example/node/node_modules/socket.io/lib/transports/index.js +++ b/example/node/node_modules/socket.io/lib/transports/index.js @@ -1,12 +1,7 @@ - /** * Export transports. */ module.exports = { - websocket: require('./websocket') - , flashsocket: require('./flashsocket') - , htmlfile: require('./htmlfile') - , 'xhr-polling': require('./xhr-polling') - , 'jsonp-polling': require('./jsonp-polling') + websocket : require( './websocket' ), flashsocket : require( './flashsocket' ), htmlfile : require( './htmlfile' ), 'xhr-polling' : require( './xhr-polling' ), 'jsonp-polling' : require( './jsonp-polling' ) }; diff --git a/example/node/node_modules/socket.io/lib/transports/jsonp-polling.js b/example/node/node_modules/socket.io/lib/transports/jsonp-polling.js index 83d11b8..424d42c 100644 --- a/example/node/node_modules/socket.io/lib/transports/jsonp-polling.js +++ b/example/node/node_modules/socket.io/lib/transports/jsonp-polling.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,7 +8,7 @@ * Module requirements. */ -var HTTPPolling = require('./http-polling'); +var HTTPPolling = require( './http-polling' ); /** * Export the constructor. @@ -23,16 +22,17 @@ exports = module.exports = JSONPPolling; * @api public */ -function JSONPPolling (mng, data, req) { - HTTPPolling.call(this, mng, data, req); +function JSONPPolling( mng, data, req ) { + HTTPPolling.call( this, mng, data, req ); - this.head = 'io.j[0]('; - this.foot = ');'; + this.head = 'io.j[0]('; + this.foot = ');'; - if (data.query.i) { - this.head = 'io.j[' + data.query.i + ']('; - } -}; + if ( data.query.i ) { + this.head = 'io.j[' + data.query.i + ']('; + } +} +; /** * Inherits from Transport. @@ -61,15 +61,15 @@ JSONPPolling.prototype.postEncoded = true; * @api private */ -JSONPPolling.prototype.onData = function (data) { - try { - data = JSON.parse(data); - } catch (e) { - this.error('parse', 'reconnect'); - return; - } +JSONPPolling.prototype.onData = function ( data ) { + try { + data = JSON.parse( data ); + } catch ( e ) { + this.error( 'parse', 'reconnect' ); + return; + } - HTTPPolling.prototype.onData.call(this, data); + HTTPPolling.prototype.onData.call( this, data ); }; /** @@ -78,19 +78,16 @@ JSONPPolling.prototype.onData = function (data) { * @api private */ -JSONPPolling.prototype.doWrite = function (data) { - HTTPPolling.prototype.doWrite.call(this); +JSONPPolling.prototype.doWrite = function ( data ) { + HTTPPolling.prototype.doWrite.call( this ); - var data = data === undefined - ? '' : this.head + JSON.stringify(data) + this.foot; + var data = data === undefined + ? '' : this.head + JSON.stringify( data ) + this.foot; - this.response.writeHead(200, { - 'Content-Type': 'text/javascript; charset=UTF-8' - , 'Content-Length': Buffer.byteLength(data) - , 'Connection': 'Keep-Alive' - , 'X-XSS-Protection': '0' - }); + this.response.writeHead( 200, { + 'Content-Type' : 'text/javascript; charset=UTF-8', 'Content-Length' : Buffer.byteLength( data ), 'Connection' : 'Keep-Alive', 'X-XSS-Protection' : '0' + } ); - this.response.write(data); - this.log.debug(this.name + ' writing', data); + this.response.write( data ); + this.log.debug( this.name + ' writing', data ); }; diff --git a/example/node/node_modules/socket.io/lib/transports/websocket.js b/example/node/node_modules/socket.io/lib/transports/websocket.js index 78a4304..de2b65d 100644 --- a/example/node/node_modules/socket.io/lib/transports/websocket.js +++ b/example/node/node_modules/socket.io/lib/transports/websocket.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,7 +8,7 @@ * Module requirements. */ -var protocolVersions = require('./websocket/'); +var protocolVersions = require( './websocket/' ); /** * Export the constructor. @@ -24,13 +23,18 @@ exports = module.exports = WebSocket; * @api public */ -function WebSocket (mng, data, req) { - var transport - , version = req.headers['sec-websocket-version']; - if (typeof version !== 'undefined' && typeof protocolVersions[version] !== 'undefined') { - transport = new protocolVersions[version](mng, data, req); - } - else transport = new protocolVersions['default'](mng, data, req); - if (typeof this.name !== 'undefined') transport.name = this.name; - return transport; -}; +function WebSocket( mng, data, req ) { + var transport + , version = req.headers['sec-websocket-version']; + if ( typeof version !== 'undefined' && typeof protocolVersions[version] !== 'undefined' ) { + transport = new protocolVersions[version]( mng, data, req ); + } + else { + transport = new protocolVersions['default']( mng, data, req ); + } + if ( typeof this.name !== 'undefined' ) { + transport.name = this.name; + } + return transport; +} +; diff --git a/example/node/node_modules/socket.io/lib/transports/websocket/default.js b/example/node/node_modules/socket.io/lib/transports/websocket/default.js index 2e861a7..238e867 100644 --- a/example/node/node_modules/socket.io/lib/transports/websocket/default.js +++ b/example/node/node_modules/socket.io/lib/transports/websocket/default.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,10 +8,10 @@ * Module requirements. */ -var Transport = require('../../transport') - , EventEmitter = process.EventEmitter - , crypto = require('crypto') - , parser = require('../../parser'); +var Transport = require( '../../transport' ) + , EventEmitter = process.EventEmitter + , crypto = require( 'crypto' ) + , parser = require( '../../parser' ); /** * Export the constructor. @@ -27,24 +26,25 @@ exports = module.exports = WebSocket; * @api public */ -function WebSocket (mng, data, req) { - // parser - var self = this; +function WebSocket( mng, data, req ) { + // parser + var self = this; - this.parser = new Parser(); - this.parser.on('data', function (packet) { - self.log.debug(self.name + ' received data packet', packet); - self.onMessage(parser.decodePacket(packet)); - }); - this.parser.on('close', function () { - self.end(); - }); - this.parser.on('error', function () { - self.end(); - }); + this.parser = new Parser(); + this.parser.on( 'data', function ( packet ) { + self.log.debug( self.name + ' received data packet', packet ); + self.onMessage( parser.decodePacket( packet ) ); + } ); + this.parser.on( 'close', function () { + self.end(); + } ); + this.parser.on( 'error', function () { + self.end(); + } ); - Transport.call(this, mng, data, req); -}; + Transport.call( this, mng, data, req ); +} +; /** * Inherits from Transport. @@ -75,97 +75,97 @@ WebSocket.prototype.protocolVersion = 'hixie-76'; */ WebSocket.prototype.onSocketConnect = function () { - var self = this; + var self = this; - this.socket.setNoDelay(true); + this.socket.setNoDelay( true ); - this.buffer = true; - this.buffered = []; + this.buffer = true; + this.buffered = []; - if (this.req.headers.upgrade !== 'WebSocket') { - this.log.warn(this.name + ' connection invalid'); - this.end(); - return; - } + if ( this.req.headers.upgrade !== 'WebSocket' ) { + this.log.warn( this.name + ' connection invalid' ); + this.end(); + return; + } - var origin = this.req.headers['origin'] - , location = ((this.manager.settings['match origin protocol'] ? - origin.match(/^https/) : this.socket.encrypted) ? - 'wss' : 'ws') - + '://' + this.req.headers.host + this.req.url - , waitingForNonce = false; + var origin = this.req.headers['origin'] + , location = ((this.manager.settings['match origin protocol'] ? + origin.match( /^https/ ) : this.socket.encrypted) ? + 'wss' : 'ws') + + '://' + this.req.headers.host + this.req.url + , waitingForNonce = false; - if (this.req.headers['sec-websocket-key1']) { - // If we don't have the nonce yet, wait for it (HAProxy compatibility). - if (! (this.req.head && this.req.head.length >= 8)) { - waitingForNonce = true; - } + if ( this.req.headers['sec-websocket-key1'] ) { + // If we don't have the nonce yet, wait for it (HAProxy compatibility). + if ( !(this.req.head && this.req.head.length >= 8) ) { + waitingForNonce = true; + } - var headers = [ - 'HTTP/1.1 101 WebSocket Protocol Handshake' - , 'Upgrade: WebSocket' - , 'Connection: Upgrade' - , 'Sec-WebSocket-Origin: ' + origin - , 'Sec-WebSocket-Location: ' + location - ]; + var headers = [ + 'HTTP/1.1 101 WebSocket Protocol Handshake' + , 'Upgrade: WebSocket' + , 'Connection: Upgrade' + , 'Sec-WebSocket-Origin: ' + origin + , 'Sec-WebSocket-Location: ' + location + ]; - if (this.req.headers['sec-websocket-protocol']){ - headers.push('Sec-WebSocket-Protocol: ' - + this.req.headers['sec-websocket-protocol']); - } - } else { - var headers = [ - 'HTTP/1.1 101 Web Socket Protocol Handshake' - , 'Upgrade: WebSocket' - , 'Connection: Upgrade' - , 'WebSocket-Origin: ' + origin - , 'WebSocket-Location: ' + location - ]; - } + if ( this.req.headers['sec-websocket-protocol'] ) { + headers.push( 'Sec-WebSocket-Protocol: ' + + this.req.headers['sec-websocket-protocol'] ); + } + } else { + var headers = [ + 'HTTP/1.1 101 Web Socket Protocol Handshake' + , 'Upgrade: WebSocket' + , 'Connection: Upgrade' + , 'WebSocket-Origin: ' + origin + , 'WebSocket-Location: ' + location + ]; + } - try { - this.socket.write(headers.concat('', '').join('\r\n')); - this.socket.setTimeout(0); - this.socket.setNoDelay(true); - this.socket.setEncoding('utf8'); - } catch (e) { - this.end(); - return; - } + try { + this.socket.write( headers.concat( '', '' ).join( '\r\n' ) ); + this.socket.setTimeout( 0 ); + this.socket.setNoDelay( true ); + this.socket.setEncoding( 'utf8' ); + } catch ( e ) { + this.end(); + return; + } - if (waitingForNonce) { - this.socket.setEncoding('binary'); - } else if (this.proveReception(headers)) { - self.flush(); - } + if ( waitingForNonce ) { + this.socket.setEncoding( 'binary' ); + } else if ( this.proveReception( headers ) ) { + self.flush(); + } - var headBuffer = ''; + var headBuffer = ''; - this.socket.on('data', function (data) { - if (waitingForNonce) { - headBuffer += data; + this.socket.on( 'data', function ( data ) { + if ( waitingForNonce ) { + headBuffer += data; - if (headBuffer.length < 8) { - return; - } + if ( headBuffer.length < 8 ) { + return; + } - // Restore the connection to utf8 encoding after receiving the nonce - self.socket.setEncoding('utf8'); - waitingForNonce = false; + // Restore the connection to utf8 encoding after receiving the nonce + self.socket.setEncoding( 'utf8' ); + waitingForNonce = false; - // Stuff the nonce into the location where it's expected to be - self.req.head = headBuffer.substr(0, 8); - headBuffer = ''; + // Stuff the nonce into the location where it's expected to be + self.req.head = headBuffer.substr( 0, 8 ); + headBuffer = ''; - if (self.proveReception(headers)) { - self.flush(); - } + if ( self.proveReception( headers ) ) { + self.flush(); + } - return; - } + return; + } - self.parser.add(data); - }); + self.parser.add( data ); + } ); }; /** @@ -174,32 +174,32 @@ WebSocket.prototype.onSocketConnect = function () { * @api private */ -WebSocket.prototype.write = function (data) { - if (this.open) { - this.drained = false; +WebSocket.prototype.write = function ( data ) { + if ( this.open ) { + this.drained = false; - if (this.buffer) { - this.buffered.push(data); - return this; - } + if ( this.buffer ) { + this.buffered.push( data ); + return this; + } - var length = Buffer.byteLength(data) - , buffer = new Buffer(2 + length); + var length = Buffer.byteLength( data ) + , buffer = new Buffer( 2 + length ); - buffer.write('\x00', 'binary'); - buffer.write(data, 1, 'utf8'); - buffer.write('\xff', 1 + length, 'binary'); + buffer.write( '\x00', 'binary' ); + buffer.write( data, 1, 'utf8' ); + buffer.write( '\xff', 1 + length, 'binary' ); - try { - if (this.socket.write(buffer)) { - this.drained = true; - } - } catch (e) { - this.end(); - } + try { + if ( this.socket.write( buffer ) ) { + this.drained = true; + } + } catch ( e ) { + this.end(); + } - this.log.debug(this.name + ' writing', data); - } + this.log.debug( this.name + ' writing', data ); + } }; /** @@ -209,11 +209,11 @@ WebSocket.prototype.write = function (data) { */ WebSocket.prototype.flush = function () { - this.buffer = false; + this.buffer = false; - for (var i = 0, l = this.buffered.length; i < l; i++) { - this.write(this.buffered.splice(0, 1)[0]); - } + for ( var i = 0, l = this.buffered.length; i < l; i++ ) { + this.write( this.buffered.splice( 0, 1 )[0] ); + } }; /** @@ -222,43 +222,43 @@ WebSocket.prototype.flush = function () { * @api private */ -WebSocket.prototype.proveReception = function (headers) { - var self = this - , k1 = this.req.headers['sec-websocket-key1'] - , k2 = this.req.headers['sec-websocket-key2']; +WebSocket.prototype.proveReception = function ( headers ) { + var self = this + , k1 = this.req.headers['sec-websocket-key1'] + , k2 = this.req.headers['sec-websocket-key2']; - if (k1 && k2){ - var md5 = crypto.createHash('md5'); + if ( k1 && k2 ) { + var md5 = crypto.createHash( 'md5' ); - [k1, k2].forEach(function (k) { - var n = parseInt(k.replace(/[^\d]/g, '')) - , spaces = k.replace(/[^ ]/g, '').length; + [k1, k2].forEach( function ( k ) { + var n = parseInt( k.replace( /[^\d]/g, '' ) ) + , spaces = k.replace( /[^ ]/g, '' ).length; - if (spaces === 0 || n % spaces !== 0){ - self.log.warn('Invalid ' + self.name + ' key: "' + k + '".'); - self.end(); - return false; - } + if ( spaces === 0 || n % spaces !== 0 ) { + self.log.warn( 'Invalid ' + self.name + ' key: "' + k + '".' ); + self.end(); + return false; + } - n /= spaces; + n /= spaces; - md5.update(String.fromCharCode( - n >> 24 & 0xFF, - n >> 16 & 0xFF, - n >> 8 & 0xFF, - n & 0xFF)); - }); + md5.update( String.fromCharCode( + n >> 24 & 0xFF, + n >> 16 & 0xFF, + n >> 8 & 0xFF, + n & 0xFF ) ); + } ); - md5.update(this.req.head.toString('binary')); + md5.update( this.req.head.toString( 'binary' ) ); - try { - this.socket.write(md5.digest('binary'), 'binary'); - } catch (e) { - this.end(); - } - } + try { + this.socket.write( md5.digest( 'binary' ), 'binary' ); + } catch ( e ) { + this.end(); + } + } - return true; + return true; }; /** @@ -267,12 +267,12 @@ WebSocket.prototype.proveReception = function (headers) { * @api private */ -WebSocket.prototype.payload = function (msgs) { - for (var i = 0, l = msgs.length; i < l; i++) { - this.write(msgs[i]); - } +WebSocket.prototype.payload = function ( msgs ) { + for ( var i = 0, l = msgs.length; i < l; i++ ) { + this.write( msgs[i] ); + } - return this; + return this; }; /** @@ -282,7 +282,7 @@ WebSocket.prototype.payload = function (msgs) { */ WebSocket.prototype.doClose = function () { - this.socket.end(); + this.socket.end(); }; /** @@ -291,10 +291,11 @@ WebSocket.prototype.doClose = function () { * @api public */ -function Parser () { - this.buffer = ''; - this.i = 0; -}; +function Parser() { + this.buffer = ''; + this.i = 0; +} +; /** * Inherits from EventEmitter. @@ -308,9 +309,9 @@ Parser.prototype.__proto__ = EventEmitter.prototype; * @api public */ -Parser.prototype.add = function (data) { - this.buffer += data; - this.parse(); +Parser.prototype.add = function ( data ) { + this.buffer += data; + this.parse(); }; /** @@ -320,30 +321,32 @@ Parser.prototype.add = function (data) { */ Parser.prototype.parse = function () { - for (var i = this.i, chr, l = this.buffer.length; i < l; i++){ - chr = this.buffer[i]; + for ( var i = this.i, chr, l = this.buffer.length; i < l; i++ ) { + chr = this.buffer[i]; - if (this.buffer.length == 2 && this.buffer[1] == '\u0000') { - this.emit('close'); - this.buffer = ''; - this.i = 0; - return; - } + if ( this.buffer.length == 2 && this.buffer[1] == '\u0000' ) { + this.emit( 'close' ); + this.buffer = ''; + this.i = 0; + return; + } - if (i === 0){ - if (chr != '\u0000') - this.error('Bad framing. Expected null byte as first frame'); - else - continue; - } + if ( i === 0 ) { + if ( chr != '\u0000' ) { + this.error( 'Bad framing. Expected null byte as first frame' ); + } + else { + continue; + } + } - if (chr == '\ufffd'){ - this.emit('data', this.buffer.substr(1, i - 1)); - this.buffer = this.buffer.substr(i + 1); - this.i = 0; - return this.parse(); - } - } + if ( chr == '\ufffd' ) { + this.emit( 'data', this.buffer.substr( 1, i - 1 ) ); + this.buffer = this.buffer.substr( i + 1 ); + this.i = 0; + return this.parse(); + } + } }; /** @@ -352,9 +355,9 @@ Parser.prototype.parse = function () { * @api private */ -Parser.prototype.error = function (reason) { - this.buffer = ''; - this.i = 0; - this.emit('error', reason); - return this; +Parser.prototype.error = function ( reason ) { + this.buffer = ''; + this.i = 0; + this.emit( 'error', reason ); + return this; }; diff --git a/example/node/node_modules/socket.io/lib/transports/websocket/hybi-07-12.js b/example/node/node_modules/socket.io/lib/transports/websocket/hybi-07-12.js index 44f666a..4d11de9 100644 --- a/example/node/node_modules/socket.io/lib/transports/websocket/hybi-07-12.js +++ b/example/node/node_modules/socket.io/lib/transports/websocket/hybi-07-12.js @@ -1,20 +1,19 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost * MIT Licensed */ - + /** * Module requirements. */ -var Transport = require('../../transport') - , EventEmitter = process.EventEmitter - , crypto = require('crypto') - , url = require('url') - , parser = require('../../parser') - , util = require('../../util'); +var Transport = require( '../../transport' ) + , EventEmitter = process.EventEmitter + , crypto = require( 'crypto' ) + , url = require( 'url' ) + , parser = require( '../../parser' ) + , util = require( '../../util' ); /** * Export the constructor. @@ -30,35 +29,36 @@ exports.Parser = Parser; * @api public */ -function WebSocket (mng, data, req) { - // parser - var self = this; +function WebSocket( mng, data, req ) { + // parser + var self = this; - this.manager = mng; - this.parser = new Parser(); - this.parser.on('data', function (packet) { - self.onMessage(parser.decodePacket(packet)); - }); - this.parser.on('ping', function () { - // version 8 ping => pong - try { - self.socket.write('\u008a\u0000'); - } - catch (e) { - self.end(); - return; - } - }); - this.parser.on('close', function () { - self.end(); - }); - this.parser.on('error', function (reason) { - self.log.warn(self.name + ' parser error: ' + reason); - self.end(); - }); + this.manager = mng; + this.parser = new Parser(); + this.parser.on( 'data', function ( packet ) { + self.onMessage( parser.decodePacket( packet ) ); + } ); + this.parser.on( 'ping', function () { + // version 8 ping => pong + try { + self.socket.write( '\u008a\u0000' ); + } + catch ( e ) { + self.end(); + return; + } + } ); + this.parser.on( 'close', function () { + self.end(); + } ); + this.parser.on( 'error', function ( reason ) { + self.log.warn( self.name + ' parser error: ' + reason ); + self.end(); + } ); - Transport.call(this, mng, data, req); -}; + Transport.call( this, mng, data, req ); +} +; /** * Inherits from Transport. @@ -89,58 +89,58 @@ WebSocket.prototype.protocolVersion = '07-12'; */ WebSocket.prototype.onSocketConnect = function () { - var self = this; + var self = this; - if (typeof this.req.headers.upgrade === 'undefined' || - this.req.headers.upgrade.toLowerCase() !== 'websocket') { - this.log.warn(this.name + ' connection invalid'); - this.end(); - return; - } + if ( typeof this.req.headers.upgrade === 'undefined' || + this.req.headers.upgrade.toLowerCase() !== 'websocket' ) { + this.log.warn( this.name + ' connection invalid' ); + this.end(); + return; + } - var origin = this.req.headers['sec-websocket-origin'] - , location = ((this.manager.settings['match origin protocol'] ? - origin.match(/^https/) : this.socket.encrypted) ? - 'wss' : 'ws') - + '://' + this.req.headers.host + this.req.url; - - if (!this.verifyOrigin(origin)) { - this.log.warn(this.name + ' connection invalid: origin mismatch'); - this.end(); - return; - } - - if (!this.req.headers['sec-websocket-key']) { - this.log.warn(this.name + ' connection invalid: received no key'); - this.end(); - return; - } - - // calc key - var key = this.req.headers['sec-websocket-key']; - var shasum = crypto.createHash('sha1'); - shasum.update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); - key = shasum.digest('base64'); + var origin = this.req.headers['sec-websocket-origin'] + , location = ((this.manager.settings['match origin protocol'] ? + origin.match( /^https/ ) : this.socket.encrypted) ? + 'wss' : 'ws') + + '://' + this.req.headers.host + this.req.url; - var headers = [ - 'HTTP/1.1 101 Switching Protocols' - , 'Upgrade: websocket' - , 'Connection: Upgrade' - , 'Sec-WebSocket-Accept: ' + key - ]; + if ( !this.verifyOrigin( origin ) ) { + this.log.warn( this.name + ' connection invalid: origin mismatch' ); + this.end(); + return; + } - try { - this.socket.write(headers.concat('', '').join('\r\n')); - this.socket.setTimeout(0); - this.socket.setNoDelay(true); - } catch (e) { - this.end(); - return; - } + if ( !this.req.headers['sec-websocket-key'] ) { + this.log.warn( this.name + ' connection invalid: received no key' ); + this.end(); + return; + } - this.socket.on('data', function (data) { - self.parser.add(data); - }); + // calc key + var key = this.req.headers['sec-websocket-key']; + var shasum = crypto.createHash( 'sha1' ); + shasum.update( key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ); + key = shasum.digest( 'base64' ); + + var headers = [ + 'HTTP/1.1 101 Switching Protocols' + , 'Upgrade: websocket' + , 'Connection: Upgrade' + , 'Sec-WebSocket-Accept: ' + key + ]; + + try { + this.socket.write( headers.concat( '', '' ).join( '\r\n' ) ); + this.socket.setTimeout( 0 ); + this.socket.setNoDelay( true ); + } catch ( e ) { + this.end(); + return; + } + + this.socket.on( 'data', function ( data ) { + self.parser.add( data ); + } ); }; /** @@ -149,33 +149,37 @@ WebSocket.prototype.onSocketConnect = function () { * @api private */ -WebSocket.prototype.verifyOrigin = function (origin) { - var origins = this.manager.get('origins'); +WebSocket.prototype.verifyOrigin = function ( origin ) { + var origins = this.manager.get( 'origins' ); - if (origin === 'null') origin = '*'; + if ( origin === 'null' ) { + origin = '*'; + } - if (origins.indexOf('*:*') !== -1) { - return true; - } + if ( origins.indexOf( '*:*' ) !== -1 ) { + return true; + } - if (origin) { - try { - var parts = url.parse(origin); - parts.port = parts.port || 80; - var ok = - ~origins.indexOf(parts.hostname + ':' + parts.port) || - ~origins.indexOf(parts.hostname + ':*') || - ~origins.indexOf('*:' + parts.port); - if (!ok) this.log.warn('illegal origin: ' + origin); - return ok; - } catch (ex) { - this.log.warn('error parsing origin'); - } - } - else { - this.log.warn('origin missing from websocket call, yet required by config'); - } - return false; + if ( origin ) { + try { + var parts = url.parse( origin ); + parts.port = parts.port || 80; + var ok = + ~origins.indexOf( parts.hostname + ':' + parts.port ) || + ~origins.indexOf( parts.hostname + ':*' ) || + ~origins.indexOf( '*:' + parts.port ); + if ( !ok ) { + this.log.warn( 'illegal origin: ' + origin ); + } + return ok; + } catch ( ex ) { + this.log.warn( 'error parsing origin' ); + } + } + else { + this.log.warn( 'origin missing from websocket call, yet required by config' ); + } + return false; }; /** @@ -184,18 +188,18 @@ WebSocket.prototype.verifyOrigin = function (origin) { * @api private */ -WebSocket.prototype.write = function (data) { - if (this.open) { - var buf = this.frame(0x81, data); - try { - this.socket.write(buf, 'binary'); - } - catch (e) { - this.end(); - return; - } - this.log.debug(this.name + ' writing', data); - } +WebSocket.prototype.write = function ( data ) { + if ( this.open ) { + var buf = this.frame( 0x81, data ); + try { + this.socket.write( buf, 'binary' ); + } + catch ( e ) { + this.end(); + return; + } + this.log.debug( this.name + ' writing', data ); + } }; /** @@ -204,12 +208,12 @@ WebSocket.prototype.write = function (data) { * @api private */ -WebSocket.prototype.payload = function (msgs) { - for (var i = 0, l = msgs.length; i < l; i++) { - this.write(msgs[i]); - } +WebSocket.prototype.payload = function ( msgs ) { + for ( var i = 0, l = msgs.length; i < l; i++ ) { + this.write( msgs[i] ); + } - return this; + return this; }; /** @@ -218,36 +222,36 @@ WebSocket.prototype.payload = function (msgs) { * @api private */ -WebSocket.prototype.frame = function (opcode, str) { - var dataBuffer = new Buffer(str) - , dataLength = dataBuffer.length - , startOffset = 2 - , secondByte = dataLength; - if (dataLength > 65536) { - startOffset = 10; - secondByte = 127; - } - else if (dataLength > 125) { - startOffset = 4; - secondByte = 126; - } - var outputBuffer = new Buffer(dataLength + startOffset); - outputBuffer[0] = opcode; - outputBuffer[1] = secondByte; - dataBuffer.copy(outputBuffer, startOffset); - switch (secondByte) { - case 126: - outputBuffer[2] = dataLength >>> 8; - outputBuffer[3] = dataLength % 256; - break; - case 127: - var l = dataLength; - for (var i = 1; i <= 8; ++i) { - outputBuffer[startOffset - i] = l & 0xff; - l >>>= 8; - } - } - return outputBuffer; +WebSocket.prototype.frame = function ( opcode, str ) { + var dataBuffer = new Buffer( str ) + , dataLength = dataBuffer.length + , startOffset = 2 + , secondByte = dataLength; + if ( dataLength > 65536 ) { + startOffset = 10; + secondByte = 127; + } + else if ( dataLength > 125 ) { + startOffset = 4; + secondByte = 126; + } + var outputBuffer = new Buffer( dataLength + startOffset ); + outputBuffer[0] = opcode; + outputBuffer[1] = secondByte; + dataBuffer.copy( outputBuffer, startOffset ); + switch ( secondByte ) { + case 126: + outputBuffer[2] = dataLength >>> 8; + outputBuffer[3] = dataLength % 256; + break; + case 127: + var l = dataLength; + for ( var i = 1; i <= 8; ++i ) { + outputBuffer[startOffset - i] = l & 0xff; + l >>>= 8; + } + } + return outputBuffer; }; /** @@ -257,7 +261,7 @@ WebSocket.prototype.frame = function (opcode, str) { */ WebSocket.prototype.doClose = function () { - this.socket.end(); + this.socket.end(); }; /** @@ -265,175 +269,178 @@ WebSocket.prototype.doClose = function () { * * @api public */ - -function Parser () { - this.state = { - activeFragmentedOperation: null, - lastFragment: false, - masked: false, - opcode: 0 - }; - this.overflow = null; - this.expectOffset = 0; - this.expectBuffer = null; - this.expectHandler = null; - this.currentMessage = ''; - var self = this; - this.opcodeHandlers = { - // text - '1': function(data) { - var finish = function(mask, data) { - self.currentMessage += self.unmask(mask, data); - if (self.state.lastFragment) { - self.emit('data', self.currentMessage); - self.currentMessage = ''; - } - self.endPacket(); - } +function Parser() { + this.state = { + activeFragmentedOperation : null, + lastFragment : false, + masked : false, + opcode : 0 + }; + this.overflow = null; + this.expectOffset = 0; + this.expectBuffer = null; + this.expectHandler = null; + this.currentMessage = ''; - var expectData = function(length) { - if (self.state.masked) { - self.expect('Mask', 4, function(data) { - var mask = data; - self.expect('Data', length, function(data) { - finish(mask, data); - }); - }); - } - else { - self.expect('Data', length, function(data) { - finish(null, data); - }); - } - } + var self = this; + this.opcodeHandlers = { + // text + '1' : function ( data ) { + var finish = function ( mask, data ) { + self.currentMessage += self.unmask( mask, data ); + if ( self.state.lastFragment ) { + self.emit( 'data', self.currentMessage ); + self.currentMessage = ''; + } + self.endPacket(); + } - // decode length - var firstLength = data[1] & 0x7f; - if (firstLength < 126) { - expectData(firstLength); - } - else if (firstLength == 126) { - self.expect('Length', 2, function(data) { - expectData(util.unpack(data)); - }); - } - else if (firstLength == 127) { - self.expect('Length', 8, function(data) { - if (util.unpack(data.slice(0, 4)) != 0) { - self.error('packets with length spanning more than 32 bit is currently not supported'); - return; - } - var lengthBytes = data.slice(4); // note: cap to 32 bit length - expectData(util.unpack(data)); - }); - } - }, - // binary - '2': function(data) { - var finish = function(mask, data) { - if (typeof self.currentMessage == 'string') self.currentMessage = []; // build a buffer list - self.currentMessage.push(self.unmask(mask, data, true)); - if (self.state.lastFragment) { - self.emit('binary', self.concatBuffers(self.currentMessage)); - self.currentMessage = ''; - } - self.endPacket(); - } + var expectData = function ( length ) { + if ( self.state.masked ) { + self.expect( 'Mask', 4, function ( data ) { + var mask = data; + self.expect( 'Data', length, function ( data ) { + finish( mask, data ); + } ); + } ); + } + else { + self.expect( 'Data', length, function ( data ) { + finish( null, data ); + } ); + } + } - var expectData = function(length) { - if (self.state.masked) { - self.expect('Mask', 4, function(data) { - var mask = data; - self.expect('Data', length, function(data) { - finish(mask, data); - }); - }); - } - else { - self.expect('Data', length, function(data) { - finish(null, data); - }); - } - } + // decode length + var firstLength = data[1] & 0x7f; + if ( firstLength < 126 ) { + expectData( firstLength ); + } + else if ( firstLength == 126 ) { + self.expect( 'Length', 2, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + else if ( firstLength == 127 ) { + self.expect( 'Length', 8, function ( data ) { + if ( util.unpack( data.slice( 0, 4 ) ) != 0 ) { + self.error( 'packets with length spanning more than 32 bit is currently not supported' ); + return; + } + var lengthBytes = data.slice( 4 ); // note: cap to 32 bit length + expectData( util.unpack( data ) ); + } ); + } + }, + // binary + '2' : function ( data ) { + var finish = function ( mask, data ) { + if ( typeof self.currentMessage == 'string' ) { + self.currentMessage = []; + } // build a buffer list + self.currentMessage.push( self.unmask( mask, data, true ) ); + if ( self.state.lastFragment ) { + self.emit( 'binary', self.concatBuffers( self.currentMessage ) ); + self.currentMessage = ''; + } + self.endPacket(); + } - // decode length - var firstLength = data[1] & 0x7f; - if (firstLength < 126) { - expectData(firstLength); - } - else if (firstLength == 126) { - self.expect('Length', 2, function(data) { - expectData(util.unpack(data)); - }); - } - else if (firstLength == 127) { - self.expect('Length', 8, function(data) { - if (util.unpack(data.slice(0, 4)) != 0) { - self.error('packets with length spanning more than 32 bit is currently not supported'); - return; - } - var lengthBytes = data.slice(4); // note: cap to 32 bit length - expectData(util.unpack(data)); - }); - } - }, - // close - '8': function(data) { - self.emit('close'); - self.reset(); - }, - // ping - '9': function(data) { - if (self.state.lastFragment == false) { - self.error('fragmented ping is not supported'); - return; - } - - var finish = function(mask, data) { - self.emit('ping', self.unmask(mask, data)); - self.endPacket(); - } + var expectData = function ( length ) { + if ( self.state.masked ) { + self.expect( 'Mask', 4, function ( data ) { + var mask = data; + self.expect( 'Data', length, function ( data ) { + finish( mask, data ); + } ); + } ); + } + else { + self.expect( 'Data', length, function ( data ) { + finish( null, data ); + } ); + } + } - var expectData = function(length) { - if (self.state.masked) { - self.expect('Mask', 4, function(data) { - var mask = data; - self.expect('Data', length, function(data) { - finish(mask, data); - }); - }); - } - else { - self.expect('Data', length, function(data) { - finish(null, data); - }); - } - } + // decode length + var firstLength = data[1] & 0x7f; + if ( firstLength < 126 ) { + expectData( firstLength ); + } + else if ( firstLength == 126 ) { + self.expect( 'Length', 2, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + else if ( firstLength == 127 ) { + self.expect( 'Length', 8, function ( data ) { + if ( util.unpack( data.slice( 0, 4 ) ) != 0 ) { + self.error( 'packets with length spanning more than 32 bit is currently not supported' ); + return; + } + var lengthBytes = data.slice( 4 ); // note: cap to 32 bit length + expectData( util.unpack( data ) ); + } ); + } + }, + // close + '8' : function ( data ) { + self.emit( 'close' ); + self.reset(); + }, + // ping + '9' : function ( data ) { + if ( self.state.lastFragment == false ) { + self.error( 'fragmented ping is not supported' ); + return; + } - // decode length - var firstLength = data[1] & 0x7f; - if (firstLength == 0) { - finish(null, null); - } - else if (firstLength < 126) { - expectData(firstLength); - } - else if (firstLength == 126) { - self.expect('Length', 2, function(data) { - expectData(util.unpack(data)); - }); - } - else if (firstLength == 127) { - self.expect('Length', 8, function(data) { - expectData(util.unpack(data)); - }); - } - } - } + var finish = function ( mask, data ) { + self.emit( 'ping', self.unmask( mask, data ) ); + self.endPacket(); + } - this.expect('Opcode', 2, this.processPacket); -}; + var expectData = function ( length ) { + if ( self.state.masked ) { + self.expect( 'Mask', 4, function ( data ) { + var mask = data; + self.expect( 'Data', length, function ( data ) { + finish( mask, data ); + } ); + } ); + } + else { + self.expect( 'Data', length, function ( data ) { + finish( null, data ); + } ); + } + } + + // decode length + var firstLength = data[1] & 0x7f; + if ( firstLength == 0 ) { + finish( null, null ); + } + else if ( firstLength < 126 ) { + expectData( firstLength ); + } + else if ( firstLength == 126 ) { + self.expect( 'Length', 2, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + else if ( firstLength == 127 ) { + self.expect( 'Length', 8, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + } + } + + this.expect( 'Opcode', 2, this.processPacket ); +} +; /** * Inherits from EventEmitter. @@ -447,25 +454,25 @@ Parser.prototype.__proto__ = EventEmitter.prototype; * @api public */ -Parser.prototype.add = function(data) { - if (this.expectBuffer == null) { - this.addToOverflow(data); - return; - } - var toRead = Math.min(data.length, this.expectBuffer.length - this.expectOffset); - data.copy(this.expectBuffer, this.expectOffset, 0, toRead); - this.expectOffset += toRead; - if (toRead < data.length) { - // at this point the overflow buffer shouldn't at all exist - this.overflow = new Buffer(data.length - toRead); - data.copy(this.overflow, 0, toRead, toRead + this.overflow.length); - } - if (this.expectOffset == this.expectBuffer.length) { - var bufferForHandler = this.expectBuffer; - this.expectBuffer = null; - this.expectOffset = 0; - this.expectHandler.call(this, bufferForHandler); - } +Parser.prototype.add = function ( data ) { + if ( this.expectBuffer == null ) { + this.addToOverflow( data ); + return; + } + var toRead = Math.min( data.length, this.expectBuffer.length - this.expectOffset ); + data.copy( this.expectBuffer, this.expectOffset, 0, toRead ); + this.expectOffset += toRead; + if ( toRead < data.length ) { + // at this point the overflow buffer shouldn't at all exist + this.overflow = new Buffer( data.length - toRead ); + data.copy( this.overflow, 0, toRead, toRead + this.overflow.length ); + } + if ( this.expectOffset == this.expectBuffer.length ) { + var bufferForHandler = this.expectBuffer; + this.expectBuffer = null; + this.expectOffset = 0; + this.expectHandler.call( this, bufferForHandler ); + } } /** @@ -474,14 +481,16 @@ Parser.prototype.add = function(data) { * @api private */ -Parser.prototype.addToOverflow = function(data) { - if (this.overflow == null) this.overflow = data; - else { - var prevOverflow = this.overflow; - this.overflow = new Buffer(this.overflow.length + data.length); - prevOverflow.copy(this.overflow, 0); - data.copy(this.overflow, prevOverflow.length); - } +Parser.prototype.addToOverflow = function ( data ) { + if ( this.overflow == null ) { + this.overflow = data; + } + else { + var prevOverflow = this.overflow; + this.overflow = new Buffer( this.overflow.length + data.length ); + prevOverflow.copy( this.overflow, 0 ); + data.copy( this.overflow, prevOverflow.length ); + } } /** @@ -490,15 +499,15 @@ Parser.prototype.addToOverflow = function(data) { * @api private */ -Parser.prototype.expect = function(what, length, handler) { - this.expectBuffer = new Buffer(length); - this.expectOffset = 0; - this.expectHandler = handler; - if (this.overflow != null) { - var toOverflow = this.overflow; - this.overflow = null; - this.add(toOverflow); - } +Parser.prototype.expect = function ( what, length, handler ) { + this.expectBuffer = new Buffer( length ); + this.expectOffset = 0; + this.expectHandler = handler; + if ( this.overflow != null ) { + var toOverflow = this.overflow; + this.overflow = null; + this.add( toOverflow ); + } } /** @@ -507,30 +516,34 @@ Parser.prototype.expect = function(what, length, handler) { * @api private */ -Parser.prototype.processPacket = function (data) { - if ((data[0] & 0x70) != 0) { - this.error('reserved fields must be empty'); - } - this.state.lastFragment = (data[0] & 0x80) == 0x80; - this.state.masked = (data[1] & 0x80) == 0x80; - var opcode = data[0] & 0xf; - if (opcode == 0) { - // continuation frame - this.state.opcode = this.state.activeFragmentedOperation; - if (!(this.state.opcode == 1 || this.state.opcode == 2)) { - this.error('continuation frame cannot follow current opcode') - return; - } - } - else { - this.state.opcode = opcode; - if (this.state.lastFragment === false) { - this.state.activeFragmentedOperation = opcode; - } - } - var handler = this.opcodeHandlers[this.state.opcode]; - if (typeof handler == 'undefined') this.error('no handler for opcode ' + this.state.opcode); - else handler(data); +Parser.prototype.processPacket = function ( data ) { + if ( (data[0] & 0x70) != 0 ) { + this.error( 'reserved fields must be empty' ); + } + this.state.lastFragment = (data[0] & 0x80) == 0x80; + this.state.masked = (data[1] & 0x80) == 0x80; + var opcode = data[0] & 0xf; + if ( opcode == 0 ) { + // continuation frame + this.state.opcode = this.state.activeFragmentedOperation; + if ( !(this.state.opcode == 1 || this.state.opcode == 2) ) { + this.error( 'continuation frame cannot follow current opcode' ) + return; + } + } + else { + this.state.opcode = opcode; + if ( this.state.lastFragment === false ) { + this.state.activeFragmentedOperation = opcode; + } + } + var handler = this.opcodeHandlers[this.state.opcode]; + if ( typeof handler == 'undefined' ) { + this.error( 'no handler for opcode ' + this.state.opcode ); + } + else { + handler( data ); + } } /** @@ -539,18 +552,18 @@ Parser.prototype.processPacket = function (data) { * @api private */ -Parser.prototype.endPacket = function() { - this.expectOffset = 0; - this.expectBuffer = null; - this.expectHandler = null; - if (this.state.lastFragment && this.state.opcode == this.state.activeFragmentedOperation) { - // end current fragmented operation - this.state.activeFragmentedOperation = null; - } - this.state.lastFragment = false; - this.state.opcode = this.state.activeFragmentedOperation != null ? this.state.activeFragmentedOperation : 0; - this.state.masked = false; - this.expect('Opcode', 2, this.processPacket); +Parser.prototype.endPacket = function () { + this.expectOffset = 0; + this.expectBuffer = null; + this.expectHandler = null; + if ( this.state.lastFragment && this.state.opcode == this.state.activeFragmentedOperation ) { + // end current fragmented operation + this.state.activeFragmentedOperation = null; + } + this.state.lastFragment = false; + this.state.opcode = this.state.activeFragmentedOperation != null ? this.state.activeFragmentedOperation : 0; + this.state.masked = false; + this.expect( 'Opcode', 2, this.processPacket ); } /** @@ -559,18 +572,18 @@ Parser.prototype.endPacket = function() { * @api private */ -Parser.prototype.reset = function() { - this.state = { - activeFragmentedOperation: null, - lastFragment: false, - masked: false, - opcode: 0 - }; - this.expectOffset = 0; - this.expectBuffer = null; - this.expectHandler = null; - this.overflow = null; - this.currentMessage = ''; +Parser.prototype.reset = function () { + this.state = { + activeFragmentedOperation : null, + lastFragment : false, + masked : false, + opcode : 0 + }; + this.expectOffset = 0; + this.expectBuffer = null; + this.expectHandler = null; + this.overflow = null; + this.currentMessage = ''; } /** @@ -579,14 +592,16 @@ Parser.prototype.reset = function() { * @api private */ -Parser.prototype.unmask = function (mask, buf, binary) { - if (mask != null) { - for (var i = 0, ll = buf.length; i < ll; i++) { - buf[i] ^= mask[i % 4]; - } - } - if (binary) return buf; - return buf != null ? buf.toString('utf8') : ''; +Parser.prototype.unmask = function ( mask, buf, binary ) { + if ( mask != null ) { + for ( var i = 0, ll = buf.length; i < ll; i++ ) { + buf[i] ^= mask[i % 4]; + } + } + if ( binary ) { + return buf; + } + return buf != null ? buf.toString( 'utf8' ) : ''; } /** @@ -595,18 +610,18 @@ Parser.prototype.unmask = function (mask, buf, binary) { * @api private */ -Parser.prototype.concatBuffers = function(buffers) { - var length = 0; - for (var i = 0, l = buffers.length; i < l; ++i) { - length += buffers[i].length; - } - var mergedBuffer = new Buffer(length); - var offset = 0; - for (var i = 0, l = buffers.length; i < l; ++i) { - buffers[i].copy(mergedBuffer, offset); - offset += buffers[i].length; - } - return mergedBuffer; +Parser.prototype.concatBuffers = function ( buffers ) { + var length = 0; + for ( var i = 0, l = buffers.length; i < l; ++i ) { + length += buffers[i].length; + } + var mergedBuffer = new Buffer( length ); + var offset = 0; + for ( var i = 0, l = buffers.length; i < l; ++i ) { + buffers[i].copy( mergedBuffer, offset ); + offset += buffers[i].length; + } + return mergedBuffer; } /** @@ -615,8 +630,8 @@ Parser.prototype.concatBuffers = function(buffers) { * @api private */ -Parser.prototype.error = function (reason) { - this.reset(); - this.emit('error', reason); - return this; +Parser.prototype.error = function ( reason ) { + this.reset(); + this.emit( 'error', reason ); + return this; }; diff --git a/example/node/node_modules/socket.io/lib/transports/websocket/hybi-16.js b/example/node/node_modules/socket.io/lib/transports/websocket/hybi-16.js index d84e10c..d49e096 100644 --- a/example/node/node_modules/socket.io/lib/transports/websocket/hybi-16.js +++ b/example/node/node_modules/socket.io/lib/transports/websocket/hybi-16.js @@ -1,20 +1,19 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost * MIT Licensed */ - + /** * Module requirements. */ -var Transport = require('../../transport') - , EventEmitter = process.EventEmitter - , crypto = require('crypto') - , url = require('url') - , parser = require('../../parser') - , util = require('../../util'); +var Transport = require( '../../transport' ) + , EventEmitter = process.EventEmitter + , crypto = require( 'crypto' ) + , url = require( 'url' ) + , parser = require( '../../parser' ) + , util = require( '../../util' ); /** * Export the constructor. @@ -30,35 +29,36 @@ exports.Parser = Parser; * @api public */ -function WebSocket (mng, data, req) { - // parser - var self = this; +function WebSocket( mng, data, req ) { + // parser + var self = this; - this.manager = mng; - this.parser = new Parser(); - this.parser.on('data', function (packet) { - self.onMessage(parser.decodePacket(packet)); - }); - this.parser.on('ping', function () { - // version 8 ping => pong - try { - self.socket.write('\u008a\u0000'); - } - catch (e) { - self.end(); - return; - } - }); - this.parser.on('close', function () { - self.end(); - }); - this.parser.on('error', function (reason) { - self.log.warn(self.name + ' parser error: ' + reason); - self.end(); - }); + this.manager = mng; + this.parser = new Parser(); + this.parser.on( 'data', function ( packet ) { + self.onMessage( parser.decodePacket( packet ) ); + } ); + this.parser.on( 'ping', function () { + // version 8 ping => pong + try { + self.socket.write( '\u008a\u0000' ); + } + catch ( e ) { + self.end(); + return; + } + } ); + this.parser.on( 'close', function () { + self.end(); + } ); + this.parser.on( 'error', function ( reason ) { + self.log.warn( self.name + ' parser error: ' + reason ); + self.end(); + } ); - Transport.call(this, mng, data, req); -}; + Transport.call( this, mng, data, req ); +} +; /** * Inherits from Transport. @@ -89,58 +89,58 @@ WebSocket.prototype.protocolVersion = '16'; */ WebSocket.prototype.onSocketConnect = function () { - var self = this; + var self = this; - if (typeof this.req.headers.upgrade === 'undefined' || - this.req.headers.upgrade.toLowerCase() !== 'websocket') { - this.log.warn(this.name + ' connection invalid'); - this.end(); - return; - } + if ( typeof this.req.headers.upgrade === 'undefined' || + this.req.headers.upgrade.toLowerCase() !== 'websocket' ) { + this.log.warn( this.name + ' connection invalid' ); + this.end(); + return; + } - var origin = this.req.headers['origin'] - , location = ((this.manager.settings['match origin protocol'] ? - origin.match(/^https/) : this.socket.encrypted) ? - 'wss' : 'ws') - + '://' + this.req.headers.host + this.req.url; - - if (!this.verifyOrigin(origin)) { - this.log.warn(this.name + ' connection invalid: origin mismatch'); - this.end(); - return; - } - - if (!this.req.headers['sec-websocket-key']) { - this.log.warn(this.name + ' connection invalid: received no key'); - this.end(); - return; - } - - // calc key - var key = this.req.headers['sec-websocket-key']; - var shasum = crypto.createHash('sha1'); - shasum.update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); - key = shasum.digest('base64'); + var origin = this.req.headers['origin'] + , location = ((this.manager.settings['match origin protocol'] ? + origin.match( /^https/ ) : this.socket.encrypted) ? + 'wss' : 'ws') + + '://' + this.req.headers.host + this.req.url; - var headers = [ - 'HTTP/1.1 101 Switching Protocols' - , 'Upgrade: websocket' - , 'Connection: Upgrade' - , 'Sec-WebSocket-Accept: ' + key - ]; + if ( !this.verifyOrigin( origin ) ) { + this.log.warn( this.name + ' connection invalid: origin mismatch' ); + this.end(); + return; + } - try { - this.socket.write(headers.concat('', '').join('\r\n')); - this.socket.setTimeout(0); - this.socket.setNoDelay(true); - } catch (e) { - this.end(); - return; - } + if ( !this.req.headers['sec-websocket-key'] ) { + this.log.warn( this.name + ' connection invalid: received no key' ); + this.end(); + return; + } - this.socket.on('data', function (data) { - self.parser.add(data); - }); + // calc key + var key = this.req.headers['sec-websocket-key']; + var shasum = crypto.createHash( 'sha1' ); + shasum.update( key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" ); + key = shasum.digest( 'base64' ); + + var headers = [ + 'HTTP/1.1 101 Switching Protocols' + , 'Upgrade: websocket' + , 'Connection: Upgrade' + , 'Sec-WebSocket-Accept: ' + key + ]; + + try { + this.socket.write( headers.concat( '', '' ).join( '\r\n' ) ); + this.socket.setTimeout( 0 ); + this.socket.setNoDelay( true ); + } catch ( e ) { + this.end(); + return; + } + + this.socket.on( 'data', function ( data ) { + self.parser.add( data ); + } ); }; /** @@ -149,33 +149,37 @@ WebSocket.prototype.onSocketConnect = function () { * @api private */ -WebSocket.prototype.verifyOrigin = function (origin) { - var origins = this.manager.get('origins'); +WebSocket.prototype.verifyOrigin = function ( origin ) { + var origins = this.manager.get( 'origins' ); - if (origin === 'null') origin = '*'; + if ( origin === 'null' ) { + origin = '*'; + } - if (origins.indexOf('*:*') !== -1) { - return true; - } + if ( origins.indexOf( '*:*' ) !== -1 ) { + return true; + } - if (origin) { - try { - var parts = url.parse(origin); - parts.port = parts.port || 80; - var ok = - ~origins.indexOf(parts.hostname + ':' + parts.port) || - ~origins.indexOf(parts.hostname + ':*') || - ~origins.indexOf('*:' + parts.port); - if (!ok) this.log.warn('illegal origin: ' + origin); - return ok; - } catch (ex) { - this.log.warn('error parsing origin'); - } - } - else { - this.log.warn('origin missing from websocket call, yet required by config'); - } - return false; + if ( origin ) { + try { + var parts = url.parse( origin ); + parts.port = parts.port || 80; + var ok = + ~origins.indexOf( parts.hostname + ':' + parts.port ) || + ~origins.indexOf( parts.hostname + ':*' ) || + ~origins.indexOf( '*:' + parts.port ); + if ( !ok ) { + this.log.warn( 'illegal origin: ' + origin ); + } + return ok; + } catch ( ex ) { + this.log.warn( 'error parsing origin' ); + } + } + else { + this.log.warn( 'origin missing from websocket call, yet required by config' ); + } + return false; }; /** @@ -184,18 +188,18 @@ WebSocket.prototype.verifyOrigin = function (origin) { * @api private */ -WebSocket.prototype.write = function (data) { - if (this.open) { - var buf = this.frame(0x81, data); - try { - this.socket.write(buf, 'binary'); - } - catch (e) { - this.end(); - return; - } - this.log.debug(this.name + ' writing', data); - } +WebSocket.prototype.write = function ( data ) { + if ( this.open ) { + var buf = this.frame( 0x81, data ); + try { + this.socket.write( buf, 'binary' ); + } + catch ( e ) { + this.end(); + return; + } + this.log.debug( this.name + ' writing', data ); + } }; /** @@ -204,12 +208,12 @@ WebSocket.prototype.write = function (data) { * @api private */ -WebSocket.prototype.payload = function (msgs) { - for (var i = 0, l = msgs.length; i < l; i++) { - this.write(msgs[i]); - } +WebSocket.prototype.payload = function ( msgs ) { + for ( var i = 0, l = msgs.length; i < l; i++ ) { + this.write( msgs[i] ); + } - return this; + return this; }; /** @@ -218,36 +222,36 @@ WebSocket.prototype.payload = function (msgs) { * @api private */ -WebSocket.prototype.frame = function (opcode, str) { - var dataBuffer = new Buffer(str) - , dataLength = dataBuffer.length - , startOffset = 2 - , secondByte = dataLength; - if (dataLength > 65536) { - startOffset = 10; - secondByte = 127; - } - else if (dataLength > 125) { - startOffset = 4; - secondByte = 126; - } - var outputBuffer = new Buffer(dataLength + startOffset); - outputBuffer[0] = opcode; - outputBuffer[1] = secondByte; - dataBuffer.copy(outputBuffer, startOffset); - switch (secondByte) { - case 126: - outputBuffer[2] = dataLength >>> 8; - outputBuffer[3] = dataLength % 256; - break; - case 127: - var l = dataLength; - for (var i = 1; i <= 8; ++i) { - outputBuffer[startOffset - i] = l & 0xff; - l >>>= 8; - } - } - return outputBuffer; +WebSocket.prototype.frame = function ( opcode, str ) { + var dataBuffer = new Buffer( str ) + , dataLength = dataBuffer.length + , startOffset = 2 + , secondByte = dataLength; + if ( dataLength > 65536 ) { + startOffset = 10; + secondByte = 127; + } + else if ( dataLength > 125 ) { + startOffset = 4; + secondByte = 126; + } + var outputBuffer = new Buffer( dataLength + startOffset ); + outputBuffer[0] = opcode; + outputBuffer[1] = secondByte; + dataBuffer.copy( outputBuffer, startOffset ); + switch ( secondByte ) { + case 126: + outputBuffer[2] = dataLength >>> 8; + outputBuffer[3] = dataLength % 256; + break; + case 127: + var l = dataLength; + for ( var i = 1; i <= 8; ++i ) { + outputBuffer[startOffset - i] = l & 0xff; + l >>>= 8; + } + } + return outputBuffer; }; /** @@ -257,7 +261,7 @@ WebSocket.prototype.frame = function (opcode, str) { */ WebSocket.prototype.doClose = function () { - this.socket.end(); + this.socket.end(); }; /** @@ -265,175 +269,178 @@ WebSocket.prototype.doClose = function () { * * @api public */ - -function Parser () { - this.state = { - activeFragmentedOperation: null, - lastFragment: false, - masked: false, - opcode: 0 - }; - this.overflow = null; - this.expectOffset = 0; - this.expectBuffer = null; - this.expectHandler = null; - this.currentMessage = ''; - var self = this; - this.opcodeHandlers = { - // text - '1': function(data) { - var finish = function(mask, data) { - self.currentMessage += self.unmask(mask, data); - if (self.state.lastFragment) { - self.emit('data', self.currentMessage); - self.currentMessage = ''; - } - self.endPacket(); - } +function Parser() { + this.state = { + activeFragmentedOperation : null, + lastFragment : false, + masked : false, + opcode : 0 + }; + this.overflow = null; + this.expectOffset = 0; + this.expectBuffer = null; + this.expectHandler = null; + this.currentMessage = ''; - var expectData = function(length) { - if (self.state.masked) { - self.expect('Mask', 4, function(data) { - var mask = data; - self.expect('Data', length, function(data) { - finish(mask, data); - }); - }); - } - else { - self.expect('Data', length, function(data) { - finish(null, data); - }); - } - } + var self = this; + this.opcodeHandlers = { + // text + '1' : function ( data ) { + var finish = function ( mask, data ) { + self.currentMessage += self.unmask( mask, data ); + if ( self.state.lastFragment ) { + self.emit( 'data', self.currentMessage ); + self.currentMessage = ''; + } + self.endPacket(); + } - // decode length - var firstLength = data[1] & 0x7f; - if (firstLength < 126) { - expectData(firstLength); - } - else if (firstLength == 126) { - self.expect('Length', 2, function(data) { - expectData(util.unpack(data)); - }); - } - else if (firstLength == 127) { - self.expect('Length', 8, function(data) { - if (util.unpack(data.slice(0, 4)) != 0) { - self.error('packets with length spanning more than 32 bit is currently not supported'); - return; - } - var lengthBytes = data.slice(4); // note: cap to 32 bit length - expectData(util.unpack(data)); - }); - } - }, - // binary - '2': function(data) { - var finish = function(mask, data) { - if (typeof self.currentMessage == 'string') self.currentMessage = []; // build a buffer list - self.currentMessage.push(self.unmask(mask, data, true)); - if (self.state.lastFragment) { - self.emit('binary', self.concatBuffers(self.currentMessage)); - self.currentMessage = ''; - } - self.endPacket(); - } + var expectData = function ( length ) { + if ( self.state.masked ) { + self.expect( 'Mask', 4, function ( data ) { + var mask = data; + self.expect( 'Data', length, function ( data ) { + finish( mask, data ); + } ); + } ); + } + else { + self.expect( 'Data', length, function ( data ) { + finish( null, data ); + } ); + } + } - var expectData = function(length) { - if (self.state.masked) { - self.expect('Mask', 4, function(data) { - var mask = data; - self.expect('Data', length, function(data) { - finish(mask, data); - }); - }); - } - else { - self.expect('Data', length, function(data) { - finish(null, data); - }); - } - } + // decode length + var firstLength = data[1] & 0x7f; + if ( firstLength < 126 ) { + expectData( firstLength ); + } + else if ( firstLength == 126 ) { + self.expect( 'Length', 2, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + else if ( firstLength == 127 ) { + self.expect( 'Length', 8, function ( data ) { + if ( util.unpack( data.slice( 0, 4 ) ) != 0 ) { + self.error( 'packets with length spanning more than 32 bit is currently not supported' ); + return; + } + var lengthBytes = data.slice( 4 ); // note: cap to 32 bit length + expectData( util.unpack( data ) ); + } ); + } + }, + // binary + '2' : function ( data ) { + var finish = function ( mask, data ) { + if ( typeof self.currentMessage == 'string' ) { + self.currentMessage = []; + } // build a buffer list + self.currentMessage.push( self.unmask( mask, data, true ) ); + if ( self.state.lastFragment ) { + self.emit( 'binary', self.concatBuffers( self.currentMessage ) ); + self.currentMessage = ''; + } + self.endPacket(); + } - // decode length - var firstLength = data[1] & 0x7f; - if (firstLength < 126) { - expectData(firstLength); - } - else if (firstLength == 126) { - self.expect('Length', 2, function(data) { - expectData(util.unpack(data)); - }); - } - else if (firstLength == 127) { - self.expect('Length', 8, function(data) { - if (util.unpack(data.slice(0, 4)) != 0) { - self.error('packets with length spanning more than 32 bit is currently not supported'); - return; - } - var lengthBytes = data.slice(4); // note: cap to 32 bit length - expectData(util.unpack(data)); - }); - } - }, - // close - '8': function(data) { - self.emit('close'); - self.reset(); - }, - // ping - '9': function(data) { - if (self.state.lastFragment == false) { - self.error('fragmented ping is not supported'); - return; - } - - var finish = function(mask, data) { - self.emit('ping', self.unmask(mask, data)); - self.endPacket(); - } + var expectData = function ( length ) { + if ( self.state.masked ) { + self.expect( 'Mask', 4, function ( data ) { + var mask = data; + self.expect( 'Data', length, function ( data ) { + finish( mask, data ); + } ); + } ); + } + else { + self.expect( 'Data', length, function ( data ) { + finish( null, data ); + } ); + } + } - var expectData = function(length) { - if (self.state.masked) { - self.expect('Mask', 4, function(data) { - var mask = data; - self.expect('Data', length, function(data) { - finish(mask, data); - }); - }); - } - else { - self.expect('Data', length, function(data) { - finish(null, data); - }); - } - } + // decode length + var firstLength = data[1] & 0x7f; + if ( firstLength < 126 ) { + expectData( firstLength ); + } + else if ( firstLength == 126 ) { + self.expect( 'Length', 2, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + else if ( firstLength == 127 ) { + self.expect( 'Length', 8, function ( data ) { + if ( util.unpack( data.slice( 0, 4 ) ) != 0 ) { + self.error( 'packets with length spanning more than 32 bit is currently not supported' ); + return; + } + var lengthBytes = data.slice( 4 ); // note: cap to 32 bit length + expectData( util.unpack( data ) ); + } ); + } + }, + // close + '8' : function ( data ) { + self.emit( 'close' ); + self.reset(); + }, + // ping + '9' : function ( data ) { + if ( self.state.lastFragment == false ) { + self.error( 'fragmented ping is not supported' ); + return; + } - // decode length - var firstLength = data[1] & 0x7f; - if (firstLength == 0) { - finish(null, null); - } - else if (firstLength < 126) { - expectData(firstLength); - } - else if (firstLength == 126) { - self.expect('Length', 2, function(data) { - expectData(util.unpack(data)); - }); - } - else if (firstLength == 127) { - self.expect('Length', 8, function(data) { - expectData(util.unpack(data)); - }); - } - } - } + var finish = function ( mask, data ) { + self.emit( 'ping', self.unmask( mask, data ) ); + self.endPacket(); + } - this.expect('Opcode', 2, this.processPacket); -}; + var expectData = function ( length ) { + if ( self.state.masked ) { + self.expect( 'Mask', 4, function ( data ) { + var mask = data; + self.expect( 'Data', length, function ( data ) { + finish( mask, data ); + } ); + } ); + } + else { + self.expect( 'Data', length, function ( data ) { + finish( null, data ); + } ); + } + } + + // decode length + var firstLength = data[1] & 0x7f; + if ( firstLength == 0 ) { + finish( null, null ); + } + else if ( firstLength < 126 ) { + expectData( firstLength ); + } + else if ( firstLength == 126 ) { + self.expect( 'Length', 2, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + else if ( firstLength == 127 ) { + self.expect( 'Length', 8, function ( data ) { + expectData( util.unpack( data ) ); + } ); + } + } + } + + this.expect( 'Opcode', 2, this.processPacket ); +} +; /** * Inherits from EventEmitter. @@ -447,25 +454,25 @@ Parser.prototype.__proto__ = EventEmitter.prototype; * @api public */ -Parser.prototype.add = function(data) { - if (this.expectBuffer == null) { - this.addToOverflow(data); - return; - } - var toRead = Math.min(data.length, this.expectBuffer.length - this.expectOffset); - data.copy(this.expectBuffer, this.expectOffset, 0, toRead); - this.expectOffset += toRead; - if (toRead < data.length) { - // at this point the overflow buffer shouldn't at all exist - this.overflow = new Buffer(data.length - toRead); - data.copy(this.overflow, 0, toRead, toRead + this.overflow.length); - } - if (this.expectOffset == this.expectBuffer.length) { - var bufferForHandler = this.expectBuffer; - this.expectBuffer = null; - this.expectOffset = 0; - this.expectHandler.call(this, bufferForHandler); - } +Parser.prototype.add = function ( data ) { + if ( this.expectBuffer == null ) { + this.addToOverflow( data ); + return; + } + var toRead = Math.min( data.length, this.expectBuffer.length - this.expectOffset ); + data.copy( this.expectBuffer, this.expectOffset, 0, toRead ); + this.expectOffset += toRead; + if ( toRead < data.length ) { + // at this point the overflow buffer shouldn't at all exist + this.overflow = new Buffer( data.length - toRead ); + data.copy( this.overflow, 0, toRead, toRead + this.overflow.length ); + } + if ( this.expectOffset == this.expectBuffer.length ) { + var bufferForHandler = this.expectBuffer; + this.expectBuffer = null; + this.expectOffset = 0; + this.expectHandler.call( this, bufferForHandler ); + } } /** @@ -474,14 +481,16 @@ Parser.prototype.add = function(data) { * @api private */ -Parser.prototype.addToOverflow = function(data) { - if (this.overflow == null) this.overflow = data; - else { - var prevOverflow = this.overflow; - this.overflow = new Buffer(this.overflow.length + data.length); - prevOverflow.copy(this.overflow, 0); - data.copy(this.overflow, prevOverflow.length); - } +Parser.prototype.addToOverflow = function ( data ) { + if ( this.overflow == null ) { + this.overflow = data; + } + else { + var prevOverflow = this.overflow; + this.overflow = new Buffer( this.overflow.length + data.length ); + prevOverflow.copy( this.overflow, 0 ); + data.copy( this.overflow, prevOverflow.length ); + } } /** @@ -490,15 +499,15 @@ Parser.prototype.addToOverflow = function(data) { * @api private */ -Parser.prototype.expect = function(what, length, handler) { - this.expectBuffer = new Buffer(length); - this.expectOffset = 0; - this.expectHandler = handler; - if (this.overflow != null) { - var toOverflow = this.overflow; - this.overflow = null; - this.add(toOverflow); - } +Parser.prototype.expect = function ( what, length, handler ) { + this.expectBuffer = new Buffer( length ); + this.expectOffset = 0; + this.expectHandler = handler; + if ( this.overflow != null ) { + var toOverflow = this.overflow; + this.overflow = null; + this.add( toOverflow ); + } } /** @@ -507,31 +516,35 @@ Parser.prototype.expect = function(what, length, handler) { * @api private */ -Parser.prototype.processPacket = function (data) { - if ((data[0] & 0x70) != 0) { - this.error('reserved fields must be empty'); - return; - } - this.state.lastFragment = (data[0] & 0x80) == 0x80; - this.state.masked = (data[1] & 0x80) == 0x80; - var opcode = data[0] & 0xf; - if (opcode == 0) { - // continuation frame - this.state.opcode = this.state.activeFragmentedOperation; - if (!(this.state.opcode == 1 || this.state.opcode == 2)) { - this.error('continuation frame cannot follow current opcode') - return; - } - } - else { - this.state.opcode = opcode; - if (this.state.lastFragment === false) { - this.state.activeFragmentedOperation = opcode; - } - } - var handler = this.opcodeHandlers[this.state.opcode]; - if (typeof handler == 'undefined') this.error('no handler for opcode ' + this.state.opcode); - else handler(data); +Parser.prototype.processPacket = function ( data ) { + if ( (data[0] & 0x70) != 0 ) { + this.error( 'reserved fields must be empty' ); + return; + } + this.state.lastFragment = (data[0] & 0x80) == 0x80; + this.state.masked = (data[1] & 0x80) == 0x80; + var opcode = data[0] & 0xf; + if ( opcode == 0 ) { + // continuation frame + this.state.opcode = this.state.activeFragmentedOperation; + if ( !(this.state.opcode == 1 || this.state.opcode == 2) ) { + this.error( 'continuation frame cannot follow current opcode' ) + return; + } + } + else { + this.state.opcode = opcode; + if ( this.state.lastFragment === false ) { + this.state.activeFragmentedOperation = opcode; + } + } + var handler = this.opcodeHandlers[this.state.opcode]; + if ( typeof handler == 'undefined' ) { + this.error( 'no handler for opcode ' + this.state.opcode ); + } + else { + handler( data ); + } } /** @@ -540,18 +553,18 @@ Parser.prototype.processPacket = function (data) { * @api private */ -Parser.prototype.endPacket = function() { - this.expectOffset = 0; - this.expectBuffer = null; - this.expectHandler = null; - if (this.state.lastFragment && this.state.opcode == this.state.activeFragmentedOperation) { - // end current fragmented operation - this.state.activeFragmentedOperation = null; - } - this.state.lastFragment = false; - this.state.opcode = this.state.activeFragmentedOperation != null ? this.state.activeFragmentedOperation : 0; - this.state.masked = false; - this.expect('Opcode', 2, this.processPacket); +Parser.prototype.endPacket = function () { + this.expectOffset = 0; + this.expectBuffer = null; + this.expectHandler = null; + if ( this.state.lastFragment && this.state.opcode == this.state.activeFragmentedOperation ) { + // end current fragmented operation + this.state.activeFragmentedOperation = null; + } + this.state.lastFragment = false; + this.state.opcode = this.state.activeFragmentedOperation != null ? this.state.activeFragmentedOperation : 0; + this.state.masked = false; + this.expect( 'Opcode', 2, this.processPacket ); } /** @@ -560,18 +573,18 @@ Parser.prototype.endPacket = function() { * @api private */ -Parser.prototype.reset = function() { - this.state = { - activeFragmentedOperation: null, - lastFragment: false, - masked: false, - opcode: 0 - }; - this.expectOffset = 0; - this.expectBuffer = null; - this.expectHandler = null; - this.overflow = null; - this.currentMessage = ''; +Parser.prototype.reset = function () { + this.state = { + activeFragmentedOperation : null, + lastFragment : false, + masked : false, + opcode : 0 + }; + this.expectOffset = 0; + this.expectBuffer = null; + this.expectHandler = null; + this.overflow = null; + this.currentMessage = ''; } /** @@ -580,14 +593,16 @@ Parser.prototype.reset = function() { * @api private */ -Parser.prototype.unmask = function (mask, buf, binary) { - if (mask != null) { - for (var i = 0, ll = buf.length; i < ll; i++) { - buf[i] ^= mask[i % 4]; - } - } - if (binary) return buf; - return buf != null ? buf.toString('utf8') : ''; +Parser.prototype.unmask = function ( mask, buf, binary ) { + if ( mask != null ) { + for ( var i = 0, ll = buf.length; i < ll; i++ ) { + buf[i] ^= mask[i % 4]; + } + } + if ( binary ) { + return buf; + } + return buf != null ? buf.toString( 'utf8' ) : ''; } /** @@ -596,18 +611,18 @@ Parser.prototype.unmask = function (mask, buf, binary) { * @api private */ -Parser.prototype.concatBuffers = function(buffers) { - var length = 0; - for (var i = 0, l = buffers.length; i < l; ++i) { - length += buffers[i].length; - } - var mergedBuffer = new Buffer(length); - var offset = 0; - for (var i = 0, l = buffers.length; i < l; ++i) { - buffers[i].copy(mergedBuffer, offset); - offset += buffers[i].length; - } - return mergedBuffer; +Parser.prototype.concatBuffers = function ( buffers ) { + var length = 0; + for ( var i = 0, l = buffers.length; i < l; ++i ) { + length += buffers[i].length; + } + var mergedBuffer = new Buffer( length ); + var offset = 0; + for ( var i = 0, l = buffers.length; i < l; ++i ) { + buffers[i].copy( mergedBuffer, offset ); + offset += buffers[i].length; + } + return mergedBuffer; } /** @@ -616,8 +631,8 @@ Parser.prototype.concatBuffers = function(buffers) { * @api private */ -Parser.prototype.error = function (reason) { - this.reset(); - this.emit('error', reason); - return this; +Parser.prototype.error = function ( reason ) { + this.reset(); + this.emit( 'error', reason ); + return this; }; diff --git a/example/node/node_modules/socket.io/lib/transports/websocket/index.js b/example/node/node_modules/socket.io/lib/transports/websocket/index.js index 3a952b7..2d30af0 100644 --- a/example/node/node_modules/socket.io/lib/transports/websocket/index.js +++ b/example/node/node_modules/socket.io/lib/transports/websocket/index.js @@ -1,11 +1,10 @@ - /** * Export websocket versions. */ module.exports = { - 7: require('./hybi-07-12'), - 8: require('./hybi-07-12'), - 13: require('./hybi-16'), - default: require('./default') + 7 : require( './hybi-07-12' ), + 8 : require( './hybi-07-12' ), + 13 : require( './hybi-16' ), + default : require( './default' ) }; diff --git a/example/node/node_modules/socket.io/lib/transports/xhr-polling.js b/example/node/node_modules/socket.io/lib/transports/xhr-polling.js index 1db5aee..07eb781 100644 --- a/example/node/node_modules/socket.io/lib/transports/xhr-polling.js +++ b/example/node/node_modules/socket.io/lib/transports/xhr-polling.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -9,7 +8,7 @@ * Module requirements. */ -var HTTPPolling = require('./http-polling'); +var HTTPPolling = require( './http-polling' ); /** * Export the constructor. @@ -23,9 +22,10 @@ exports = module.exports = XHRPolling; * @api public */ -function XHRPolling (mng, data, req) { - HTTPPolling.call(this, mng, data, req); -}; +function XHRPolling( mng, data, req ) { + HTTPPolling.call( this, mng, data, req ); +} +; /** * Inherits from Transport. @@ -47,23 +47,21 @@ XHRPolling.prototype.name = 'xhr-polling'; * @api private */ -XHRPolling.prototype.doWrite = function (data) { - HTTPPolling.prototype.doWrite.call(this); +XHRPolling.prototype.doWrite = function ( data ) { + HTTPPolling.prototype.doWrite.call( this ); - var origin = this.req.headers.origin - , headers = { - 'Content-Type': 'text/plain; charset=UTF-8' - , 'Content-Length': data === undefined ? 0 : Buffer.byteLength(data) - , 'Connection': 'Keep-Alive' - }; + var origin = this.req.headers.origin + , headers = { + 'Content-Type' : 'text/plain; charset=UTF-8', 'Content-Length' : data === undefined ? 0 : Buffer.byteLength( data ), 'Connection' : 'Keep-Alive' + }; - if (origin) { - // https://developer.mozilla.org/En/HTTP_Access_Control - headers['Access-Control-Allow-Origin'] = origin; - headers['Access-Control-Allow-Credentials'] = 'true'; - } + if ( origin ) { + // https://developer.mozilla.org/En/HTTP_Access_Control + headers['Access-Control-Allow-Origin'] = origin; + headers['Access-Control-Allow-Credentials'] = 'true'; + } - this.response.writeHead(200, headers); - this.response.write(data); - this.log.debug(this.name + ' writing', data); + this.response.writeHead( 200, headers ); + this.response.write( data ); + this.log.debug( this.name + ' writing', data ); }; diff --git a/example/node/node_modules/socket.io/lib/util.js b/example/node/node_modules/socket.io/lib/util.js index f7d9f2b..60e691c 100644 --- a/example/node/node_modules/socket.io/lib/util.js +++ b/example/node/node_modules/socket.io/lib/util.js @@ -1,4 +1,3 @@ - /*! * socket.io-node * Copyright(c) 2011 LearnBoost @@ -15,13 +14,14 @@ * @api public */ -exports.toArray = function (enu) { - var arr = []; +exports.toArray = function ( enu ) { + var arr = []; - for (var i = 0, l = enu.length; i < l; i++) - arr.push(enu[i]); + for ( var i = 0, l = enu.length; i < l; i++ ) { + arr.push( enu[i] ); + } - return arr; + return arr; }; /** @@ -30,12 +30,12 @@ exports.toArray = function (enu) { * @api public */ -exports.unpack = function (buffer) { - var n = 0; - for (var i = 0; i < buffer.length; ++i) { - n = (i == 0) ? buffer[i] : (n * 256) + buffer[i]; - } - return n; +exports.unpack = function ( buffer ) { + var n = 0; + for ( var i = 0; i < buffer.length; ++i ) { + n = (i == 0) ? buffer[i] : (n * 256) + buffer[i]; + } + return n; } /** @@ -44,7 +44,7 @@ exports.unpack = function (buffer) { * @api public */ -exports.padl = function (s,n,c) { - return new Array(1 + n - s.length).join(c) + s; +exports.padl = function ( s, n, c ) { + return new Array( 1 + n - s.length ).join( c ) + s; } diff --git a/example/node/node_modules/socket.io/node_modules/policyfile/doc/index.html b/example/node/node_modules/socket.io/node_modules/policyfile/doc/index.html index 743fcda..67e8a60 100644 --- a/example/node/node_modules/socket.io/node_modules/policyfile/doc/index.html +++ b/example/node/node_modules/socket.io/node_modules/policyfile/doc/index.html @@ -1,375 +1,552 @@ - - FlashPolicyFileServer - - - - - - - - + + FlashPolicyFileServer + + + + + +

    FlashPolicyFileServer

    server

    lib/server.js
    -

    Module dependencies and cached references. -

    -
    -
    var slice = Array.prototype.slice
    -  , net = require('net');
    -
    + + + + + + + + - - + + - - +
      +
    • log false or a function that can output log information, defaults to console.log?
    • +
    + +

    + +
      +
    • param: Object options Options to customize the servers functionality.

      +
    • +
    • param: Array origins The origins that are allowed on this server, defaults + to *:*.

    • +
    • api: public

    • +
    + + - - +
      +
    • param: Number port The port number it should be listening to.

    • +
    • param: Server server A HTTP server instance, this will be used to listen + for inline requests

    • +
    • param: Function cb The callback needs to be called once server is ready

      +
    • +
    • api: public

    • +
    + + - - +
      +
    • param: Arguments The origins that need to be added.

    • +
    • api: public

    • +
    + + - - - - - - - - - + - + // only remove and recompile if we have a match + if (position &gt; 0){ + this.origins.splice(position,1); + this.compile(); + } + + returnthis; + }; + - - + + - - + + + + + + + + + + + + + - + + +

    FlashPolicyFileServer

    server

    lib/server.js
    -

    The server that does the Policy File severing

    - -

    Options

    - -
    • log false or a function that can output log information, defaults to console.log?
    - -

    - -
    • param: Object options Options to customize the servers functionality.

    • param: Array origins The origins that are allowed on this server, defaults to *:*.

    • api: public

    -
    -
    function Server(options, origins){
    -  var me = this;
    -  
    -  this.origins = origins || ['*:*'];
    -  this.port = 843;
    -  this.log = console.log;
    -  
    -  // merge `this` with the options
    -  Object.keys(options).forEach(function(key){
    -    me[key] &amp;&amp; (me[key] = options[key])
    -  });
    -  
    -  // create the net server
    -  this.socket = net.createServer(function createServer(socket){
    -    socket.on('error', function socketError(){ me.responder.call(me, socket) });
    -    me.responder.call(me, socket);
    -  });
    -  
    -  // Listen for errors as the port might be blocked because we do not have root priv.
    -  this.socket.on('error', function serverError(err){
    -    // Special and common case error handling
    -    if (err.errno == 13){
    -      me.log &amp;&amp; me.log(
    -        'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' +
    -        (
    -          me.server
    -          ? 'The Flash Policy file will now be served inline over the supplied HTTP server, Flash Policy files request will suffer.'
    -          : 'No fallback server supplied.'
    -        )
    -      );
    -      
    -      me.socket.removeAllListeners();
    -      delete me.socket;
    -
    -      me.emit('connect_failed', err);
    -    } else {
    -      me.log &amp;&amp; me.log('FlashPolicyFileServer received a error event:\n' + (err.message ? err.message : err));
    -    }
    -  });
    -  
    -  this.socket.on('timeout', function serverTimeout(){});
    -  this.socket.on('close', function serverClosed(err){
    -    err &amp;&amp; me.log &amp;&amp; me.log('Server closing due to an error: \n' + (err.message ? err.message : err));
    -    
    -    if (me.server){
    -      // not online anymore
    -      delete me.server.online;
    -      
    -      // Remove the inline policy listener if we close down
    -      // but only when the server was `online` (see listen prototype)
    -      if( me.server['@'] &amp;&amp; me.server.online){
    -        me.server.removeListener('connection', me.server['@']);
    -      }
    -    }
    -    me.log &amp;&amp; me.log('Shutting down FlashPolicyFileServer');
    -  });
    -  
    -  // Compile the initial `buffer`
    -  this.compile();
    -}
    -
    +

    Module dependencies and cached references. +

    +
    +
    var slice = Array.prototype.slice
    +	, net = require('net');
    +
    -

    Start listening for requests

    +
    +

    The server that does the Policy File severing

    -

    +

    Options

    -
    • param: Number port The port number it should be listening to.

    • param: Server server A HTTP server instance, this will be used to listen for inline requests

    • param: Function cb The callback needs to be called once server is ready

    • api: public

    -
    -
    Server.prototype.listen = function listen(port, server, cb){
    -  var me = this
    -    , args = slice.call(arguments, 0)
    -    , callback;
    -  
    -  // assign the correct vars, for flexible arguments
    -  args.forEach(function args(arg){
    -    var type = typeof arg;
    -    
    -    if (type === 'number') me.port = arg;
    -    if (type === 'function') callback = arg;
    -    if (type === 'object') me.server = arg;
    -  });
    -  
    -  if (this.server){
    -    
    -    // no one in their right mind would ever create a `@` prototype, so Im just gonna store
    -    // my function on the server, so I can remove it later again once the server(s) closes
    -    this.server['@'] = function connection(socket){
    -      socket.once('data', function requestData(data){
    -        // if it's a Flash policy request, and we can write to the 
    -        if (
    -             data
    -          &amp;&amp; data[0] === 60
    -          &amp;&amp; data.toString() === '<policy-file-request/>\0'
    -          &amp;&amp; socket
    -          &amp;&amp; (socket.readyState === 'open' || socket.readyState === 'writeOnly')
    -        ){
    -          // send the buffer
    -          socket.end(me.buffer);
    -        }
    -      });
    -    };
    -    // attach it
    -    this.server.on('connection', this.server['@']);
    -  }
    -  
    -  // We add a callback method, so we can set a flag for when the server is `enabled` or `online`.
    -  // this flag is needed because if a error occurs and the we cannot boot up the server the
    -  // fallback functionality should not be removed during the `close` event
    -  this.socket.listen(this.port, function serverListening(){
    -   me.socket.online = true;
    -   
    -   if (callback) callback(), callback = undefined;
    -   
    -  });
    -  
    -  return this;
    -};
    -
    +
    function Server(options,
    +	origins){
    +	var me = this;
    +
    +	this.origins = origins ||
    +	['*:*'];
    +	this.port = 843;
    +	this.log = console.log;
    +
    +	// merge `this` with the options
    +	Object.keys(options).forEach(function(key){
    +	me[key] &amp;&amp; (me[key] = options[key])
    +	});
    +
    +	// create the net server
    +	this.socket = net.createServer(function createServer(socket){
    +	socket.on('error', function socketError(){ me.responder.call(me, socket) });
    +	me.responder.call(me, socket);
    +	});
    +
    +	// Listen for errors as the port might be blocked because we do not have root priv.
    +	this.socket.on('error', function serverError(err){
    +	// Special and common case error handling
    +	if (err.errno == 13){
    +	me.log &amp;&amp; me.log(
    +	'Unable to listen to port `' + me.port
    +	+ '` as your Node.js instance does not have root privileges. ' +
    +	(
    +	me.server
    +	? 'The Flash Policy file will now be served inline over the supplied HTTP server, Flash Policy files request will suffer.'
    +	: 'No fallback server supplied.'
    +	)
    +	);
    +
    +	me.socket.removeAllListeners();
    +	delete me.socket;
    +
    +	me.emit('connect_failed',
    +	err);
    +	} else {
    +	me.log &amp;&amp; me.log('FlashPolicyFileServer received a error event:\n' + (err.message ? err.message :
    +	err));
    +	}
    +	});
    +
    +	this.socket.on('timeout', function serverTimeout(){});
    +	this.socket.on('close', function serverClosed(err){
    +	err &amp;&amp; me.log &amp;&amp; me.log('Server closing due to an error: \n' + (err.message ? err.message :
    +	err));
    +
    +	if (me.server){
    +	// not online anymore
    +	delete me.server.online;
    +
    +	// Remove the inline policy listener if we close down
    +	// but only when the server was `online` (see listen prototype)
    +	if( me.server['@'] &amp;&amp; me.server.online){
    +	me.server.removeListener('connection', me.server['@']);
    +	}
    +	}
    +	me.log &amp;&amp; me.log('Shutting down FlashPolicyFileServer');
    +	});
    +
    +	// Compile the initial `buffer`
    +	this.compile();
    +	}
    +
    -

    Adds a new origin to the Flash Policy File.

    +
    +

    Start listening for requests

    -

    +

    -
    • param: Arguments The origins that need to be added.

    • api: public

    -
    -
    Server.prototype.add = function add(){
    -  var args = slice.call(arguments, 0)
    -    , i = args.length;
    -  
    -  // flag duplicates
    -  while (i--){
    -    if (this.origins.indexOf(args[i]) &gt;= 0){
    -      args[i] = null;
    -    }
    -  }
    -  
    -  // Add all the arguments to the array
    -  // but first we want to remove all `falsy` values from the args
    -  Array.prototype.push.apply(
    -    this.origins
    -  , args.filter(function(value){ return !!value })
    -  );
    -  
    -  this.compile();
    -  return this;
    -};
    -
    +
    Server.prototype.listen = function listen(port, server, cb){
    +	var me = this
    +	, args = slice.call(arguments, 0)
    +	, callback;
    +
    +	// assign the correct vars, for flexible arguments
    +	args.forEach(function args(arg){
    +	var type = typeof arg;
    +
    +	if (type === 'number') me.port = arg;
    +	if (type === 'function')
    +	callback = arg;
    +	if (type === 'object') me.server = arg;
    +	});
    +
    +	if (this.server){
    +
    +	// no one in their right mind would ever create a `@` prototype, so Im just gonna store
    +	// my function on the server, so I can remove it later again once the server(s) closes
    +	this.server['@'] = function connection(socket){
    +	socket.once('data', function requestData(data){
    +	// if it's a Flash policy request, and we can write to the 
    +	if (
    +	data
    +	&amp;&amp; data[0] === 60
    +	&amp;&amp; data.toString() === '<policy-file-request/>\0'
    +	&amp;&amp; socket
    +	&amp;&amp; (socket.readyState === 'open' || socket.readyState === 'writeOnly')
    +	){
    +	// send the buffer
    +	socket.end(me.buffer);
    +	}
    +	});
    +	};
    +	// attach it
    +	this.server.on('connection', this.server['@']);
    +	}
    +
    +	// We add a callback method, so we can set a flag for when the server is `enabled` or `online`.
    +	// this flag is needed because if a error occurs and the we cannot boot up the server the
    +	// fallback functionality should not be removed during the `close` event
    +	this.socket.listen(this.port, function serverListening(){
    +	me.socket.online = true;
    +
    +	if (callback) callback(),
    +	callback = undefined;
    +
    +	});
    +
    +	return this;
    +	};
    +
    -

    Removes a origin from the Flash Policy File.

    +
    +

    Adds a new origin to the Flash Policy File.

    -

    +

    -
    • param: String origin The origin that needs to be removed from the server

    • api: public

    -
    -
    Server.prototype.remove = function remove(origin){
    -  var position = this.origins.indexOf(origin);
    -  
    -  // only remove and recompile if we have a match
    -  if (position &gt; 0){
    -    this.origins.splice(position,1);
    -    this.compile();
    -  }
    -  
    -  return this;
    -};
    -
    +
    Server.prototype.add =
    +	function add(){
    +	var args = slice.call(arguments, 0)
    +	, i = args.length;
    +
    +	// flag duplicates
    +	while (i--){
    +	if (this.origins.indexOf(args[i]) &gt;= 0){
    +	args[i] = null;
    +	}
    +	}
    +
    +	// Add all the arguments to the array
    +	// but first we want to remove all `falsy` values from the args
    +	Array.prototype.push.apply(
    +	this.origins
    +	, args.filter(function(value){ return !!value })
    +	);
    +
    +	this.compile();
    +	return this;
    +	};
    +
    -

    Closes and cleans up the server

    +
    +

    Removes a origin from the Flash Policy File.

    -
    • api: public

    -
    -
    Server.prototype.close = function close(){
    -  this.socket.removeAllListeners();
    -  this.socket.close();
    -  
    -  return this;
    -};
    -
    -

    Proxy the event listener requests to the created Net server -

    -
    -
    Object.keys(process.EventEmitter.prototype).forEach(function proxy(key){
    -  Server.prototype[key] = Server.prototype[key] || function (){
    -    if (this.socket) this.socket[key].apply(this.socket, arguments);
    -    return this;
    -  };
    -});
    -
    -

    Creates a new server instance.

    +

    -

    +
      +
    • param: String origin The origin that needs to be removed from the server +

    • +
    • api: public

    • +
    +
    +
    Server.prototype.remove = function remove(origin){
    +	var position = this.origins.indexOf(origin);
     
    -
    • param: Object options A options object to override the default config

    • param: Array origins The origins that should be allowed by the server

    • api: public

    -
    -
    exports.createServer = function createServer(options, origins){
    -  origins = Array.isArray(origins) ? origins : (Array.isArray(options) ? options : false);
    -  options = !Array.isArray(options) &amp;&amp; options ? options : {};
    -  
    -  return new Server(options, origins);
    -};
    -
    -

    Provide a hook to the original server, so it can be extended if needed. -

    -
    -
    exports.Server = Server;
    -
    +

    Closes and cleans up the server

    + +
      +
    • api: public

    • +
    +
    +
    Server.prototype.close
    +	= function close(){
    +	this.socket.removeAllListeners();
    +	this.socket.close();
    +
    +	return this;
    +	};
    +
    -

    Module version -

    -
    -
    exports.version = '0.0.2';
    +	
    +

    Proxy the event listener requests to the created Net server +

    +
    +
    Object.keys(process.EventEmitter.prototype).forEach(function proxy(key){
    +	Server.prototype[key] = Server.prototype[key] ||
    +	function (){
    +	if (this.socket) this.socket[key].apply(this.socket, arguments);
    +	return this;
    +	};
    +	});
    +
    +

    Creates a new server instance.

    + +

    + +
      +
    • param: Object options A options object to override the default config

      +
    • +
    • param: Array origins The origins that should be allowed by the server

      +
    • +
    • api: public

    • +
    +
    +
    exports.createServer = function
    +	createServer(options, origins){
    +	origins = Array.isArray(origins) ? origins : (Array.isArray(options) ? options : false);
    +	options = !Array.isArray(options) &amp;&amp; options ?
    +	options : {};
    +
    +	return new Server(options, origins);
    +	};
    +
    +

    Provide a hook to the original server, so it can be extended if needed. +

    +
    +
    exports.Server = Server;
    +
    +

    Module version +

    +
    +
    exports.version = '0.0.2';
     
    -
    \ No newline at end of file diff --git a/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.fallback.js b/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.fallback.js index b439449..b6bfa86 100644 --- a/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.fallback.js +++ b/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.fallback.js @@ -1,8 +1,11 @@ -var http = require('http') - , fspfs = require('../'); +var http = require( 'http' ) + , fspfs = require( '../' ); -var server = http.createServer(function(q,r){ r.writeHead(200); r.end(':3') }) - , flash = fspfs.createServer(); +var server = http.createServer( function ( q, r ) { + r.writeHead( 200 ); + r.end( ':3' ) + } ) + , flash = fspfs.createServer(); -server.listen(8080); -flash.listen(8081,server); \ No newline at end of file +server.listen( 8080 ); +flash.listen( 8081, server ); \ No newline at end of file diff --git a/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.js b/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.js index 5e2290f..7b4fcbe 100644 --- a/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.js +++ b/example/node/node_modules/socket.io/node_modules/policyfile/examples/basic.js @@ -1,5 +1,5 @@ -var http = require('http') - , fspfs = require('../'); +var http = require( 'http' ) + , fspfs = require( '../' ); var flash = fspfs.createServer(); flash.listen(); \ No newline at end of file diff --git a/example/node/node_modules/socket.io/node_modules/policyfile/index.js b/example/node/node_modules/socket.io/node_modules/policyfile/index.js index 60cf298..e5aedb8 100644 --- a/example/node/node_modules/socket.io/node_modules/policyfile/index.js +++ b/example/node/node_modules/socket.io/node_modules/policyfile/index.js @@ -1 +1 @@ -module.exports = require('./lib/server.js'); \ No newline at end of file +module.exports = require( './lib/server.js' ); \ No newline at end of file diff --git a/example/node/node_modules/socket.io/node_modules/policyfile/lib/server.js b/example/node/node_modules/socket.io/node_modules/policyfile/lib/server.js index a525772..c54fe09 100644 --- a/example/node/node_modules/socket.io/node_modules/policyfile/lib/server.js +++ b/example/node/node_modules/socket.io/node_modules/policyfile/lib/server.js @@ -3,7 +3,7 @@ */ var slice = Array.prototype.slice - , net = require('net'); + , net = require( 'net' ); /** * The server that does the Policy File severing @@ -16,66 +16,67 @@ var slice = Array.prototype.slice * @api public */ -function Server (options, origins) { - var me = this; +function Server( options, origins ) { + var me = this; - this.origins = origins || ['*:*']; - this.port = 843; - this.log = console.log; + this.origins = origins || ['*:*']; + this.port = 843; + this.log = console.log; - // merge `this` with the options - Object.keys(options).forEach(function (key) { - me[key] && (me[key] = options[key]) - }); + // merge `this` with the options + Object.keys( options ).forEach( function ( key ) { + me[key] && (me[key] = options[key]) + } ); - // create the net server - this.socket = net.createServer(function createServer (socket) { - socket.on('error', function socketError () { - me.responder.call(me, socket); - }); + // create the net server + this.socket = net.createServer( function createServer( socket ) { + socket.on( 'error', function socketError() { + me.responder.call( me, socket ); + } ); - me.responder.call(me, socket); - }); + me.responder.call( me, socket ); + } ); - // Listen for errors as the port might be blocked because we do not have root priv. - this.socket.on('error', function serverError (err) { - // Special and common case error handling - if (err.errno == 13) { - me.log && me.log( - 'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' + - ( - me.server - ? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.' - : 'No fallback server supplied, we will be unable to answer Flash Policy File requests.' - ) - ); + // Listen for errors as the port might be blocked because we do not have root priv. + this.socket.on( 'error', function serverError( err ) { + // Special and common case error handling + if ( err.errno == 13 ) { + me.log && me.log( + 'Unable to listen to port `' + me.port + '` as your Node.js instance does not have root privileges. ' + + ( + me.server + ? 'The Flash Policy File requests will only be served inline over the supplied HTTP server. Inline serving is slower than a dedicated server instance.' + : 'No fallback server supplied, we will be unable to answer Flash Policy File requests.' + ) + ); - me.emit('connect_failed', err); - me.socket.removeAllListeners(); - delete me.socket; - } else { - me.log && me.log('FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err)); - } - }); + me.emit( 'connect_failed', err ); + me.socket.removeAllListeners(); + delete me.socket; + } else { + me.log && me.log( 'FlashPolicyFileServer received an error event:\n' + (err.message ? err.message : err) ); + } + } ); - this.socket.on('timeout', function serverTimeout () {}); - this.socket.on('close', function serverClosed (err) { - err && me.log && me.log('Server closing due to an error: \n' + (err.message ? err.message : err)); + this.socket.on( 'timeout', function serverTimeout() { + } ); + this.socket.on( 'close', function serverClosed( err ) { + err && me.log && me.log( 'Server closing due to an error: \n' + (err.message ? err.message : err) ); - if (me.server) { - // Remove the inline policy listener if we close down - // but only when the server was `online` (see listen prototype) - if (me.server['@'] && me.server.online) { - me.server.removeListener('connection', me.server['@']); - } + if ( me.server ) { + // Remove the inline policy listener if we close down + // but only when the server was `online` (see listen prototype) + if ( me.server['@'] && me.server.online ) { + me.server.removeListener( 'connection', me.server['@'] ); + } - // not online anymore - delete me.server.online; - } - }); + // not online anymore + delete me.server.online; + } + } ); - // Compile the initial `buffer` - this.compile(); + // Compile the initial `buffer` + this.compile(); } /** @@ -87,58 +88,65 @@ function Server (options, origins) { * @api public */ -Server.prototype.listen = function listen (port, server, cb){ - var me = this - , args = slice.call(arguments, 0) - , callback; - - // assign the correct vars, for flexible arguments - args.forEach(function args (arg){ - var type = typeof arg; +Server.prototype.listen = function listen( port, server, cb ) { + var me = this + , args = slice.call( arguments, 0 ) + , callback; - if (type === 'number') me.port = arg; - if (type === 'function') callback = arg; - if (type === 'object') me.server = arg; - }); + // assign the correct vars, for flexible arguments + args.forEach( function args( arg ) { + var type = typeof arg; - if (this.server) { + if ( type === 'number' ) { + me.port = arg; + } + if ( type === 'function' ) { + callback = arg; + } + if ( type === 'object' ) { + me.server = arg; + } + } ); - // no one in their right mind would ever create a `@` prototype, so Im just gonna store - // my function on the server, so I can remove it later again once the server(s) closes - this.server['@'] = function connection (socket) { - socket.once('data', function requestData (data) { - // if it's a Flash policy request, and we can write to the - if ( - data - && data[0] === 60 - && data.toString() === '\0' - && socket - && (socket.readyState === 'open' || socket.readyState === 'writeOnly') - ){ - // send the buffer - try { - socket.end(me.buffer); - } catch (e) {} - } - }); - }; + if ( this.server ) { - // attach it - this.server.on('connection', this.server['@']); - } + // no one in their right mind would ever create a `@` prototype, so Im just gonna store + // my function on the server, so I can remove it later again once the server(s) closes + this.server['@'] = function connection( socket ) { + socket.once( 'data', function requestData( data ) { + // if it's a Flash policy request, and we can write to the + if ( + data + && data[0] === 60 + && data.toString() === '\0' + && socket + && (socket.readyState === 'open' || socket.readyState === 'writeOnly') + ) { + // send the buffer + try { + socket.end( me.buffer ); + } catch ( e ) { + } + } + } ); + }; - // We add a callback method, so we can set a flag for when the server is `enabled` or `online`. - // this flag is needed because if a error occurs and the we cannot boot up the server the - // fallback functionality should not be removed during the `close` event - this.port >= 0 && this.socket.listen(this.port, function serverListening () { - me.socket.online = true; - if (callback) { - callback.call(me); - callback = undefined; - } - }); + // attach it + this.server.on( 'connection', this.server['@'] ); + } - return this; + // We add a callback method, so we can set a flag for when the server is `enabled` or `online`. + // this flag is needed because if a error occurs and the we cannot boot up the server the + // fallback functionality should not be removed during the `close` event + this.port >= 0 && this.socket.listen( this.port, function serverListening() { + me.socket.online = true; + if ( callback ) { + callback.call( me ); + callback = undefined; + } + } ); + + return this; }; /** @@ -148,12 +156,13 @@ Server.prototype.listen = function listen (port, server, cb){ * @api private */ -Server.prototype.responder = function responder (socket){ - if (socket && socket.readyState == 'open' && socket.end) { - try { - socket.end(this.buffer); - } catch (e) {} - } +Server.prototype.responder = function responder( socket ) { + if ( socket && socket.readyState == 'open' && socket.end ) { + try { + socket.end( this.buffer ); + } catch ( e ) { + } + } }; /** @@ -163,25 +172,25 @@ Server.prototype.responder = function responder (socket){ * @api private */ -Server.prototype.compile = function compile (){ - var xml = [ - '' - , '' - , '' - ]; +Server.prototype.compile = function compile() { + var xml = [ + '' + , '' + , '' + ]; - // add the allow access element - this.origins.forEach(function origin (origin){ - var parts = origin.split(':'); - xml.push(''); - }); + // add the allow access element + this.origins.forEach( function origin( origin ) { + var parts = origin.split( ':' ); + xml.push( '' ); + } ); - xml.push(''); + xml.push( '' ); - // store the result in a buffer so we don't have to re-generate it all the time - this.buffer = new Buffer(xml.join(''), 'utf8'); + // store the result in a buffer so we don't have to re-generate it all the time + this.buffer = new Buffer( xml.join( '' ), 'utf8' ); - return this; + return this; }; /** @@ -191,28 +200,28 @@ Server.prototype.compile = function compile (){ * @api public */ -Server.prototype.add = function add(){ - var args = slice.call(arguments, 0) - , i = args.length; +Server.prototype.add = function add() { + var args = slice.call( arguments, 0 ) + , i = args.length; - // flag duplicates - while (i--) { - if (this.origins.indexOf(args[i]) >= 0){ - args[i] = null; - } - } + // flag duplicates + while ( i-- ) { + if ( this.origins.indexOf( args[i] ) >= 0 ) { + args[i] = null; + } + } - // Add all the arguments to the array - // but first we want to remove all `falsy` values from the args - Array.prototype.push.apply( - this.origins - , args.filter(function filter (value) { - return !!value; - }) - ); + // Add all the arguments to the array + // but first we want to remove all `falsy` values from the args + Array.prototype.push.apply( + this.origins + , args.filter( function filter( value ) { + return !!value; + } ) + ); - this.compile(); - return this; + this.compile(); + return this; }; /** @@ -222,16 +231,16 @@ Server.prototype.add = function add(){ * @api public */ -Server.prototype.remove = function remove (origin){ - var position = this.origins.indexOf(origin); +Server.prototype.remove = function remove( origin ) { + var position = this.origins.indexOf( origin ); - // only remove and recompile if we have a match - if (position > 0) { - this.origins.splice(position,1); - this.compile(); - } + // only remove and recompile if we have a match + if ( position > 0 ) { + this.origins.splice( position, 1 ); + this.compile(); + } - return this; + return this; }; /** @@ -240,26 +249,26 @@ Server.prototype.remove = function remove (origin){ * @api public */ -Server.prototype.close = function close () { - this.socket.removeAllListeners(); - this.socket.close(); +Server.prototype.close = function close() { + this.socket.removeAllListeners(); + this.socket.close(); - return this; + return this; }; /** * Proxy the event listener requests to the created Net server */ -Object.keys(process.EventEmitter.prototype).forEach(function proxy (key){ - Server.prototype[key] = Server.prototype[key] || function () { - if (this.socket) { - this.socket[key].apply(this.socket, arguments); - } +Object.keys( process.EventEmitter.prototype ).forEach( function proxy( key ) { + Server.prototype[key] = Server.prototype[key] || function () { + if ( this.socket ) { + this.socket[key].apply( this.socket, arguments ); + } - return this; - }; -}); + return this; + }; +} ); /** * Creates a new server instance. @@ -269,11 +278,11 @@ Object.keys(process.EventEmitter.prototype).forEach(function proxy (key){ * @api public */ -exports.createServer = function createServer(options, origins){ - origins = Array.isArray(origins) ? origins : (Array.isArray(options) ? options : false); - options = !Array.isArray(options) && options ? options : {}; +exports.createServer = function createServer( options, origins ) { + origins = Array.isArray( origins ) ? origins : (Array.isArray( options ) ? options : false); + options = !Array.isArray( options ) && options ? options : {}; - return new Server(options, origins); + return new Server( options, origins ); }; /** diff --git a/example/node/node_modules/socket.io/node_modules/policyfile/package.json b/example/node/node_modules/socket.io/node_modules/policyfile/package.json index 78526c5..d1c7d9b 100644 --- a/example/node/node_modules/socket.io/node_modules/policyfile/package.json +++ b/example/node/node_modules/socket.io/node_modules/policyfile/package.json @@ -1,32 +1,29 @@ { - "name": "policyfile" - , "version": "0.0.4" - , "author": "Arnout Kazemier" - , "description": "Flash Socket Policy File Server. A server to respond to Flash Socket Policy requests, both inline and through a dedicated server instance." - , "main": "index" - , "keywords":[ - "flash" - , "socket" - , "policy" - , "file" - , "server" - , "Flash Socket Policy File Server" - , "cross domain" - ] - , "directories": { - "lib": "./lib" - } - , "maintainers": [{ - "name":"Arnout Kazemier" - , "email":"info@3rd-Eden.com" - , "web":"http://blog.3rd-Eden.com" - }] - , "licenses": [{ - "type": "MIT" - , "url": "https://github.com/3rd-Eden/FlashPolicyFileServer/blob/master/LICENSE" - }] - , "repositories": [{ - "type": "git" - , "url" : "https://github.com/3rd-Eden/FlashPolicyFileServer.git" - }] + "name" : "policyfile", "version" : "0.0.4", "author" : "Arnout Kazemier", "description" : "Flash Socket Policy File Server. A server to respond to Flash Socket Policy requests, both inline and through a dedicated server instance.", "main" : "index", "keywords" : [ + "flash" + , "socket" + , "policy" + , "file" + , "server" + , "Flash Socket Policy File Server" + , "cross domain" +], "directories" : { + "lib" : "./lib" +}, "maintainers" : [ + { + "name" : "Arnout Kazemier", + "email" : "info@3rd-Eden.com", + "web" : "http://blog.3rd-Eden.com" + } +], "licenses" : [ + { + "type" : "MIT", + "url" : "https://github.com/3rd-Eden/FlashPolicyFileServer/blob/master/LICENSE" + } +], "repositories" : [ + { + "type" : "git", + "url" : "https://github.com/3rd-Eden/FlashPolicyFileServer.git" + } +] } diff --git a/example/node/node_modules/socket.io/node_modules/policyfile/tests/unit.test.js b/example/node/node_modules/socket.io/node_modules/policyfile/tests/unit.test.js index 932b3c1..32a0090 100644 --- a/example/node/node_modules/socket.io/node_modules/policyfile/tests/unit.test.js +++ b/example/node/node_modules/socket.io/node_modules/policyfile/tests/unit.test.js @@ -1,231 +1,216 @@ -var fspfs = require('../') - , fs = require('fs') - , http = require('http') - , https = require('https') - , net = require('net') - , should = require('should') - , assert = require('assert'); +var fspfs = require( '../' ) + , fs = require( 'fs' ) + , http = require( 'http' ) + , https = require( 'https' ) + , net = require( 'net' ) + , should = require( 'should' ) + , assert = require( 'assert' ); module.exports = { - // Library version should be Semver compatible - 'Library version': function(){ - fspfs.version.should.match(/^\d+\.\d+\.\d+$/); - } + // Library version should be Semver compatible + 'Library version' : function () { + fspfs.version.should.match( /^\d+\.\d+\.\d+$/ ); + } - // Creating a server instace should not cause any problems - // either using the new Server or createServer method. -, 'Create Server instance': function(){ - var server = fspfs.createServer() - , server2 = new fspfs.Server({log:false}, ['blog.3rd-Eden.com:1337']); - - // server 2 options test - server2.log.should.be.false; - server2.origins.length.should.equal(1); - server2.origins[0].should.equal('blog.3rd-Eden.com:1337'); - - // server defaults - (typeof server.log).should.be.equal('function'); - server.origins.length.should.equal(1); - server.origins[0].should.equal('*:*'); - - // instance checking, sanity check - assert.ok(server instanceof fspfs.Server); - assert.ok(!!server.buffer); - - // more options testing - server = fspfs.createServer(['blog.3rd-Eden.com:80']); - server.origins.length.should.equal(1); - server.origins[0].should.equal('blog.3rd-Eden.com:80'); - - server = fspfs.createServer({log:false},['blog.3rd-Eden.com:80']); - server.log.should.be.false; - server.origins.length.should.equal(1); - server.origins[0].should.equal('blog.3rd-Eden.com:80'); - - } + // Creating a server instace should not cause any problems + // either using the new Server or createServer method., 'Create Server instance' : function () { + var server = fspfs.createServer() + , server2 = new fspfs.Server( {log : false}, ['blog.3rd-Eden.com:1337'] ); -, 'Add origin': function(){ - var server = fspfs.createServer(); - server.add('google.com:80', 'blog.3rd-Eden.com:1337'); - - server.origins.length.should.equal(3); - server.origins.indexOf('google.com:80').should.be.above(0); - - // don't allow duplicates - server.add('google.com:80', 'google.com:80'); - - var i = server.origins.length - , count = 0; - - while(i--){ - if (server.origins[i] === 'google.com:80'){ - count++; - } - } - - count.should.equal(1); - } + // server 2 options test + server2.log.should.be.false; + server2.origins.length.should.equal( 1 ); + server2.origins[0].should.equal( 'blog.3rd-Eden.com:1337' ); -, 'Remove origin': function(){ - var server = fspfs.createServer(); - server.add('google.com:80', 'blog.3rd-Eden.com:1337'); - server.origins.length.should.equal(3); - - server.remove('google.com:80'); - server.origins.length.should.equal(2); - server.origins.indexOf('google.com:80').should.equal(-1); - } + // server defaults + (typeof server.log).should.be.equal( 'function' ); + server.origins.length.should.equal( 1 ); + server.origins[0].should.equal( '*:*' ); -, 'Buffer': function(){ - var server = fspfs.createServer(); - - Buffer.isBuffer(server.buffer).should.be.true; - server.buffer.toString().indexOf('to-ports="*"').should.be.above(0); - server.buffer.toString().indexOf('domain="*"').should.be.above(0); - server.buffer.toString().indexOf('domain="google.com"').should.equal(-1); - - // The buffers should be rebuild when new origins are added - server.add('google.com:80'); - server.buffer.toString().indexOf('to-ports="80"').should.be.above(0); - server.buffer.toString().indexOf('domain="google.com"').should.be.above(0); - - server.remove('google.com:80'); - server.buffer.toString().indexOf('to-ports="80"').should.equal(-1); - server.buffer.toString().indexOf('domain="google.com"').should.equal(-1); - } + // instance checking, sanity check + assert.ok( server instanceof fspfs.Server ); + assert.ok( !!server.buffer ); -, 'Responder': function(){ - var server = fspfs.createServer() - , calls = 0 - // dummy socket to emulate a `real` socket - , dummySocket = { - readyState: 'open' - , end: function(buffer){ - calls++; - Buffer.isBuffer(buffer).should.be.true; - buffer.toString().should.equal(server.buffer.toString()); - } - }; - - server.responder(dummySocket); - calls.should.equal(1); - } + // more options testing + server = fspfs.createServer( ['blog.3rd-Eden.com:80'] ); + server.origins.length.should.equal( 1 ); + server.origins[0].should.equal( 'blog.3rd-Eden.com:80' ); -, 'Event proxy': function(){ - var server = fspfs.createServer() - , calls = 0; - - Object.keys(process.EventEmitter.prototype).forEach(function proxy(key){ - assert.ok(!!server[key] && typeof server[key] === 'function'); - }); - - // test if it works by calling a none default event - server.on('pew', function(){ - calls++; - }); - - server.emit('pew'); - calls.should.equal(1); - } + server = fspfs.createServer( {log : false}, ['blog.3rd-Eden.com:80'] ); + server.log.should.be.false; + server.origins.length.should.equal( 1 ); + server.origins[0].should.equal( 'blog.3rd-Eden.com:80' ); -, 'inline response http': function(){ - var port = 1335 - , httpserver = http.createServer(function(q,r){r.writeHead(200);r.end(':3')}) - , server = fspfs.createServer(); - - httpserver.listen(port, function(){ - server.listen(port + 1, httpserver, function(){ - var client = net.createConnection(port); - client.write('\0'); - client.on('error', function(err){ - assert.ok(!err, err) - }); - client.on('data', function(data){ - - var response = data.toString(); - console.log(response); - - response.indexOf('to-ports="*"').should.be.above(0); - response.indexOf('domain="*"').should.be.above(0); - response.indexOf('domain="google.com"').should.equal(-1); - - // clean up - client.destroy(); - server.close(); - httpserver.close(); - }); - }); - }); - } + }, 'Add origin' : function () { + var server = fspfs.createServer(); + server.add( 'google.com:80', 'blog.3rd-Eden.com:1337' ); -, 'server response': function(){ - var port = 1340 - , server = fspfs.createServer(); - - server.listen(port, function(){ - var client = net.createConnection(port); - client.write('\0'); - client.on('error', function(err){ - assert.ok(!err, err) - }); - client.on('data', function(data){ - - var response = data.toString(); - - response.indexOf('to-ports="*"').should.be.above(0); - response.indexOf('domain="*"').should.be.above(0); - response.indexOf('domain="google.com"').should.equal(-1); - - // clean up - client.destroy(); - server.close(); - }); - }); - } + server.origins.length.should.equal( 3 ); + server.origins.indexOf( 'google.com:80' ).should.be.above( 0 ); -, 'inline response https': function(){ - var port = 1345 - , ssl = { - key: fs.readFileSync(__dirname + '/ssl/ssl.private.key').toString() - , cert: fs.readFileSync(__dirname + '/ssl/ssl.crt').toString() - } - , httpserver = https.createServer(ssl, function(q,r){r.writeHead(200);r.end(':3')}) - , server = fspfs.createServer(); - - httpserver.listen(port, function(){ - server.listen(port + 1, httpserver, function(){ - var client = net.createConnection(port); - client.write('\0'); - client.on('error', function(err){ - assert.ok(!err, err) - }); - client.on('data', function(data){ - - var response = data.toString(); - - response.indexOf('to-ports="*"').should.be.above(0); - response.indexOf('domain="*"').should.be.above(0); - response.indexOf('domain="google.com"').should.equal(-1); - - // clean up - client.destroy(); - server.close(); - httpserver.close(); - }); - }); - }); - } + // don't allow duplicates + server.add( 'google.com:80', 'google.com:80' ); -, 'connect_failed': function(){ - var server = fspfs.createServer(); - - server.on('connect_failed', function(){ - assert.ok(true); - }); - - server.listen(function(){ - assert.ok(false, 'Run this test without root access'); - server.close(); - }); - } + var i = server.origins.length + , count = 0; + + while ( i-- ) { + if ( server.origins[i] === 'google.com:80' ) { + count++; + } + } + + count.should.equal( 1 ); + }, 'Remove origin' : function () { + var server = fspfs.createServer(); + server.add( 'google.com:80', 'blog.3rd-Eden.com:1337' ); + server.origins.length.should.equal( 3 ); + + server.remove( 'google.com:80' ); + server.origins.length.should.equal( 2 ); + server.origins.indexOf( 'google.com:80' ).should.equal( -1 ); + }, 'Buffer' : function () { + var server = fspfs.createServer(); + + Buffer.isBuffer( server.buffer ).should.be.true; + server.buffer.toString().indexOf( 'to-ports="*"' ).should.be.above( 0 ); + server.buffer.toString().indexOf( 'domain="*"' ).should.be.above( 0 ); + server.buffer.toString().indexOf( 'domain="google.com"' ).should.equal( -1 ); + + // The buffers should be rebuild when new origins are added + server.add( 'google.com:80' ); + server.buffer.toString().indexOf( 'to-ports="80"' ).should.be.above( 0 ); + server.buffer.toString().indexOf( 'domain="google.com"' ).should.be.above( 0 ); + + server.remove( 'google.com:80' ); + server.buffer.toString().indexOf( 'to-ports="80"' ).should.equal( -1 ); + server.buffer.toString().indexOf( 'domain="google.com"' ).should.equal( -1 ); + }, 'Responder' : function () { + var server = fspfs.createServer() + , calls = 0 + // dummy socket to emulate a `real` socket + , dummySocket = { + readyState : 'open', end : function ( buffer ) { + calls++; + Buffer.isBuffer( buffer ).should.be.true; + buffer.toString().should.equal( server.buffer.toString() ); + } + }; + + server.responder( dummySocket ); + calls.should.equal( 1 ); + }, 'Event proxy' : function () { + var server = fspfs.createServer() + , calls = 0; + + Object.keys( process.EventEmitter.prototype ).forEach( function proxy( key ) { + assert.ok( !!server[key] && typeof server[key] === 'function' ); + } ); + + // test if it works by calling a none default event + server.on( 'pew', function () { + calls++; + } ); + + server.emit( 'pew' ); + calls.should.equal( 1 ); + }, 'inline response http' : function () { + var port = 1335 + , httpserver = http.createServer( function ( q, r ) { + r.writeHead( 200 ); + r.end( ':3' ) + } ) + , server = fspfs.createServer(); + + httpserver.listen( port, function () { + server.listen( port + 1, httpserver, function () { + var client = net.createConnection( port ); + client.write( '\0' ); + client.on( 'error', function ( err ) { + assert.ok( !err, err ) + } ); + client.on( 'data', function ( data ) { + + var response = data.toString(); + console.log( response ); + + response.indexOf( 'to-ports="*"' ).should.be.above( 0 ); + response.indexOf( 'domain="*"' ).should.be.above( 0 ); + response.indexOf( 'domain="google.com"' ).should.equal( -1 ); + + // clean up + client.destroy(); + server.close(); + httpserver.close(); + } ); + } ); + } ); + }, 'server response' : function () { + var port = 1340 + , server = fspfs.createServer(); + + server.listen( port, function () { + var client = net.createConnection( port ); + client.write( '\0' ); + client.on( 'error', function ( err ) { + assert.ok( !err, err ) + } ); + client.on( 'data', function ( data ) { + + var response = data.toString(); + + response.indexOf( 'to-ports="*"' ).should.be.above( 0 ); + response.indexOf( 'domain="*"' ).should.be.above( 0 ); + response.indexOf( 'domain="google.com"' ).should.equal( -1 ); + + // clean up + client.destroy(); + server.close(); + } ); + } ); + }, 'inline response https' : function () { + var port = 1345 + , ssl = { + key : fs.readFileSync( __dirname + '/ssl/ssl.private.key' ).toString(), cert : fs.readFileSync( __dirname + '/ssl/ssl.crt' ).toString() + } + , httpserver = https.createServer( ssl, function ( q, r ) { + r.writeHead( 200 ); + r.end( ':3' ) + } ) + , server = fspfs.createServer(); + + httpserver.listen( port, function () { + server.listen( port + 1, httpserver, function () { + var client = net.createConnection( port ); + client.write( '\0' ); + client.on( 'error', function ( err ) { + assert.ok( !err, err ) + } ); + client.on( 'data', function ( data ) { + + var response = data.toString(); + + response.indexOf( 'to-ports="*"' ).should.be.above( 0 ); + response.indexOf( 'domain="*"' ).should.be.above( 0 ); + response.indexOf( 'domain="google.com"' ).should.equal( -1 ); + + // clean up + client.destroy(); + server.close(); + httpserver.close(); + } ); + } ); + } ); + }, 'connect_failed' : function () { + var server = fspfs.createServer(); + + server.on( 'connect_failed', function () { + assert.ok( true ); + } ); + + server.listen( function () { + assert.ok( false, 'Run this test without root access' ); + server.close(); + } ); + } }; \ No newline at end of file diff --git a/example/node/node_modules/socket.io/node_modules/redis/eval_test.js b/example/node/node_modules/socket.io/node_modules/redis/eval_test.js index c1fbf8a..db214af 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/eval_test.js +++ b/example/node/node_modules/socket.io/node_modules/redis/eval_test.js @@ -1,9 +1,9 @@ -var redis = require("./index"), - client = redis.createClient(); +var redis = require( "./index" ), + client = redis.createClient(); redis.debug_mode = true; -client.eval("return 100.5", 0, function (err, res) { - console.dir(err); - console.dir(res); -}); +client.eval( "return 100.5", 0, function ( err, res ) { + console.dir( err ); + console.dir( res ); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/auth.js b/example/node/node_modules/socket.io/node_modules/redis/examples/auth.js index 6c0a563..a9ca0dc 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/auth.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/auth.js @@ -1,5 +1,5 @@ -var redis = require("redis"), - client = redis.createClient(); +var redis = require( "redis" ), + client = redis.createClient(); // This command is magical. Client stashes the password and will issue on every connect. -client.auth("somepass"); +client.auth( "somepass" ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/backpressure_drain.js b/example/node/node_modules/socket.io/node_modules/redis/examples/backpressure_drain.js index 3488ef4..68310a6 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/backpressure_drain.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/backpressure_drain.js @@ -1,33 +1,33 @@ -var redis = require("../index"), - client = redis.createClient(null, null, { - command_queue_high_water: 5, - command_queue_low_water: 1 - }), - remaining_ops = 100000, paused = false; +var redis = require( "../index" ), + client = redis.createClient( null, null, { + command_queue_high_water : 5, + command_queue_low_water : 1 + } ), + remaining_ops = 100000, paused = false; function op() { - if (remaining_ops <= 0) { - console.error("Finished."); - process.exit(0); - } + if ( remaining_ops <= 0 ) { + console.error( "Finished." ); + process.exit( 0 ); + } - remaining_ops--; - if (client.hset("test hash", "val " + remaining_ops, remaining_ops) === false) { - console.log("Pausing at " + remaining_ops); - paused = true; - } else { - process.nextTick(op); - } + remaining_ops--; + if ( client.hset( "test hash", "val " + remaining_ops, remaining_ops ) === false ) { + console.log( "Pausing at " + remaining_ops ); + paused = true; + } else { + process.nextTick( op ); + } } -client.on("drain", function () { - if (paused) { - console.log("Resuming at " + remaining_ops); - paused = false; - process.nextTick(op); - } else { - console.log("Got drain while not paused at " + remaining_ops); - } -}); +client.on( "drain", function () { + if ( paused ) { + console.log( "Resuming at " + remaining_ops ); + paused = false; + process.nextTick( op ); + } else { + console.log( "Got drain while not paused at " + remaining_ops ); + } +} ); op(); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/extend.js b/example/node/node_modules/socket.io/node_modules/redis/examples/extend.js index 488b8c2..d6c57e0 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/extend.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/extend.js @@ -1,24 +1,24 @@ -var redis = require("redis"), - client = redis.createClient(); +var redis = require( "redis" ), + client = redis.createClient(); // Extend the RedisClient prototype to add a custom method // This one converts the results from "INFO" into a JavaScript Object -redis.RedisClient.prototype.parse_info = function (callback) { - this.info(function (err, res) { - var lines = res.toString().split("\r\n").sort(); - var obj = {}; - lines.forEach(function (line) { - var parts = line.split(':'); - if (parts[1]) { - obj[parts[0]] = parts[1]; - } - }); - callback(obj) - }); +redis.RedisClient.prototype.parse_info = function ( callback ) { + this.info( function ( err, res ) { + var lines = res.toString().split( "\r\n" ).sort(); + var obj = {}; + lines.forEach( function ( line ) { + var parts = line.split( ':' ); + if ( parts[1] ) { + obj[parts[0]] = parts[1]; + } + } ); + callback( obj ) + } ); }; -client.parse_info(function (info) { - console.dir(info); - client.quit(); -}); +client.parse_info( function ( info ) { + console.dir( info ); + client.quit(); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/file.js b/example/node/node_modules/socket.io/node_modules/redis/examples/file.js index 4d2b5d1..21cc509 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/file.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/file.js @@ -1,32 +1,34 @@ // Read a file from disk, store it in Redis, then read it back from Redis. -var redis = require("redis"), - client = redis.createClient(), - fs = require("fs"), - filename = "kids_in_cart.jpg"; +var redis = require( "redis" ), + client = redis.createClient(), + fs = require( "fs" ), + filename = "kids_in_cart.jpg"; // Get the file I use for testing like this: // curl http://ranney.com/kids_in_cart.jpg -o kids_in_cart.jpg // or just use your own file. // Read a file from fs, store it in Redis, get it back from Redis, write it back to fs. -fs.readFile(filename, function (err, data) { - if (err) throw err - console.log("Read " + data.length + " bytes from filesystem."); - - client.set(filename, data, redis.print); // set entire file - client.get(filename, function (err, reply) { // get entire file - if (err) { - console.log("Get error: " + err); - } else { - fs.writeFile("duplicate_" + filename, reply, function (err) { - if (err) { - console.log("Error on write: " + err) - } else { - console.log("File written."); - } - client.end(); - }); - } - }); -}); +fs.readFile( filename, function ( err, data ) { + if ( err ) { + throw err + } + console.log( "Read " + data.length + " bytes from filesystem." ); + + client.set( filename, data, redis.print ); // set entire file + client.get( filename, function ( err, reply ) { // get entire file + if ( err ) { + console.log( "Get error: " + err ); + } else { + fs.writeFile( "duplicate_" + filename, reply, function ( err ) { + if ( err ) { + console.log( "Error on write: " + err ) + } else { + console.log( "File written." ); + } + client.end(); + } ); + } + } ); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/mget.js b/example/node/node_modules/socket.io/node_modules/redis/examples/mget.js index 936740d..a38929b 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/mget.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/mget.js @@ -1,5 +1,5 @@ -var client = require("redis").createClient(); +var client = require( "redis" ).createClient(); -client.mget(["sessions started", "sessions started", "foo"], function (err, res) { - console.dir(res); -}); \ No newline at end of file +client.mget( ["sessions started", "sessions started", "foo"], function ( err, res ) { + console.dir( res ); +} ); \ No newline at end of file diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/monitor.js b/example/node/node_modules/socket.io/node_modules/redis/examples/monitor.js index 2cb6a4e..77e0c60 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/monitor.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/monitor.js @@ -1,10 +1,10 @@ -var client = require("../index").createClient(), - util = require("util"); +var client = require( "../index" ).createClient(), + util = require( "util" ); -client.monitor(function (err, res) { - console.log("Entering monitoring mode."); -}); +client.monitor( function ( err, res ) { + console.log( "Entering monitoring mode." ); +} ); -client.on("monitor", function (time, args) { - console.log(time + ": " + util.inspect(args)); -}); +client.on( "monitor", function ( time, args ) { + console.log( time + ": " + util.inspect( args ) ); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/multi.js b/example/node/node_modules/socket.io/node_modules/redis/examples/multi.js index 35c08e1..9162894 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/multi.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/multi.js @@ -1,46 +1,46 @@ -var redis = require("redis"), - client = redis.createClient(), set_size = 20; +var redis = require( "redis" ), + client = redis.createClient(), set_size = 20; -client.sadd("bigset", "a member"); -client.sadd("bigset", "another member"); +client.sadd( "bigset", "a member" ); +client.sadd( "bigset", "another member" ); -while (set_size > 0) { - client.sadd("bigset", "member " + set_size); - set_size -= 1; +while ( set_size > 0 ) { + client.sadd( "bigset", "member " + set_size ); + set_size -= 1; } // multi chain with an individual callback client.multi() - .scard("bigset") - .smembers("bigset") - .keys("*", function (err, replies) { - client.mget(replies, redis.print); - }) - .dbsize() - .exec(function (err, replies) { - console.log("MULTI got " + replies.length + " replies"); - replies.forEach(function (reply, index) { - console.log("Reply " + index + ": " + reply.toString()); - }); - }); + .scard( "bigset" ) + .smembers( "bigset" ) + .keys( "*", function ( err, replies ) { + client.mget( replies, redis.print ); + } ) + .dbsize() + .exec( function ( err, replies ) { + console.log( "MULTI got " + replies.length + " replies" ); + replies.forEach( function ( reply, index ) { + console.log( "Reply " + index + ": " + reply.toString() ); + } ); + } ); -client.mset("incr thing", 100, "incr other thing", 1, redis.print); +client.mset( "incr thing", 100, "incr other thing", 1, redis.print ); // start a separate multi command queue var multi = client.multi(); -multi.incr("incr thing", redis.print); -multi.incr("incr other thing", redis.print); +multi.incr( "incr thing", redis.print ); +multi.incr( "incr other thing", redis.print ); // runs immediately -client.get("incr thing", redis.print); // 100 +client.get( "incr thing", redis.print ); // 100 // drains multi queue and runs atomically -multi.exec(function (err, replies) { - console.log(replies); // 101, 2 -}); +multi.exec( function ( err, replies ) { + console.log( replies ); // 101, 2 +} ); // you can re-run the same transaction if you like -multi.exec(function (err, replies) { - console.log(replies); // 102, 3 - client.quit(); -}); +multi.exec( function ( err, replies ) { + console.log( replies ); // 102, 3 + client.quit(); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/multi2.js b/example/node/node_modules/socket.io/node_modules/redis/examples/multi2.js index 8be4d73..4e326ce 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/multi2.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/multi2.js @@ -1,29 +1,29 @@ -var redis = require("redis"), - client = redis.createClient(), multi; +var redis = require( "redis" ), + client = redis.createClient(), multi; // start a separate command queue for multi multi = client.multi(); -multi.incr("incr thing", redis.print); -multi.incr("incr other thing", redis.print); +multi.incr( "incr thing", redis.print ); +multi.incr( "incr other thing", redis.print ); // runs immediately -client.mset("incr thing", 100, "incr other thing", 1, redis.print); +client.mset( "incr thing", 100, "incr other thing", 1, redis.print ); // drains multi queue and runs atomically -multi.exec(function (err, replies) { - console.log(replies); // 101, 2 -}); +multi.exec( function ( err, replies ) { + console.log( replies ); // 101, 2 +} ); // you can re-run the same transaction if you like -multi.exec(function (err, replies) { - console.log(replies); // 102, 3 - client.quit(); -}); +multi.exec( function ( err, replies ) { + console.log( replies ); // 102, 3 + client.quit(); +} ); -client.multi([ - ["mget", "multifoo", "multibar", redis.print], - ["incr", "multifoo"], - ["incr", "multibar"] -]).exec(function (err, replies) { - console.log(replies.toString()); -}); +client.multi( [ + ["mget", "multifoo", "multibar", redis.print], + ["incr", "multifoo"], + ["incr", "multibar"] +] ).exec( function ( err, replies ) { + console.log( replies.toString() ); + } ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/psubscribe.js b/example/node/node_modules/socket.io/node_modules/redis/examples/psubscribe.js index c57117b..9830de3 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/psubscribe.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/psubscribe.js @@ -1,33 +1,33 @@ -var redis = require("redis"), - client1 = redis.createClient(), - client2 = redis.createClient(), - client3 = redis.createClient(), - client4 = redis.createClient(), - msg_count = 0; +var redis = require( "redis" ), + client1 = redis.createClient(), + client2 = redis.createClient(), + client3 = redis.createClient(), + client4 = redis.createClient(), + msg_count = 0; redis.debug_mode = false; -client1.on("psubscribe", function (pattern, count) { - console.log("client1 psubscribed to " + pattern + ", " + count + " total subscriptions"); - client2.publish("channeltwo", "Me!"); - client3.publish("channelthree", "Me too!"); - client4.publish("channelfour", "And me too!"); -}); +client1.on( "psubscribe", function ( pattern, count ) { + console.log( "client1 psubscribed to " + pattern + ", " + count + " total subscriptions" ); + client2.publish( "channeltwo", "Me!" ); + client3.publish( "channelthree", "Me too!" ); + client4.publish( "channelfour", "And me too!" ); +} ); -client1.on("punsubscribe", function (pattern, count) { - console.log("client1 punsubscribed from " + pattern + ", " + count + " total subscriptions"); - client4.end(); - client3.end(); - client2.end(); - client1.end(); -}); +client1.on( "punsubscribe", function ( pattern, count ) { + console.log( "client1 punsubscribed from " + pattern + ", " + count + " total subscriptions" ); + client4.end(); + client3.end(); + client2.end(); + client1.end(); +} ); -client1.on("pmessage", function (pattern, channel, message) { - console.log("("+ pattern +")" + " client1 received message on " + channel + ": " + message); - msg_count += 1; - if (msg_count === 3) { - client1.punsubscribe(); - } -}); +client1.on( "pmessage", function ( pattern, channel, message ) { + console.log( "(" + pattern + ")" + " client1 received message on " + channel + ": " + message ); + msg_count += 1; + if ( msg_count === 3 ) { + client1.punsubscribe(); + } +} ); -client1.psubscribe("channel*"); +client1.psubscribe( "channel*" ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/pub_sub.js b/example/node/node_modules/socket.io/node_modules/redis/examples/pub_sub.js index aa508d6..2e8fc3e 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/pub_sub.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/pub_sub.js @@ -1,41 +1,41 @@ -var redis = require("redis"), - client1 = redis.createClient(), msg_count = 0, - client2 = redis.createClient(); +var redis = require( "redis" ), + client1 = redis.createClient(), msg_count = 0, + client2 = redis.createClient(); redis.debug_mode = false; // Most clients probably don't do much on "subscribe". This example uses it to coordinate things within one program. -client1.on("subscribe", function (channel, count) { - console.log("client1 subscribed to " + channel + ", " + count + " total subscriptions"); - if (count === 2) { - client2.publish("a nice channel", "I am sending a message."); - client2.publish("another one", "I am sending a second message."); - client2.publish("a nice channel", "I am sending my last message."); - } -}); +client1.on( "subscribe", function ( channel, count ) { + console.log( "client1 subscribed to " + channel + ", " + count + " total subscriptions" ); + if ( count === 2 ) { + client2.publish( "a nice channel", "I am sending a message." ); + client2.publish( "another one", "I am sending a second message." ); + client2.publish( "a nice channel", "I am sending my last message." ); + } +} ); -client1.on("unsubscribe", function (channel, count) { - console.log("client1 unsubscribed from " + channel + ", " + count + " total subscriptions"); - if (count === 0) { - client2.end(); - client1.end(); - } -}); +client1.on( "unsubscribe", function ( channel, count ) { + console.log( "client1 unsubscribed from " + channel + ", " + count + " total subscriptions" ); + if ( count === 0 ) { + client2.end(); + client1.end(); + } +} ); -client1.on("message", function (channel, message) { - console.log("client1 channel " + channel + ": " + message); - msg_count += 1; - if (msg_count === 3) { - client1.unsubscribe(); - } -}); +client1.on( "message", function ( channel, message ) { + console.log( "client1 channel " + channel + ": " + message ); + msg_count += 1; + if ( msg_count === 3 ) { + client1.unsubscribe(); + } +} ); -client1.on("ready", function () { - // if you need auth, do it here - client1.incr("did a thing"); - client1.subscribe("a nice channel", "another one"); -}); +client1.on( "ready", function () { + // if you need auth, do it here + client1.incr( "did a thing" ); + client1.subscribe( "a nice channel", "another one" ); +} ); -client2.on("ready", function () { - // if you need auth, do it here -}); +client2.on( "ready", function () { + // if you need auth, do it here +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/simple.js b/example/node/node_modules/socket.io/node_modules/redis/examples/simple.js index b93c557..9fd0cd0 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/simple.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/simple.js @@ -1,17 +1,17 @@ -var redis = require("redis"), - client = redis.createClient(); +var redis = require( "redis" ), + client = redis.createClient(); -client.on("error", function (err) { - console.log("Redis connection error to " + client.host + ":" + client.port + " - " + err); -}); +client.on( "error", function ( err ) { + console.log( "Redis connection error to " + client.host + ":" + client.port + " - " + err ); +} ); -client.set("string key", "string val", redis.print); -client.hset("hash key", "hashtest 1", "some value", redis.print); -client.hset(["hash key", "hashtest 2", "some other value"], redis.print); -client.hkeys("hash key", function (err, replies) { - console.log(replies.length + " replies:"); - replies.forEach(function (reply, i) { - console.log(" " + i + ": " + reply); - }); - client.quit(); -}); +client.set( "string key", "string val", redis.print ); +client.hset( "hash key", "hashtest 1", "some value", redis.print ); +client.hset( ["hash key", "hashtest 2", "some other value"], redis.print ); +client.hkeys( "hash key", function ( err, replies ) { + console.log( replies.length + " replies:" ); + replies.forEach( function ( reply, i ) { + console.log( " " + i + ": " + reply ); + } ); + client.quit(); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/subqueries.js b/example/node/node_modules/socket.io/node_modules/redis/examples/subqueries.js index 560db24..25b8716 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/subqueries.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/subqueries.js @@ -1,15 +1,15 @@ // Sending commands in response to other commands. // This example runs "type" against every key in the database // -var client = require("redis").createClient(); +var client = require( "redis" ).createClient(); -client.keys("*", function (err, keys) { - keys.forEach(function (key, pos) { - client.type(key, function (err, keytype) { - console.log(key + " is " + keytype); - if (pos === (keys.length - 1)) { - client.quit(); - } - }); - }); -}); +client.keys( "*", function ( err, keys ) { + keys.forEach( function ( key, pos ) { + client.type( key, function ( err, keytype ) { + console.log( key + " is " + keytype ); + if ( pos === (keys.length - 1) ) { + client.quit(); + } + } ); + } ); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/subquery.js b/example/node/node_modules/socket.io/node_modules/redis/examples/subquery.js index 861657e..c65a060 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/subquery.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/subquery.js @@ -1,19 +1,19 @@ -var client = require("redis").createClient(); +var client = require( "redis" ).createClient(); -function print_results(obj) { - console.dir(obj); +function print_results( obj ) { + console.dir( obj ); } // build a map of all keys and their types -client.keys("*", function (err, all_keys) { - var key_types = {}; - - all_keys.forEach(function (key, pos) { // use second arg of forEach to get pos - client.type(key, function (err, type) { - key_types[key] = type; - if (pos === all_keys.length - 1) { // callbacks all run in order - print_results(key_types); - } - }); - }); -}); +client.keys( "*", function ( err, all_keys ) { + var key_types = {}; + + all_keys.forEach( function ( key, pos ) { // use second arg of forEach to get pos + client.type( key, function ( err, type ) { + key_types[key] = type; + if ( pos === all_keys.length - 1 ) { // callbacks all run in order + print_results( key_types ); + } + } ); + } ); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/unix_socket.js b/example/node/node_modules/socket.io/node_modules/redis/examples/unix_socket.js index 4a5e0bb..bfee2b5 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/unix_socket.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/unix_socket.js @@ -1,29 +1,29 @@ -var redis = require("redis"), - client = redis.createClient("/tmp/redis.sock"), - profiler = require("v8-profiler"); +var redis = require( "redis" ), + client = redis.createClient( "/tmp/redis.sock" ), + profiler = require( "v8-profiler" ); -client.on("connect", function () { - console.log("Got Unix socket connection.") -}); +client.on( "connect", function () { + console.log( "Got Unix socket connection." ) +} ); -client.on("error", function (err) { - console.log(err.message); -}); +client.on( "error", function ( err ) { + console.log( err.message ); +} ); -client.set("space chars", "space value"); +client.set( "space chars", "space value" ); -setInterval(function () { - client.get("space chars"); -}, 100); +setInterval( function () { + client.get( "space chars" ); +}, 100 ); function done() { - client.info(function (err, reply) { - console.log(reply.toString()); - client.quit(); - }); + client.info( function ( err, reply ) { + console.log( reply.toString() ); + client.quit(); + } ); } -setTimeout(function () { - console.log("Taking snapshot."); - var snap = profiler.takeSnapshot(); -}, 5000); +setTimeout( function () { + console.log( "Taking snapshot." ); + var snap = profiler.takeSnapshot(); +}, 5000 ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/examples/web_server.js b/example/node/node_modules/socket.io/node_modules/redis/examples/web_server.js index 9fd8592..7a11878 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/examples/web_server.js +++ b/example/node/node_modules/socket.io/node_modules/redis/examples/web_server.js @@ -1,31 +1,32 @@ // A simple web server that generates dyanmic content based on responses from Redis -var http = require("http"), server, - redis_client = require("redis").createClient(); +var http = require( "http" ), server, + redis_client = require( "redis" ).createClient(); -server = http.createServer(function (request, response) { - response.writeHead(200, { - "Content-Type": "text/plain" - }); - - var redis_info, total_requests; - - redis_client.info(function (err, reply) { - redis_info = reply; // stash response in outer scope - }); - redis_client.incr("requests", function (err, reply) { - total_requests = reply; // stash response in outer scope - }); - redis_client.hincrby("ip", request.connection.remoteAddress, 1); - redis_client.hgetall("ip", function (err, reply) { - // This is the last reply, so all of the previous replies must have completed already - response.write("This page was generated after talking to redis.\n\n" + - "Redis info:\n" + redis_info + "\n" + - "Total requests: " + total_requests + "\n\n" + - "IP count: \n"); - Object.keys(reply).forEach(function (ip) { - response.write(" " + ip + ": " + reply[ip] + "\n"); - }); - response.end(); - }); -}).listen(80); +server = http.createServer( + function ( request, response ) { + response.writeHead( 200, { + "Content-Type" : "text/plain" + } ); + + var redis_info, total_requests; + + redis_client.info( function ( err, reply ) { + redis_info = reply; // stash response in outer scope + } ); + redis_client.incr( "requests", function ( err, reply ) { + total_requests = reply; // stash response in outer scope + } ); + redis_client.hincrby( "ip", request.connection.remoteAddress, 1 ); + redis_client.hgetall( "ip", function ( err, reply ) { + // This is the last reply, so all of the previous replies must have completed already + response.write( "This page was generated after talking to redis.\n\n" + + "Redis info:\n" + redis_info + "\n" + + "Total requests: " + total_requests + "\n\n" + + "IP count: \n" ); + Object.keys( reply ).forEach( function ( ip ) { + response.write( " " + ip + ": " + reply[ip] + "\n" ); + } ); + response.end(); + } ); + } ).listen( 80 ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/generate_commands.js b/example/node/node_modules/socket.io/node_modules/redis/generate_commands.js index e94d74e..d9ca8fa 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/generate_commands.js +++ b/example/node/node_modules/socket.io/node_modules/redis/generate_commands.js @@ -1,40 +1,41 @@ -var http = require("http"), - sys = require("sys"), - fs = require("fs"); +var http = require( "http" ), + sys = require( "sys" ), + fs = require( "fs" ); function prettyCurrentTime() { - var date = new Date(); - return date.toLocaleString(); + var date = new Date(); + return date.toLocaleString(); } -function write_file(commands, path) { - var file_contents, out_commands; +function write_file( commands, path ) { + var file_contents, out_commands; - console.log("Writing " + Object.keys(commands).length + " commands to " + path); + console.log( "Writing " + Object.keys( commands ).length + " commands to " + path ); - file_contents = "// This file was generated by ./generate_commands.js on " + prettyCurrentTime() + "\n"; + file_contents = "// This file was generated by ./generate_commands.js on " + prettyCurrentTime() + "\n"; - out_commands = Object.keys(commands).map(function (key) { - return key.toLowerCase(); - }); + out_commands = Object.keys( commands ).map( function ( key ) { + return key.toLowerCase(); + } ); - file_contents += "module.exports = " + JSON.stringify(out_commands, null, " ") + ";\n"; + file_contents += "module.exports = " + JSON.stringify( out_commands, null, " " ) + ";\n"; - fs.writeFile(path, file_contents); + fs.writeFile( path, file_contents ); } -http.get({host: "redis.io", path: "/commands.json"}, function (res) { - var body = ""; +http.get( {host : "redis.io", path : "/commands.json"}, + function ( res ) { + var body = ""; - console.log("Response from redis.io/commands.json: " + res.statusCode); + console.log( "Response from redis.io/commands.json: " + res.statusCode ); - res.on('data', function (chunk) { - body += chunk; - }); + res.on( 'data', function ( chunk ) { + body += chunk; + } ); - res.on('end', function () { - write_file(JSON.parse(body), "lib/commands.js"); - }); -}).on('error', function (e) { - console.log("Error fetching command list from redis.io: " + e.message); -}); + res.on( 'end', function () { + write_file( JSON.parse( body ), "lib/commands.js" ); + } ); + } ).on( 'error', function ( e ) { + console.log( "Error fetching command list from redis.io: " + e.message ); + } ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/index.js b/example/node/node_modules/socket.io/node_modules/redis/index.js index 8728cea..5cfb3fb 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/index.js +++ b/example/node/node_modules/socket.io/node_modules/redis/index.js @@ -1,860 +1,862 @@ /*global Buffer require exports console setTimeout */ -var net = require("net"), - util = require("./lib/util").util, - Queue = require("./lib/queue").Queue, - to_array = require("./lib/to_array"), - events = require("events"), - parsers = [], commands, - default_port = 6379, - default_host = "127.0.0.1"; +var net = require( "net" ), + util = require( "./lib/util" ).util, + Queue = require( "./lib/queue" ).Queue, + to_array = require( "./lib/to_array" ), + events = require( "events" ), + parsers = [], commands, + default_port = 6379, + default_host = "127.0.0.1"; // can set this to true to enable for all connections exports.debug_mode = false; // hiredis might not be installed try { - require("./lib/parser/hiredis"); - parsers.push(require("./lib/parser/hiredis")); -} catch (err) { - if (exports.debug_mode) { - console.log("hiredis parser not installed."); - } + require( "./lib/parser/hiredis" ); + parsers.push( require( "./lib/parser/hiredis" ) ); +} catch ( err ) { + if ( exports.debug_mode ) { + console.log( "hiredis parser not installed." ); + } } -parsers.push(require("./lib/parser/javascript")); +parsers.push( require( "./lib/parser/javascript" ) ); -function RedisClient(stream, options) { - this.stream = stream; - this.options = options || {}; +function RedisClient( stream, options ) { + this.stream = stream; + this.options = options || {}; - this.connected = false; - this.ready = false; - this.connections = 0; - this.attempts = 1; - this.should_buffer = false; - this.command_queue_high_water = this.options.command_queue_high_water || 1000; - this.command_queue_low_water = this.options.command_queue_low_water || 0; - this.command_queue = new Queue(); // holds sent commands to de-pipeline them - this.offline_queue = new Queue(); // holds commands issued but not able to be sent - this.commands_sent = 0; - this.retry_delay = 250; // inital reconnection delay - this.current_retry_delay = this.retry_delay; - this.retry_backoff = 1.7; // each retry waits current delay * retry_backoff - this.subscriptions = false; - this.monitoring = false; - this.closing = false; - this.server_info = {}; - this.auth_pass = null; + this.connected = false; + this.ready = false; + this.connections = 0; + this.attempts = 1; + this.should_buffer = false; + this.command_queue_high_water = this.options.command_queue_high_water || 1000; + this.command_queue_low_water = this.options.command_queue_low_water || 0; + this.command_queue = new Queue(); // holds sent commands to de-pipeline them + this.offline_queue = new Queue(); // holds commands issued but not able to be sent + this.commands_sent = 0; + this.retry_delay = 250; // inital reconnection delay + this.current_retry_delay = this.retry_delay; + this.retry_backoff = 1.7; // each retry waits current delay * retry_backoff + this.subscriptions = false; + this.monitoring = false; + this.closing = false; + this.server_info = {}; + this.auth_pass = null; - var parser_module, self = this; + var parser_module, self = this; - if (self.options.parser) { - if (! parsers.some(function (parser) { - if (parser.name === self.options.parser) { - parser_module = parser; - if (exports.debug_mode) { - console.log("Using parser module: " + parser_module.name); - } - return true; - } - })) { - throw new Error("Couldn't find named parser " + self.options.parser + " on this system"); - } - } else { - if (exports.debug_mode) { - console.log("Using default parser module: " + parsers[0].name); - } - parser_module = parsers[0]; - } + if ( self.options.parser ) { + if ( !parsers.some( function ( parser ) { + if ( parser.name === self.options.parser ) { + parser_module = parser; + if ( exports.debug_mode ) { + console.log( "Using parser module: " + parser_module.name ); + } + return true; + } + } ) ) { + throw new Error( "Couldn't find named parser " + self.options.parser + " on this system" ); + } + } else { + if ( exports.debug_mode ) { + console.log( "Using default parser module: " + parsers[0].name ); + } + parser_module = parsers[0]; + } - parser_module.debug_mode = exports.debug_mode; - this.reply_parser = new parser_module.Parser({ - return_buffers: self.options.return_buffers || false - }); + parser_module.debug_mode = exports.debug_mode; + this.reply_parser = new parser_module.Parser( { + return_buffers : self.options.return_buffers || false + } ); - // "reply error" is an error sent back by Redis - this.reply_parser.on("reply error", function (reply) { - self.return_error(new Error(reply)); - }); - this.reply_parser.on("reply", function (reply) { - self.return_reply(reply); - }); - // "error" is bad. Somehow the parser got confused. It'll try to reset and continue. - this.reply_parser.on("error", function (err) { - self.emit("error", new Error("Redis reply parser error: " + err.stack)); - }); + // "reply error" is an error sent back by Redis + this.reply_parser.on( "reply error", function ( reply ) { + self.return_error( new Error( reply ) ); + } ); + this.reply_parser.on( "reply", function ( reply ) { + self.return_reply( reply ); + } ); + // "error" is bad. Somehow the parser got confused. It'll try to reset and continue. + this.reply_parser.on( "error", function ( err ) { + self.emit( "error", new Error( "Redis reply parser error: " + err.stack ) ); + } ); - this.stream.on("connect", function () { - self.on_connect(); - }); + this.stream.on( "connect", function () { + self.on_connect(); + } ); - this.stream.on("data", function (buffer_from_socket) { - self.on_data(buffer_from_socket); - }); + this.stream.on( "data", function ( buffer_from_socket ) { + self.on_data( buffer_from_socket ); + } ); - this.stream.on("error", function (msg) { - if (this.closing) { - return; - } + this.stream.on( "error", function ( msg ) { + if ( this.closing ) { + return; + } - var message = "Redis connection to " + self.host + ":" + self.port + " failed - " + msg.message; + var message = "Redis connection to " + self.host + ":" + self.port + " failed - " + msg.message; - if (exports.debug_mode) { - console.warn(message); - } - self.offline_queue.forEach(function (args) { - if (typeof args[2] === "function") { - args[2](message); - } - }); - self.offline_queue = new Queue(); + if ( exports.debug_mode ) { + console.warn( message ); + } + self.offline_queue.forEach( function ( args ) { + if ( typeof args[2] === "function" ) { + args[2]( message ); + } + } ); + self.offline_queue = new Queue(); - self.command_queue.forEach(function (args) { - if (typeof args[2] === "function") { - args[2](message); - } - }); - self.command_queue = new Queue(); + self.command_queue.forEach( function ( args ) { + if ( typeof args[2] === "function" ) { + args[2]( message ); + } + } ); + self.command_queue = new Queue(); - self.connected = false; - self.ready = false; + self.connected = false; + self.ready = false; - self.emit("error", new Error(message)); - // "error" events get turned into exceptions if they aren't listened for. If the user handled this error - // then we should try to reconnect. - self.connection_gone("error"); - }); + self.emit( "error", new Error( message ) ); + // "error" events get turned into exceptions if they aren't listened for. If the user handled this error + // then we should try to reconnect. + self.connection_gone( "error" ); + } ); - this.stream.on("close", function () { - self.connection_gone("close"); - }); + this.stream.on( "close", function () { + self.connection_gone( "close" ); + } ); - this.stream.on("end", function () { - self.connection_gone("end"); - }); + this.stream.on( "end", function () { + self.connection_gone( "end" ); + } ); - this.stream.on("drain", function () { - self.should_buffer = false; - self.emit("drain"); - }); + this.stream.on( "drain", function () { + self.should_buffer = false; + self.emit( "drain" ); + } ); - events.EventEmitter.call(this); + events.EventEmitter.call( this ); } -util.inherits(RedisClient, events.EventEmitter); +util.inherits( RedisClient, events.EventEmitter ); exports.RedisClient = RedisClient; RedisClient.prototype.do_auth = function () { - var self = this; + var self = this; - if (exports.debug_mode) { - console.log("Sending auth to " + self.host + ":" + self.port + " fd " + self.stream.fd); - } - self.send_anyway = true; - self.send_command("auth", [this.auth_pass], function (err, res) { - if (err) { - if (err.toString().match("LOADING")) { - // if redis is still loading the db, it will not authenticate and everything else will fail - console.log("Redis still loading, trying to authenticate later"); - setTimeout(function () { - self.do_auth(); - }, 2000); // TODO - magic number alert - return; - } else { - return self.emit("error", "Auth error: " + err); - } - } - if (res.toString() !== "OK") { - return self.emit("error", "Auth failed: " + res.toString()); - } - if (exports.debug_mode) { - console.log("Auth succeeded " + self.host + ":" + self.port + " fd " + self.stream.fd); - } - if (self.auth_callback) { - self.auth_callback(err, res); - self.auth_callback = null; - } + if ( exports.debug_mode ) { + console.log( "Sending auth to " + self.host + ":" + self.port + " fd " + self.stream.fd ); + } + self.send_anyway = true; + self.send_command( "auth", [this.auth_pass], function ( err, res ) { + if ( err ) { + if ( err.toString().match( "LOADING" ) ) { + // if redis is still loading the db, it will not authenticate and everything else will fail + console.log( "Redis still loading, trying to authenticate later" ); + setTimeout( function () { + self.do_auth(); + }, 2000 ); // TODO - magic number alert + return; + } else { + return self.emit( "error", "Auth error: " + err ); + } + } + if ( res.toString() !== "OK" ) { + return self.emit( "error", "Auth failed: " + res.toString() ); + } + if ( exports.debug_mode ) { + console.log( "Auth succeeded " + self.host + ":" + self.port + " fd " + self.stream.fd ); + } + if ( self.auth_callback ) { + self.auth_callback( err, res ); + self.auth_callback = null; + } - // now we are really connected - self.emit("connect"); - if (self.options.no_ready_check) { - self.ready = true; - self.send_offline_queue(); - } else { - self.ready_check(); - } - }); - self.send_anyway = false; + // now we are really connected + self.emit( "connect" ); + if ( self.options.no_ready_check ) { + self.ready = true; + self.send_offline_queue(); + } else { + self.ready_check(); + } + } ); + self.send_anyway = false; }; RedisClient.prototype.on_connect = function () { - if (exports.debug_mode) { - console.log("Stream connected " + this.host + ":" + this.port + " fd " + this.stream.fd); - } - var self = this; + if ( exports.debug_mode ) { + console.log( "Stream connected " + this.host + ":" + this.port + " fd " + this.stream.fd ); + } + var self = this; - this.connected = true; - this.ready = false; - this.attempts = 0; - this.connections += 1; - this.command_queue = new Queue(); - this.emitted_end = false; - this.retry_timer = null; - this.current_retry_delay = this.retry_time; - this.stream.setNoDelay(); - this.stream.setTimeout(0); + this.connected = true; + this.ready = false; + this.attempts = 0; + this.connections += 1; + this.command_queue = new Queue(); + this.emitted_end = false; + this.retry_timer = null; + this.current_retry_delay = this.retry_time; + this.stream.setNoDelay(); + this.stream.setTimeout( 0 ); - if (this.auth_pass) { - this.do_auth(); - } else { - this.emit("connect"); + if ( this.auth_pass ) { + this.do_auth(); + } else { + this.emit( "connect" ); - if (this.options.no_ready_check) { - this.ready = true; - this.send_offline_queue(); - } else { - this.ready_check(); - } - } + if ( this.options.no_ready_check ) { + this.ready = true; + this.send_offline_queue(); + } else { + this.ready_check(); + } + } }; RedisClient.prototype.ready_check = function () { - var self = this; + var self = this; - function send_info_cmd() { - if (exports.debug_mode) { - console.log("checking server ready state..."); - } + function send_info_cmd() { + if ( exports.debug_mode ) { + console.log( "checking server ready state..." ); + } - self.send_anyway = true; // secret flag to send_command to send something even if not "ready" - self.info(function (err, res) { - if (err) { - return self.emit("error", "Ready check failed: " + err); - } + self.send_anyway = true; // secret flag to send_command to send something even if not "ready" + self.info( function ( err, res ) { + if ( err ) { + return self.emit( "error", "Ready check failed: " + err ); + } - var lines = res.toString().split("\r\n"), obj = {}, retry_time; + var lines = res.toString().split( "\r\n" ), obj = {}, retry_time; - lines.forEach(function (line) { - var parts = line.split(':'); - if (parts[1]) { - obj[parts[0]] = parts[1]; - } - }); + lines.forEach( function ( line ) { + var parts = line.split( ':' ); + if ( parts[1] ) { + obj[parts[0]] = parts[1]; + } + } ); - obj.versions = []; - obj.redis_version.split('.').forEach(function (num) { - obj.versions.push(+num); - }); + obj.versions = []; + obj.redis_version.split( '.' ).forEach( function ( num ) { + obj.versions.push( +num ); + } ); - // expose info key/vals to users - self.server_info = obj; + // expose info key/vals to users + self.server_info = obj; - if (!obj.loading || (obj.loading && obj.loading === "0")) { - if (exports.debug_mode) { - console.log("Redis server ready."); - } - self.ready = true; + if ( !obj.loading || (obj.loading && obj.loading === "0") ) { + if ( exports.debug_mode ) { + console.log( "Redis server ready." ); + } + self.ready = true; - self.send_offline_queue(); - self.emit("ready"); - } else { - retry_time = obj.loading_eta_seconds * 1000; - if (retry_time > 1000) { - retry_time = 1000; - } - if (exports.debug_mode) { - console.log("Redis server still loading, trying again in " + retry_time); - } - setTimeout(send_info_cmd, retry_time); - } - }); - self.send_anyway = false; - } + self.send_offline_queue(); + self.emit( "ready" ); + } else { + retry_time = obj.loading_eta_seconds * 1000; + if ( retry_time > 1000 ) { + retry_time = 1000; + } + if ( exports.debug_mode ) { + console.log( "Redis server still loading, trying again in " + retry_time ); + } + setTimeout( send_info_cmd, retry_time ); + } + } ); + self.send_anyway = false; + } - send_info_cmd(); + send_info_cmd(); }; RedisClient.prototype.send_offline_queue = function () { - var command_obj, buffered_writes = 0; - while (this.offline_queue.length > 0) { - command_obj = this.offline_queue.shift(); - if (exports.debug_mode) { - console.log("Sending offline command: " + command_obj.command); - } - buffered_writes += !this.send_command(command_obj.command, command_obj.args, command_obj.callback); - } - this.offline_queue = new Queue(); - // Even though items were shifted off, Queue backing store still uses memory until next add, so just get a new Queue + var command_obj, buffered_writes = 0; + while ( this.offline_queue.length > 0 ) { + command_obj = this.offline_queue.shift(); + if ( exports.debug_mode ) { + console.log( "Sending offline command: " + command_obj.command ); + } + buffered_writes += !this.send_command( command_obj.command, command_obj.args, command_obj.callback ); + } + this.offline_queue = new Queue(); + // Even though items were shifted off, Queue backing store still uses memory until next add, so just get a new Queue - if (!buffered_writes) { - this.should_buffer = false; - this.emit("drain"); - } + if ( !buffered_writes ) { + this.should_buffer = false; + this.emit( "drain" ); + } }; -RedisClient.prototype.connection_gone = function (why) { - var self = this; +RedisClient.prototype.connection_gone = function ( why ) { + var self = this; - // If a retry is already in progress, just let that happen - if (this.retry_timer) { - return; - } + // If a retry is already in progress, just let that happen + if ( this.retry_timer ) { + return; + } - // Note that this may trigger another "close" or "end" event - this.stream.destroy(); + // Note that this may trigger another "close" or "end" event + this.stream.destroy(); - if (exports.debug_mode) { - console.warn("Redis connection is gone from " + why + " event."); - } - this.connected = false; - this.ready = false; - this.subscriptions = false; - this.monitoring = false; + if ( exports.debug_mode ) { + console.warn( "Redis connection is gone from " + why + " event." ); + } + this.connected = false; + this.ready = false; + this.subscriptions = false; + this.monitoring = false; - // since we are collapsing end and close, users don't expect to be called twice - if (! this.emitted_end) { - this.emit("end"); - this.emitted_end = true; - } + // since we are collapsing end and close, users don't expect to be called twice + if ( !this.emitted_end ) { + this.emit( "end" ); + this.emitted_end = true; + } - this.command_queue.forEach(function (args) { - if (typeof args[2] === "function") { - args[2]("Server connection closed"); - } - }); - this.command_queue = new Queue(); + this.command_queue.forEach( function ( args ) { + if ( typeof args[2] === "function" ) { + args[2]( "Server connection closed" ); + } + } ); + this.command_queue = new Queue(); - // If this is a requested shutdown, then don't retry - if (this.closing) { - this.retry_timer = null; - return; - } + // If this is a requested shutdown, then don't retry + if ( this.closing ) { + this.retry_timer = null; + return; + } - this.current_retry_delay = this.retry_delay * this.retry_backoff; + this.current_retry_delay = this.retry_delay * this.retry_backoff; - if (exports.debug_mode) { - console.log("Retry connection in " + this.current_retry_delay + " ms"); - } - this.attempts += 1; - this.emit("reconnecting", { - delay: this.current_retry_delay, - attempt: this.attempts - }); - this.retry_timer = setTimeout(function () { - if (exports.debug_mode) { - console.log("Retrying connection..."); - } - self.stream.connect(self.port, self.host); - self.retry_timer = null; - }, this.current_retry_delay); + if ( exports.debug_mode ) { + console.log( "Retry connection in " + this.current_retry_delay + " ms" ); + } + this.attempts += 1; + this.emit( "reconnecting", { + delay : this.current_retry_delay, + attempt : this.attempts + } ); + this.retry_timer = setTimeout( function () { + if ( exports.debug_mode ) { + console.log( "Retrying connection..." ); + } + self.stream.connect( self.port, self.host ); + self.retry_timer = null; + }, this.current_retry_delay ); }; -RedisClient.prototype.on_data = function (data) { - if (exports.debug_mode) { - console.log("net read " + this.host + ":" + this.port + " fd " + this.stream.fd + ": " + data.toString()); - } +RedisClient.prototype.on_data = function ( data ) { + if ( exports.debug_mode ) { + console.log( "net read " + this.host + ":" + this.port + " fd " + this.stream.fd + ": " + data.toString() ); + } - try { - this.reply_parser.execute(data); - } catch (err) { - // This is an unexpected parser problem, an exception that came from the parser code itself. - // Parser should emit "error" events if it notices things are out of whack. - // Callbacks that throw exceptions will land in return_reply(), below. - // TODO - it might be nice to have a different "error" event for different types of errors - this.emit("error", err); - } + try { + this.reply_parser.execute( data ); + } catch ( err ) { + // This is an unexpected parser problem, an exception that came from the parser code itself. + // Parser should emit "error" events if it notices things are out of whack. + // Callbacks that throw exceptions will land in return_reply(), below. + // TODO - it might be nice to have a different "error" event for different types of errors + this.emit( "error", err ); + } }; -RedisClient.prototype.return_error = function (err) { - var command_obj = this.command_queue.shift(), queue_len = this.command_queue.getLength(); +RedisClient.prototype.return_error = function ( err ) { + var command_obj = this.command_queue.shift(), queue_len = this.command_queue.getLength(); - if (this.subscriptions === false && queue_len === 0) { - this.emit("idle"); - this.command_queue = new Queue(); - } - if (this.should_buffer && queue_len <= this.command_queue_low_water) { - this.emit("drain"); - this.should_buffer = false; - } + if ( this.subscriptions === false && queue_len === 0 ) { + this.emit( "idle" ); + this.command_queue = new Queue(); + } + if ( this.should_buffer && queue_len <= this.command_queue_low_water ) { + this.emit( "drain" ); + this.should_buffer = false; + } - if (command_obj && typeof command_obj.callback === "function") { - try { - command_obj.callback(err); - } catch (callback_err) { - // if a callback throws an exception, re-throw it on a new stack so the parser can keep going - process.nextTick(function () { - throw callback_err; - }); - } - } else { - console.log("node_redis: no callback to send error: " + err.message); - // this will probably not make it anywhere useful, but we might as well throw - process.nextTick(function () { - throw err; - }); - } + if ( command_obj && typeof command_obj.callback === "function" ) { + try { + command_obj.callback( err ); + } catch ( callback_err ) { + // if a callback throws an exception, re-throw it on a new stack so the parser can keep going + process.nextTick( function () { + throw callback_err; + } ); + } + } else { + console.log( "node_redis: no callback to send error: " + err.message ); + // this will probably not make it anywhere useful, but we might as well throw + process.nextTick( function () { + throw err; + } ); + } }; -RedisClient.prototype.return_reply = function (reply) { - var command_obj = this.command_queue.shift(), - obj, i, len, key, val, type, timestamp, args, queue_len = this.command_queue.getLength(); +RedisClient.prototype.return_reply = function ( reply ) { + var command_obj = this.command_queue.shift(), + obj, i, len, key, val, type, timestamp, args, queue_len = this.command_queue.getLength(); - if (this.subscriptions === false && queue_len === 0) { - this.emit("idle"); - this.command_queue = new Queue(); // explicitly reclaim storage from old Queue - } - if (this.should_buffer && queue_len <= this.command_queue_low_water) { - this.emit("drain"); - this.should_buffer = false; - } + if ( this.subscriptions === false && queue_len === 0 ) { + this.emit( "idle" ); + this.command_queue = new Queue(); // explicitly reclaim storage from old Queue + } + if ( this.should_buffer && queue_len <= this.command_queue_low_water ) { + this.emit( "drain" ); + this.should_buffer = false; + } - if (command_obj && !command_obj.sub_command) { - if (typeof command_obj.callback === "function") { - // HGETALL special case replies with keyed Buffers - if (reply && 'hgetall' === command_obj.command.toLowerCase()) { - obj = {}; - for (i = 0, len = reply.length; i < len; i += 2) { - key = reply[i].toString(); - val = reply[i + 1]; - obj[key] = val; - } - reply = obj; - } + if ( command_obj && !command_obj.sub_command ) { + if ( typeof command_obj.callback === "function" ) { + // HGETALL special case replies with keyed Buffers + if ( reply && 'hgetall' === command_obj.command.toLowerCase() ) { + obj = {}; + for ( i = 0, len = reply.length; i < len; i += 2 ) { + key = reply[i].toString(); + val = reply[i + 1]; + obj[key] = val; + } + reply = obj; + } - try { - command_obj.callback(null, reply); - } catch (err) { - // if a callback throws an exception, re-throw it on a new stack so the parser can keep going - process.nextTick(function () { - throw err; - }); - } - } else if (exports.debug_mode) { - console.log("no callback for reply: " + (reply && reply.toString && reply.toString())); - } - } else if (this.subscriptions || (command_obj && command_obj.sub_command)) { - if (Array.isArray(reply)) { - type = reply[0].toString(); + try { + command_obj.callback( null, reply ); + } catch ( err ) { + // if a callback throws an exception, re-throw it on a new stack so the parser can keep going + process.nextTick( function () { + throw err; + } ); + } + } else if ( exports.debug_mode ) { + console.log( "no callback for reply: " + (reply && reply.toString && reply.toString()) ); + } + } else if ( this.subscriptions || (command_obj && command_obj.sub_command) ) { + if ( Array.isArray( reply ) ) { + type = reply[0].toString(); - if (type === "message") { - this.emit("message", reply[1].toString(), reply[2]); // channel, message - } else if (type === "pmessage") { - this.emit("pmessage", reply[1].toString(), reply[2].toString(), reply[3]); // pattern, channel, message - } else if (type === "subscribe" || type === "unsubscribe" || type === "psubscribe" || type === "punsubscribe") { - if (reply[2] === 0) { - this.subscriptions = false; - if (this.debug_mode) { - console.log("All subscriptions removed, exiting pub/sub mode"); - } - } - this.emit(type, reply[1].toString(), reply[2]); // channel, count - } else { - throw new Error("subscriptions are active but got unknown reply type " + type); - } - } else if (! this.closing) { - throw new Error("subscriptions are active but got an invalid reply: " + reply); - } - } else if (this.monitoring) { - len = reply.indexOf(" "); - timestamp = reply.slice(0, len); - // TODO - this de-quoting doesn't work correctly if you put JSON strings in your values. - args = reply.slice(len + 1).match(/"[^"]+"/g).map(function (elem) { - return elem.replace(/"/g, ""); - }); - this.emit("monitor", timestamp, args); - } else { - throw new Error("node_redis command queue state error. If you can reproduce this, please report it."); - } + if ( type === "message" ) { + this.emit( "message", reply[1].toString(), reply[2] ); // channel, message + } else if ( type === "pmessage" ) { + this.emit( "pmessage", reply[1].toString(), reply[2].toString(), reply[3] ); // pattern, channel, message + } else if ( type === "subscribe" || type === "unsubscribe" || type === "psubscribe" || type === "punsubscribe" ) { + if ( reply[2] === 0 ) { + this.subscriptions = false; + if ( this.debug_mode ) { + console.log( "All subscriptions removed, exiting pub/sub mode" ); + } + } + this.emit( type, reply[1].toString(), reply[2] ); // channel, count + } else { + throw new Error( "subscriptions are active but got unknown reply type " + type ); + } + } else if ( !this.closing ) { + throw new Error( "subscriptions are active but got an invalid reply: " + reply ); + } + } else if ( this.monitoring ) { + len = reply.indexOf( " " ); + timestamp = reply.slice( 0, len ); + // TODO - this de-quoting doesn't work correctly if you put JSON strings in your values. + args = reply.slice( len + 1 ).match( /"[^"]+"/g ).map( function ( elem ) { + return elem.replace( /"/g, "" ); + } ); + this.emit( "monitor", timestamp, args ); + } else { + throw new Error( "node_redis command queue state error. If you can reproduce this, please report it." ); + } }; // This Command constructor is ever so slightly faster than using an object literal -function Command(command, args, sub_command, callback) { - this.command = command; - this.args = args; - this.sub_command = sub_command; - this.callback = callback; +function Command( command, args, sub_command, callback ) { + this.command = command; + this.args = args; + this.sub_command = sub_command; + this.callback = callback; } -RedisClient.prototype.send_command = function (command, args, callback) { - var arg, this_args, command_obj, i, il, elem_count, stream = this.stream, buffer_args, command_str = "", buffered_writes = 0; +RedisClient.prototype.send_command = function ( command, args, callback ) { + var arg, this_args, command_obj, i, il, elem_count, stream = this.stream, buffer_args, command_str = "", buffered_writes = 0; - if (typeof command !== "string") { - throw new Error("First argument to send_command must be the command name string, not " + typeof command); - } + if ( typeof command !== "string" ) { + throw new Error( "First argument to send_command must be the command name string, not " + typeof command ); + } - if (Array.isArray(args)) { - if (typeof callback === "function") { - // probably the fastest way: - // client.command([arg1, arg2], cb); (straight passthrough) - // send_command(command, [arg1, arg2], cb); - } else if (! callback) { - // most people find this variable argument length form more convenient, but it uses arguments, which is slower - // client.command(arg1, arg2, cb); (wraps up arguments into an array) - // send_command(command, [arg1, arg2, cb]); - // client.command(arg1, arg2); (callback is optional) - // send_command(command, [arg1, arg2]); - if (typeof args[args.length - 1] === "function") { - callback = args[args.length - 1]; - args.length -= 1; - } - } else { - throw new Error("send_command: last argument must be a callback or undefined"); - } - } else { - throw new Error("send_command: second argument must be an array"); - } + if ( Array.isArray( args ) ) { + if ( typeof callback === "function" ) { + // probably the fastest way: + // client.command([arg1, arg2], cb); (straight passthrough) + // send_command(command, [arg1, arg2], cb); + } else if ( !callback ) { + // most people find this variable argument length form more convenient, but it uses arguments, which is slower + // client.command(arg1, arg2, cb); (wraps up arguments into an array) + // send_command(command, [arg1, arg2, cb]); + // client.command(arg1, arg2); (callback is optional) + // send_command(command, [arg1, arg2]); + if ( typeof args[args.length - 1] === "function" ) { + callback = args[args.length - 1]; + args.length -= 1; + } + } else { + throw new Error( "send_command: last argument must be a callback or undefined" ); + } + } else { + throw new Error( "send_command: second argument must be an array" ); + } - // if the last argument is an array, expand it out. This allows commands like this: - // client.command(arg1, [arg2, arg3, arg4], cb); - // and converts to: - // client.command(arg1, arg2, arg3, arg4, cb); - // which is convenient for some things like sadd - if (Array.isArray(args[args.length - 1])) { - args = args.slice(0, -1).concat(args[args.length - 1]); - } + // if the last argument is an array, expand it out. This allows commands like this: + // client.command(arg1, [arg2, arg3, arg4], cb); + // and converts to: + // client.command(arg1, arg2, arg3, arg4, cb); + // which is convenient for some things like sadd + if ( Array.isArray( args[args.length - 1] ) ) { + args = args.slice( 0, -1 ).concat( args[args.length - 1] ); + } - command_obj = new Command(command, args, false, callback); + command_obj = new Command( command, args, false, callback ); - if ((!this.ready && !this.send_anyway) || !stream.writable) { - if (exports.debug_mode) { - if (!stream.writable) { - console.log("send command: stream is not writeable."); - } - - console.log("Queueing " + command + " for next server connection."); - } - this.offline_queue.push(command_obj); - this.should_buffer = true; - return false; - } + if ( (!this.ready && !this.send_anyway) || !stream.writable ) { + if ( exports.debug_mode ) { + if ( !stream.writable ) { + console.log( "send command: stream is not writeable." ); + } - if (command === "subscribe" || command === "psubscribe" || command === "unsubscribe" || command === "punsubscribe") { - if (this.subscriptions === false && exports.debug_mode) { - console.log("Entering pub/sub mode from " + command); - } - command_obj.sub_command = true; - this.subscriptions = true; - } else if (command === "monitor") { - this.monitoring = true; - } else if (command === "quit") { - this.closing = true; - } else if (this.subscriptions === true) { - throw new Error("Connection in pub/sub mode, only pub/sub commands may be used"); - } - this.command_queue.push(command_obj); - this.commands_sent += 1; + console.log( "Queueing " + command + " for next server connection." ); + } + this.offline_queue.push( command_obj ); + this.should_buffer = true; + return false; + } - elem_count = 1; - buffer_args = false; + if ( command === "subscribe" || command === "psubscribe" || command === "unsubscribe" || command === "punsubscribe" ) { + if ( this.subscriptions === false && exports.debug_mode ) { + console.log( "Entering pub/sub mode from " + command ); + } + command_obj.sub_command = true; + this.subscriptions = true; + } else if ( command === "monitor" ) { + this.monitoring = true; + } else if ( command === "quit" ) { + this.closing = true; + } else if ( this.subscriptions === true ) { + throw new Error( "Connection in pub/sub mode, only pub/sub commands may be used" ); + } + this.command_queue.push( command_obj ); + this.commands_sent += 1; - elem_count += args.length; + elem_count = 1; + buffer_args = false; - // Always use "Multi bulk commands", but if passed any Buffer args, then do multiple writes, one for each arg - // This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer. - // Also, why am I putting user documentation in the library source code? + elem_count += args.length; - command_str = "*" + elem_count + "\r\n$" + command.length + "\r\n" + command + "\r\n"; + // Always use "Multi bulk commands", but if passed any Buffer args, then do multiple writes, one for each arg + // This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer. + // Also, why am I putting user documentation in the library source code? - for (i = 0, il = args.length, arg; i < il; i += 1) { - if (Buffer.isBuffer(args[i])) { - buffer_args = true; - } - } + command_str = "*" + elem_count + "\r\n$" + command.length + "\r\n" + command + "\r\n"; - if (! buffer_args) { // Build up a string and send entire command in one write - for (i = 0, il = args.length, arg; i < il; i += 1) { - arg = args[i]; - if (typeof arg !== "string") { - arg = String(arg); - } - command_str += "$" + Buffer.byteLength(arg) + "\r\n" + arg + "\r\n"; - } - if (exports.debug_mode) { - console.log("send " + this.host + ":" + this.port + " fd " + this.stream.fd + ": " + command_str); - } - buffered_writes += !stream.write(command_str); - } else { - if (exports.debug_mode) { - console.log("send command (" + command_str + ") has Buffer arguments"); - } - buffered_writes += !stream.write(command_str); + for ( i = 0, il = args.length, arg; i < il; i += 1 ) { + if ( Buffer.isBuffer( args[i] ) ) { + buffer_args = true; + } + } - for (i = 0, il = args.length, arg; i < il; i += 1) { - arg = args[i]; - if (!(Buffer.isBuffer(arg) || arg instanceof String)) { - arg = String(arg); - } + if ( !buffer_args ) { // Build up a string and send entire command in one write + for ( i = 0, il = args.length, arg; i < il; i += 1 ) { + arg = args[i]; + if ( typeof arg !== "string" ) { + arg = String( arg ); + } + command_str += "$" + Buffer.byteLength( arg ) + "\r\n" + arg + "\r\n"; + } + if ( exports.debug_mode ) { + console.log( "send " + this.host + ":" + this.port + " fd " + this.stream.fd + ": " + command_str ); + } + buffered_writes += !stream.write( command_str ); + } else { + if ( exports.debug_mode ) { + console.log( "send command (" + command_str + ") has Buffer arguments" ); + } + buffered_writes += !stream.write( command_str ); - if (Buffer.isBuffer(arg)) { - if (arg.length === 0) { - if (exports.debug_mode) { - console.log("send_command: using empty string for 0 length buffer"); - } - buffered_writes += !stream.write("$0\r\n\r\n"); - } else { - buffered_writes += !stream.write("$" + arg.length + "\r\n"); - buffered_writes += !stream.write(arg); - buffered_writes += !stream.write("\r\n"); - if (exports.debug_mode) { - console.log("send_command: buffer send " + arg.length + " bytes"); - } - } - } else { - if (exports.debug_mode) { - console.log("send_command: string send " + Buffer.byteLength(arg) + " bytes: " + arg); - } - buffered_writes += !stream.write("$" + Buffer.byteLength(arg) + "\r\n" + arg + "\r\n"); - } - } - } - if (exports.debug_mode) { - console.log("send_command buffered_writes: " + buffered_writes, " should_buffer: " + this.should_buffer); - } - if (buffered_writes || this.command_queue.getLength() >= this.command_queue_high_water) { - this.should_buffer = true; - } - return !this.should_buffer; + for ( i = 0, il = args.length, arg; i < il; i += 1 ) { + arg = args[i]; + if ( !(Buffer.isBuffer( arg ) || arg instanceof String) ) { + arg = String( arg ); + } + + if ( Buffer.isBuffer( arg ) ) { + if ( arg.length === 0 ) { + if ( exports.debug_mode ) { + console.log( "send_command: using empty string for 0 length buffer" ); + } + buffered_writes += !stream.write( "$0\r\n\r\n" ); + } else { + buffered_writes += !stream.write( "$" + arg.length + "\r\n" ); + buffered_writes += !stream.write( arg ); + buffered_writes += !stream.write( "\r\n" ); + if ( exports.debug_mode ) { + console.log( "send_command: buffer send " + arg.length + " bytes" ); + } + } + } else { + if ( exports.debug_mode ) { + console.log( "send_command: string send " + Buffer.byteLength( arg ) + " bytes: " + arg ); + } + buffered_writes += !stream.write( "$" + Buffer.byteLength( arg ) + "\r\n" + arg + "\r\n" ); + } + } + } + if ( exports.debug_mode ) { + console.log( "send_command buffered_writes: " + buffered_writes, " should_buffer: " + this.should_buffer ); + } + if ( buffered_writes || this.command_queue.getLength() >= this.command_queue_high_water ) { + this.should_buffer = true; + } + return !this.should_buffer; }; RedisClient.prototype.end = function () { - this.stream._events = {}; - this.connected = false; - this.ready = false; - return this.stream.end(); + this.stream._events = {}; + this.connected = false; + this.ready = false; + return this.stream.end(); }; -function Multi(client, args) { - this.client = client; - this.queue = [["MULTI"]]; - if (Array.isArray(args)) { - this.queue = this.queue.concat(args); - } +function Multi( client, args ) { + this.client = client; + this.queue = [ + ["MULTI"] + ]; + if ( Array.isArray( args ) ) { + this.queue = this.queue.concat( args ); + } } exports.Multi = Multi; // take 2 arrays and return the union of their elements -function set_union(seta, setb) { - var obj = {}; - - seta.forEach(function (val) { - obj[val] = true; - }); - setb.forEach(function (val) { - obj[val] = true; - }); - return Object.keys(obj); +function set_union( seta, setb ) { + var obj = {}; + + seta.forEach( function ( val ) { + obj[val] = true; + } ); + setb.forEach( function ( val ) { + obj[val] = true; + } ); + return Object.keys( obj ); } // This static list of commands is updated from time to time. ./lib/commands.js can be updated with generate_commands.js -commands = set_union(["get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", - "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", - "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", - "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", - "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", - "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", - "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", - "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", - "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", - "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require("./lib/commands")); +commands = set_union( ["get", "set", "setnx", "setex", "append", "strlen", "del", "exists", "setbit", "getbit", "setrange", "getrange", "substr", + "incr", "decr", "mget", "rpush", "lpush", "rpushx", "lpushx", "linsert", "rpop", "lpop", "brpop", "brpoplpush", "blpop", "llen", "lindex", + "lset", "lrange", "ltrim", "lrem", "rpoplpush", "sadd", "srem", "smove", "sismember", "scard", "spop", "srandmember", "sinter", "sinterstore", + "sunion", "sunionstore", "sdiff", "sdiffstore", "smembers", "zadd", "zincrby", "zrem", "zremrangebyscore", "zremrangebyrank", "zunionstore", + "zinterstore", "zrange", "zrangebyscore", "zrevrangebyscore", "zcount", "zrevrange", "zcard", "zscore", "zrank", "zrevrank", "hset", "hsetnx", + "hget", "hmset", "hmget", "hincrby", "hdel", "hlen", "hkeys", "hvals", "hgetall", "hexists", "incrby", "decrby", "getset", "mset", "msetnx", + "randomkey", "select", "move", "rename", "renamenx", "expire", "expireat", "keys", "dbsize", "auth", "ping", "echo", "save", "bgsave", + "bgrewriteaof", "shutdown", "lastsave", "type", "multi", "exec", "discard", "sync", "flushdb", "flushall", "sort", "info", "monitor", "ttl", + "persist", "slaveof", "debug", "config", "subscribe", "unsubscribe", "psubscribe", "punsubscribe", "publish", "watch", "unwatch", "cluster", + "restore", "migrate", "dump", "object", "client", "eval", "evalsha"], require( "./lib/commands" ) ); -commands.forEach(function (command) { - RedisClient.prototype[command] = function (args, callback) { - if (Array.isArray(args) && typeof callback === "function") { - return this.send_command(command, args, callback); - } else { - return this.send_command(command, to_array(arguments)); - } - }; - RedisClient.prototype[command.toUpperCase()] = RedisClient.prototype[command]; +commands.forEach( function ( command ) { + RedisClient.prototype[command] = function ( args, callback ) { + if ( Array.isArray( args ) && typeof callback === "function" ) { + return this.send_command( command, args, callback ); + } else { + return this.send_command( command, to_array( arguments ) ); + } + }; + RedisClient.prototype[command.toUpperCase()] = RedisClient.prototype[command]; - Multi.prototype[command] = function () { - this.queue.push([command].concat(to_array(arguments))); - return this; - }; - Multi.prototype[command.toUpperCase()] = Multi.prototype[command]; -}); + Multi.prototype[command] = function () { + this.queue.push( [command].concat( to_array( arguments ) ) ); + return this; + }; + Multi.prototype[command.toUpperCase()] = Multi.prototype[command]; +} ); // Stash auth for connect and reconnect. Send immediately if already connected. RedisClient.prototype.auth = function () { - var args = to_array(arguments); - this.auth_pass = args[0]; - this.auth_callback = args[1]; - if (exports.debug_mode) { - console.log("Saving auth as " + this.auth_pass); - } + var args = to_array( arguments ); + this.auth_pass = args[0]; + this.auth_callback = args[1]; + if ( exports.debug_mode ) { + console.log( "Saving auth as " + this.auth_pass ); + } - if (this.connected) { - this.send_command("auth", args); - } + if ( this.connected ) { + this.send_command( "auth", args ); + } }; RedisClient.prototype.AUTH = RedisClient.prototype.auth; -RedisClient.prototype.hmget = function (arg1, arg2, arg3) { - if (Array.isArray(arg2) && typeof arg3 === "function") { - return this.send_command("hmget", [arg1].concat(arg2), arg3); - } else if (Array.isArray(arg1) && typeof arg2 === "function") { - return this.send_command("hmget", arg1, arg2); - } else { - return this.send_command("hmget", to_array(arguments)); - } +RedisClient.prototype.hmget = function ( arg1, arg2, arg3 ) { + if ( Array.isArray( arg2 ) && typeof arg3 === "function" ) { + return this.send_command( "hmget", [arg1].concat( arg2 ), arg3 ); + } else if ( Array.isArray( arg1 ) && typeof arg2 === "function" ) { + return this.send_command( "hmget", arg1, arg2 ); + } else { + return this.send_command( "hmget", to_array( arguments ) ); + } }; RedisClient.prototype.HMGET = RedisClient.prototype.hmget; -RedisClient.prototype.hmset = function (args, callback) { - var tmp_args, tmp_keys, i, il, key; +RedisClient.prototype.hmset = function ( args, callback ) { + var tmp_args, tmp_keys, i, il, key; - if (Array.isArray(args) && typeof callback === "function") { - return this.send_command("hmset", args, callback); - } + if ( Array.isArray( args ) && typeof callback === "function" ) { + return this.send_command( "hmset", args, callback ); + } - args = to_array(arguments); - if (typeof args[args.length - 1] === "function") { - callback = args[args.length - 1]; - args.length -= 1; - } else { - callback = null; - } + args = to_array( arguments ); + if ( typeof args[args.length - 1] === "function" ) { + callback = args[args.length - 1]; + args.length -= 1; + } else { + callback = null; + } - if (args.length === 2 && typeof args[0] === "string" && typeof args[1] === "object") { - // User does: client.hmset(key, {key1: val1, key2: val2}) - tmp_args = [ args[0] ]; - tmp_keys = Object.keys(args[1]); - for (i = 0, il = tmp_keys.length; i < il ; i++) { - key = tmp_keys[i]; - tmp_args.push(key); - tmp_args.push(args[1][key]); - } - args = tmp_args; - } + if ( args.length === 2 && typeof args[0] === "string" && typeof args[1] === "object" ) { + // User does: client.hmset(key, {key1: val1, key2: val2}) + tmp_args = [ args[0] ]; + tmp_keys = Object.keys( args[1] ); + for ( i = 0, il = tmp_keys.length; i < il; i++ ) { + key = tmp_keys[i]; + tmp_args.push( key ); + tmp_args.push( args[1][key] ); + } + args = tmp_args; + } - return this.send_command("hmset", args, callback); + return this.send_command( "hmset", args, callback ); }; RedisClient.prototype.HMSET = RedisClient.prototype.hmset; Multi.prototype.hmset = function () { - var args = to_array(arguments), tmp_args; - if (args.length >= 2 && typeof args[0] === "string" && typeof args[1] === "object") { - tmp_args = [ "hmset", args[0] ]; - Object.keys(args[1]).map(function (key) { - tmp_args.push(key); - tmp_args.push(args[1][key]); - }); - if (args[2]) { - tmp_args.push(args[2]); - } - args = tmp_args; - } else { - args.unshift("hmset"); - } + var args = to_array( arguments ), tmp_args; + if ( args.length >= 2 && typeof args[0] === "string" && typeof args[1] === "object" ) { + tmp_args = [ "hmset", args[0] ]; + Object.keys( args[1] ).map( function ( key ) { + tmp_args.push( key ); + tmp_args.push( args[1][key] ); + } ); + if ( args[2] ) { + tmp_args.push( args[2] ); + } + args = tmp_args; + } else { + args.unshift( "hmset" ); + } - this.queue.push(args); - return this; + this.queue.push( args ); + return this; }; Multi.prototype.HMSET = Multi.prototype.hmset; -Multi.prototype.exec = function (callback) { - var self = this; +Multi.prototype.exec = function ( callback ) { + var self = this; - // drain queue, callback will catch "QUEUED" or error - // TODO - get rid of all of these anonymous functions which are elegant but slow - this.queue.forEach(function (args, index) { - var command = args[0], obj; - if (typeof args[args.length - 1] === "function") { - args = args.slice(1, -1); - } else { - args = args.slice(1); - } - if (args.length === 1 && Array.isArray(args[0])) { - args = args[0]; - } - if (command === 'hmset' && typeof args[1] === 'object') { - obj = args.pop(); - Object.keys(obj).forEach(function (key) { - args.push(key); - args.push(obj[key]); - }); - } - this.client.send_command(command, args, function (err, reply) { - if (err) { - var cur = self.queue[index]; - if (typeof cur[cur.length - 1] === "function") { - cur[cur.length - 1](err); - } else { - throw new Error(err); - } - self.queue.splice(index, 1); - } - }); - }, this); + // drain queue, callback will catch "QUEUED" or error + // TODO - get rid of all of these anonymous functions which are elegant but slow + this.queue.forEach( function ( args, index ) { + var command = args[0], obj; + if ( typeof args[args.length - 1] === "function" ) { + args = args.slice( 1, -1 ); + } else { + args = args.slice( 1 ); + } + if ( args.length === 1 && Array.isArray( args[0] ) ) { + args = args[0]; + } + if ( command === 'hmset' && typeof args[1] === 'object' ) { + obj = args.pop(); + Object.keys( obj ).forEach( function ( key ) { + args.push( key ); + args.push( obj[key] ); + } ); + } + this.client.send_command( command, args, function ( err, reply ) { + if ( err ) { + var cur = self.queue[index]; + if ( typeof cur[cur.length - 1] === "function" ) { + cur[cur.length - 1]( err ); + } else { + throw new Error( err ); + } + self.queue.splice( index, 1 ); + } + } ); + }, this ); - // TODO - make this callback part of Multi.prototype instead of creating it each time - return this.client.send_command("EXEC", [], function (err, replies) { - if (err) { - if (callback) { - callback(new Error(err)); - return; - } else { - throw new Error(err); - } - } + // TODO - make this callback part of Multi.prototype instead of creating it each time + return this.client.send_command( "EXEC", [], function ( err, replies ) { + if ( err ) { + if ( callback ) { + callback( new Error( err ) ); + return; + } else { + throw new Error( err ); + } + } - var i, il, j, jl, reply, args, obj, key, val; + var i, il, j, jl, reply, args, obj, key, val; - if (replies) { - for (i = 1, il = self.queue.length; i < il; i += 1) { - reply = replies[i - 1]; - args = self.queue[i]; + if ( replies ) { + for ( i = 1, il = self.queue.length; i < il; i += 1 ) { + reply = replies[i - 1]; + args = self.queue[i]; - // Convert HGETALL reply to object - if (reply && args[0].toLowerCase() === "hgetall") { - obj = {}; - for (j = 0, jl = reply.length; j < jl; j += 2) { - key = reply[j].toString(); - val = reply[j + 1]; - obj[key] = val; - } - replies[i - 1] = reply = obj; - } + // Convert HGETALL reply to object + if ( reply && args[0].toLowerCase() === "hgetall" ) { + obj = {}; + for ( j = 0, jl = reply.length; j < jl; j += 2 ) { + key = reply[j].toString(); + val = reply[j + 1]; + obj[key] = val; + } + replies[i - 1] = reply = obj; + } - if (typeof args[args.length - 1] === "function") { - args[args.length - 1](null, reply); - } - } - } + if ( typeof args[args.length - 1] === "function" ) { + args[args.length - 1]( null, reply ); + } + } + } - if (callback) { - callback(null, replies); - } - }); + if ( callback ) { + callback( null, replies ); + } + } ); }; -RedisClient.prototype.multi = function (args) { - return new Multi(this, args); +RedisClient.prototype.multi = function ( args ) { + return new Multi( this, args ); }; -RedisClient.prototype.MULTI = function (args) { - return new Multi(this, args); +RedisClient.prototype.MULTI = function ( args ) { + return new Multi( this, args ); }; -exports.createClient = function (port_arg, host_arg, options) { - var port = port_arg || default_port, - host = host_arg || default_host, - redis_client, net_client; +exports.createClient = function ( port_arg, host_arg, options ) { + var port = port_arg || default_port, + host = host_arg || default_host, + redis_client, net_client; - net_client = net.createConnection(port, host); + net_client = net.createConnection( port, host ); - redis_client = new RedisClient(net_client, options); + redis_client = new RedisClient( net_client, options ); - redis_client.port = port; - redis_client.host = host; + redis_client.port = port; + redis_client.host = host; - return redis_client; + return redis_client; }; -exports.print = function (err, reply) { - if (err) { - console.log("Error: " + err); - } else { - console.log("Reply: " + reply); - } +exports.print = function ( err, reply ) { + if ( err ) { + console.log( "Error: " + err ); + } else { + console.log( "Reply: " + reply ); + } }; diff --git a/example/node/node_modules/socket.io/node_modules/redis/lib/commands.js b/example/node/node_modules/socket.io/node_modules/redis/lib/commands.js index 0293ae8..1fa4bb3 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/lib/commands.js +++ b/example/node/node_modules/socket.io/node_modules/redis/lib/commands.js @@ -1,126 +1,126 @@ // This file was generated by ./generate_commands.js on Tue Jun 28 2011 22:37:02 GMT-0700 (PDT) module.exports = [ - "append", - "auth", - "bgrewriteaof", - "bgsave", - "blpop", - "brpop", - "brpoplpush", - "config get", - "config set", - "config resetstat", - "dbsize", - "debug object", - "debug segfault", - "decr", - "decrby", - "del", - "discard", - "echo", - "exec", - "exists", - "expire", - "expireat", - "flushall", - "flushdb", - "get", - "getbit", - "getrange", - "getset", - "hdel", - "hexists", - "hget", - "hgetall", - "hincrby", - "hkeys", - "hlen", - "hmget", - "hmset", - "hset", - "hsetnx", - "hvals", - "incr", - "incrby", - "info", - "keys", - "lastsave", - "lindex", - "linsert", - "llen", - "lpop", - "lpush", - "lpushx", - "lrange", - "lrem", - "lset", - "ltrim", - "mget", - "monitor", - "move", - "mset", - "msetnx", - "multi", - "object", - "persist", - "ping", - "psubscribe", - "publish", - "punsubscribe", - "quit", - "randomkey", - "rename", - "renamenx", - "rpop", - "rpoplpush", - "rpush", - "rpushx", - "sadd", - "save", - "scard", - "sdiff", - "sdiffstore", - "select", - "set", - "setbit", - "setex", - "setnx", - "setrange", - "shutdown", - "sinter", - "sinterstore", - "sismember", - "slaveof", - "smembers", - "smove", - "sort", - "spop", - "srandmember", - "srem", - "strlen", - "subscribe", - "sunion", - "sunionstore", - "sync", - "ttl", - "type", - "unsubscribe", - "unwatch", - "watch", - "zadd", - "zcard", - "zcount", - "zincrby", - "zinterstore", - "zrange", - "zrangebyscore", - "zrank", - "zrem", - "zremrangebyrank", - "zremrangebyscore", - "zrevrange", - "zrevrangebyscore", - "zrevrank", - "zscore", - "zunionstore" + "append", + "auth", + "bgrewriteaof", + "bgsave", + "blpop", + "brpop", + "brpoplpush", + "config get", + "config set", + "config resetstat", + "dbsize", + "debug object", + "debug segfault", + "decr", + "decrby", + "del", + "discard", + "echo", + "exec", + "exists", + "expire", + "expireat", + "flushall", + "flushdb", + "get", + "getbit", + "getrange", + "getset", + "hdel", + "hexists", + "hget", + "hgetall", + "hincrby", + "hkeys", + "hlen", + "hmget", + "hmset", + "hset", + "hsetnx", + "hvals", + "incr", + "incrby", + "info", + "keys", + "lastsave", + "lindex", + "linsert", + "llen", + "lpop", + "lpush", + "lpushx", + "lrange", + "lrem", + "lset", + "ltrim", + "mget", + "monitor", + "move", + "mset", + "msetnx", + "multi", + "object", + "persist", + "ping", + "psubscribe", + "publish", + "punsubscribe", + "quit", + "randomkey", + "rename", + "renamenx", + "rpop", + "rpoplpush", + "rpush", + "rpushx", + "sadd", + "save", + "scard", + "sdiff", + "sdiffstore", + "select", + "set", + "setbit", + "setex", + "setnx", + "setrange", + "shutdown", + "sinter", + "sinterstore", + "sismember", + "slaveof", + "smembers", + "smove", + "sort", + "spop", + "srandmember", + "srem", + "strlen", + "subscribe", + "sunion", + "sunionstore", + "sync", + "ttl", + "type", + "unsubscribe", + "unwatch", + "watch", + "zadd", + "zcard", + "zcount", + "zincrby", + "zinterstore", + "zrange", + "zrangebyscore", + "zrank", + "zrem", + "zremrangebyrank", + "zremrangebyscore", + "zrevrange", + "zrevrangebyscore", + "zrevrank", + "zscore", + "zunionstore" ]; diff --git a/example/node/node_modules/socket.io/node_modules/redis/lib/parser/hiredis.js b/example/node/node_modules/socket.io/node_modules/redis/lib/parser/hiredis.js index 9dba8c9..49adb1b 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/lib/parser/hiredis.js +++ b/example/node/node_modules/socket.io/node_modules/redis/lib/parser/hiredis.js @@ -1,41 +1,41 @@ /*global Buffer require exports console setTimeout */ -var events = require("events"), - util = require("../util").util, - hiredis = require("hiredis"); +var events = require( "events" ), + util = require( "../util" ).util, + hiredis = require( "hiredis" ); exports.debug_mode = false; exports.name = "hiredis"; -function HiredisReplyParser(options) { - this.name = exports.name; - this.options = options || {}; - this.reset(); - events.EventEmitter.call(this); +function HiredisReplyParser( options ) { + this.name = exports.name; + this.options = options || {}; + this.reset(); + events.EventEmitter.call( this ); } -util.inherits(HiredisReplyParser, events.EventEmitter); +util.inherits( HiredisReplyParser, events.EventEmitter ); exports.Parser = HiredisReplyParser; HiredisReplyParser.prototype.reset = function () { - this.reader = new hiredis.Reader({ - return_buffers: this.options.return_buffers || false - }); + this.reader = new hiredis.Reader( { + return_buffers : this.options.return_buffers || false + } ); }; -HiredisReplyParser.prototype.execute = function (data) { - var reply; - this.reader.feed(data); - try { - while ((reply = this.reader.get()) !== undefined) { - if (reply && reply.constructor === Error) { - this.emit("reply error", reply); - } else { - this.emit("reply", reply); - } - } - } catch (err) { - this.emit("error", err); - } +HiredisReplyParser.prototype.execute = function ( data ) { + var reply; + this.reader.feed( data ); + try { + while ( (reply = this.reader.get()) !== undefined ) { + if ( reply && reply.constructor === Error ) { + this.emit( "reply error", reply ); + } else { + this.emit( "reply", reply ); + } + } + } catch ( err ) { + this.emit( "error", err ); + } }; diff --git a/example/node/node_modules/socket.io/node_modules/redis/lib/parser/javascript.js b/example/node/node_modules/socket.io/node_modules/redis/lib/parser/javascript.js index 6f250c9..a18e3e6 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/lib/parser/javascript.js +++ b/example/node/node_modules/socket.io/node_modules/redis/lib/parser/javascript.js @@ -5,312 +5,312 @@ // do not use delete // use numbers for parser state -var events = require("events"), - util = require("../util").util; +var events = require( "events" ), + util = require( "../util" ).util; exports.debug_mode = false; exports.name = "javascript"; -function RedisReplyParser(options) { - this.name = exports.name; - this.options = options || {}; - this.reset(); - events.EventEmitter.call(this); +function RedisReplyParser( options ) { + this.name = exports.name; + this.options = options || {}; + this.reset(); + events.EventEmitter.call( this ); } -util.inherits(RedisReplyParser, events.EventEmitter); +util.inherits( RedisReplyParser, events.EventEmitter ); exports.Parser = RedisReplyParser; // Buffer.toString() is quite slow for small strings -function small_toString(buf, len) { - var tmp = "", i; +function small_toString( buf, len ) { + var tmp = "", i; - for (i = 0; i < len; i += 1) { - tmp += String.fromCharCode(buf[i]); - } + for ( i = 0; i < len; i += 1 ) { + tmp += String.fromCharCode( buf[i] ); + } - return tmp; + return tmp; } // Reset parser to it's original state. RedisReplyParser.prototype.reset = function () { - this.return_buffer = new Buffer(16384); // for holding replies, might grow - this.return_string = ""; - this.tmp_string = ""; // for holding size fields + this.return_buffer = new Buffer( 16384 ); // for holding replies, might grow + this.return_string = ""; + this.tmp_string = ""; // for holding size fields - this.multi_bulk_length = 0; - this.multi_bulk_replies = null; - this.multi_bulk_pos = 0; - this.multi_bulk_nested_length = 0; - this.multi_bulk_nested_replies = null; + this.multi_bulk_length = 0; + this.multi_bulk_replies = null; + this.multi_bulk_pos = 0; + this.multi_bulk_nested_length = 0; + this.multi_bulk_nested_replies = null; - this.states = { - TYPE: 1, - SINGLE_LINE: 2, - MULTI_BULK_COUNT: 3, - INTEGER_LINE: 4, - BULK_LENGTH: 5, - ERROR_LINE: 6, - BULK_DATA: 7, - UNKNOWN_TYPE: 8, - FINAL_CR: 9, - FINAL_LF: 10, - MULTI_BULK_COUNT_LF: 11 - }; - - this.state = this.states.TYPE; + this.states = { + TYPE : 1, + SINGLE_LINE : 2, + MULTI_BULK_COUNT : 3, + INTEGER_LINE : 4, + BULK_LENGTH : 5, + ERROR_LINE : 6, + BULK_DATA : 7, + UNKNOWN_TYPE : 8, + FINAL_CR : 9, + FINAL_LF : 10, + MULTI_BULK_COUNT_LF : 11 + }; + + this.state = this.states.TYPE; }; -RedisReplyParser.prototype.parser_error = function (message) { - this.emit("error", message); - this.reset(); +RedisReplyParser.prototype.parser_error = function ( message ) { + this.emit( "error", message ); + this.reset(); }; -RedisReplyParser.prototype.execute = function (incoming_buf) { - var pos = 0, bd_tmp, bd_str, i, il, states = this.states; - //, state_times = {}, start_execute = new Date(), start_switch, end_switch, old_state; - //start_switch = new Date(); +RedisReplyParser.prototype.execute = function ( incoming_buf ) { + var pos = 0, bd_tmp, bd_str, i, il, states = this.states; + //, state_times = {}, start_execute = new Date(), start_switch, end_switch, old_state; + //start_switch = new Date(); - while (pos < incoming_buf.length) { - // old_state = this.state; - // console.log("execute: " + this.state + ", " + pos + "/" + incoming_buf.length + ", " + String.fromCharCode(incoming_buf[pos])); + while ( pos < incoming_buf.length ) { + // old_state = this.state; + // console.log("execute: " + this.state + ", " + pos + "/" + incoming_buf.length + ", " + String.fromCharCode(incoming_buf[pos])); - switch (this.state) { - case states.TYPE: - this.type = incoming_buf[pos]; - pos += 1; + switch ( this.state ) { + case states.TYPE: + this.type = incoming_buf[pos]; + pos += 1; - switch (this.type) { - case 43: // + - this.state = states.SINGLE_LINE; - this.return_buffer.end = 0; - this.return_string = ""; - break; - case 42: // * - this.state = states.MULTI_BULK_COUNT; - this.tmp_string = ""; - break; - case 58: // : - this.state = states.INTEGER_LINE; - this.return_buffer.end = 0; - this.return_string = ""; - break; - case 36: // $ - this.state = states.BULK_LENGTH; - this.tmp_string = ""; - break; - case 45: // - - this.state = states.ERROR_LINE; - this.return_buffer.end = 0; - this.return_string = ""; - break; - default: - this.state = states.UNKNOWN_TYPE; - } - break; - case states.INTEGER_LINE: - if (incoming_buf[pos] === 13) { - this.send_reply(+small_toString(this.return_buffer, this.return_buffer.end)); - this.state = states.FINAL_LF; - } else { - this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; - this.return_buffer.end += 1; - } - pos += 1; - break; - case states.ERROR_LINE: - if (incoming_buf[pos] === 13) { - this.send_error(this.return_buffer.toString("ascii", 0, this.return_buffer.end)); - this.state = states.FINAL_LF; - } else { - this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; - this.return_buffer.end += 1; - } - pos += 1; - break; - case states.SINGLE_LINE: - if (incoming_buf[pos] === 13) { - this.send_reply(this.return_string); - this.state = states.FINAL_LF; - } else { - this.return_string += String.fromCharCode(incoming_buf[pos]); - } - pos += 1; - break; - case states.MULTI_BULK_COUNT: - if (incoming_buf[pos] === 13) { // \r - this.state = states.MULTI_BULK_COUNT_LF; - } else { - this.tmp_string += String.fromCharCode(incoming_buf[pos]); - } - pos += 1; - break; - case states.MULTI_BULK_COUNT_LF: - if (incoming_buf[pos] === 10) { // \n - if (this.multi_bulk_length) { // nested multi-bulk - this.multi_bulk_nested_length = this.multi_bulk_length; - this.multi_bulk_nested_replies = this.multi_bulk_replies; - this.multi_bulk_nested_pos = this.multi_bulk_pos; - } - this.multi_bulk_length = +this.tmp_string; - this.multi_bulk_pos = 0; - this.state = states.TYPE; - if (this.multi_bulk_length < 0) { - this.send_reply(null); - this.multi_bulk_length = 0; - } else if (this.multi_bulk_length === 0) { - this.multi_bulk_pos = 0; - this.multi_bulk_replies = null; - this.send_reply([]); - } else { - this.multi_bulk_replies = new Array(this.multi_bulk_length); - } - } else { - this.parser_error(new Error("didn't see LF after NL reading multi bulk count")); - return; - } - pos += 1; - break; - case states.BULK_LENGTH: - if (incoming_buf[pos] === 13) { // \r - this.state = states.BULK_LF; - } else { - this.tmp_string += String.fromCharCode(incoming_buf[pos]); - } - pos += 1; - break; - case states.BULK_LF: - if (incoming_buf[pos] === 10) { // \n - this.bulk_length = +this.tmp_string; - if (this.bulk_length === -1) { - this.send_reply(null); - this.state = states.TYPE; - } else if (this.bulk_length === 0) { - this.send_reply(new Buffer("")); - this.state = states.FINAL_CR; - } else { - this.state = states.BULK_DATA; - if (this.bulk_length > this.return_buffer.length) { - if (exports.debug_mode) { - console.log("Growing return_buffer from " + this.return_buffer.length + " to " + this.bulk_length); - } - this.return_buffer = new Buffer(this.bulk_length); - } - this.return_buffer.end = 0; - } - } else { - this.parser_error(new Error("didn't see LF after NL while reading bulk length")); - return; - } - pos += 1; - break; - case states.BULK_DATA: - this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; - this.return_buffer.end += 1; - pos += 1; - if (this.return_buffer.end === this.bulk_length) { - bd_tmp = new Buffer(this.bulk_length); - // When the response is small, Buffer.copy() is a lot slower. - if (this.bulk_length > 10) { - this.return_buffer.copy(bd_tmp, 0, 0, this.bulk_length); - } else { - for (i = 0, il = this.bulk_length; i < il; i += 1) { - bd_tmp[i] = this.return_buffer[i]; - } - } - this.send_reply(bd_tmp); - this.state = states.FINAL_CR; - } - break; - case states.FINAL_CR: - if (incoming_buf[pos] === 13) { // \r - this.state = states.FINAL_LF; - pos += 1; - } else { - this.parser_error(new Error("saw " + incoming_buf[pos] + " when expecting final CR")); - return; - } - break; - case states.FINAL_LF: - if (incoming_buf[pos] === 10) { // \n - this.state = states.TYPE; - pos += 1; - } else { - this.parser_error(new Error("saw " + incoming_buf[pos] + " when expecting final LF")); - return; - } - break; - default: - this.parser_error(new Error("invalid state " + this.state)); - } - // end_switch = new Date(); - // if (state_times[old_state] === undefined) { - // state_times[old_state] = 0; - // } - // state_times[old_state] += (end_switch - start_switch); - // start_switch = end_switch; - } - // console.log("execute ran for " + (Date.now() - start_execute) + " ms, on " + incoming_buf.length + " Bytes. "); - // Object.keys(state_times).forEach(function (state) { - // console.log(" " + state + ": " + state_times[state]); - // }); + switch ( this.type ) { + case 43: // + + this.state = states.SINGLE_LINE; + this.return_buffer.end = 0; + this.return_string = ""; + break; + case 42: // * + this.state = states.MULTI_BULK_COUNT; + this.tmp_string = ""; + break; + case 58: // : + this.state = states.INTEGER_LINE; + this.return_buffer.end = 0; + this.return_string = ""; + break; + case 36: // $ + this.state = states.BULK_LENGTH; + this.tmp_string = ""; + break; + case 45: // - + this.state = states.ERROR_LINE; + this.return_buffer.end = 0; + this.return_string = ""; + break; + default: + this.state = states.UNKNOWN_TYPE; + } + break; + case states.INTEGER_LINE: + if ( incoming_buf[pos] === 13 ) { + this.send_reply( +small_toString( this.return_buffer, this.return_buffer.end ) ); + this.state = states.FINAL_LF; + } else { + this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; + this.return_buffer.end += 1; + } + pos += 1; + break; + case states.ERROR_LINE: + if ( incoming_buf[pos] === 13 ) { + this.send_error( this.return_buffer.toString( "ascii", 0, this.return_buffer.end ) ); + this.state = states.FINAL_LF; + } else { + this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; + this.return_buffer.end += 1; + } + pos += 1; + break; + case states.SINGLE_LINE: + if ( incoming_buf[pos] === 13 ) { + this.send_reply( this.return_string ); + this.state = states.FINAL_LF; + } else { + this.return_string += String.fromCharCode( incoming_buf[pos] ); + } + pos += 1; + break; + case states.MULTI_BULK_COUNT: + if ( incoming_buf[pos] === 13 ) { // \r + this.state = states.MULTI_BULK_COUNT_LF; + } else { + this.tmp_string += String.fromCharCode( incoming_buf[pos] ); + } + pos += 1; + break; + case states.MULTI_BULK_COUNT_LF: + if ( incoming_buf[pos] === 10 ) { // \n + if ( this.multi_bulk_length ) { // nested multi-bulk + this.multi_bulk_nested_length = this.multi_bulk_length; + this.multi_bulk_nested_replies = this.multi_bulk_replies; + this.multi_bulk_nested_pos = this.multi_bulk_pos; + } + this.multi_bulk_length = +this.tmp_string; + this.multi_bulk_pos = 0; + this.state = states.TYPE; + if ( this.multi_bulk_length < 0 ) { + this.send_reply( null ); + this.multi_bulk_length = 0; + } else if ( this.multi_bulk_length === 0 ) { + this.multi_bulk_pos = 0; + this.multi_bulk_replies = null; + this.send_reply( [] ); + } else { + this.multi_bulk_replies = new Array( this.multi_bulk_length ); + } + } else { + this.parser_error( new Error( "didn't see LF after NL reading multi bulk count" ) ); + return; + } + pos += 1; + break; + case states.BULK_LENGTH: + if ( incoming_buf[pos] === 13 ) { // \r + this.state = states.BULK_LF; + } else { + this.tmp_string += String.fromCharCode( incoming_buf[pos] ); + } + pos += 1; + break; + case states.BULK_LF: + if ( incoming_buf[pos] === 10 ) { // \n + this.bulk_length = +this.tmp_string; + if ( this.bulk_length === -1 ) { + this.send_reply( null ); + this.state = states.TYPE; + } else if ( this.bulk_length === 0 ) { + this.send_reply( new Buffer( "" ) ); + this.state = states.FINAL_CR; + } else { + this.state = states.BULK_DATA; + if ( this.bulk_length > this.return_buffer.length ) { + if ( exports.debug_mode ) { + console.log( "Growing return_buffer from " + this.return_buffer.length + " to " + this.bulk_length ); + } + this.return_buffer = new Buffer( this.bulk_length ); + } + this.return_buffer.end = 0; + } + } else { + this.parser_error( new Error( "didn't see LF after NL while reading bulk length" ) ); + return; + } + pos += 1; + break; + case states.BULK_DATA: + this.return_buffer[this.return_buffer.end] = incoming_buf[pos]; + this.return_buffer.end += 1; + pos += 1; + if ( this.return_buffer.end === this.bulk_length ) { + bd_tmp = new Buffer( this.bulk_length ); + // When the response is small, Buffer.copy() is a lot slower. + if ( this.bulk_length > 10 ) { + this.return_buffer.copy( bd_tmp, 0, 0, this.bulk_length ); + } else { + for ( i = 0, il = this.bulk_length; i < il; i += 1 ) { + bd_tmp[i] = this.return_buffer[i]; + } + } + this.send_reply( bd_tmp ); + this.state = states.FINAL_CR; + } + break; + case states.FINAL_CR: + if ( incoming_buf[pos] === 13 ) { // \r + this.state = states.FINAL_LF; + pos += 1; + } else { + this.parser_error( new Error( "saw " + incoming_buf[pos] + " when expecting final CR" ) ); + return; + } + break; + case states.FINAL_LF: + if ( incoming_buf[pos] === 10 ) { // \n + this.state = states.TYPE; + pos += 1; + } else { + this.parser_error( new Error( "saw " + incoming_buf[pos] + " when expecting final LF" ) ); + return; + } + break; + default: + this.parser_error( new Error( "invalid state " + this.state ) ); + } + // end_switch = new Date(); + // if (state_times[old_state] === undefined) { + // state_times[old_state] = 0; + // } + // state_times[old_state] += (end_switch - start_switch); + // start_switch = end_switch; + } + // console.log("execute ran for " + (Date.now() - start_execute) + " ms, on " + incoming_buf.length + " Bytes. "); + // Object.keys(state_times).forEach(function (state) { + // console.log(" " + state + ": " + state_times[state]); + // }); }; -RedisReplyParser.prototype.send_error = function (reply) { - if (this.multi_bulk_length > 0 || this.multi_bulk_nested_length > 0) { - // TODO - can this happen? Seems like maybe not. - this.add_multi_bulk_reply(reply); - } else { - this.emit("reply error", reply); - } +RedisReplyParser.prototype.send_error = function ( reply ) { + if ( this.multi_bulk_length > 0 || this.multi_bulk_nested_length > 0 ) { + // TODO - can this happen? Seems like maybe not. + this.add_multi_bulk_reply( reply ); + } else { + this.emit( "reply error", reply ); + } }; -RedisReplyParser.prototype.send_reply = function (reply) { - if (this.multi_bulk_length > 0 || this.multi_bulk_nested_length > 0) { - if (!this.options.return_buffers && Buffer.isBuffer(reply)) { - this.add_multi_bulk_reply(reply.toString("utf8")); - } else { - this.add_multi_bulk_reply(reply); - } - } else { - if (!this.options.return_buffers && Buffer.isBuffer(reply)) { - this.emit("reply", reply.toString("utf8")); - } else { - this.emit("reply", reply); - } - } +RedisReplyParser.prototype.send_reply = function ( reply ) { + if ( this.multi_bulk_length > 0 || this.multi_bulk_nested_length > 0 ) { + if ( !this.options.return_buffers && Buffer.isBuffer( reply ) ) { + this.add_multi_bulk_reply( reply.toString( "utf8" ) ); + } else { + this.add_multi_bulk_reply( reply ); + } + } else { + if ( !this.options.return_buffers && Buffer.isBuffer( reply ) ) { + this.emit( "reply", reply.toString( "utf8" ) ); + } else { + this.emit( "reply", reply ); + } + } }; -RedisReplyParser.prototype.add_multi_bulk_reply = function (reply) { - if (this.multi_bulk_replies) { - this.multi_bulk_replies[this.multi_bulk_pos] = reply; - this.multi_bulk_pos += 1; - if (this.multi_bulk_pos < this.multi_bulk_length) { - return; - } - } else { - this.multi_bulk_replies = reply; - } +RedisReplyParser.prototype.add_multi_bulk_reply = function ( reply ) { + if ( this.multi_bulk_replies ) { + this.multi_bulk_replies[this.multi_bulk_pos] = reply; + this.multi_bulk_pos += 1; + if ( this.multi_bulk_pos < this.multi_bulk_length ) { + return; + } + } else { + this.multi_bulk_replies = reply; + } - if (this.multi_bulk_nested_length > 0) { - this.multi_bulk_nested_replies[this.multi_bulk_nested_pos] = this.multi_bulk_replies; - this.multi_bulk_nested_pos += 1; + if ( this.multi_bulk_nested_length > 0 ) { + this.multi_bulk_nested_replies[this.multi_bulk_nested_pos] = this.multi_bulk_replies; + this.multi_bulk_nested_pos += 1; - this.multi_bulk_length = 0; - this.multi_bulk_replies = null; - this.multi_bulk_pos = 0; + this.multi_bulk_length = 0; + this.multi_bulk_replies = null; + this.multi_bulk_pos = 0; - if (this.multi_bulk_nested_length === this.multi_bulk_nested_pos) { - this.emit("reply", this.multi_bulk_nested_replies); - this.multi_bulk_nested_length = 0; - this.multi_bulk_nested_pos = 0; - this.multi_bulk_nested_replies = null; - } - } else { - this.emit("reply", this.multi_bulk_replies); - this.multi_bulk_length = 0; - this.multi_bulk_replies = null; - this.multi_bulk_pos = 0; - } + if ( this.multi_bulk_nested_length === this.multi_bulk_nested_pos ) { + this.emit( "reply", this.multi_bulk_nested_replies ); + this.multi_bulk_nested_length = 0; + this.multi_bulk_nested_pos = 0; + this.multi_bulk_nested_replies = null; + } + } else { + this.emit( "reply", this.multi_bulk_replies ); + this.multi_bulk_length = 0; + this.multi_bulk_replies = null; + this.multi_bulk_pos = 0; + } }; diff --git a/example/node/node_modules/socket.io/node_modules/redis/lib/queue.js b/example/node/node_modules/socket.io/node_modules/redis/lib/queue.js index 5cc3c42..df4cb46 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/lib/queue.js +++ b/example/node/node_modules/socket.io/node_modules/redis/lib/queue.js @@ -1,58 +1,58 @@ -var to_array = require("./to_array"); +var to_array = require( "./to_array" ); // Queue class adapted from Tim Caswell's pattern library // http://github.com/creationix/pattern/blob/master/lib/pattern/queue.js function Queue() { - this.tail = []; - this.head = to_array(arguments); - this.offset = 0; + this.tail = []; + this.head = to_array( arguments ); + this.offset = 0; } Queue.prototype.shift = function () { - if (this.offset === this.head.length) { - var tmp = this.head; - tmp.length = 0; - this.head = this.tail; - this.tail = tmp; - this.offset = 0; - if (this.head.length === 0) { - return; - } - } - return this.head[this.offset++]; // sorry, JSLint + if ( this.offset === this.head.length ) { + var tmp = this.head; + tmp.length = 0; + this.head = this.tail; + this.tail = tmp; + this.offset = 0; + if ( this.head.length === 0 ) { + return; + } + } + return this.head[this.offset++]; // sorry, JSLint }; -Queue.prototype.push = function (item) { - return this.tail.push(item); +Queue.prototype.push = function ( item ) { + return this.tail.push( item ); }; -Queue.prototype.forEach = function (fn, thisv) { - var array = this.head.slice(this.offset), i, il; +Queue.prototype.forEach = function ( fn, thisv ) { + var array = this.head.slice( this.offset ), i, il; - array.push.apply(array, this.tail); + array.push.apply( array, this.tail ); - if (thisv) { - for (i = 0, il = array.length; i < il; i += 1) { - fn.call(thisv, array[i], i, array); - } - } else { - for (i = 0, il = array.length; i < il; i += 1) { - fn(array[i], i, array); - } - } + if ( thisv ) { + for ( i = 0, il = array.length; i < il; i += 1 ) { + fn.call( thisv, array[i], i, array ); + } + } else { + for ( i = 0, il = array.length; i < il; i += 1 ) { + fn( array[i], i, array ); + } + } - return array; + return array; }; Queue.prototype.getLength = function () { - return this.head.length - this.offset + this.tail.length; + return this.head.length - this.offset + this.tail.length; }; - -Object.defineProperty(Queue.prototype, 'length', { - get: function () { - return this.getLength(); - } -}); + +Object.defineProperty( Queue.prototype, 'length', { + get : function () { + return this.getLength(); + } +} ); exports.Queue = Queue; diff --git a/example/node/node_modules/socket.io/node_modules/redis/lib/to_array.js b/example/node/node_modules/socket.io/node_modules/redis/lib/to_array.js index 88a57e1..b669cf8 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/lib/to_array.js +++ b/example/node/node_modules/socket.io/node_modules/redis/lib/to_array.js @@ -1,12 +1,12 @@ -function to_array(args) { - var len = args.length, - arr = new Array(len), i; +function to_array( args ) { + var len = args.length, + arr = new Array( len ), i; - for (i = 0; i < len; i += 1) { - arr[i] = args[i]; - } + for ( i = 0; i < len; i += 1 ) { + arr[i] = args[i]; + } - return arr; + return arr; } module.exports = to_array; diff --git a/example/node/node_modules/socket.io/node_modules/redis/lib/util.js b/example/node/node_modules/socket.io/node_modules/redis/lib/util.js index 3dc41a5..511da33 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/lib/util.js +++ b/example/node/node_modules/socket.io/node_modules/redis/lib/util.js @@ -1,6 +1,6 @@ -if (process.versions.node.match(/^0.3/)) { - exports.util = require("util"); +if ( process.versions.node.match( /^0.3/ ) ) { + exports.util = require( "util" ); } else { - // This module is called "sys" in 0.2.x - exports.util = require("sys"); + // This module is called "sys" in 0.2.x + exports.util = require( "sys" ); } diff --git a/example/node/node_modules/socket.io/node_modules/redis/multi_bench.js b/example/node/node_modules/socket.io/node_modules/redis/multi_bench.js index b78c126..d7c76ef 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/multi_bench.js +++ b/example/node/node_modules/socket.io/node_modules/redis/multi_bench.js @@ -1,135 +1,137 @@ -var redis = require("./index"), - num_clients = parseInt(process.argv[2], 10) || 50, - active_clients = 0, - clients = new Array(num_clients), - num_requests = 20000, - issued_requests = 0, - latency = new Array(num_requests), - tests = [], - test_start, parser_logged = false, - client_options = { - return_buffers: false - }; +var redis = require( "./index" ), + num_clients = parseInt( process.argv[2], 10 ) || 50, + active_clients = 0, + clients = new Array( num_clients ), + num_requests = 20000, + issued_requests = 0, + latency = new Array( num_requests ), + tests = [], + test_start, parser_logged = false, + client_options = { + return_buffers : false + }; redis.debug_mode = false; -tests.push({ - descr: "PING", - command: ["ping"] -}); +tests.push( { + descr : "PING", + command : ["ping"] +} ); -tests.push({ - descr: "SET", - command: ["set", "foo_rand000000000000", "bar"] -}); +tests.push( { + descr : "SET", + command : ["set", "foo_rand000000000000", "bar"] +} ); -tests.push({ - descr: "GET", - command: ["get", "foo_rand000000000000"] -}); +tests.push( { + descr : "GET", + command : ["get", "foo_rand000000000000"] +} ); -tests.push({ - descr: "INCR", - command: ["incr", "counter_rand000000000000"] -}); +tests.push( { + descr : "INCR", + command : ["incr", "counter_rand000000000000"] +} ); -tests.push({ - descr: "LPUSH", - command: ["lpush", "mylist", new Array(8).join("-")] -}); +tests.push( { + descr : "LPUSH", + command : ["lpush", "mylist", new Array( 8 ).join( "-" )] +} ); -tests.push({ - descr: "LRANGE (10 elements)", - command: ["lrange", "mylist", "0", "9"] -}); +tests.push( { + descr : "LRANGE (10 elements)", + command : ["lrange", "mylist", "0", "9"] +} ); -tests.push({ - descr: "LRANGE (100 elements)", - command: ["lrange", "mylist", "0", "99"] -}); +tests.push( { + descr : "LRANGE (100 elements)", + command : ["lrange", "mylist", "0", "99"] +} ); -function create_clients(callback) { - if (active_clients === num_clients) { - // common case is all clients are already created - console.log("create_clients: all clients already created " + num_clients); - callback(); - } else { - var client, connected = active_clients; +function create_clients( callback ) { + if ( active_clients === num_clients ) { + // common case is all clients are already created + console.log( "create_clients: all clients already created " + num_clients ); + callback(); + } else { + var client, connected = active_clients; - while (active_clients < num_clients) { - client = clients[active_clients++] = redis.createClient(6379, "127.0.0.1", client_options); - if (! parser_logged) { - console.log("Using reply parser " + client.reply_parser.name); - parser_logged = true; - } - client.on("connect", function () { - // Fire callback when all clients are connected - connected += 1; - if (connected === num_clients) { - callback(); - } - }); - // TODO - need to check for client disconnect - client.on("error", function (msg) { - console.log("Connect problem:" + msg.stack); - }); - } - } + while ( active_clients < num_clients ) { + client = clients[active_clients++] = redis.createClient( 6379, "127.0.0.1", client_options ); + if ( !parser_logged ) { + console.log( "Using reply parser " + client.reply_parser.name ); + parser_logged = true; + } + client.on( "connect", function () { + // Fire callback when all clients are connected + connected += 1; + if ( connected === num_clients ) { + callback(); + } + } ); + // TODO - need to check for client disconnect + client.on( "error", function ( msg ) { + console.log( "Connect problem:" + msg.stack ); + } ); + } + } } -function issue_request(client, test, cmd, args) { - var i = issued_requests++; - latency[i] = Date.now(); +function issue_request( client, test, cmd, args ) { + var i = issued_requests++; + latency[i] = Date.now(); - client[cmd](args, function() { - latency[i] = Date.now() - latency[i]; - if (issued_requests < num_requests) { - issue_request(client, test, cmd, args); - } else { - client.end(); - if (--active_clients == 0) - test_complete(test); - } - }); + client[cmd]( args, function () { + latency[i] = Date.now() - latency[i]; + if ( issued_requests < num_requests ) { + issue_request( client, test, cmd, args ); + } else { + client.end(); + if ( --active_clients == 0 ) { + test_complete( test ); + } + } + } ); } -function test_run(test) { - create_clients(function() { - var i = num_clients, - cmd = test.command[0], - args = test.command.slice(1); +function test_run( test ) { + create_clients( function () { + var i = num_clients, + cmd = test.command[0], + args = test.command.slice( 1 ); - test_start = Date.now(); - issued_requests = 0; - while(i-- && issued_requests < num_requests) { - issue_request(clients[i], test, cmd, args); - } - }); + test_start = Date.now(); + issued_requests = 0; + while ( i-- && issued_requests < num_requests ) { + issue_request( clients[i], test, cmd, args ); + } + } ); } -function test_complete(test) { - var min, max, sum, avg; - var total_time = Date.now() - test_start; - var op_rate = (issued_requests / (total_time / 1000.0)).toFixed(2); - var i; +function test_complete( test ) { + var min, max, sum, avg; + var total_time = Date.now() - test_start; + var op_rate = (issued_requests / (total_time / 1000.0)).toFixed( 2 ); + var i; - latency.sort(); - min = latency[0]; - max = latency[issued_requests-1]; - for (sum = 0, i = 0; i < issued_requests; i++) - sum += latency[i]; - avg = (sum / issued_requests).toFixed(3); + latency.sort(); + min = latency[0]; + max = latency[issued_requests - 1]; + for ( sum = 0, i = 0; i < issued_requests; i++ ) { + sum += latency[i]; + } + avg = (sum / issued_requests).toFixed( 3 ); - console.log(test.descr + ": " + issued_requests + " ops " + op_rate + " ops/sec " + min + "/" + max + "/" + avg); + console.log( test.descr + ": " + issued_requests + " ops " + op_rate + " ops/sec " + min + "/" + max + "/" + avg ); - next(); + next(); } function next() { - var test = tests.shift(); - if (test) { - test_run(test); - } + var test = tests.shift(); + if ( test ) { + test_run( test ); + } } next(); diff --git a/example/node/node_modules/socket.io/node_modules/redis/package.json b/example/node/node_modules/socket.io/node_modules/redis/package.json index 6ad55ca..a45f4af 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/package.json +++ b/example/node/node_modules/socket.io/node_modules/redis/package.json @@ -1,26 +1,26 @@ { "name" : "redis", - "version" : "0.6.7", - "description" : "Redis client library", - "author": "Matt Ranney ", - "contributors": [ - "Rick Olson", - "Tim-Smart", - "TJ Holowaychuk", - "Orion Henry", - "Hank Sims", - "Aivo Paas", - "Paul Carey", - "Pieter Noordhuis", - "Andy Ray", - "Vladimir Dronnikov", - "Dave Hoover" - ], - "main": "./index.js", - "scripts": { - "test": "node ./test.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/mranney/node_redis.git" - } + "version" : "0.6.7", + "description" : "Redis client library", + "author" : "Matt Ranney ", + "contributors" : [ + "Rick Olson", + "Tim-Smart", + "TJ Holowaychuk", + "Orion Henry", + "Hank Sims", + "Aivo Paas", + "Paul Carey", + "Pieter Noordhuis", + "Andy Ray", + "Vladimir Dronnikov", + "Dave Hoover" + ], + "main" : "./index.js", + "scripts" : { + "test" : "node ./test.js" + }, + "repository" : { + "type" : "git", + "url" : "git://github.com/mranney/node_redis.git" + } } diff --git a/example/node/node_modules/socket.io/node_modules/redis/simple_test.js b/example/node/node_modules/socket.io/node_modules/redis/simple_test.js index f32ab9d..f2878eb 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/simple_test.js +++ b/example/node/node_modules/socket.io/node_modules/redis/simple_test.js @@ -1,3 +1,3 @@ -var client = require("./index").createClient(); +var client = require( "./index" ).createClient(); -client.hmset("test hash", "key 1", "val 1", "key 2", "val 2"); +client.hmset( "test hash", "key 1", "val 1", "key 2", "val 2" ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/test.js b/example/node/node_modules/socket.io/node_modules/redis/test.js index 7489e0c..9ecba12 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/test.js +++ b/example/node/node_modules/socket.io/node_modules/redis/test.js @@ -1,1248 +1,1248 @@ /*global require console setTimeout process Buffer */ -var redis = require("./index"), - client = redis.createClient(), - client2 = redis.createClient(), - client3 = redis.createClient(), - client4 = redis.createClient(9006, "filefish.redistogo.com"), - assert = require("assert"), - util = require("./lib/util").util, - test_db_num = 15, // this DB will be flushed and used for testing - tests = {}, - connected = false, - ended = false, - next, cur_start, run_next_test, all_tests, all_start, test_count; +var redis = require( "./index" ), + client = redis.createClient(), + client2 = redis.createClient(), + client3 = redis.createClient(), + client4 = redis.createClient( 9006, "filefish.redistogo.com" ), + assert = require( "assert" ), + util = require( "./lib/util" ).util, + test_db_num = 15, // this DB will be flushed and used for testing + tests = {}, + connected = false, + ended = false, + next, cur_start, run_next_test, all_tests, all_start, test_count; // Set this to truthy to see the wire protocol and other debugging info redis.debug_mode = process.argv[2]; -function buffers_to_strings(arr) { - return arr.map(function (val) { - return val.toString(); - }); +function buffers_to_strings( arr ) { + return arr.map( function ( val ) { + return val.toString(); + } ); } -function require_number(expected, label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(expected, results, label + " " + expected + " !== " + results); - assert.strictEqual(typeof results, "number", label); - return true; - }; +function require_number( expected, label ) { + return function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( expected, results, label + " " + expected + " !== " + results ); + assert.strictEqual( typeof results, "number", label ); + return true; + }; } -function require_number_any(label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(typeof results, "number", label + " " + results + " is not a number"); - return true; - }; +function require_number_any( label ) { + return function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( typeof results, "number", label + " " + results + " is not a number" ); + return true; + }; } -function require_number_pos(label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(true, (results > 0), label + " " + results + " is not a positive number"); - return true; - }; +function require_number_pos( label ) { + return function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( true, (results > 0), label + " " + results + " is not a positive number" ); + return true; + }; } -function require_string(str, label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.equal(str, results, label + " " + str + " does not match " + results); - return true; - }; +function require_string( str, label ) { + return function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.equal( str, results, label + " " + str + " does not match " + results ); + return true; + }; } -function require_null(label) { - return function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(null, results, label + ": " + results + " is not null"); - return true; - }; +function require_null( label ) { + return function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( null, results, label + ": " + results + " is not null" ); + return true; + }; } -function require_error(label) { - return function (err, results) { - assert.notEqual(err, null, label + " err is null, but an error is expected here."); - return true; - }; +function require_error( label ) { + return function ( err, results ) { + assert.notEqual( err, null, label + " err is null, but an error is expected here." ); + return true; + }; } -function is_empty_array(obj) { - return Array.isArray(obj) && obj.length === 0; +function is_empty_array( obj ) { + return Array.isArray( obj ) && obj.length === 0; } -function last(name, fn) { - return function (err, results) { - fn(err, results); - next(name); - }; +function last( name, fn ) { + return function ( err, results ) { + fn( err, results ); + next( name ); + }; } -next = function next(name) { - console.log(" \x1b[33m" + (Date.now() - cur_start) + "\x1b[0m ms"); - run_next_test(); +next = function next( name ) { + console.log( " \x1b[33m" + (Date.now() - cur_start) + "\x1b[0m ms" ); + run_next_test(); }; // Tests are run in the order they are defined. So FLUSHDB should be stay first. tests.FLUSHDB = function () { - var name = "FLUSHDB"; - client.select(test_db_num, require_string("OK", name)); - client2.select(test_db_num, require_string("OK", name)); - client3.select(test_db_num, require_string("OK", name)); - client.mset("flush keys 1", "flush val 1", "flush keys 2", "flush val 2", require_string("OK", name)); - client.FLUSHDB(require_string("OK", name)); - client.dbsize(last(name, require_number(0, name))); + var name = "FLUSHDB"; + client.select( test_db_num, require_string( "OK", name ) ); + client2.select( test_db_num, require_string( "OK", name ) ); + client3.select( test_db_num, require_string( "OK", name ) ); + client.mset( "flush keys 1", "flush val 1", "flush keys 2", "flush val 2", require_string( "OK", name ) ); + client.FLUSHDB( require_string( "OK", name ) ); + client.dbsize( last( name, require_number( 0, name ) ) ); }; tests.MULTI_1 = function () { - var name = "MULTI_1", multi1, multi2; + var name = "MULTI_1", multi1, multi2; - // Provoke an error at queue time - multi1 = client.multi(); - multi1.mset("multifoo", "10", "multibar", "20", require_string("OK", name)); - multi1.set("foo2", require_error(name)); - multi1.incr("multifoo", require_number(11, name)); - multi1.incr("multibar", require_number(21, name)); - multi1.exec(); + // Provoke an error at queue time + multi1 = client.multi(); + multi1.mset( "multifoo", "10", "multibar", "20", require_string( "OK", name ) ); + multi1.set( "foo2", require_error( name ) ); + multi1.incr( "multifoo", require_number( 11, name ) ); + multi1.incr( "multibar", require_number( 21, name ) ); + multi1.exec(); - // Confirm that the previous command, while containing an error, still worked. - multi2 = client.multi(); - multi2.incr("multibar", require_number(22, name)); - multi2.incr("multifoo", require_number(12, name)); - multi2.exec(function (err, replies) { - assert.strictEqual(22, replies[0]); - assert.strictEqual(12, replies[1]); - next(name); - }); + // Confirm that the previous command, while containing an error, still worked. + multi2 = client.multi(); + multi2.incr( "multibar", require_number( 22, name ) ); + multi2.incr( "multifoo", require_number( 12, name ) ); + multi2.exec( function ( err, replies ) { + assert.strictEqual( 22, replies[0] ); + assert.strictEqual( 12, replies[1] ); + next( name ); + } ); }; tests.MULTI_2 = function () { - var name = "MULTI_2"; + var name = "MULTI_2"; - // test nested multi-bulk replies - client.multi([ - ["mget", "multifoo", "multibar", function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("12", res[0].toString(), name); - assert.strictEqual("22", res[1].toString(), name); - }], - ["set", "foo2", require_error(name)], - ["incr", "multifoo", require_number(13, name)], - ["incr", "multibar", require_number(23, name)] - ]).exec(function (err, replies) { - assert.strictEqual(2, replies[0].length, name); - assert.strictEqual("12", replies[0][0].toString(), name); - assert.strictEqual("22", replies[0][1].toString(), name); + // test nested multi-bulk replies + client.multi( [ + ["mget", "multifoo", "multibar", function ( err, res ) { + assert.strictEqual( 2, res.length, name ); + assert.strictEqual( "12", res[0].toString(), name ); + assert.strictEqual( "22", res[1].toString(), name ); + }], + ["set", "foo2", require_error( name )], + ["incr", "multifoo", require_number( 13, name )], + ["incr", "multibar", require_number( 23, name )] + ] ).exec( function ( err, replies ) { + assert.strictEqual( 2, replies[0].length, name ); + assert.strictEqual( "12", replies[0][0].toString(), name ); + assert.strictEqual( "22", replies[0][1].toString(), name ); - assert.strictEqual("13", replies[1].toString()); - assert.strictEqual("23", replies[2].toString()); - next(name); - }); + assert.strictEqual( "13", replies[1].toString() ); + assert.strictEqual( "23", replies[2].toString() ); + next( name ); + } ); }; tests.MULTI_3 = function () { - var name = "MULTI_3"; + var name = "MULTI_3"; - client.sadd("some set", "mem 1"); - client.sadd("some set", "mem 2"); - client.sadd("some set", "mem 3"); - client.sadd("some set", "mem 4"); + client.sadd( "some set", "mem 1" ); + client.sadd( "some set", "mem 2" ); + client.sadd( "some set", "mem 3" ); + client.sadd( "some set", "mem 4" ); - // make sure empty mb reply works - client.del("some missing set"); - client.smembers("some missing set", function (err, reply) { - // make sure empty mb reply works - assert.strictEqual(true, is_empty_array(reply), name); - }); - - // test nested multi-bulk replies with empty mb elements. - client.multi([ - ["smembers", "some set"], - ["del", "some set"], - ["smembers", "some set"] - ]) - .scard("some set") - .exec(function (err, replies) { - assert.strictEqual(true, is_empty_array(replies[2]), name); - next(name); - }); + // make sure empty mb reply works + client.del( "some missing set" ); + client.smembers( "some missing set", function ( err, reply ) { + // make sure empty mb reply works + assert.strictEqual( true, is_empty_array( reply ), name ); + } ); + + // test nested multi-bulk replies with empty mb elements. + client.multi( [ + ["smembers", "some set"], + ["del", "some set"], + ["smembers", "some set"] + ] ) + .scard( "some set" ) + .exec( function ( err, replies ) { + assert.strictEqual( true, is_empty_array( replies[2] ), name ); + next( name ); + } ); }; tests.MULTI_4 = function () { - var name = "MULTI_4"; + var name = "MULTI_4"; - client.multi() - .mset('some', '10', 'keys', '20') - .incr('some') - .incr('keys') - .mget('some', 'keys') - .exec(function (err, replies) { - assert.strictEqual(null, err); - assert.equal('OK', replies[0]); - assert.equal(11, replies[1]); - assert.equal(21, replies[2]); - assert.equal(11, replies[3][0].toString()); - assert.equal(21, replies[3][1].toString()); - next(name); - }); + client.multi() + .mset( 'some', '10', 'keys', '20' ) + .incr( 'some' ) + .incr( 'keys' ) + .mget( 'some', 'keys' ) + .exec( function ( err, replies ) { + assert.strictEqual( null, err ); + assert.equal( 'OK', replies[0] ); + assert.equal( 11, replies[1] ); + assert.equal( 21, replies[2] ); + assert.equal( 11, replies[3][0].toString() ); + assert.equal( 21, replies[3][1].toString() ); + next( name ); + } ); }; tests.MULTI_5 = function () { - var name = "MULTI_5"; + var name = "MULTI_5"; - // test nested multi-bulk replies with nulls. - client.multi([ - ["mget", ["multifoo", "some", "random value", "keys"]], - ["incr", "multifoo"] - ]) - .exec(function (err, replies) { - assert.strictEqual(replies.length, 2, name); - assert.strictEqual(replies[0].length, 4, name); - next(name); - }); + // test nested multi-bulk replies with nulls. + client.multi( [ + ["mget", ["multifoo", "some", "random value", "keys"]], + ["incr", "multifoo"] + ] ) + .exec( function ( err, replies ) { + assert.strictEqual( replies.length, 2, name ); + assert.strictEqual( replies[0].length, 4, name ); + next( name ); + } ); }; tests.MULTI_6 = function () { - var name = "MULTI_6"; + var name = "MULTI_6"; - client.multi() - .hmset("multihash", "a", "foo", "b", 1) - .hmset("multihash", { - extra: "fancy", - things: "here" - }) - .hgetall("multihash") - .exec(function (err, replies) { - assert.strictEqual(null, err); - assert.equal("OK", replies[0]); - assert.equal(Object.keys(replies[2]).length, 4); - assert.equal("foo", replies[2].a); - assert.equal("1", replies[2].b); - assert.equal("fancy", replies[2].extra); - assert.equal("here", replies[2].things); - next(name); - }); + client.multi() + .hmset( "multihash", "a", "foo", "b", 1 ) + .hmset( "multihash", { + extra : "fancy", + things : "here" + } ) + .hgetall( "multihash" ) + .exec( function ( err, replies ) { + assert.strictEqual( null, err ); + assert.equal( "OK", replies[0] ); + assert.equal( Object.keys( replies[2] ).length, 4 ); + assert.equal( "foo", replies[2].a ); + assert.equal( "1", replies[2].b ); + assert.equal( "fancy", replies[2].extra ); + assert.equal( "here", replies[2].things ); + next( name ); + } ); }; tests.EVAL_1 = function () { - var name = "EVAL_1"; + var name = "EVAL_1"; - if (client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 9) { - // test {EVAL - Lua integer -> Redis protocol type conversion} - client.eval("return 100.5", 0, require_number(100, name)); - // test {EVAL - Lua string -> Redis protocol type conversion} - client.eval("return 'hello world'", 0, require_string("hello world", name)); - // test {EVAL - Lua true boolean -> Redis protocol type conversion} - client.eval("return true", 0, require_number(1, name)); - // test {EVAL - Lua false boolean -> Redis protocol type conversion} - client.eval("return false", 0, require_null(name)); - // test {EVAL - Lua status code reply -> Redis protocol type conversion} - client.eval("return {ok='fine'}", 0, require_string("fine", name)); - // test {EVAL - Lua error reply -> Redis protocol type conversion} - client.eval("return {err='this is an error'}", 0, require_error(name)); - // test {EVAL - Lua table -> Redis protocol type conversion} - client.eval("return {1,2,3,'ciao',{1,2}}", 0, function (err, res) { - assert.strictEqual(5, res.length, name); - assert.strictEqual(1, res[0], name); - assert.strictEqual(2, res[1], name); - assert.strictEqual(3, res[2], name); - assert.strictEqual("ciao", res[3], name); - assert.strictEqual(2, res[4].length, name); - assert.strictEqual(1, res[4][0], name); - assert.strictEqual(2, res[4][1], name); - }); - // test {EVAL - Are the KEYS and ARGS arrays populated correctly?} - client.eval("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", 2, "a", "b", "c", "d", function (err, res) { - assert.strictEqual(4, res.length, name); - assert.strictEqual("a", res[0], name); - assert.strictEqual("b", res[1], name); - assert.strictEqual("c", res[2], name); - assert.strictEqual("d", res[3], name); - }); - // test {EVAL - is Lua able to call Redis API?} - client.set("mykey", "myval"); - client.eval("return redis.call('get','mykey')", 0, require_string("myval", name)); - // test {EVALSHA - Can we call a SHA1 if already defined?} - client.evalsha("9bd632c7d33e571e9f24556ebed26c3479a87129", 0, require_string("myval", name)); - // test {EVALSHA - Do we get an error on non defined SHA1?} - client.evalsha("ffffffffffffffffffffffffffffffffffffffff", 0, require_error(name)); - // test {EVAL - Redis integer -> Lua type conversion} - client.set("x", 0); - client.eval("local foo = redis.call('incr','x')\n" + "return {type(foo),foo}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("number", res[0], name); - assert.strictEqual(1, res[1], name); - }); - // test {EVAL - Redis bulk -> Lua type conversion} - client.eval("local foo = redis.call('get','mykey'); return {type(foo),foo}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("string", res[0], name); - assert.strictEqual("myval", res[1], name); - }); - // test {EVAL - Redis multi bulk -> Lua type conversion} - client.del("mylist"); - client.rpush("mylist", "a"); - client.rpush("mylist", "b"); - client.rpush("mylist", "c"); - client.eval("local foo = redis.call('lrange','mylist',0,-1)\n" + "return {type(foo),foo[1],foo[2],foo[3],# foo}", 0, function (err, res) { - assert.strictEqual(5, res.length, name); - assert.strictEqual("table", res[0], name); - assert.strictEqual("a", res[1], name); - assert.strictEqual("b", res[2], name); - assert.strictEqual("c", res[3], name); - assert.strictEqual(3, res[4], name); - }); - // test {EVAL - Redis status reply -> Lua type conversion} - client.eval("local foo = redis.call('set','mykey','myval'); return {type(foo),foo['ok']}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("table", res[0], name); - assert.strictEqual("OK", res[1], name); - }); - // test {EVAL - Redis error reply -> Lua type conversion} - client.set("mykey", "myval"); - client.eval("local foo = redis.call('incr','mykey'); return {type(foo),foo['err']}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("table", res[0], name); - assert.strictEqual("ERR value is not an integer or out of range", res[1], name); - }); - // test {EVAL - Redis nil bulk reply -> Lua type conversion} - client.del("mykey"); - client.eval("local foo = redis.call('get','mykey'); return {type(foo),foo == false}", 0, function (err, res) { - assert.strictEqual(2, res.length, name); - assert.strictEqual("boolean", res[0], name); - assert.strictEqual(1, res[1], name); - }); - // test {EVAL - Script can't run more than configured time limit} { - client.config("set", "lua-time-limit", 1); - client.eval("local i = 0; while true do i=i+1 end", 0, last("name", require_error(name))); - } else { - console.log("Skipping " + name + " because server version isn't new enough."); - next(name); - } + if ( client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 9 ) { + // test {EVAL - Lua integer -> Redis protocol type conversion} + client.eval( "return 100.5", 0, require_number( 100, name ) ); + // test {EVAL - Lua string -> Redis protocol type conversion} + client.eval( "return 'hello world'", 0, require_string( "hello world", name ) ); + // test {EVAL - Lua true boolean -> Redis protocol type conversion} + client.eval( "return true", 0, require_number( 1, name ) ); + // test {EVAL - Lua false boolean -> Redis protocol type conversion} + client.eval( "return false", 0, require_null( name ) ); + // test {EVAL - Lua status code reply -> Redis protocol type conversion} + client.eval( "return {ok='fine'}", 0, require_string( "fine", name ) ); + // test {EVAL - Lua error reply -> Redis protocol type conversion} + client.eval( "return {err='this is an error'}", 0, require_error( name ) ); + // test {EVAL - Lua table -> Redis protocol type conversion} + client.eval( "return {1,2,3,'ciao',{1,2}}", 0, function ( err, res ) { + assert.strictEqual( 5, res.length, name ); + assert.strictEqual( 1, res[0], name ); + assert.strictEqual( 2, res[1], name ); + assert.strictEqual( 3, res[2], name ); + assert.strictEqual( "ciao", res[3], name ); + assert.strictEqual( 2, res[4].length, name ); + assert.strictEqual( 1, res[4][0], name ); + assert.strictEqual( 2, res[4][1], name ); + } ); + // test {EVAL - Are the KEYS and ARGS arrays populated correctly?} + client.eval( "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", 2, "a", "b", "c", "d", function ( err, res ) { + assert.strictEqual( 4, res.length, name ); + assert.strictEqual( "a", res[0], name ); + assert.strictEqual( "b", res[1], name ); + assert.strictEqual( "c", res[2], name ); + assert.strictEqual( "d", res[3], name ); + } ); + // test {EVAL - is Lua able to call Redis API?} + client.set( "mykey", "myval" ); + client.eval( "return redis.call('get','mykey')", 0, require_string( "myval", name ) ); + // test {EVALSHA - Can we call a SHA1 if already defined?} + client.evalsha( "9bd632c7d33e571e9f24556ebed26c3479a87129", 0, require_string( "myval", name ) ); + // test {EVALSHA - Do we get an error on non defined SHA1?} + client.evalsha( "ffffffffffffffffffffffffffffffffffffffff", 0, require_error( name ) ); + // test {EVAL - Redis integer -> Lua type conversion} + client.set( "x", 0 ); + client.eval( "local foo = redis.call('incr','x')\n" + "return {type(foo),foo}", 0, function ( err, res ) { + assert.strictEqual( 2, res.length, name ); + assert.strictEqual( "number", res[0], name ); + assert.strictEqual( 1, res[1], name ); + } ); + // test {EVAL - Redis bulk -> Lua type conversion} + client.eval( "local foo = redis.call('get','mykey'); return {type(foo),foo}", 0, function ( err, res ) { + assert.strictEqual( 2, res.length, name ); + assert.strictEqual( "string", res[0], name ); + assert.strictEqual( "myval", res[1], name ); + } ); + // test {EVAL - Redis multi bulk -> Lua type conversion} + client.del( "mylist" ); + client.rpush( "mylist", "a" ); + client.rpush( "mylist", "b" ); + client.rpush( "mylist", "c" ); + client.eval( "local foo = redis.call('lrange','mylist',0,-1)\n" + "return {type(foo),foo[1],foo[2],foo[3],# foo}", 0, function ( err, res ) { + assert.strictEqual( 5, res.length, name ); + assert.strictEqual( "table", res[0], name ); + assert.strictEqual( "a", res[1], name ); + assert.strictEqual( "b", res[2], name ); + assert.strictEqual( "c", res[3], name ); + assert.strictEqual( 3, res[4], name ); + } ); + // test {EVAL - Redis status reply -> Lua type conversion} + client.eval( "local foo = redis.call('set','mykey','myval'); return {type(foo),foo['ok']}", 0, function ( err, res ) { + assert.strictEqual( 2, res.length, name ); + assert.strictEqual( "table", res[0], name ); + assert.strictEqual( "OK", res[1], name ); + } ); + // test {EVAL - Redis error reply -> Lua type conversion} + client.set( "mykey", "myval" ); + client.eval( "local foo = redis.call('incr','mykey'); return {type(foo),foo['err']}", 0, function ( err, res ) { + assert.strictEqual( 2, res.length, name ); + assert.strictEqual( "table", res[0], name ); + assert.strictEqual( "ERR value is not an integer or out of range", res[1], name ); + } ); + // test {EVAL - Redis nil bulk reply -> Lua type conversion} + client.del( "mykey" ); + client.eval( "local foo = redis.call('get','mykey'); return {type(foo),foo == false}", 0, function ( err, res ) { + assert.strictEqual( 2, res.length, name ); + assert.strictEqual( "boolean", res[0], name ); + assert.strictEqual( 1, res[1], name ); + } ); + // test {EVAL - Script can't run more than configured time limit} { + client.config( "set", "lua-time-limit", 1 ); + client.eval( "local i = 0; while true do i=i+1 end", 0, last( "name", require_error( name ) ) ); + } else { + console.log( "Skipping " + name + " because server version isn't new enough." ); + next( name ); + } }; tests.WATCH_MULTI = function () { - var name = 'WATCH_MULTI', multi; + var name = 'WATCH_MULTI', multi; - if (client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 1) { - client.watch(name); - client.incr(name); - multi = client.multi(); - multi.incr(name); - multi.exec(last(name, require_null(name))); - } else { - console.log("Skipping " + name + " because server version isn't new enough."); - next(name); - } + if ( client.server_info.versions[0] >= 2 && client.server_info.versions[1] >= 1 ) { + client.watch( name ); + client.incr( name ); + multi = client.multi(); + multi.incr( name ); + multi.exec( last( name, require_null( name ) ) ); + } else { + console.log( "Skipping " + name + " because server version isn't new enough." ); + next( name ); + } }; tests.reconnect = function () { - var name = "reconnect"; + var name = "reconnect"; - client.set("recon 1", "one"); - client.set("recon 2", "two", function (err, res) { - // Do not do this in normal programs. This is to simulate the server closing on us. - // For orderly shutdown in normal programs, do client.quit() - client.stream.destroy(); - }); - - client.on("reconnecting", function on_recon(params) { - client.on("connect", function on_connect() { - client.select(test_db_num, require_string("OK", name)); - client.get("recon 1", require_string("one", name)); - client.get("recon 1", require_string("one", name)); - client.get("recon 2", require_string("two", name)); - client.get("recon 2", require_string("two", name)); - client.removeListener("connect", on_connect); - client.removeListener("reconnecting", on_recon); - next(name); - }); - }); + client.set( "recon 1", "one" ); + client.set( "recon 2", "two", function ( err, res ) { + // Do not do this in normal programs. This is to simulate the server closing on us. + // For orderly shutdown in normal programs, do client.quit() + client.stream.destroy(); + } ); + + client.on( "reconnecting", function on_recon( params ) { + client.on( "connect", function on_connect() { + client.select( test_db_num, require_string( "OK", name ) ); + client.get( "recon 1", require_string( "one", name ) ); + client.get( "recon 1", require_string( "one", name ) ); + client.get( "recon 2", require_string( "two", name ) ); + client.get( "recon 2", require_string( "two", name ) ); + client.removeListener( "connect", on_connect ); + client.removeListener( "reconnecting", on_recon ); + next( name ); + } ); + } ); }; tests.HSET = function () { - var key = "test hash", - field1 = new Buffer("0123456789"), - value1 = new Buffer("abcdefghij"), - field2 = new Buffer(0), - value2 = new Buffer(0), - name = "HSET"; + var key = "test hash", + field1 = new Buffer( "0123456789" ), + value1 = new Buffer( "abcdefghij" ), + field2 = new Buffer( 0 ), + value2 = new Buffer( 0 ), + name = "HSET"; - client.HSET(key, field1, value1, require_number(1, name)); - client.HGET(key, field1, require_string(value1.toString(), name)); + client.HSET( key, field1, value1, require_number( 1, name ) ); + client.HGET( key, field1, require_string( value1.toString(), name ) ); - // Empty value - client.HSET(key, field1, value2, require_number(0, name)); - client.HGET([key, field1], require_string("", name)); + // Empty value + client.HSET( key, field1, value2, require_number( 0, name ) ); + client.HGET( [key, field1], require_string( "", name ) ); - // Empty key, empty value - client.HSET([key, field2, value1], require_number(1, name)); - client.HSET(key, field2, value2, last(name, require_number(0, name))); + // Empty key, empty value + client.HSET( [key, field2, value1], require_number( 1, name ) ); + client.HSET( key, field2, value2, last( name, require_number( 0, name ) ) ); }; tests.HMSET_BUFFER_AND_ARRAY = function () { - // Saving a buffer and an array to the same key should not error - var key = "test hash", - field1 = "buffer", - value1 = new Buffer("abcdefghij"), - field2 = "array", - value2 = ["array contents"], - name = "HSET"; + // Saving a buffer and an array to the same key should not error + var key = "test hash", + field1 = "buffer", + value1 = new Buffer( "abcdefghij" ), + field2 = "array", + value2 = ["array contents"], + name = "HSET"; - client.HMSET(key, field1, value1, field2, value2, last(name, require_string("OK", name))); + client.HMSET( key, field1, value1, field2, value2, last( name, require_string( "OK", name ) ) ); }; // TODO - add test for HMSET. It is special. Test for all forms as well as optional callbacks tests.HMGET = function () { - var key1 = "test hash 1", key2 = "test hash 2", name = "HMGET"; + var key1 = "test hash 1", key2 = "test hash 2", name = "HMGET"; - // redis-like hmset syntax - client.HMSET(key1, "0123456789", "abcdefghij", "some manner of key", "a type of value", require_string("OK", name)); + // redis-like hmset syntax + client.HMSET( key1, "0123456789", "abcdefghij", "some manner of key", "a type of value", require_string( "OK", name ) ); - // fancy hmset syntax - client.HMSET(key2, { - "0123456789": "abcdefghij", - "some manner of key": "a type of value" - }, require_string("OK", name)); + // fancy hmset syntax + client.HMSET( key2, { + "0123456789" : "abcdefghij", + "some manner of key" : "a type of value" + }, require_string( "OK", name ) ); - client.HMGET(key1, "0123456789", "some manner of key", function (err, reply) { - assert.strictEqual("abcdefghij", reply[0].toString(), name); - assert.strictEqual("a type of value", reply[1].toString(), name); - }); + client.HMGET( key1, "0123456789", "some manner of key", function ( err, reply ) { + assert.strictEqual( "abcdefghij", reply[0].toString(), name ); + assert.strictEqual( "a type of value", reply[1].toString(), name ); + } ); - client.HMGET(key2, "0123456789", "some manner of key", function (err, reply) { - assert.strictEqual("abcdefghij", reply[0].toString(), name); - assert.strictEqual("a type of value", reply[1].toString(), name); - }); + client.HMGET( key2, "0123456789", "some manner of key", function ( err, reply ) { + assert.strictEqual( "abcdefghij", reply[0].toString(), name ); + assert.strictEqual( "a type of value", reply[1].toString(), name ); + } ); - client.HMGET(key1, ["0123456789"], function (err, reply) { - assert.strictEqual("abcdefghij", reply[0], name); - }); + client.HMGET( key1, ["0123456789"], function ( err, reply ) { + assert.strictEqual( "abcdefghij", reply[0], name ); + } ); - client.HMGET(key1, ["0123456789", "some manner of key"], function (err, reply) { - assert.strictEqual("abcdefghij", reply[0], name); - assert.strictEqual("a type of value", reply[1], name); - }); + client.HMGET( key1, ["0123456789", "some manner of key"], function ( err, reply ) { + assert.strictEqual( "abcdefghij", reply[0], name ); + assert.strictEqual( "a type of value", reply[1], name ); + } ); - client.HMGET(key1, "missing thing", "another missing thing", function (err, reply) { - assert.strictEqual(null, reply[0], name); - assert.strictEqual(null, reply[1], name); - next(name); - }); + client.HMGET( key1, "missing thing", "another missing thing", function ( err, reply ) { + assert.strictEqual( null, reply[0], name ); + assert.strictEqual( null, reply[1], name ); + next( name ); + } ); }; tests.HINCRBY = function () { - var name = "HINCRBY"; - client.hset("hash incr", "value", 10, require_number(1, name)); - client.HINCRBY("hash incr", "value", 1, require_number(11, name)); - client.HINCRBY("hash incr", "value 2", 1, last(name, require_number(1, name))); + var name = "HINCRBY"; + client.hset( "hash incr", "value", 10, require_number( 1, name ) ); + client.HINCRBY( "hash incr", "value", 1, require_number( 11, name ) ); + client.HINCRBY( "hash incr", "value 2", 1, last( name, require_number( 1, name ) ) ); }; tests.SUBSCRIBE = function () { - var client1 = client, msg_count = 0, name = "SUBSCRIBE"; + var client1 = client, msg_count = 0, name = "SUBSCRIBE"; - client1.on("subscribe", function (channel, count) { - if (channel === "chan1") { - client2.publish("chan1", "message 1", require_number(1, name)); - client2.publish("chan2", "message 2", require_number(1, name)); - client2.publish("chan1", "message 3", require_number(1, name)); - } - }); + client1.on( "subscribe", function ( channel, count ) { + if ( channel === "chan1" ) { + client2.publish( "chan1", "message 1", require_number( 1, name ) ); + client2.publish( "chan2", "message 2", require_number( 1, name ) ); + client2.publish( "chan1", "message 3", require_number( 1, name ) ); + } + } ); - client1.on("unsubscribe", function (channel, count) { - if (count === 0) { - // make sure this connection can go into and out of pub/sub mode - client1.incr("did a thing", last(name, require_number(2, name))); - } - }); + client1.on( "unsubscribe", function ( channel, count ) { + if ( count === 0 ) { + // make sure this connection can go into and out of pub/sub mode + client1.incr( "did a thing", last( name, require_number( 2, name ) ) ); + } + } ); - client1.on("message", function (channel, message) { - msg_count += 1; - assert.strictEqual("message " + msg_count, message.toString()); - if (msg_count === 3) { - client1.unsubscribe("chan1", "chan2"); - } - }); + client1.on( "message", function ( channel, message ) { + msg_count += 1; + assert.strictEqual( "message " + msg_count, message.toString() ); + if ( msg_count === 3 ) { + client1.unsubscribe( "chan1", "chan2" ); + } + } ); - client1.set("did a thing", 1, require_string("OK", name)); - client1.subscribe("chan1", "chan2"); + client1.set( "did a thing", 1, require_string( "OK", name ) ); + client1.subscribe( "chan1", "chan2" ); }; tests.SUBSCRIBE_QUIT = function () { - var name = "SUBSCRIBE_QUIT"; - client3.on("end", function () { - next(name); - }); - client3.on("subscribe", function (channel, count) { - client3.quit(); - }); - client3.subscribe("chan3"); + var name = "SUBSCRIBE_QUIT"; + client3.on( "end", function () { + next( name ); + } ); + client3.on( "subscribe", function ( channel, count ) { + client3.quit(); + } ); + client3.subscribe( "chan3" ); }; tests.EXISTS = function () { - var name = "EXISTS"; - client.del("foo", "foo2", require_number_any(name)); - client.set("foo", "bar", require_string("OK", name)); - client.EXISTS("foo", require_number(1, name)); - client.EXISTS("foo2", last(name, require_number(0, name))); + var name = "EXISTS"; + client.del( "foo", "foo2", require_number_any( name ) ); + client.set( "foo", "bar", require_string( "OK", name ) ); + client.EXISTS( "foo", require_number( 1, name ) ); + client.EXISTS( "foo2", last( name, require_number( 0, name ) ) ); }; tests.DEL = function () { - var name = "DEL"; - client.DEL("delkey", require_number_any(name)); - client.set("delkey", "delvalue", require_string("OK", name)); - client.DEL("delkey", require_number(1, name)); - client.exists("delkey", require_number(0, name)); - client.DEL("delkey", require_number(0, name)); - client.mset("delkey", "delvalue", "delkey2", "delvalue2", require_string("OK", name)); - client.DEL("delkey", "delkey2", last(name, require_number(2, name))); + var name = "DEL"; + client.DEL( "delkey", require_number_any( name ) ); + client.set( "delkey", "delvalue", require_string( "OK", name ) ); + client.DEL( "delkey", require_number( 1, name ) ); + client.exists( "delkey", require_number( 0, name ) ); + client.DEL( "delkey", require_number( 0, name ) ); + client.mset( "delkey", "delvalue", "delkey2", "delvalue2", require_string( "OK", name ) ); + client.DEL( "delkey", "delkey2", last( name, require_number( 2, name ) ) ); }; tests.TYPE = function () { - var name = "TYPE"; - client.set(["string key", "should be a string"], require_string("OK", name)); - client.rpush(["list key", "should be a list"], require_number_pos(name)); - client.sadd(["set key", "should be a set"], require_number_any(name)); - client.zadd(["zset key", "10.0", "should be a zset"], require_number_any(name)); - client.hset(["hash key", "hashtest", "should be a hash"], require_number_any(0, name)); - - client.TYPE(["string key"], require_string("string", name)); - client.TYPE(["list key"], require_string("list", name)); - client.TYPE(["set key"], require_string("set", name)); - client.TYPE(["zset key"], require_string("zset", name)); - client.TYPE("not here yet", require_string("none", name)); - client.TYPE(["hash key"], last(name, require_string("hash", name))); + var name = "TYPE"; + client.set( ["string key", "should be a string"], require_string( "OK", name ) ); + client.rpush( ["list key", "should be a list"], require_number_pos( name ) ); + client.sadd( ["set key", "should be a set"], require_number_any( name ) ); + client.zadd( ["zset key", "10.0", "should be a zset"], require_number_any( name ) ); + client.hset( ["hash key", "hashtest", "should be a hash"], require_number_any( 0, name ) ); + + client.TYPE( ["string key"], require_string( "string", name ) ); + client.TYPE( ["list key"], require_string( "list", name ) ); + client.TYPE( ["set key"], require_string( "set", name ) ); + client.TYPE( ["zset key"], require_string( "zset", name ) ); + client.TYPE( "not here yet", require_string( "none", name ) ); + client.TYPE( ["hash key"], last( name, require_string( "hash", name ) ) ); }; tests.KEYS = function () { - var name = "KEYS"; - client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string("OK", name)); - client.KEYS(["test keys*"], function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(2, results.length, name); - assert.strictEqual("test keys 1", results[0].toString(), name); - assert.strictEqual("test keys 2", results[1].toString(), name); - next(name); - }); + var name = "KEYS"; + client.mset( ["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string( "OK", name ) ); + client.KEYS( ["test keys*"], function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( 2, results.length, name ); + assert.strictEqual( "test keys 1", results[0].toString(), name ); + assert.strictEqual( "test keys 2", results[1].toString(), name ); + next( name ); + } ); }; tests.MULTIBULK_ZERO_LENGTH = function () { - var name = "MULTIBULK_ZERO_LENGTH"; - client.KEYS(['users:*'], function (err, results) { - assert.strictEqual(null, err, 'error on empty multibulk reply'); - assert.strictEqual(true, is_empty_array(results), "not an empty array"); - next(name); - }); + var name = "MULTIBULK_ZERO_LENGTH"; + client.KEYS( ['users:*'], function ( err, results ) { + assert.strictEqual( null, err, 'error on empty multibulk reply' ); + assert.strictEqual( true, is_empty_array( results ), "not an empty array" ); + next( name ); + } ); }; tests.RANDOMKEY = function () { - var name = "RANDOMKEY"; - client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string("OK", name)); - client.RANDOMKEY([], function (err, results) { - assert.strictEqual(null, err, name + " result sent back unexpected error: " + err); - assert.strictEqual(true, /\w+/.test(results), name); - next(name); - }); + var name = "RANDOMKEY"; + client.mset( ["test keys 1", "test val 1", "test keys 2", "test val 2"], require_string( "OK", name ) ); + client.RANDOMKEY( [], function ( err, results ) { + assert.strictEqual( null, err, name + " result sent back unexpected error: " + err ); + assert.strictEqual( true, /\w+/.test( results ), name ); + next( name ); + } ); }; tests.RENAME = function () { - var name = "RENAME"; - client.set(['foo', 'bar'], require_string("OK", name)); - client.RENAME(["foo", "new foo"], require_string("OK", name)); - client.exists(["foo"], require_number(0, name)); - client.exists(["new foo"], last(name, require_number(1, name))); + var name = "RENAME"; + client.set( ['foo', 'bar'], require_string( "OK", name ) ); + client.RENAME( ["foo", "new foo"], require_string( "OK", name ) ); + client.exists( ["foo"], require_number( 0, name ) ); + client.exists( ["new foo"], last( name, require_number( 1, name ) ) ); }; tests.RENAMENX = function () { - var name = "RENAMENX"; - client.set(['foo', 'bar'], require_string("OK", name)); - client.set(['foo2', 'bar2'], require_string("OK", name)); - client.RENAMENX(["foo", "foo2"], require_number(0, name)); - client.exists(["foo"], require_number(1, name)); - client.exists(["foo2"], require_number(1, name)); - client.del(["foo2"], require_number(1, name)); - client.RENAMENX(["foo", "foo2"], require_number(1, name)); - client.exists(["foo"], require_number(0, name)); - client.exists(["foo2"], last(name, require_number(1, name))); + var name = "RENAMENX"; + client.set( ['foo', 'bar'], require_string( "OK", name ) ); + client.set( ['foo2', 'bar2'], require_string( "OK", name ) ); + client.RENAMENX( ["foo", "foo2"], require_number( 0, name ) ); + client.exists( ["foo"], require_number( 1, name ) ); + client.exists( ["foo2"], require_number( 1, name ) ); + client.del( ["foo2"], require_number( 1, name ) ); + client.RENAMENX( ["foo", "foo2"], require_number( 1, name ) ); + client.exists( ["foo"], require_number( 0, name ) ); + client.exists( ["foo2"], last( name, require_number( 1, name ) ) ); }; tests.DBSIZE = function () { - var name = "DBSIZE"; - client.set(['foo', 'bar'], require_string("OK", name)); - client.DBSIZE([], last(name, require_number_pos("DBSIZE"))); + var name = "DBSIZE"; + client.set( ['foo', 'bar'], require_string( "OK", name ) ); + client.DBSIZE( [], last( name, require_number_pos( "DBSIZE" ) ) ); }; tests.GET = function () { - var name = "GET"; - client.set(["get key", "get val"], require_string("OK", name)); - client.GET(["get key"], last(name, require_string("get val", name))); + var name = "GET"; + client.set( ["get key", "get val"], require_string( "OK", name ) ); + client.GET( ["get key"], last( name, require_string( "get val", name ) ) ); }; tests.SET = function () { - var name = "SET"; - client.SET(["set key", "set val"], require_string("OK", name)); - client.get(["set key"], last(name, require_string("set val", name))); + var name = "SET"; + client.SET( ["set key", "set val"], require_string( "OK", name ) ); + client.get( ["set key"], last( name, require_string( "set val", name ) ) ); }; tests.GETSET = function () { - var name = "GETSET"; - client.set(["getset key", "getset val"], require_string("OK", name)); - client.GETSET(["getset key", "new getset val"], require_string("getset val", name)); - client.get(["getset key"], last(name, require_string("new getset val", name))); + var name = "GETSET"; + client.set( ["getset key", "getset val"], require_string( "OK", name ) ); + client.GETSET( ["getset key", "new getset val"], require_string( "getset val", name ) ); + client.get( ["getset key"], last( name, require_string( "new getset val", name ) ) ); }; tests.MGET = function () { - var name = "MGET"; - client.mset(["mget keys 1", "mget val 1", "mget keys 2", "mget val 2", "mget keys 3", "mget val 3"], require_string("OK", name)); - client.MGET("mget keys 1", "mget keys 2", "mget keys 3", function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(3, results.length, name); - assert.strictEqual("mget val 1", results[0].toString(), name); - assert.strictEqual("mget val 2", results[1].toString(), name); - assert.strictEqual("mget val 3", results[2].toString(), name); - }); - client.MGET(["mget keys 1", "mget keys 2", "mget keys 3"], function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(3, results.length, name); - assert.strictEqual("mget val 1", results[0].toString(), name); - assert.strictEqual("mget val 2", results[1].toString(), name); - assert.strictEqual("mget val 3", results[2].toString(), name); - }); - client.MGET(["mget keys 1", "some random shit", "mget keys 2", "mget keys 3"], function (err, results) { - assert.strictEqual(null, err, "result sent back unexpected error: " + err); - assert.strictEqual(4, results.length, name); - assert.strictEqual("mget val 1", results[0].toString(), name); - assert.strictEqual(null, results[1], name); - assert.strictEqual("mget val 2", results[2].toString(), name); - assert.strictEqual("mget val 3", results[3].toString(), name); - next(name); - }); + var name = "MGET"; + client.mset( ["mget keys 1", "mget val 1", "mget keys 2", "mget val 2", "mget keys 3", "mget val 3"], require_string( "OK", name ) ); + client.MGET( "mget keys 1", "mget keys 2", "mget keys 3", function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( 3, results.length, name ); + assert.strictEqual( "mget val 1", results[0].toString(), name ); + assert.strictEqual( "mget val 2", results[1].toString(), name ); + assert.strictEqual( "mget val 3", results[2].toString(), name ); + } ); + client.MGET( ["mget keys 1", "mget keys 2", "mget keys 3"], function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( 3, results.length, name ); + assert.strictEqual( "mget val 1", results[0].toString(), name ); + assert.strictEqual( "mget val 2", results[1].toString(), name ); + assert.strictEqual( "mget val 3", results[2].toString(), name ); + } ); + client.MGET( ["mget keys 1", "some random shit", "mget keys 2", "mget keys 3"], function ( err, results ) { + assert.strictEqual( null, err, "result sent back unexpected error: " + err ); + assert.strictEqual( 4, results.length, name ); + assert.strictEqual( "mget val 1", results[0].toString(), name ); + assert.strictEqual( null, results[1], name ); + assert.strictEqual( "mget val 2", results[2].toString(), name ); + assert.strictEqual( "mget val 3", results[3].toString(), name ); + next( name ); + } ); }; tests.SETNX = function () { - var name = "SETNX"; - client.set(["setnx key", "setnx value"], require_string("OK", name)); - client.SETNX(["setnx key", "new setnx value"], require_number(0, name)); - client.del(["setnx key"], require_number(1, name)); - client.exists(["setnx key"], require_number(0, name)); - client.SETNX(["setnx key", "new setnx value"], require_number(1, name)); - client.exists(["setnx key"], last(name, require_number(1, name))); + var name = "SETNX"; + client.set( ["setnx key", "setnx value"], require_string( "OK", name ) ); + client.SETNX( ["setnx key", "new setnx value"], require_number( 0, name ) ); + client.del( ["setnx key"], require_number( 1, name ) ); + client.exists( ["setnx key"], require_number( 0, name ) ); + client.SETNX( ["setnx key", "new setnx value"], require_number( 1, name ) ); + client.exists( ["setnx key"], last( name, require_number( 1, name ) ) ); }; tests.SETEX = function () { - var name = "SETEX"; - client.SETEX(["setex key", "100", "setex val"], require_string("OK", name)); - client.exists(["setex key"], require_number(1, name)); - client.ttl(["setex key"], last(name, require_number_pos(name))); + var name = "SETEX"; + client.SETEX( ["setex key", "100", "setex val"], require_string( "OK", name ) ); + client.exists( ["setex key"], require_number( 1, name ) ); + client.ttl( ["setex key"], last( name, require_number_pos( name ) ) ); }; tests.MSETNX = function () { - var name = "MSETNX"; - client.mset(["mset1", "val1", "mset2", "val2", "mset3", "val3"], require_string("OK", name)); - client.MSETNX(["mset3", "val3", "mset4", "val4"], require_number(0, name)); - client.del(["mset3"], require_number(1, name)); - client.MSETNX(["mset3", "val3", "mset4", "val4"], require_number(1, name)); - client.exists(["mset3"], require_number(1, name)); - client.exists(["mset4"], last(name, require_number(1, name))); + var name = "MSETNX"; + client.mset( ["mset1", "val1", "mset2", "val2", "mset3", "val3"], require_string( "OK", name ) ); + client.MSETNX( ["mset3", "val3", "mset4", "val4"], require_number( 0, name ) ); + client.del( ["mset3"], require_number( 1, name ) ); + client.MSETNX( ["mset3", "val3", "mset4", "val4"], require_number( 1, name ) ); + client.exists( ["mset3"], require_number( 1, name ) ); + client.exists( ["mset4"], last( name, require_number( 1, name ) ) ); }; tests.HGETALL = function () { - var name = "HGETALL"; - client.hmset(["hosts", "mjr", "1", "another", "23", "home", "1234"], require_string("OK", name)); - client.HGETALL(["hosts"], function (err, obj) { - assert.strictEqual(null, err, name + " result sent back unexpected error: " + err); - assert.strictEqual(3, Object.keys(obj).length, name); - assert.strictEqual("1", obj.mjr.toString(), name); - assert.strictEqual("23", obj.another.toString(), name); - assert.strictEqual("1234", obj.home.toString(), name); - next(name); - }); + var name = "HGETALL"; + client.hmset( ["hosts", "mjr", "1", "another", "23", "home", "1234"], require_string( "OK", name ) ); + client.HGETALL( ["hosts"], function ( err, obj ) { + assert.strictEqual( null, err, name + " result sent back unexpected error: " + err ); + assert.strictEqual( 3, Object.keys( obj ).length, name ); + assert.strictEqual( "1", obj.mjr.toString(), name ); + assert.strictEqual( "23", obj.another.toString(), name ); + assert.strictEqual( "1234", obj.home.toString(), name ); + next( name ); + } ); }; tests.HGETALL_NULL = function () { - var name = "HGETALL_NULL"; + var name = "HGETALL_NULL"; - client.hgetall('missing', function (err, obj) { - assert.strictEqual(null, err); - assert.deepEqual([], obj); - next(name); - }); + client.hgetall( 'missing', function ( err, obj ) { + assert.strictEqual( null, err ); + assert.deepEqual( [], obj ); + next( name ); + } ); }; tests.UTF8 = function () { - var name = "UTF8", - utf8_sample = "ಠ_ಠ"; + var name = "UTF8", + utf8_sample = "ಠ_ಠ"; - client.set(["utf8test", utf8_sample], require_string("OK", name)); - client.get(["utf8test"], function (err, obj) { - assert.strictEqual(null, err); - assert.strictEqual(utf8_sample, obj); - next(name); - }); + client.set( ["utf8test", utf8_sample], require_string( "OK", name ) ); + client.get( ["utf8test"], function ( err, obj ) { + assert.strictEqual( null, err ); + assert.strictEqual( utf8_sample, obj ); + next( name ); + } ); }; // Set tests were adapted from Brian Hammond's redis-node-client.js, which has a comprehensive test suite tests.SADD = function () { - var name = "SADD"; - - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.sadd('set0', 'member0', last(name, require_number(0, name))); + var name = "SADD"; + + client.del( 'set0' ); + client.sadd( 'set0', 'member0', require_number( 1, name ) ); + client.sadd( 'set0', 'member0', last( name, require_number( 0, name ) ) ); }; tests.SADD2 = function () { - var name = "SADD2"; - - client.del("set0"); - client.sadd("set0", ["member0", "member1", "member2"], require_number(3, name)); - client.smembers("set0", function (err, res) { - assert.strictEqual(res.length, 3); - assert.strictEqual(res[0], "member0"); - assert.strictEqual(res[1], "member1"); - assert.strictEqual(res[2], "member2"); - next(name); - }); + var name = "SADD2"; + + client.del( "set0" ); + client.sadd( "set0", ["member0", "member1", "member2"], require_number( 3, name ) ); + client.smembers( "set0", function ( err, res ) { + assert.strictEqual( res.length, 3 ); + assert.strictEqual( res[0], "member0" ); + assert.strictEqual( res[1], "member1" ); + assert.strictEqual( res[2], "member2" ); + next( name ); + } ); }; tests.SISMEMBER = function () { - var name = "SISMEMBER"; - - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.sismember('set0', 'member0', require_number(1, name)); - client.sismember('set0', 'member1', last(name, require_number(0, name))); + var name = "SISMEMBER"; + + client.del( 'set0' ); + client.sadd( 'set0', 'member0', require_number( 1, name ) ); + client.sismember( 'set0', 'member0', require_number( 1, name ) ); + client.sismember( 'set0', 'member1', last( name, require_number( 0, name ) ) ); }; tests.SCARD = function () { - var name = "SCARD"; - - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.scard('set0', require_number(1, name)); - client.sadd('set0', 'member1', require_number(1, name)); - client.scard('set0', last(name, require_number(2, name))); + var name = "SCARD"; + + client.del( 'set0' ); + client.sadd( 'set0', 'member0', require_number( 1, name ) ); + client.scard( 'set0', require_number( 1, name ) ); + client.sadd( 'set0', 'member1', require_number( 1, name ) ); + client.scard( 'set0', last( name, require_number( 2, name ) ) ); }; tests.SREM = function () { - var name = "SREM"; + var name = "SREM"; - client.del('set0'); - client.sadd('set0', 'member0', require_number(1, name)); - client.srem('set0', 'foobar', require_number(0, name)); - client.srem('set0', 'member0', require_number(1, name)); - client.scard('set0', last(name, require_number(0, name))); + client.del( 'set0' ); + client.sadd( 'set0', 'member0', require_number( 1, name ) ); + client.srem( 'set0', 'foobar', require_number( 0, name ) ); + client.srem( 'set0', 'member0', require_number( 1, name ) ); + client.scard( 'set0', last( name, require_number( 0, name ) ) ); }; tests.SPOP = function () { - var name = "SPOP"; - - client.del('zzz'); - client.sadd('zzz', 'member0', require_number(1, name)); - client.scard('zzz', require_number(1, name)); + var name = "SPOP"; - client.spop('zzz', function (err, value) { - if (err) { - assert.fail(err); - } - assert.equal(value, 'member0', name); - }); + client.del( 'zzz' ); + client.sadd( 'zzz', 'member0', require_number( 1, name ) ); + client.scard( 'zzz', require_number( 1, name ) ); - client.scard('zzz', last(name, require_number(0, name))); + client.spop( 'zzz', function ( err, value ) { + if ( err ) { + assert.fail( err ); + } + assert.equal( value, 'member0', name ); + } ); + + client.scard( 'zzz', last( name, require_number( 0, name ) ) ); }; tests.SDIFF = function () { - var name = "SDIFF"; - - client.del('foo'); - client.sadd('foo', 'x', require_number(1, name)); - client.sadd('foo', 'a', require_number(1, name)); - client.sadd('foo', 'b', require_number(1, name)); - client.sadd('foo', 'c', require_number(1, name)); + var name = "SDIFF"; - client.sadd('bar', 'c', require_number(1, name)); + client.del( 'foo' ); + client.sadd( 'foo', 'x', require_number( 1, name ) ); + client.sadd( 'foo', 'a', require_number( 1, name ) ); + client.sadd( 'foo', 'b', require_number( 1, name ) ); + client.sadd( 'foo', 'c', require_number( 1, name ) ); - client.sadd('baz', 'a', require_number(1, name)); - client.sadd('baz', 'd', require_number(1, name)); + client.sadd( 'bar', 'c', require_number( 1, name ) ); - client.sdiff('foo', 'bar', 'baz', function (err, values) { - if (err) { - assert.fail(err, name); - } - values.sort(); - assert.equal(values.length, 2, name); - assert.equal(values[0], 'b', name); - assert.equal(values[1], 'x', name); - next(name); - }); + client.sadd( 'baz', 'a', require_number( 1, name ) ); + client.sadd( 'baz', 'd', require_number( 1, name ) ); + + client.sdiff( 'foo', 'bar', 'baz', function ( err, values ) { + if ( err ) { + assert.fail( err, name ); + } + values.sort(); + assert.equal( values.length, 2, name ); + assert.equal( values[0], 'b', name ); + assert.equal( values[1], 'x', name ); + next( name ); + } ); }; tests.SDIFFSTORE = function () { - var name = "SDIFFSTORE"; - - client.del('foo'); - client.del('bar'); - client.del('baz'); - client.del('quux'); + var name = "SDIFFSTORE"; - client.sadd('foo', 'x', require_number(1, name)); - client.sadd('foo', 'a', require_number(1, name)); - client.sadd('foo', 'b', require_number(1, name)); - client.sadd('foo', 'c', require_number(1, name)); + client.del( 'foo' ); + client.del( 'bar' ); + client.del( 'baz' ); + client.del( 'quux' ); - client.sadd('bar', 'c', require_number(1, name)); + client.sadd( 'foo', 'x', require_number( 1, name ) ); + client.sadd( 'foo', 'a', require_number( 1, name ) ); + client.sadd( 'foo', 'b', require_number( 1, name ) ); + client.sadd( 'foo', 'c', require_number( 1, name ) ); - client.sadd('baz', 'a', require_number(1, name)); - client.sadd('baz', 'd', require_number(1, name)); + client.sadd( 'bar', 'c', require_number( 1, name ) ); - // NB: SDIFFSTORE returns the number of elements in the dstkey + client.sadd( 'baz', 'a', require_number( 1, name ) ); + client.sadd( 'baz', 'd', require_number( 1, name ) ); - client.sdiffstore('quux', 'foo', 'bar', 'baz', require_number(2, name)); + // NB: SDIFFSTORE returns the number of elements in the dstkey - client.smembers('quux', function (err, values) { - if (err) { - assert.fail(err, name); - } - var members = buffers_to_strings(values).sort(); + client.sdiffstore( 'quux', 'foo', 'bar', 'baz', require_number( 2, name ) ); - assert.deepEqual(members, [ 'b', 'x' ], name); - next(name); - }); + client.smembers( 'quux', function ( err, values ) { + if ( err ) { + assert.fail( err, name ); + } + var members = buffers_to_strings( values ).sort(); + + assert.deepEqual( members, [ 'b', 'x' ], name ); + next( name ); + } ); }; tests.SMEMBERS = function () { - var name = "SMEMBERS"; - - client.del('foo'); - client.sadd('foo', 'x', require_number(1, name)); + var name = "SMEMBERS"; - client.smembers('foo', function (err, members) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(members), [ 'x' ], name); - }); + client.del( 'foo' ); + client.sadd( 'foo', 'x', require_number( 1, name ) ); - client.sadd('foo', 'y', require_number(1, name)); + client.smembers( 'foo', function ( err, members ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( members ), [ 'x' ], name ); + } ); - client.smembers('foo', function (err, values) { - if (err) { - assert.fail(err, name); - } - assert.equal(values.length, 2, name); - var members = buffers_to_strings(values).sort(); + client.sadd( 'foo', 'y', require_number( 1, name ) ); - assert.deepEqual(members, [ 'x', 'y' ], name); - next(name); - }); + client.smembers( 'foo', function ( err, values ) { + if ( err ) { + assert.fail( err, name ); + } + assert.equal( values.length, 2, name ); + var members = buffers_to_strings( values ).sort(); + + assert.deepEqual( members, [ 'x', 'y' ], name ); + next( name ); + } ); }; tests.SMOVE = function () { - var name = "SMOVE"; + var name = "SMOVE"; - client.del('foo'); - client.del('bar'); + client.del( 'foo' ); + client.del( 'bar' ); - client.sadd('foo', 'x', require_number(1, name)); - client.smove('foo', 'bar', 'x', require_number(1, name)); - client.sismember('foo', 'x', require_number(0, name)); - client.sismember('bar', 'x', require_number(1, name)); - client.smove('foo', 'bar', 'x', last(name, require_number(0, name))); + client.sadd( 'foo', 'x', require_number( 1, name ) ); + client.smove( 'foo', 'bar', 'x', require_number( 1, name ) ); + client.sismember( 'foo', 'x', require_number( 0, name ) ); + client.sismember( 'bar', 'x', require_number( 1, name ) ); + client.smove( 'foo', 'bar', 'x', last( name, require_number( 0, name ) ) ); }; tests.SINTER = function () { - var name = "SINTER"; + var name = "SINTER"; - client.del('sa'); - client.del('sb'); - client.del('sc'); - - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); + client.del( 'sa' ); + client.del( 'sb' ); + client.del( 'sc' ); - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); + client.sadd( 'sa', 'a', require_number( 1, name ) ); + client.sadd( 'sa', 'b', require_number( 1, name ) ); + client.sadd( 'sa', 'c', require_number( 1, name ) ); - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); + client.sadd( 'sb', 'b', require_number( 1, name ) ); + client.sadd( 'sb', 'c', require_number( 1, name ) ); + client.sadd( 'sb', 'd', require_number( 1, name ) ); - client.sinter('sa', 'sb', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 2, name); - assert.deepEqual(buffers_to_strings(intersection).sort(), [ 'b', 'c' ], name); - }); + client.sadd( 'sc', 'c', require_number( 1, name ) ); + client.sadd( 'sc', 'd', require_number( 1, name ) ); + client.sadd( 'sc', 'e', require_number( 1, name ) ); - client.sinter('sb', 'sc', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 2, name); - assert.deepEqual(buffers_to_strings(intersection).sort(), [ 'c', 'd' ], name); - }); + client.sinter( 'sa', 'sb', function ( err, intersection ) { + if ( err ) { + assert.fail( err, name ); + } + assert.equal( intersection.length, 2, name ); + assert.deepEqual( buffers_to_strings( intersection ).sort(), [ 'b', 'c' ], name ); + } ); - client.sinter('sa', 'sc', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 1, name); - assert.equal(intersection[0], 'c', name); - }); + client.sinter( 'sb', 'sc', function ( err, intersection ) { + if ( err ) { + assert.fail( err, name ); + } + assert.equal( intersection.length, 2, name ); + assert.deepEqual( buffers_to_strings( intersection ).sort(), [ 'c', 'd' ], name ); + } ); - // 3-way + client.sinter( 'sa', 'sc', function ( err, intersection ) { + if ( err ) { + assert.fail( err, name ); + } + assert.equal( intersection.length, 1, name ); + assert.equal( intersection[0], 'c', name ); + } ); - client.sinter('sa', 'sb', 'sc', function (err, intersection) { - if (err) { - assert.fail(err, name); - } - assert.equal(intersection.length, 1, name); - assert.equal(intersection[0], 'c', name); - next(name); - }); + // 3-way + + client.sinter( 'sa', 'sb', 'sc', function ( err, intersection ) { + if ( err ) { + assert.fail( err, name ); + } + assert.equal( intersection.length, 1, name ); + assert.equal( intersection[0], 'c', name ); + next( name ); + } ); }; tests.SINTERSTORE = function () { - var name = "SINTERSTORE"; + var name = "SINTERSTORE"; - client.del('sa'); - client.del('sb'); - client.del('sc'); - client.del('foo'); + client.del( 'sa' ); + client.del( 'sb' ); + client.del( 'sc' ); + client.del( 'foo' ); - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); + client.sadd( 'sa', 'a', require_number( 1, name ) ); + client.sadd( 'sa', 'b', require_number( 1, name ) ); + client.sadd( 'sa', 'c', require_number( 1, name ) ); - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); + client.sadd( 'sb', 'b', require_number( 1, name ) ); + client.sadd( 'sb', 'c', require_number( 1, name ) ); + client.sadd( 'sb', 'd', require_number( 1, name ) ); - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); + client.sadd( 'sc', 'c', require_number( 1, name ) ); + client.sadd( 'sc', 'd', require_number( 1, name ) ); + client.sadd( 'sc', 'e', require_number( 1, name ) ); - client.sinterstore('foo', 'sa', 'sb', 'sc', require_number(1, name)); + client.sinterstore( 'foo', 'sa', 'sb', 'sc', require_number( 1, name ) ); - client.smembers('foo', function (err, members) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(members), [ 'c' ], name); - next(name); - }); + client.smembers( 'foo', function ( err, members ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( members ), [ 'c' ], name ); + next( name ); + } ); }; tests.SUNION = function () { - var name = "SUNION"; - - client.del('sa'); - client.del('sb'); - client.del('sc'); - - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); + var name = "SUNION"; - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); + client.del( 'sa' ); + client.del( 'sb' ); + client.del( 'sc' ); - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); + client.sadd( 'sa', 'a', require_number( 1, name ) ); + client.sadd( 'sa', 'b', require_number( 1, name ) ); + client.sadd( 'sa', 'c', require_number( 1, name ) ); - client.sunion('sa', 'sb', 'sc', function (err, union) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(union).sort(), ['a', 'b', 'c', 'd', 'e'], name); - next(name); - }); + client.sadd( 'sb', 'b', require_number( 1, name ) ); + client.sadd( 'sb', 'c', require_number( 1, name ) ); + client.sadd( 'sb', 'd', require_number( 1, name ) ); + + client.sadd( 'sc', 'c', require_number( 1, name ) ); + client.sadd( 'sc', 'd', require_number( 1, name ) ); + client.sadd( 'sc', 'e', require_number( 1, name ) ); + + client.sunion( 'sa', 'sb', 'sc', function ( err, union ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( union ).sort(), ['a', 'b', 'c', 'd', 'e'], name ); + next( name ); + } ); }; tests.SUNIONSTORE = function () { - var name = "SUNIONSTORE"; - - client.del('sa'); - client.del('sb'); - client.del('sc'); - client.del('foo'); - - client.sadd('sa', 'a', require_number(1, name)); - client.sadd('sa', 'b', require_number(1, name)); - client.sadd('sa', 'c', require_number(1, name)); + var name = "SUNIONSTORE"; - client.sadd('sb', 'b', require_number(1, name)); - client.sadd('sb', 'c', require_number(1, name)); - client.sadd('sb', 'd', require_number(1, name)); + client.del( 'sa' ); + client.del( 'sb' ); + client.del( 'sc' ); + client.del( 'foo' ); - client.sadd('sc', 'c', require_number(1, name)); - client.sadd('sc', 'd', require_number(1, name)); - client.sadd('sc', 'e', require_number(1, name)); + client.sadd( 'sa', 'a', require_number( 1, name ) ); + client.sadd( 'sa', 'b', require_number( 1, name ) ); + client.sadd( 'sa', 'c', require_number( 1, name ) ); - client.sunionstore('foo', 'sa', 'sb', 'sc', function (err, cardinality) { - if (err) { - assert.fail(err, name); - } - assert.equal(cardinality, 5, name); - }); + client.sadd( 'sb', 'b', require_number( 1, name ) ); + client.sadd( 'sb', 'c', require_number( 1, name ) ); + client.sadd( 'sb', 'd', require_number( 1, name ) ); - client.smembers('foo', function (err, members) { - if (err) { - assert.fail(err, name); - } - assert.equal(members.length, 5, name); - assert.deepEqual(buffers_to_strings(members).sort(), ['a', 'b', 'c', 'd', 'e'], name); - next(name); - }); + client.sadd( 'sc', 'c', require_number( 1, name ) ); + client.sadd( 'sc', 'd', require_number( 1, name ) ); + client.sadd( 'sc', 'e', require_number( 1, name ) ); + + client.sunionstore( 'foo', 'sa', 'sb', 'sc', function ( err, cardinality ) { + if ( err ) { + assert.fail( err, name ); + } + assert.equal( cardinality, 5, name ); + } ); + + client.smembers( 'foo', function ( err, members ) { + if ( err ) { + assert.fail( err, name ); + } + assert.equal( members.length, 5, name ); + assert.deepEqual( buffers_to_strings( members ).sort(), ['a', 'b', 'c', 'd', 'e'], name ); + next( name ); + } ); }; // SORT test adapted from Brian Hammond's redis-node-client.js, which has a comprehensive test suite tests.SORT = function () { - var name = "SORT"; + var name = "SORT"; - client.del('y'); - client.del('x'); - - client.rpush('y', 'd', require_number(1, name)); - client.rpush('y', 'b', require_number(2, name)); - client.rpush('y', 'a', require_number(3, name)); - client.rpush('y', 'c', require_number(4, name)); + client.del( 'y' ); + client.del( 'x' ); - client.rpush('x', '3', require_number(1, name)); - client.rpush('x', '9', require_number(2, name)); - client.rpush('x', '2', require_number(3, name)); - client.rpush('x', '4', require_number(4, name)); + client.rpush( 'y', 'd', require_number( 1, name ) ); + client.rpush( 'y', 'b', require_number( 2, name ) ); + client.rpush( 'y', 'a', require_number( 3, name ) ); + client.rpush( 'y', 'c', require_number( 4, name ) ); - client.set('w3', '4', require_string("OK", name)); - client.set('w9', '5', require_string("OK", name)); - client.set('w2', '12', require_string("OK", name)); - client.set('w4', '6', require_string("OK", name)); + client.rpush( 'x', '3', require_number( 1, name ) ); + client.rpush( 'x', '9', require_number( 2, name ) ); + client.rpush( 'x', '2', require_number( 3, name ) ); + client.rpush( 'x', '4', require_number( 4, name ) ); - client.set('o2', 'buz', require_string("OK", name)); - client.set('o3', 'foo', require_string("OK", name)); - client.set('o4', 'baz', require_string("OK", name)); - client.set('o9', 'bar', require_string("OK", name)); + client.set( 'w3', '4', require_string( "OK", name ) ); + client.set( 'w9', '5', require_string( "OK", name ) ); + client.set( 'w2', '12', require_string( "OK", name ) ); + client.set( 'w4', '6', require_string( "OK", name ) ); - client.set('p2', 'qux', require_string("OK", name)); - client.set('p3', 'bux', require_string("OK", name)); - client.set('p4', 'lux', require_string("OK", name)); - client.set('p9', 'tux', require_string("OK", name)); + client.set( 'o2', 'buz', require_string( "OK", name ) ); + client.set( 'o3', 'foo', require_string( "OK", name ) ); + client.set( 'o4', 'baz', require_string( "OK", name ) ); + client.set( 'o9', 'bar', require_string( "OK", name ) ); - // Now the data has been setup, we can test. + client.set( 'p2', 'qux', require_string( "OK", name ) ); + client.set( 'p3', 'bux', require_string( "OK", name ) ); + client.set( 'p4', 'lux', require_string( "OK", name ) ); + client.set( 'p9', 'tux', require_string( "OK", name ) ); - // But first, test basic sorting. + // Now the data has been setup, we can test. - // y = [ d b a c ] - // sort y ascending = [ a b c d ] - // sort y descending = [ d c b a ] + // But first, test basic sorting. - client.sort('y', 'asc', 'alpha', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['a', 'b', 'c', 'd'], name); - }); + // y = [ d b a c ] + // sort y ascending = [ a b c d ] + // sort y descending = [ d c b a ] - client.sort('y', 'desc', 'alpha', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['d', 'c', 'b', 'a'], name); - }); + client.sort( 'y', 'asc', 'alpha', function ( err, sorted ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( sorted ), ['a', 'b', 'c', 'd'], name ); + } ); - // Now try sorting numbers in a list. - // x = [ 3, 9, 2, 4 ] + client.sort( 'y', 'desc', 'alpha', function ( err, sorted ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( sorted ), ['d', 'c', 'b', 'a'], name ); + } ); - client.sort('x', 'asc', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), [2, 3, 4, 9], name); - }); + // Now try sorting numbers in a list. + // x = [ 3, 9, 2, 4 ] - client.sort('x', 'desc', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), [9, 4, 3, 2], name); - }); + client.sort( 'x', 'asc', function ( err, sorted ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( sorted ), [2, 3, 4, 9], name ); + } ); - // Try sorting with a 'by' pattern. + client.sort( 'x', 'desc', function ( err, sorted ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( sorted ), [9, 4, 3, 2], name ); + } ); - client.sort('x', 'by', 'w*', 'asc', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), [3, 9, 4, 2], name); - }); + // Try sorting with a 'by' pattern. - // Try sorting with a 'by' pattern and 1 'get' pattern. + client.sort( 'x', 'by', 'w*', 'asc', function ( err, sorted ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( sorted ), [3, 9, 4, 2], name ); + } ); - client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['foo', 'bar', 'baz', 'buz'], name); - }); + // Try sorting with a 'by' pattern and 1 'get' pattern. - // Try sorting with a 'by' pattern and 2 'get' patterns. + client.sort( 'x', 'by', 'w*', 'asc', 'get', 'o*', function ( err, sorted ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( sorted ), ['foo', 'bar', 'baz', 'buz'], name ); + } ); - client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', function (err, sorted) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(sorted), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name); - }); + // Try sorting with a 'by' pattern and 2 'get' patterns. - // Try sorting with a 'by' pattern and 2 'get' patterns. - // Instead of getting back the sorted set/list, store the values to a list. - // Then check that the values are there in the expected order. + client.sort( 'x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', function ( err, sorted ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( sorted ), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name ); + } ); - client.sort('x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', 'store', 'bacon', function (err) { - if (err) { - assert.fail(err, name); - } - }); + // Try sorting with a 'by' pattern and 2 'get' patterns. + // Instead of getting back the sorted set/list, store the values to a list. + // Then check that the values are there in the expected order. - client.lrange('bacon', 0, -1, function (err, values) { - if (err) { - assert.fail(err, name); - } - assert.deepEqual(buffers_to_strings(values), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name); - next(name); - }); - - // TODO - sort by hash value + client.sort( 'x', 'by', 'w*', 'asc', 'get', 'o*', 'get', 'p*', 'store', 'bacon', function ( err ) { + if ( err ) { + assert.fail( err, name ); + } + } ); + + client.lrange( 'bacon', 0, -1, function ( err, values ) { + if ( err ) { + assert.fail( err, name ); + } + assert.deepEqual( buffers_to_strings( values ), ['foo', 'bux', 'bar', 'tux', 'baz', 'lux', 'buz', 'qux'], name ); + next( name ); + } ); + + // TODO - sort by hash value }; tests.BLPOP = function () { - var name = "BLPOP"; - - client.rpush("blocking list", "initial value", function (err, res) { - client2.BLPOP("blocking list", 0, function (err, res) { - assert.strictEqual("blocking list", res[0].toString()); - assert.strictEqual("initial value", res[1].toString()); - - client.rpush("blocking list", "wait for this value"); - }); - client2.BLPOP("blocking list", 0, function (err, res) { - assert.strictEqual("blocking list", res[0].toString()); - assert.strictEqual("wait for this value", res[1].toString()); - next(name); - }); - }); + var name = "BLPOP"; + + client.rpush( "blocking list", "initial value", function ( err, res ) { + client2.BLPOP( "blocking list", 0, function ( err, res ) { + assert.strictEqual( "blocking list", res[0].toString() ); + assert.strictEqual( "initial value", res[1].toString() ); + + client.rpush( "blocking list", "wait for this value" ); + } ); + client2.BLPOP( "blocking list", 0, function ( err, res ) { + assert.strictEqual( "blocking list", res[0].toString() ); + assert.strictEqual( "wait for this value", res[1].toString() ); + next( name ); + } ); + } ); }; tests.BLPOP_TIMEOUT = function () { - var name = "BLPOP_TIMEOUT"; - - // try to BLPOP the list again, which should be empty. This should timeout and return null. - client2.BLPOP("blocking list", 1, function (err, res) { - if (err) { - throw err; - } + var name = "BLPOP_TIMEOUT"; - assert.strictEqual(res, null); - next(name); - }); + // try to BLPOP the list again, which should be empty. This should timeout and return null. + client2.BLPOP( "blocking list", 1, function ( err, res ) { + if ( err ) { + throw err; + } + + assert.strictEqual( res, null ); + next( name ); + } ); }; tests.EXPIRE = function () { - var name = "EXPIRE"; - client.set(['expiry key', 'bar'], require_string("OK", name)); - client.EXPIRE(["expiry key", "1"], require_number_pos(name)); - setTimeout(function () { - client.exists(["expiry key"], last(name, require_number(0, name))); - }, 2000); + var name = "EXPIRE"; + client.set( ['expiry key', 'bar'], require_string( "OK", name ) ); + client.EXPIRE( ["expiry key", "1"], require_number_pos( name ) ); + setTimeout( function () { + client.exists( ["expiry key"], last( name, require_number( 0, name ) ) ); + }, 2000 ); }; tests.TTL = function () { - var name = "TTL"; - client.set(["ttl key", "ttl val"], require_string("OK", name)); - client.expire(["ttl key", "100"], require_number_pos(name)); - setTimeout(function () { - client.TTL(["ttl key"], last(name, require_number_pos(0, name))); - }, 500); + var name = "TTL"; + client.set( ["ttl key", "ttl val"], require_string( "OK", name ) ); + client.expire( ["ttl key", "100"], require_number_pos( name ) ); + setTimeout( function () { + client.TTL( ["ttl key"], last( name, require_number_pos( 0, name ) ) ); + }, 500 ); }; -all_tests = Object.keys(tests); +all_tests = Object.keys( tests ); all_start = new Date(); test_count = 0; run_next_test = function run_next_test() { - var test_name = all_tests.shift(); - if (typeof tests[test_name] === "function") { - util.print('- \x1b[1m' + test_name.toLowerCase() + '\x1b[0m:'); - cur_start = new Date(); - test_count += 1; - tests[test_name](); - } else { - console.log('\n completed \x1b[32m%d\x1b[0m tests in \x1b[33m%d\x1b[0m ms\n', test_count, new Date() - all_start); - client.quit(); - client2.quit(); - client4.quit(); - } + var test_name = all_tests.shift(); + if ( typeof tests[test_name] === "function" ) { + util.print( '- \x1b[1m' + test_name.toLowerCase() + '\x1b[0m:' ); + cur_start = new Date(); + test_count += 1; + tests[test_name](); + } else { + console.log( '\n completed \x1b[32m%d\x1b[0m tests in \x1b[33m%d\x1b[0m ms\n', test_count, new Date() - all_start ); + client.quit(); + client2.quit(); + client4.quit(); + } }; -console.log("Using reply parser " + client.reply_parser.name); +console.log( "Using reply parser " + client.reply_parser.name ); -client.once("ready", function start_tests() { - console.log("Connected to " + client.host + ":" + client.port + ", Redis server version " + client.server_info.redis_version + "\n"); +client.once( "ready", function start_tests() { + console.log( "Connected to " + client.host + ":" + client.port + ", Redis server version " + client.server_info.redis_version + "\n" ); - run_next_test(); + run_next_test(); - connected = true; -}); + connected = true; +} ); -client.on('end', function () { - ended = true; -}); +client.on( 'end', function () { + ended = true; +} ); // TODO - need a better way to test auth, maybe auto-config a local Redis server? Sounds hard. // Yes, this is the real password. Please be nice, thanks. -client4.auth("664b1b6aaf134e1ec281945a8de702a9", function (err, res) { - var name = "AUTH_4"; +client4.auth( "664b1b6aaf134e1ec281945a8de702a9", function ( err, res ) { + var name = "AUTH_4"; - if (err) { - assert.fail(err, name); - } - assert.strictEqual("OK", res.toString(), "auth"); -}); + if ( err ) { + assert.fail( err, name ); + } + assert.strictEqual( "OK", res.toString(), "auth" ); +} ); // Exit immediately on connection failure, which triggers "exit", below, which fails the test -client.on("error", function (err) { - console.error("client: " + err.stack); - process.exit(); -}); -client2.on("error", function (err) { - console.error("client2: " + err.stack); - process.exit(); -}); -client3.on("error", function (err) { - console.error("client3: " + err.stack); - process.exit(); -}); +client.on( "error", function ( err ) { + console.error( "client: " + err.stack ); + process.exit(); +} ); +client2.on( "error", function ( err ) { + console.error( "client2: " + err.stack ); + process.exit(); +} ); +client3.on( "error", function ( err ) { + console.error( "client3: " + err.stack ); + process.exit(); +} ); -client.on("reconnecting", function (params) { +client.on( "reconnecting", function ( params ) { // console.log("reconnecting: " + util.inspect(params)); -}); +} ); -process.on('uncaughtException', function (err) { - console.error("Uncaught exception: " + err.stack); - process.exit(1); -}); +process.on( 'uncaughtException', function ( err ) { + console.error( "Uncaught exception: " + err.stack ); + process.exit( 1 ); +} ); -process.on('exit', function (code) { - assert.equal(true, connected); - assert.equal(true, ended); -}); +process.on( 'exit', function ( code ) { + assert.equal( true, connected ); + assert.equal( true, ended ); +} ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/buffer_bench.js b/example/node/node_modules/socket.io/node_modules/redis/tests/buffer_bench.js index a504fbc..61f66c4 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/buffer_bench.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/buffer_bench.js @@ -1,89 +1,93 @@ -var source = new Buffer(100), - dest = new Buffer(100), i, j, k, tmp, count = 1000000, bytes = 100; - -for (i = 99 ; i >= 0 ; i--) { - source[i] = 120; +var source = new Buffer( 100 ), + dest = new Buffer( 100 ), i, j, k, tmp, count = 1000000, bytes = 100; + +for ( i = 99; i >= 0; i-- ) { + source[i] = 120; } var str = "This is a nice String.", - buf = new Buffer("This is a lovely Buffer."); + buf = new Buffer( "This is a lovely Buffer." ); var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (Buffer.isBuffer(str)) {} +for ( i = count * 100; i > 0; i-- ) { + if ( Buffer.isBuffer( str ) ) { + } } var end = new Date(); -console.log("Buffer.isBuffer(str) " + (end - start) + " ms"); +console.log( "Buffer.isBuffer(str) " + (end - start) + " ms" ); var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (Buffer.isBuffer(buf)) {} +for ( i = count * 100; i > 0; i-- ) { + if ( Buffer.isBuffer( buf ) ) { + } } var end = new Date(); -console.log("Buffer.isBuffer(buf) " + (end - start) + " ms"); +console.log( "Buffer.isBuffer(buf) " + (end - start) + " ms" ); var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (str instanceof Buffer) {} +for ( i = count * 100; i > 0; i-- ) { + if ( str instanceof Buffer ) { + } } var end = new Date(); -console.log("str instanceof Buffer " + (end - start) + " ms"); +console.log( "str instanceof Buffer " + (end - start) + " ms" ); var start = new Date(); -for (i = count * 100; i > 0 ; i--) { - if (buf instanceof Buffer) {} +for ( i = count * 100; i > 0; i-- ) { + if ( buf instanceof Buffer ) { + } } var end = new Date(); -console.log("buf instanceof Buffer " + (end - start) + " ms"); +console.log( "buf instanceof Buffer " + (end - start) + " ms" ); -for (i = bytes ; i > 0 ; i --) { - var start = new Date(); - for (j = count ; j > 0; j--) { - tmp = source.toString("ascii", 0, bytes); - } - var end = new Date(); - console.log("toString() " + i + " bytes " + (end - start) + " ms"); +for ( i = bytes; i > 0; i-- ) { + var start = new Date(); + for ( j = count; j > 0; j-- ) { + tmp = source.toString( "ascii", 0, bytes ); + } + var end = new Date(); + console.log( "toString() " + i + " bytes " + (end - start) + " ms" ); } -for (i = bytes ; i > 0 ; i --) { - var start = new Date(); - for (j = count ; j > 0; j--) { - tmp = ""; - for (k = 0; k <= i ; k++) { - tmp += String.fromCharCode(source[k]); - } - } - var end = new Date(); - console.log("manual string " + i + " bytes " + (end - start) + " ms"); +for ( i = bytes; i > 0; i-- ) { + var start = new Date(); + for ( j = count; j > 0; j-- ) { + tmp = ""; + for ( k = 0; k <= i; k++ ) { + tmp += String.fromCharCode( source[k] ); + } + } + var end = new Date(); + console.log( "manual string " + i + " bytes " + (end - start) + " ms" ); } -for (i = bytes ; i > 0 ; i--) { - var start = new Date(); - for (j = count ; j > 0 ; j--) { - for (k = i ; k > 0 ; k--) { - dest[k] = source[k]; - } - } - var end = new Date(); - console.log("Manual copy " + i + " bytes " + (end - start) + " ms"); +for ( i = bytes; i > 0; i-- ) { + var start = new Date(); + for ( j = count; j > 0; j-- ) { + for ( k = i; k > 0; k-- ) { + dest[k] = source[k]; + } + } + var end = new Date(); + console.log( "Manual copy " + i + " bytes " + (end - start) + " ms" ); } -for (i = bytes ; i > 0 ; i--) { - var start = new Date(); - for (j = count ; j > 0 ; j--) { - for (k = i ; k > 0 ; k--) { - dest[k] = 120; - } - } - var end = new Date(); - console.log("Direct assignment " + i + " bytes " + (end - start) + " ms"); +for ( i = bytes; i > 0; i-- ) { + var start = new Date(); + for ( j = count; j > 0; j-- ) { + for ( k = i; k > 0; k-- ) { + dest[k] = 120; + } + } + var end = new Date(); + console.log( "Direct assignment " + i + " bytes " + (end - start) + " ms" ); } -for (i = bytes ; i > 0 ; i--) { - var start = new Date(); - for (j = count ; j > 0 ; j--) { - source.copy(dest, 0, 0, i); - } - var end = new Date(); - console.log("Buffer.copy() " + i + " bytes " + (end - start) + " ms"); +for ( i = bytes; i > 0; i-- ) { + var start = new Date(); + for ( j = count; j > 0; j-- ) { + source.copy( dest, 0, 0, i ); + } + var end = new Date(); + console.log( "Buffer.copy() " + i + " bytes " + (end - start) + " ms" ); } diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/reconnect_test.js b/example/node/node_modules/socket.io/node_modules/redis/tests/reconnect_test.js index 08a6ca6..8da86c9 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/reconnect_test.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/reconnect_test.js @@ -1,27 +1,27 @@ -var redis = require("redis").createClient(); +var redis = require( "redis" ).createClient(); -redis.on("error", function (err) { - console.log("Redis says: " + err); -}); +redis.on( "error", function ( err ) { + console.log( "Redis says: " + err ); +} ); -redis.on("ready", function () { - console.log("Redis ready."); -}); +redis.on( "ready", function () { + console.log( "Redis ready." ); +} ); -redis.on("reconnecting", function (arg) { - console.log("Redis reconnecting: " + JSON.stringify(arg)); -}); -redis.on("connect", function () { - console.log("Redis connected."); -}); +redis.on( "reconnecting", function ( arg ) { + console.log( "Redis reconnecting: " + JSON.stringify( arg ) ); +} ); +redis.on( "connect", function () { + console.log( "Redis connected." ); +} ); -setInterval(function () { - var now = Date.now(); - redis.set("now", now, function (err, res) { - if (err) { - console.log(now + " Redis reply error: " + err); - } else { - console.log(now + " Redis reply: " + res); - } - }); -}, 200); +setInterval( function () { + var now = Date.now(); + redis.set( "now", now, function ( err, res ) { + if ( err ) { + console.log( now + " Redis reply error: " + err ); + } else { + console.log( now + " Redis reply: " + res ); + } + } ); +}, 200 ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/codec.js b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/codec.js index 7d764f6..002f2b0 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/codec.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/codec.js @@ -1,15 +1,17 @@ var json = { - encode: JSON.stringify, - decode: JSON.parse + encode : JSON.stringify, + decode : JSON.parse }; -var MsgPack = require('node-msgpack'); +var MsgPack = require( 'node-msgpack' ); msgpack = { - encode: MsgPack.pack, - decode: function(str) { return MsgPack.unpack(new Buffer(str)); } + encode : MsgPack.pack, + decode : function ( str ) { + return MsgPack.unpack( new Buffer( str ) ); + } }; -bison = require('bison'); +bison = require( 'bison' ); module.exports = json; //module.exports = msgpack; diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/pub.js b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/pub.js index 0acde7a..4d41d7f 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/pub.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/pub.js @@ -1,38 +1,41 @@ 'use strict'; -var freemem = require('os').freemem; -var profiler = require('v8-profiler'); -var codec = require('../codec'); +var freemem = require( 'os' ).freemem; +var profiler = require( 'v8-profiler' ); +var codec = require( '../codec' ); var sent = 0; -var pub = require('redis').createClient(null, null, { +var pub = require( 'redis' ).createClient( null, null, { //command_queue_high_water: 5, //command_queue_low_water: 1 -}) -.on('ready', function() { - this.emit('drain'); -}) -.on('drain', function() { - process.nextTick(exec); -}); +} ) + .on( 'ready', function () { + this.emit( 'drain' ); + } ) + .on( 'drain', function () { + process.nextTick( exec ); + } ); -var payload = '1'; for (var i = 0; i < 12; ++i) payload += payload; -console.log('Message payload length', payload.length); +var payload = '1'; +for ( var i = 0; i < 12; ++i ) { + payload += payload; +} +console.log( 'Message payload length', payload.length ); function exec() { - pub.publish('timeline', codec.encode({ foo: payload })); + pub.publish( 'timeline', codec.encode( { foo : payload } ) ); ++sent; - if (!pub.should_buffer) { - process.nextTick(exec); + if ( !pub.should_buffer ) { + process.nextTick( exec ); } } -profiler.takeSnapshot('s_0'); +profiler.takeSnapshot( 's_0' ); exec(); -setInterval(function() { - profiler.takeSnapshot('s_' + sent); - console.error('sent', sent, 'free', freemem(), 'cmdqlen', pub.command_queue.length, 'offqlen', pub.offline_queue.length); -}, 2000); +setInterval( function () { + profiler.takeSnapshot( 's_' + sent ); + console.error( 'sent', sent, 'free', freemem(), 'cmdqlen', pub.command_queue.length, 'offqlen', pub.offline_queue.length ); +}, 2000 ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/server.js b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/server.js index 035e6b7..f332358 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/server.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/pubsub/server.js @@ -1,23 +1,23 @@ 'use strict'; -var freemem = require('os').freemem; -var codec = require('../codec'); +var freemem = require( 'os' ).freemem; +var codec = require( '../codec' ); var id = Math.random(); var recv = 0; -var sub = require('redis').createClient() - .on('ready', function() { - this.subscribe('timeline'); - }) - .on('message', function(channel, message) { +var sub = require( 'redis' ).createClient() + .on( 'ready', function () { + this.subscribe( 'timeline' ); + } ) + .on( 'message', function ( channel, message ) { var self = this; - if (message) { - message = codec.decode(message); + if ( message ) { + message = codec.decode( message ); ++recv; } - }); + } ); -setInterval(function() { - console.error('id', id, 'received', recv, 'free', freemem()); -}, 2000); +setInterval( function () { + console.error( 'id', id, 'received', recv, 'free', freemem() ); +}, 2000 ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/pub.js b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/pub.js index 9caf1d0..7653812 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/pub.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/pub.js @@ -1,31 +1,34 @@ 'use strict'; -var freemem = require('os').freemem; +var freemem = require( 'os' ).freemem; //var profiler = require('v8-profiler'); -var codec = require('../codec'); +var codec = require( '../codec' ); var sent = 0; -var pub = require('redis').createClient(null, null, { +var pub = require( 'redis' ).createClient( null, null, { //command_queue_high_water: 5, //command_queue_low_water: 1 -}) -.on('ready', function() { - this.del('timeline'); - this.emit('drain'); -}) -.on('drain', function() { - process.nextTick(exec); -}); +} ) + .on( 'ready', function () { + this.del( 'timeline' ); + this.emit( 'drain' ); + } ) + .on( 'drain', function () { + process.nextTick( exec ); + } ); -var payload = '1'; for (var i = 0; i < 12; ++i) payload += payload; -console.log('Message payload length', payload.length); +var payload = '1'; +for ( var i = 0; i < 12; ++i ) { + payload += payload; +} +console.log( 'Message payload length', payload.length ); function exec() { - pub.rpush('timeline', codec.encode({ foo: payload })); + pub.rpush( 'timeline', codec.encode( { foo : payload } ) ); ++sent; - if (!pub.should_buffer) { - process.nextTick(exec); + if ( !pub.should_buffer ) { + process.nextTick( exec ); } } @@ -33,17 +36,17 @@ function exec() { exec(); -setInterval(function() { +setInterval( function () { //var ss = profiler.takeSnapshot('s_' + sent); //console.error(ss.stringify()); - pub.llen('timeline', function(err, result) { - console.error('sent', sent, 'free', freemem(), + pub.llen( 'timeline', function ( err, result ) { + console.error( 'sent', sent, 'free', freemem(), 'cmdqlen', pub.command_queue.length, 'offqlen', pub.offline_queue.length, 'llen', result ); - }); -}, 2000); + } ); +}, 2000 ); /*setTimeout(function() { - process.exit(); -}, 30000);*/ + process.exit(); + }, 30000);*/ diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/server.js b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/server.js index 9cbcdd9..142c976 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/server.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/rpushblpop/server.js @@ -1,30 +1,30 @@ 'use strict'; -var freemem = require('os').freemem; -var codec = require('../codec'); +var freemem = require( 'os' ).freemem; +var codec = require( '../codec' ); var id = Math.random(); var recv = 0; -var cmd = require('redis').createClient(); -var sub = require('redis').createClient() - .on('ready', function() { - this.emit('timeline'); - }) - .on('timeline', function() { +var cmd = require( 'redis' ).createClient(); +var sub = require( 'redis' ).createClient() + .on( 'ready', function () { + this.emit( 'timeline' ); + } ) + .on( 'timeline', function () { var self = this; - this.blpop('timeline', 0, function(err, result) { + this.blpop( 'timeline', 0, function ( err, result ) { var message = result[1]; - if (message) { - message = codec.decode(message); + if ( message ) { + message = codec.decode( message ); ++recv; } - self.emit('timeline'); - }); - }); + self.emit( 'timeline' ); + } ); + } ); -setInterval(function() { - cmd.llen('timeline', function(err, result) { - console.error('id', id, 'received', recv, 'free', freemem(), 'llen', result); - }); -}, 2000); +setInterval( function () { + cmd.llen( 'timeline', function ( err, result ) { + console.error( 'id', id, 'received', recv, 'free', freemem(), 'llen', result ); + } ); +}, 2000 ); diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/speed/speed.js b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/speed/speed.js index 8e43cbc..545a245 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/stress/speed/speed.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/stress/speed/speed.js @@ -1,84 +1,110 @@ -var msgpack = require('node-msgpack'); -var bison = require('bison'); +var msgpack = require( 'node-msgpack' ); +var bison = require( 'bison' ); var codec = { - JSON: { - encode: JSON.stringify, - decode: JSON.parse + JSON : { + encode : JSON.stringify, + decode : JSON.parse }, - msgpack: { - encode: msgpack.pack, - decode: msgpack.unpack + msgpack : { + encode : msgpack.pack, + decode : msgpack.unpack }, - bison: bison + bison : bison }; var obj, l; var s = '0'; -for (var i = 0; i < 12; ++i) s += s; +for ( var i = 0; i < 12; ++i ) { + s += s; +} obj = { - foo: s, - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [], - a: s, - ccc: s, - b: s + s + s + foo : s, + arrrrrr : [ + {a : 1, b : false, c : null, d : 1.0}, + 1111, + 2222, + 33333333 + ], + rand : [], + a : s, + ccc : s, + b : s + s + s }; -for (i = 0; i < 100; ++i) obj.rand.push(Math.random()); -forObj(obj); +for ( i = 0; i < 100; ++i ) { + obj.rand.push( Math.random() ); +} +forObj( obj ); obj = { - foo: s, - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [] + foo : s, + arrrrrr : [ + {a : 1, b : false, c : null, d : 1.0}, + 1111, + 2222, + 33333333 + ], + rand : [] }; -for (i = 0; i < 100; ++i) obj.rand.push(Math.random()); -forObj(obj); +for ( i = 0; i < 100; ++i ) { + obj.rand.push( Math.random() ); +} +forObj( obj ); obj = { - foo: s, - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [] + foo : s, + arrrrrr : [ + {a : 1, b : false, c : null, d : 1.0}, + 1111, + 2222, + 33333333 + ], + rand : [] }; -forObj(obj); +forObj( obj ); obj = { - arrrrrr: [{a:1,b:false,c:null,d:1.0}, 1111, 2222, 33333333], - rand: [] + arrrrrr : [ + {a : 1, b : false, c : null, d : 1.0}, + 1111, + 2222, + 33333333 + ], + rand : [] }; -forObj(obj); +forObj( obj ); -function run(obj, codec) { +function run( obj, codec ) { var t1 = Date.now(); var n = 10000; - for (var i = 0; i < n; ++i) { - codec.decode(l = codec.encode(obj)); + for ( var i = 0; i < n; ++i ) { + codec.decode( l = codec.encode( obj ) ); } var t2 = Date.now(); //console.log('DONE', n*1000/(t2-t1), 'codecs/sec, length=', l.length); - return [n*1000/(t2-t1), l.length]; + return [n * 1000 / (t2 - t1), l.length]; } -function series(obj, cname, n) { +function series( obj, cname, n ) { var rate = 0; var len = 0; - for (var i = 0; i < n; ++i) { - var r = run(obj, codec[cname]); + for ( var i = 0; i < n; ++i ) { + var r = run( obj, codec[cname] ); rate += r[0]; len += r[1]; } rate /= n; len /= n; - console.log(cname + ' ' + rate + ' ' + len); + console.log( cname + ' ' + rate + ' ' + len ); return [rate, len]; } -function forObj(obj) { +function forObj( obj ) { var r = { - JSON: series(obj, 'JSON', 20), - msgpack: series(obj, 'msgpack', 20), - bison: series(obj, 'bison', 20) + JSON : series( obj, 'JSON', 20 ), + msgpack : series( obj, 'msgpack', 20 ), + bison : series( obj, 'bison', 20 ) }; return r; } diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/sub_quit_test.js b/example/node/node_modules/socket.io/node_modules/redis/tests/sub_quit_test.js index ad1f413..875ac9f 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/sub_quit_test.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/sub_quit_test.js @@ -1,18 +1,18 @@ -var client = require("redis").createClient(), - client2 = require("redis").createClient(); +var client = require( "redis" ).createClient(), + client2 = require( "redis" ).createClient(); -client.subscribe("something"); -client.on("subscribe", function (channel, count) { - console.log("Got sub: " + channel); - client.unsubscribe("something"); -}); +client.subscribe( "something" ); +client.on( "subscribe", function ( channel, count ) { + console.log( "Got sub: " + channel ); + client.unsubscribe( "something" ); +} ); -client.on("unsubscribe", function (channel, count) { - console.log("Got unsub: " + channel + ", quitting"); - client.quit(); -}); +client.on( "unsubscribe", function ( channel, count ) { + console.log( "Got unsub: " + channel + ", quitting" ); + client.quit(); +} ); // exercise unsub before sub -client2.unsubscribe("something"); -client2.subscribe("another thing"); +client2.unsubscribe( "something" ); +client2.subscribe( "another thing" ); client2.quit(); diff --git a/example/node/node_modules/socket.io/node_modules/redis/tests/test_start_stop.js b/example/node/node_modules/socket.io/node_modules/redis/tests/test_start_stop.js index 0770893..13079ad 100644 --- a/example/node/node_modules/socket.io/node_modules/redis/tests/test_start_stop.js +++ b/example/node/node_modules/socket.io/node_modules/redis/tests/test_start_stop.js @@ -1,12 +1,12 @@ -var redis = require("./index"), - client = redis.createClient(); +var redis = require( "./index" ), + client = redis.createClient(); // This currently doesn't work, due to what I beleive to be a bug in redis 2.0.1. // INFO and QUIT are pipelined together, and the socket closes before the INFO // command gets a reply. redis.debug_mode = true; -client.info(redis.print); +client.info( redis.print ); client.quit(); // A workaround is: diff --git a/example/node/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js b/example/node/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js index 2dea613..f24be5d 100644 --- a/example/node/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js +++ b/example/node/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js @@ -6,454 +6,458 @@ * MIT Licensed */ -(function (exports, global) { +(function ( exports, global ) { - /** - * IO namespace. - * - * @namespace - */ + /** + * IO namespace. + * + * @namespace + */ - var io = exports; + var io = exports; - /** - * Socket.IO version - * - * @api public - */ + /** + * Socket.IO version + * + * @api public + */ - io.version = '0.9.3'; + io.version = '0.9.3'; - /** - * Protocol implemented. - * - * @api public - */ + /** + * Protocol implemented. + * + * @api public + */ - io.protocol = 1; + io.protocol = 1; - /** - * Available transports, these will be populated with the available transports - * - * @api public - */ + /** + * Available transports, these will be populated with the available transports + * + * @api public + */ - io.transports = []; + io.transports = []; - /** - * Keep track of jsonp callbacks. - * - * @api private - */ + /** + * Keep track of jsonp callbacks. + * + * @api private + */ - io.j = []; + io.j = []; - /** - * Keep track of our io.Sockets - * - * @api private - */ - io.sockets = {}; + /** + * Keep track of our io.Sockets + * + * @api private + */ + io.sockets = {}; - /** - * Manages connections to hosts. - * - * @param {String} uri - * @Param {Boolean} force creation of new socket (defaults to false) - * @api public - */ + /** + * Manages connections to hosts. + * + * @param {String} uri + * @Param {Boolean} force creation of new socket (defaults to false) + * @api public + */ - io.connect = function (host, details) { - var uri = io.util.parseUri(host) - , uuri - , socket; + io.connect = function ( host, details ) { + var uri = io.util.parseUri( host ) + , uuri + , socket; - if (global && global.location) { - uri.protocol = uri.protocol || global.location.protocol.slice(0, -1); - uri.host = uri.host || (global.document - ? global.document.domain : global.location.hostname); - uri.port = uri.port || global.location.port; - } + if ( global && global.location ) { + uri.protocol = uri.protocol || global.location.protocol.slice( 0, -1 ); + uri.host = uri.host || (global.document + ? global.document.domain : global.location.hostname); + uri.port = uri.port || global.location.port; + } - uuri = io.util.uniqueUri(uri); + uuri = io.util.uniqueUri( uri ); - var options = { - host: uri.host - , secure: 'https' == uri.protocol - , port: uri.port || ('https' == uri.protocol ? 443 : 80) - , query: uri.query || '' - }; + var options = { + host : uri.host, secure : 'https' == uri.protocol, port : uri.port || ('https' == uri.protocol ? 443 : 80), query : uri.query || '' + }; - io.util.merge(options, details); + io.util.merge( options, details ); - if (options['force new connection'] || !io.sockets[uuri]) { - socket = new io.Socket(options); - } + if ( options['force new connection'] || !io.sockets[uuri] ) { + socket = new io.Socket( options ); + } - if (!options['force new connection'] && socket) { - io.sockets[uuri] = socket; - } + if ( !options['force new connection'] && socket ) { + io.sockets[uuri] = socket; + } - socket = socket || io.sockets[uuri]; + socket = socket || io.sockets[uuri]; - // if path is different from '' or / - return socket.of(uri.path.length > 1 ? uri.path : ''); - }; + // if path is different from '' or / + return socket.of( uri.path.length > 1 ? uri.path : '' ); + }; -})('object' === typeof module ? module.exports : (this.io = {}), this); +})( 'object' === typeof module ? module.exports : (this.io = {}), this ); /** * socket.io * Copyright(c) 2011 LearnBoost * MIT Licensed */ -(function (exports, global) { - - /** - * Utilities namespace. - * - * @namespace - */ - - var util = exports.util = {}; - - /** - * Parses an URI - * - * @author Steven Levithan (MIT license) - * @api public - */ - - var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; - - var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', - 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', - 'anchor']; - - util.parseUri = function (str) { - var m = re.exec(str || '') - , uri = {} - , i = 14; - - while (i--) { - uri[parts[i]] = m[i] || ''; - } - - return uri; - }; - - /** - * Produces a unique url that identifies a Socket.IO connection. - * - * @param {Object} uri - * @api public - */ - - util.uniqueUri = function (uri) { - var protocol = uri.protocol - , host = uri.host - , port = uri.port; - - if ('document' in global) { - host = host || document.domain; - port = port || (protocol == 'https' - && document.location.protocol !== 'https:' ? 443 : document.location.port); - } else { - host = host || 'localhost'; - - if (!port && protocol == 'https') { - port = 443; - } - } - - return (protocol || 'http') + '://' + host + ':' + (port || 80); - }; - - /** - * Mergest 2 query strings in to once unique query string - * - * @param {String} base - * @param {String} addition - * @api public - */ - - util.query = function (base, addition) { - var query = util.chunkQuery(base || '') - , components = []; - - util.merge(query, util.chunkQuery(addition || '')); - for (var part in query) { - if (query.hasOwnProperty(part)) { - components.push(part + '=' + query[part]); - } - } - - return components.length ? '?' + components.join('&') : ''; - }; - - /** - * Transforms a querystring in to an object - * - * @param {String} qs - * @api public - */ - - util.chunkQuery = function (qs) { - var query = {} - , params = qs.split('&') - , i = 0 - , l = params.length - , kv; - - for (; i < l; ++i) { - kv = params[i].split('='); - if (kv[0]) { - query[kv[0]] = kv[1]; - } - } - - return query; - }; - - /** - * Executes the given function when the page is loaded. - * - * io.util.load(function () { console.log('page loaded'); }); - * - * @param {Function} fn - * @api public - */ - - var pageLoaded = false; - - util.load = function (fn) { - if ('document' in global && document.readyState === 'complete' || pageLoaded) { - return fn(); - } - - util.on(global, 'load', fn, false); - }; - - /** - * Adds an event. - * - * @api private - */ - - util.on = function (element, event, fn, capture) { - if (element.attachEvent) { - element.attachEvent('on' + event, fn); - } else if (element.addEventListener) { - element.addEventListener(event, fn, capture); - } - }; - - /** - * Generates the correct `XMLHttpRequest` for regular and cross domain requests. - * - * @param {Boolean} [xdomain] Create a request that can be used cross domain. - * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest. - * @api private - */ - - util.request = function (xdomain) { - - if (xdomain && 'undefined' != typeof XDomainRequest) { - return new XDomainRequest(); - } - - if ('undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS)) { - return new XMLHttpRequest(); - } - - if (!xdomain) { - try { - return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP'); - } catch(e) { } - } - - return null; - }; - - /** - * XHR based transport constructor. - * - * @constructor - * @api public - */ - - /** - * Change the internal pageLoaded value. - */ - - if ('undefined' != typeof window) { - util.load(function () { - pageLoaded = true; - }); - } - - /** - * Defers a function to ensure a spinner is not displayed by the browser - * - * @param {Function} fn - * @api public - */ - - util.defer = function (fn) { - if (!util.ua.webkit || 'undefined' != typeof importScripts) { - return fn(); - } - - util.load(function () { - setTimeout(fn, 100); - }); - }; - - /** - * Merges two objects. - * - * @api public - */ - - util.merge = function merge (target, additional, deep, lastseen) { - var seen = lastseen || [] - , depth = typeof deep == 'undefined' ? 2 : deep - , prop; - - for (prop in additional) { - if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) { - if (typeof target[prop] !== 'object' || !depth) { - target[prop] = additional[prop]; - seen.push(additional[prop]); - } else { - util.merge(target[prop], additional[prop], depth - 1, seen); - } - } - } - - return target; - }; - - /** - * Merges prototypes from objects - * - * @api public - */ - - util.mixin = function (ctor, ctor2) { - util.merge(ctor.prototype, ctor2.prototype); - }; - - /** - * Shortcut for prototypical and static inheritance. - * - * @api private - */ - - util.inherit = function (ctor, ctor2) { - function f() {}; - f.prototype = ctor2.prototype; - ctor.prototype = new f; - }; - - /** - * Checks if the given object is an Array. - * - * io.util.isArray([]); // true - * io.util.isArray({}); // false - * - * @param Object obj - * @api public - */ - - util.isArray = Array.isArray || function (obj) { - return Object.prototype.toString.call(obj) === '[object Array]'; - }; - - /** - * Intersects values of two arrays into a third - * - * @api public - */ - - util.intersect = function (arr, arr2) { - var ret = [] - , longest = arr.length > arr2.length ? arr : arr2 - , shortest = arr.length > arr2.length ? arr2 : arr; - - for (var i = 0, l = shortest.length; i < l; i++) { - if (~util.indexOf(longest, shortest[i])) - ret.push(shortest[i]); - } - - return ret; - } - - /** - * Array indexOf compatibility. - * - * @see bit.ly/a5Dxa2 - * @api public - */ - - util.indexOf = function (arr, o, i) { - - for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0; - i < j && arr[i] !== o; i++) {} - - return j <= i ? -1 : i; - }; - - /** - * Converts enumerables to array. - * - * @api public - */ - - util.toArray = function (enu) { - var arr = []; - - for (var i = 0, l = enu.length; i < l; i++) - arr.push(enu[i]); - - return arr; - }; - - /** - * UA / engines detection namespace. - * - * @namespace - */ - - util.ua = {}; - - /** - * Whether the UA supports CORS for XHR. - * - * @api public - */ - - util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () { - try { - var a = new XMLHttpRequest(); - } catch (e) { - return false; - } - - return a.withCredentials != undefined; - })(); - - /** - * Detect webkit. - * - * @api public - */ - - util.ua.webkit = 'undefined' != typeof navigator - && /webkit/i.test(navigator.userAgent); - -})('undefined' != typeof io ? io : module.exports, this); +(function ( exports, global ) { + + /** + * Utilities namespace. + * + * @namespace + */ + + var util = exports.util = {}; + + /** + * Parses an URI + * + * @author Steven Levithan (MIT license) + * @api public + */ + + var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; + + var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', + 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', + 'anchor']; + + util.parseUri = function ( str ) { + var m = re.exec( str || '' ) + , uri = {} + , i = 14; + + while ( i-- ) { + uri[parts[i]] = m[i] || ''; + } + + return uri; + }; + + /** + * Produces a unique url that identifies a Socket.IO connection. + * + * @param {Object} uri + * @api public + */ + + util.uniqueUri = function ( uri ) { + var protocol = uri.protocol + , host = uri.host + , port = uri.port; + + if ( 'document' in global ) { + host = host || document.domain; + port = port || (protocol == 'https' + && document.location.protocol !== 'https:' ? 443 : document.location.port); + } else { + host = host || 'localhost'; + + if ( !port && protocol == 'https' ) { + port = 443; + } + } + + return (protocol || 'http') + '://' + host + ':' + (port || 80); + }; + + /** + * Mergest 2 query strings in to once unique query string + * + * @param {String} base + * @param {String} addition + * @api public + */ + + util.query = function ( base, addition ) { + var query = util.chunkQuery( base || '' ) + , components = []; + + util.merge( query, util.chunkQuery( addition || '' ) ); + for ( var part in query ) { + if ( query.hasOwnProperty( part ) ) { + components.push( part + '=' + query[part] ); + } + } + + return components.length ? '?' + components.join( '&' ) : ''; + }; + + /** + * Transforms a querystring in to an object + * + * @param {String} qs + * @api public + */ + + util.chunkQuery = function ( qs ) { + var query = {} + , params = qs.split( '&' ) + , i = 0 + , l = params.length + , kv; + + for ( ; i < l; ++i ) { + kv = params[i].split( '=' ); + if ( kv[0] ) { + query[kv[0]] = kv[1]; + } + } + + return query; + }; + + /** + * Executes the given function when the page is loaded. + * + * io.util.load(function () { console.log('page loaded'); }); + * + * @param {Function} fn + * @api public + */ + + var pageLoaded = false; + + util.load = function ( fn ) { + if ( 'document' in global && document.readyState === 'complete' || pageLoaded ) { + return fn(); + } + + util.on( global, 'load', fn, false ); + }; + + /** + * Adds an event. + * + * @api private + */ + + util.on = function ( element, event, fn, capture ) { + if ( element.attachEvent ) { + element.attachEvent( 'on' + event, fn ); + } else if ( element.addEventListener ) { + element.addEventListener( event, fn, capture ); + } + }; + + /** + * Generates the correct `XMLHttpRequest` for regular and cross domain requests. + * + * @param {Boolean} [xdomain] Create a request that can be used cross domain. + * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest. + * @api private + */ + + util.request = function ( xdomain ) { + + if ( xdomain && 'undefined' != typeof XDomainRequest ) { + return new XDomainRequest(); + } + + if ( 'undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS) ) { + return new XMLHttpRequest(); + } + + if ( !xdomain ) { + try { + return new window[(['Active'].concat( 'Object' ).join( 'X' ))]( 'Microsoft.XMLHTTP' ); + } catch ( e ) { + } + } + + return null; + }; + + /** + * XHR based transport constructor. + * + * @constructor + * @api public + */ + + /** + * Change the internal pageLoaded value. + */ + + if ( 'undefined' != typeof window ) { + util.load( function () { + pageLoaded = true; + } ); + } + + /** + * Defers a function to ensure a spinner is not displayed by the browser + * + * @param {Function} fn + * @api public + */ + + util.defer = function ( fn ) { + if ( !util.ua.webkit || 'undefined' != typeof importScripts ) { + return fn(); + } + + util.load( function () { + setTimeout( fn, 100 ); + } ); + }; + + /** + * Merges two objects. + * + * @api public + */ + + util.merge = function merge( target, additional, deep, lastseen ) { + var seen = lastseen || [] + , depth = typeof deep == 'undefined' ? 2 : deep + , prop; + + for ( prop in additional ) { + if ( additional.hasOwnProperty( prop ) && util.indexOf( seen, prop ) < 0 ) { + if ( typeof target[prop] !== 'object' || !depth ) { + target[prop] = additional[prop]; + seen.push( additional[prop] ); + } else { + util.merge( target[prop], additional[prop], depth - 1, seen ); + } + } + } + + return target; + }; + + /** + * Merges prototypes from objects + * + * @api public + */ + + util.mixin = function ( ctor, ctor2 ) { + util.merge( ctor.prototype, ctor2.prototype ); + }; + + /** + * Shortcut for prototypical and static inheritance. + * + * @api private + */ + + util.inherit = function ( ctor, ctor2 ) { + function f() { + } + + ; + f.prototype = ctor2.prototype; + ctor.prototype = new f; + }; + + /** + * Checks if the given object is an Array. + * + * io.util.isArray([]); // true + * io.util.isArray({}); // false + * + * @param Object obj + * @api public + */ + + util.isArray = Array.isArray || function ( obj ) { + return Object.prototype.toString.call( obj ) === '[object Array]'; + }; + + /** + * Intersects values of two arrays into a third + * + * @api public + */ + + util.intersect = function ( arr, arr2 ) { + var ret = [] + , longest = arr.length > arr2.length ? arr : arr2 + , shortest = arr.length > arr2.length ? arr2 : arr; + + for ( var i = 0, l = shortest.length; i < l; i++ ) { + if ( ~util.indexOf( longest, shortest[i] ) ) { + ret.push( shortest[i] ); + } + } + + return ret; + } + + /** + * Array indexOf compatibility. + * + * @see bit.ly/a5Dxa2 + * @api public + */ + + util.indexOf = function ( arr, o, i ) { + + for ( var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0; + i < j && arr[i] !== o; i++ ) { + } + + return j <= i ? -1 : i; + }; + + /** + * Converts enumerables to array. + * + * @api public + */ + + util.toArray = function ( enu ) { + var arr = []; + + for ( var i = 0, l = enu.length; i < l; i++ ) { + arr.push( enu[i] ); + } + + return arr; + }; + + /** + * UA / engines detection namespace. + * + * @namespace + */ + + util.ua = {}; + + /** + * Whether the UA supports CORS for XHR. + * + * @api public + */ + + util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () { + try { + var a = new XMLHttpRequest(); + } catch ( e ) { + return false; + } + + return a.withCredentials != undefined; + })(); + + /** + * Detect webkit. + * + * @api public + */ + + util.ua.webkit = 'undefined' != typeof navigator + && /webkit/i.test( navigator.userAgent ); + +})( 'undefined' != typeof io ? io : module.exports, this ); /** * socket.io @@ -461,182 +465,187 @@ * MIT Licensed */ -(function (exports, io) { +(function ( exports, io ) { - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports.EventEmitter = EventEmitter; + exports.EventEmitter = EventEmitter; - /** - * Event emitter constructor. - * - * @api public. - */ + /** + * Event emitter constructor. + * + * @api public. + */ - function EventEmitter () {}; + function EventEmitter() { + } - /** - * Adds a listener - * - * @api public - */ + ; - EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } + /** + * Adds a listener + * + * @api public + */ - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (io.util.isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } + EventEmitter.prototype.on = function ( name, fn ) { + if ( !this.$events ) { + this.$events = {}; + } - return this; - }; + if ( !this.$events[name] ) { + this.$events[name] = fn; + } else if ( io.util.isArray( this.$events[name] ) ) { + this.$events[name].push( fn ); + } else { + this.$events[name] = [this.$events[name], fn]; + } - EventEmitter.prototype.addListener = EventEmitter.prototype.on; + return this; + }; - /** - * Adds a volatile listener. - * - * @api public - */ + EventEmitter.prototype.addListener = EventEmitter.prototype.on; - EventEmitter.prototype.once = function (name, fn) { - var self = this; + /** + * Adds a volatile listener. + * + * @api public + */ - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; + EventEmitter.prototype.once = function ( name, fn ) { + var self = this; - on.listener = fn; - this.on(name, on); + function on() { + self.removeListener( name, on ); + fn.apply( this, arguments ); + } - return this; - }; + ; - /** - * Removes a listener. - * - * @api public - */ + on.listener = fn; + this.on( name, on ); - EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; + return this; + }; - if (io.util.isArray(list)) { - var pos = -1; + /** + * Removes a listener. + * + * @api public + */ - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } + EventEmitter.prototype.removeListener = function ( name, fn ) { + if ( this.$events && this.$events[name] ) { + var list = this.$events[name]; - if (pos < 0) { - return this; - } + if ( io.util.isArray( list ) ) { + var pos = -1; - list.splice(pos, 1); + for ( var i = 0, l = list.length; i < l; i++ ) { + if ( list[i] === fn || (list[i].listener && list[i].listener === fn) ) { + pos = i; + break; + } + } - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } + if ( pos < 0 ) { + return this; + } - return this; - }; + list.splice( pos, 1 ); - /** - * Removes all listeners for an event. - * - * @api public - */ + if ( !list.length ) { + delete this.$events[name]; + } + } else if ( list === fn || (list.listener && list.listener === fn) ) { + delete this.$events[name]; + } + } - EventEmitter.prototype.removeAllListeners = function (name) { - // TODO: enable this when node 0.5 is stable - //if (name === undefined) { - //this.$events = {}; - //return this; - //} + return this; + }; - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } + /** + * Removes all listeners for an event. + * + * @api public + */ - return this; - }; + EventEmitter.prototype.removeAllListeners = function ( name ) { + // TODO: enable this when node 0.5 is stable + //if (name === undefined) { + //this.$events = {}; + //return this; + //} - /** - * Gets all listeners for a certain event. - * - * @api publci - */ + if ( this.$events && this.$events[name] ) { + this.$events[name] = null; + } - EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } + return this; + }; - if (!this.$events[name]) { - this.$events[name] = []; - } + /** + * Gets all listeners for a certain event. + * + * @api publci + */ - if (!io.util.isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } + EventEmitter.prototype.listeners = function ( name ) { + if ( !this.$events ) { + this.$events = {}; + } - return this.$events[name]; - }; + if ( !this.$events[name] ) { + this.$events[name] = []; + } - /** - * Emits an event. - * - * @api public - */ + if ( !io.util.isArray( this.$events[name] ) ) { + this.$events[name] = [this.$events[name]]; + } - EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } + return this.$events[name]; + }; - var handler = this.$events[name]; + /** + * Emits an event. + * + * @api public + */ - if (!handler) { - return false; - } + EventEmitter.prototype.emit = function ( name ) { + if ( !this.$events ) { + return false; + } - var args = Array.prototype.slice.call(arguments, 1); + var handler = this.$events[name]; - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (io.util.isArray(handler)) { - var listeners = handler.slice(); + if ( !handler ) { + return false; + } - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } + var args = Array.prototype.slice.call( arguments, 1 ); - return true; - }; + if ( 'function' == typeof handler ) { + handler.apply( this, args ); + } else if ( io.util.isArray( handler ) ) { + var listeners = handler.slice(); + + for ( var i = 0, l = listeners.length; i < l; i++ ) { + listeners[i].apply( this, args ); + } + } else { + return false; + } + + return true; + }; })( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports + 'undefined' != typeof io ? io : module.exports + , 'undefined' != typeof io ? io : module.parent.exports ); /** @@ -649,192 +658,193 @@ * Based on JSON2 (http://www.JSON.org/js.html). */ -(function (exports, nativeJSON) { - "use strict"; +(function ( exports, nativeJSON ) { + "use strict"; - // use native JSON if it's available - if (nativeJSON && nativeJSON.parse){ - return exports.JSON = { - parse: nativeJSON.parse - , stringify: nativeJSON.stringify - } - } + // use native JSON if it's available + if ( nativeJSON && nativeJSON.parse ) { + return exports.JSON = { + parse : nativeJSON.parse, stringify : nativeJSON.stringify + } + } - var JSON = exports.JSON = {}; + var JSON = exports.JSON = {}; - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } + function f( n ) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } - function date(d, key) { - return isFinite(d.valueOf()) ? - d.getUTCFullYear() + '-' + - f(d.getUTCMonth() + 1) + '-' + - f(d.getUTCDate()) + 'T' + - f(d.getUTCHours()) + ':' + - f(d.getUTCMinutes()) + ':' + - f(d.getUTCSeconds()) + 'Z' : null; - }; + function date( d, key ) { + return isFinite( d.valueOf() ) ? + d.getUTCFullYear() + '-' + + f( d.getUTCMonth() + 1 ) + '-' + + f( d.getUTCDate() ) + 'T' + + f( d.getUTCHours() ) + ':' + + f( d.getUTCMinutes() ) + ':' + + f( d.getUTCSeconds() ) + 'Z' : null; + } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; + ; + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b' : '\\b', + '\t' : '\\t', + '\n' : '\\n', + '\f' : '\\f', + '\r' : '\\r', + '"' : '\\"', + '\\' : '\\\\' + }, + rep; - function quote(string) { + function quote( string ) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } + escapable.lastIndex = 0; + return escapable.test( string ) ? '"' + string.replace( escapable, function ( a ) { + var c = meta[a]; + return typeof c === 'string' ? c : + '\\u' + ('0000' + a.charCodeAt( 0 ).toString( 16 )).slice( -4 ); + } ) + '"' : '"' + string + '"'; + } - function str(key, holder) { + function str( key, holder ) { // Produce a string from holder[key]. - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. - if (value instanceof Date) { - value = date(key); - } + if ( value instanceof Date ) { + value = date( key ); + } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } + if ( typeof rep === 'function' ) { + value = rep.call( holder, key, value ); + } // What happens next depends on the value's type. - switch (typeof value) { - case 'string': - return quote(value); + switch ( typeof value ) { + case 'string': + return quote( value ); - case 'number': + case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. - return isFinite(value) ? String(value) : 'null'; + return isFinite( value ) ? String( value ) : 'null'; - case 'boolean': - case 'null': + case 'boolean': + case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. - return String(value); + return String( value ); // If the type is 'object', we might be dealing with an object or an array or // null. - case 'object': + case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. - if (!value) { - return 'null'; - } + if ( !value ) { + return 'null'; + } // Make an array to hold the partial results of stringifying this object value. - gap += indent; - partial = []; + gap += indent; + partial = []; // Is the value an array? - if (Object.prototype.toString.apply(value) === '[object Array]') { + if ( Object.prototype.toString.apply( value ) === '[object Array]' ) { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } + length = value.length; + for ( i = 0; i < length; i += 1 ) { + partial[i] = str( i, value ) || 'null'; + } // Join all of the elements together, separated with commas, and wrap them in // brackets. - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } + v = partial.length === 0 ? '[]' : gap ? + '[\n' + gap + partial.join( ',\n' + gap ) + '\n' + mind + ']' : + '[' + partial.join( ',' ) + ']'; + gap = mind; + return v; + } // If the replacer is an array, use it to select the members to be stringified. - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { + if ( rep && typeof rep === 'object' ) { + length = rep.length; + for ( i = 0; i < length; i += 1 ) { + if ( typeof rep[i] === 'string' ) { + k = rep[i]; + v = str( k, value ); + if ( v ) { + partial.push( quote( k ) + (gap ? ': ' : ':') + v ); + } + } + } + } else { // Otherwise, iterate through all of the keys in the object. - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } + for ( k in value ) { + if ( Object.prototype.hasOwnProperty.call( value, k ) ) { + v = str( k, value ); + if ( v ) { + partial.push( quote( k ) + (gap ? ': ' : ':') + v ); + } + } + } + } // Join all of the member texts together, separated with commas, // and wrap them in braces. - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } + v = partial.length === 0 ? '{}' : gap ? + '{\n' + gap + partial.join( ',\n' + gap ) + '\n' + mind + '}' : + '{' + partial.join( ',' ) + '}'; + gap = mind; + return v; + } + } // If the JSON object does not yet have a stringify method, give it one. - JSON.stringify = function (value, replacer, space) { + JSON.stringify = function ( value, replacer, space ) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function @@ -842,123 +852,123 @@ // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. - var i; - gap = ''; - indent = ''; + var i; + gap = ''; + indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } + if ( typeof space === 'number' ) { + for ( i = 0; i < space; i += 1 ) { + indent += ' '; + } // If the space parameter is a string, it will be used as the indent string. - } else if (typeof space === 'string') { - indent = space; - } + } else if ( typeof space === 'string' ) { + indent = space; + } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } + rep = replacer; + if ( replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number') ) { + throw new Error( 'JSON.stringify' ); + } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. - return str('', {'': value}); - }; + return str( '', {'' : value} ); + }; // If the JSON object does not yet have a parse method, give it one. - JSON.parse = function (text, reviver) { - // The parse method takes a text and an optional reviver function, and returns - // a JavaScript value if the text is a valid JSON text. + JSON.parse = function ( text, reviver ) { + // The parse method takes a text and an optional reviver function, and returns + // a JavaScript value if the text is a valid JSON text. - var j; + var j; - function walk(holder, key) { + function walk( holder, key ) { - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. + // The walk method is used to recursively walk the resulting structure so + // that modifications can be made. - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } + var k, v, value = holder[key]; + if ( value && typeof value === 'object' ) { + for ( k in value ) { + if ( Object.prototype.hasOwnProperty.call( value, k ) ) { + v = walk( value, k ); + if ( v !== undefined ) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call( holder, key, value ); + } - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. + // Parsing happens in four stages. In the first stage, we replace certain + // Unicode characters with escape sequences. JavaScript handles many characters + // incorrectly, either silently deleting them, or treating them as line endings. - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } + text = String( text ); + cx.lastIndex = 0; + if ( cx.test( text ) ) { + text = text.replace( cx, function ( a ) { + return '\\u' + + ('0000' + a.charCodeAt( 0 ).toString( 16 )).slice( -4 ); + } ); + } - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with '()' and 'new' - // because they can cause invocation, and '=' because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. + // In the second stage, we run the text against regular expressions that look + // for non-JSON patterns. We are especially concerned with '()' and 'new' + // because they can cause invocation, and '=' because it can cause mutation. + // But just to be safe, we want to reject all unexpected forms. - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we - // replace all simple value tokens with ']' characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or ']' or - // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + // We split the second stage into 4 regexp operations in order to work around + // crippling inefficiencies in IE's and Safari's regexp engines. First we + // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we + // replace all simple value tokens with ']' characters. Third, we delete all + // open brackets that follow a colon or comma or that begin the text. Finally, + // we look to see that the remaining characters are only whitespace or ']' or + // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + if ( /^[\],:{}\s]*$/ + .test( text.replace( /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@' ) + .replace( /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']' ) + .replace( /(?:^|:|,)(?:\s*\[)+/g, '' ) ) ) { - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The '{' operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. + // In the third stage we use the eval function to compile the text into a + // JavaScript structure. The '{' operator is subject to a syntactic ambiguity + // in JavaScript: it can begin a block or an object literal. We wrap the text + // in parens to eliminate the ambiguity. - j = eval('(' + text + ')'); + j = eval( '(' + text + ')' ); - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. + // In the optional fourth stage, we recursively walk the new structure, passing + // each name/value pair to a reviver function for possible transformation. - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } + return typeof reviver === 'function' ? + walk( {'' : j}, '' ) : j; + } - // If the text is not JSON parseable, then a SyntaxError is thrown. + // If the text is not JSON parseable, then a SyntaxError is thrown. - throw new SyntaxError('JSON.parse'); - }; + throw new SyntaxError( 'JSON.parse' ); + }; })( - 'undefined' != typeof io ? io : module.exports - , typeof JSON !== 'undefined' ? JSON : undefined + 'undefined' != typeof io ? io : module.exports + , typeof JSON !== 'undefined' ? JSON : undefined ); /** @@ -967,260 +977,272 @@ * MIT Licensed */ -(function (exports, io) { +(function ( exports, io ) { - /** - * Parser namespace. - * - * @namespace - */ + /** + * Parser namespace. + * + * @namespace + */ - var parser = exports.parser = {}; + var parser = exports.parser = {}; - /** - * Packet types. - */ + /** + * Packet types. + */ - var packets = parser.packets = [ - 'disconnect' - , 'connect' - , 'heartbeat' - , 'message' - , 'json' - , 'event' - , 'ack' - , 'error' - , 'noop' - ]; + var packets = parser.packets = [ + 'disconnect' + , 'connect' + , 'heartbeat' + , 'message' + , 'json' + , 'event' + , 'ack' + , 'error' + , 'noop' + ]; - /** - * Errors reasons. - */ + /** + * Errors reasons. + */ - var reasons = parser.reasons = [ - 'transport not supported' - , 'client not handshaken' - , 'unauthorized' - ]; + var reasons = parser.reasons = [ + 'transport not supported' + , 'client not handshaken' + , 'unauthorized' + ]; - /** - * Errors advice. - */ + /** + * Errors advice. + */ - var advice = parser.advice = [ - 'reconnect' - ]; + var advice = parser.advice = [ + 'reconnect' + ]; - /** - * Shortcuts. - */ + /** + * Shortcuts. + */ - var JSON = io.JSON - , indexOf = io.util.indexOf; + var JSON = io.JSON + , indexOf = io.util.indexOf; - /** - * Encodes a packet. - * - * @api private - */ + /** + * Encodes a packet. + * + * @api private + */ - parser.encodePacket = function (packet) { - var type = indexOf(packets, packet.type) - , id = packet.id || '' - , endpoint = packet.endpoint || '' - , ack = packet.ack - , data = null; + parser.encodePacket = function ( packet ) { + var type = indexOf( packets, packet.type ) + , id = packet.id || '' + , endpoint = packet.endpoint || '' + , ack = packet.ack + , data = null; - switch (packet.type) { - case 'error': - var reason = packet.reason ? indexOf(reasons, packet.reason) : '' - , adv = packet.advice ? indexOf(advice, packet.advice) : ''; + switch ( packet.type ) { + case 'error': + var reason = packet.reason ? indexOf( reasons, packet.reason ) : '' + , adv = packet.advice ? indexOf( advice, packet.advice ) : ''; - if (reason !== '' || adv !== '') - data = reason + (adv !== '' ? ('+' + adv) : ''); + if ( reason !== '' || adv !== '' ) { + data = reason + (adv !== '' ? ('+' + adv) : ''); + } - break; + break; - case 'message': - if (packet.data !== '') - data = packet.data; - break; + case 'message': + if ( packet.data !== '' ) { + data = packet.data; + } + break; - case 'event': - var ev = { name: packet.name }; + case 'event': + var ev = { name : packet.name }; - if (packet.args && packet.args.length) { - ev.args = packet.args; - } + if ( packet.args && packet.args.length ) { + ev.args = packet.args; + } - data = JSON.stringify(ev); - break; + data = JSON.stringify( ev ); + break; - case 'json': - data = JSON.stringify(packet.data); - break; + case 'json': + data = JSON.stringify( packet.data ); + break; - case 'connect': - if (packet.qs) - data = packet.qs; - break; + case 'connect': + if ( packet.qs ) { + data = packet.qs; + } + break; - case 'ack': - data = packet.ackId - + (packet.args && packet.args.length - ? '+' + JSON.stringify(packet.args) : ''); - break; - } + case 'ack': + data = packet.ackId + + (packet.args && packet.args.length + ? '+' + JSON.stringify( packet.args ) : ''); + break; + } - // construct packet with required fragments - var encoded = [ - type - , id + (ack == 'data' ? '+' : '') - , endpoint - ]; + // construct packet with required fragments + var encoded = [ + type + , id + (ack == 'data' ? '+' : '') + , endpoint + ]; - // data fragment is optional - if (data !== null && data !== undefined) - encoded.push(data); + // data fragment is optional + if ( data !== null && data !== undefined ) { + encoded.push( data ); + } - return encoded.join(':'); - }; + return encoded.join( ':' ); + }; - /** - * Encodes multiple messages (payload). - * - * @param {Array} messages - * @api private - */ + /** + * Encodes multiple messages (payload). + * + * @param {Array} messages + * @api private + */ - parser.encodePayload = function (packets) { - var decoded = ''; + parser.encodePayload = function ( packets ) { + var decoded = ''; - if (packets.length == 1) - return packets[0]; + if ( packets.length == 1 ) { + return packets[0]; + } - for (var i = 0, l = packets.length; i < l; i++) { - var packet = packets[i]; - decoded += '\ufffd' + packet.length + '\ufffd' + packets[i]; - } + for ( var i = 0, l = packets.length; i < l; i++ ) { + var packet = packets[i]; + decoded += '\ufffd' + packet.length + '\ufffd' + packets[i]; + } - return decoded; - }; + return decoded; + }; - /** - * Decodes a packet - * - * @api private - */ + /** + * Decodes a packet + * + * @api private + */ - var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/; + var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/; - parser.decodePacket = function (data) { - var pieces = data.match(regexp); + parser.decodePacket = function ( data ) { + var pieces = data.match( regexp ); - if (!pieces) return {}; + if ( !pieces ) { + return {}; + } - var id = pieces[2] || '' - , data = pieces[5] || '' - , packet = { - type: packets[pieces[1]] - , endpoint: pieces[4] || '' - }; + var id = pieces[2] || '' + , data = pieces[5] || '' + , packet = { + type : packets[pieces[1]], endpoint : pieces[4] || '' + }; - // whether we need to acknowledge the packet - if (id) { - packet.id = id; - if (pieces[3]) - packet.ack = 'data'; - else - packet.ack = true; - } + // whether we need to acknowledge the packet + if ( id ) { + packet.id = id; + if ( pieces[3] ) { + packet.ack = 'data'; + } + else { + packet.ack = true; + } + } - // handle different packet types - switch (packet.type) { - case 'error': - var pieces = data.split('+'); - packet.reason = reasons[pieces[0]] || ''; - packet.advice = advice[pieces[1]] || ''; - break; + // handle different packet types + switch ( packet.type ) { + case 'error': + var pieces = data.split( '+' ); + packet.reason = reasons[pieces[0]] || ''; + packet.advice = advice[pieces[1]] || ''; + break; - case 'message': - packet.data = data || ''; - break; + case 'message': + packet.data = data || ''; + break; - case 'event': - try { - var opts = JSON.parse(data); - packet.name = opts.name; - packet.args = opts.args; - } catch (e) { } + case 'event': + try { + var opts = JSON.parse( data ); + packet.name = opts.name; + packet.args = opts.args; + } catch ( e ) { + } - packet.args = packet.args || []; - break; + packet.args = packet.args || []; + break; - case 'json': - try { - packet.data = JSON.parse(data); - } catch (e) { } - break; + case 'json': + try { + packet.data = JSON.parse( data ); + } catch ( e ) { + } + break; - case 'connect': - packet.qs = data || ''; - break; + case 'connect': + packet.qs = data || ''; + break; - case 'ack': - var pieces = data.match(/^([0-9]+)(\+)?(.*)/); - if (pieces) { - packet.ackId = pieces[1]; - packet.args = []; + case 'ack': + var pieces = data.match( /^([0-9]+)(\+)?(.*)/ ); + if ( pieces ) { + packet.ackId = pieces[1]; + packet.args = []; - if (pieces[3]) { - try { - packet.args = pieces[3] ? JSON.parse(pieces[3]) : []; - } catch (e) { } - } - } - break; + if ( pieces[3] ) { + try { + packet.args = pieces[3] ? JSON.parse( pieces[3] ) : []; + } catch ( e ) { + } + } + } + break; - case 'disconnect': - case 'heartbeat': - break; - }; + case 'disconnect': + case 'heartbeat': + break; + } + ; - return packet; - }; + return packet; + }; - /** - * Decodes data payload. Detects multiple messages - * - * @return {Array} messages - * @api public - */ + /** + * Decodes data payload. Detects multiple messages + * + * @return {Array} messages + * @api public + */ - parser.decodePayload = function (data) { - // IE doesn't like data[i] for unicode chars, charAt works fine - if (data.charAt(0) == '\ufffd') { - var ret = []; + parser.decodePayload = function ( data ) { + // IE doesn't like data[i] for unicode chars, charAt works fine + if ( data.charAt( 0 ) == '\ufffd' ) { + var ret = []; - for (var i = 1, length = ''; i < data.length; i++) { - if (data.charAt(i) == '\ufffd') { - ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length))); - i += Number(length) + 1; - length = ''; - } else { - length += data.charAt(i); - } - } + for ( var i = 1, length = ''; i < data.length; i++ ) { + if ( data.charAt( i ) == '\ufffd' ) { + ret.push( parser.decodePacket( data.substr( i + 1 ).substr( 0, length ) ) ); + i += Number( length ) + 1; + length = ''; + } else { + length += data.charAt( i ); + } + } - return ret; - } else { - return [parser.decodePacket(data)]; - } - }; + return ret; + } else { + return [parser.decodePacket( data )]; + } + }; })( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports + 'undefined' != typeof io ? io : module.exports + , 'undefined' != typeof io ? io : module.parent.exports ); /** * socket.io @@ -1228,240 +1250,244 @@ * MIT Licensed */ -(function (exports, io) { +(function ( exports, io ) { - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports.Transport = Transport; + exports.Transport = Transport; - /** - * This is the transport template for all supported transport methods. - * - * @constructor - * @api public - */ + /** + * This is the transport template for all supported transport methods. + * + * @constructor + * @api public + */ - function Transport (socket, sessid) { - this.socket = socket; - this.sessid = sessid; - }; + function Transport( socket, sessid ) { + this.socket = socket; + this.sessid = sessid; + } - /** - * Apply EventEmitter mixin. - */ + ; - io.util.mixin(Transport, io.EventEmitter); + /** + * Apply EventEmitter mixin. + */ - /** - * Handles the response from the server. When a new response is received - * it will automatically update the timeout, decode the message and - * forwards the response to the onMessage function for further processing. - * - * @param {String} data Response from the server. - * @api private - */ + io.util.mixin( Transport, io.EventEmitter ); - Transport.prototype.onData = function (data) { - this.clearCloseTimeout(); - - // If the connection in currently open (or in a reopening state) reset the close - // timeout since we have just received data. This check is necessary so - // that we don't reset the timeout on an explicitly disconnected connection. - if (this.socket.connected || this.socket.connecting || this.socket.reconnecting) { - this.setCloseTimeout(); - } + /** + * Handles the response from the server. When a new response is received + * it will automatically update the timeout, decode the message and + * forwards the response to the onMessage function for further processing. + * + * @param {String} data Response from the server. + * @api private + */ - if (data !== '') { - // todo: we should only do decodePayload for xhr transports - var msgs = io.parser.decodePayload(data); + Transport.prototype.onData = function ( data ) { + this.clearCloseTimeout(); - if (msgs && msgs.length) { - for (var i = 0, l = msgs.length; i < l; i++) { - this.onPacket(msgs[i]); - } - } - } + // If the connection in currently open (or in a reopening state) reset the close + // timeout since we have just received data. This check is necessary so + // that we don't reset the timeout on an explicitly disconnected connection. + if ( this.socket.connected || this.socket.connecting || this.socket.reconnecting ) { + this.setCloseTimeout(); + } - return this; - }; + if ( data !== '' ) { + // todo: we should only do decodePayload for xhr transports + var msgs = io.parser.decodePayload( data ); - /** - * Handles packets. - * - * @api private - */ + if ( msgs && msgs.length ) { + for ( var i = 0, l = msgs.length; i < l; i++ ) { + this.onPacket( msgs[i] ); + } + } + } - Transport.prototype.onPacket = function (packet) { - this.socket.setHeartbeatTimeout(); + return this; + }; - if (packet.type == 'heartbeat') { - return this.onHeartbeat(); - } + /** + * Handles packets. + * + * @api private + */ - if (packet.type == 'connect' && packet.endpoint == '') { - this.onConnect(); - } + Transport.prototype.onPacket = function ( packet ) { + this.socket.setHeartbeatTimeout(); - this.socket.onPacket(packet); + if ( packet.type == 'heartbeat' ) { + return this.onHeartbeat(); + } - return this; - }; + if ( packet.type == 'connect' && packet.endpoint == '' ) { + this.onConnect(); + } - /** - * Sets close timeout - * - * @api private - */ - - Transport.prototype.setCloseTimeout = function () { - if (!this.closeTimeout) { - var self = this; + this.socket.onPacket( packet ); - this.closeTimeout = setTimeout(function () { - self.onDisconnect(); - }, this.socket.closeTimeout); - } - }; + return this; + }; - /** - * Called when transport disconnects. - * - * @api private - */ + /** + * Sets close timeout + * + * @api private + */ - Transport.prototype.onDisconnect = function () { - if (this.close && this.open) this.close(); - this.clearTimeouts(); - this.socket.onDisconnect(); - return this; - }; + Transport.prototype.setCloseTimeout = function () { + if ( !this.closeTimeout ) { + var self = this; - /** - * Called when transport connects - * - * @api private - */ + this.closeTimeout = setTimeout( function () { + self.onDisconnect(); + }, this.socket.closeTimeout ); + } + }; - Transport.prototype.onConnect = function () { - this.socket.onConnect(); - return this; - } + /** + * Called when transport disconnects. + * + * @api private + */ - /** - * Clears close timeout - * - * @api private - */ + Transport.prototype.onDisconnect = function () { + if ( this.close && this.open ) { + this.close(); + } + this.clearTimeouts(); + this.socket.onDisconnect(); + return this; + }; - Transport.prototype.clearCloseTimeout = function () { - if (this.closeTimeout) { - clearTimeout(this.closeTimeout); - this.closeTimeout = null; - } - }; + /** + * Called when transport connects + * + * @api private + */ - /** - * Clear timeouts - * - * @api private - */ + Transport.prototype.onConnect = function () { + this.socket.onConnect(); + return this; + } - Transport.prototype.clearTimeouts = function () { - this.clearCloseTimeout(); + /** + * Clears close timeout + * + * @api private + */ - if (this.reopenTimeout) { - clearTimeout(this.reopenTimeout); - } - }; + Transport.prototype.clearCloseTimeout = function () { + if ( this.closeTimeout ) { + clearTimeout( this.closeTimeout ); + this.closeTimeout = null; + } + }; - /** - * Sends a packet - * - * @param {Object} packet object. - * @api private - */ + /** + * Clear timeouts + * + * @api private + */ - Transport.prototype.packet = function (packet) { - this.send(io.parser.encodePacket(packet)); - }; + Transport.prototype.clearTimeouts = function () { + this.clearCloseTimeout(); - /** - * Send the received heartbeat message back to server. So the server - * knows we are still connected. - * - * @param {String} heartbeat Heartbeat response from the server. - * @api private - */ + if ( this.reopenTimeout ) { + clearTimeout( this.reopenTimeout ); + } + }; - Transport.prototype.onHeartbeat = function (heartbeat) { - this.packet({ type: 'heartbeat' }); - }; - - /** - * Called when the transport opens. - * - * @api private - */ + /** + * Sends a packet + * + * @param {Object} packet object. + * @api private + */ - Transport.prototype.onOpen = function () { - this.open = true; - this.clearCloseTimeout(); - this.socket.onOpen(); - }; + Transport.prototype.packet = function ( packet ) { + this.send( io.parser.encodePacket( packet ) ); + }; - /** - * Notifies the base when the connection with the Socket.IO server - * has been disconnected. - * - * @api private - */ + /** + * Send the received heartbeat message back to server. So the server + * knows we are still connected. + * + * @param {String} heartbeat Heartbeat response from the server. + * @api private + */ - Transport.prototype.onClose = function () { - var self = this; + Transport.prototype.onHeartbeat = function ( heartbeat ) { + this.packet( { type : 'heartbeat' } ); + }; - /* FIXME: reopen delay causing a infinit loop - this.reopenTimeout = setTimeout(function () { - self.open(); - }, this.socket.options['reopen delay']);*/ + /** + * Called when the transport opens. + * + * @api private + */ - this.open = false; - this.socket.onClose(); - this.onDisconnect(); - }; + Transport.prototype.onOpen = function () { + this.open = true; + this.clearCloseTimeout(); + this.socket.onOpen(); + }; - /** - * Generates a connection url based on the Socket.IO URL Protocol. - * See for more details. - * - * @returns {String} Connection url - * @api private - */ + /** + * Notifies the base when the connection with the Socket.IO server + * has been disconnected. + * + * @api private + */ - Transport.prototype.prepareUrl = function () { - var options = this.socket.options; + Transport.prototype.onClose = function () { + var self = this; - return this.scheme() + '://' - + options.host + ':' + options.port + '/' - + options.resource + '/' + io.protocol - + '/' + this.name + '/' + this.sessid; - }; + /* FIXME: reopen delay causing a infinit loop + this.reopenTimeout = setTimeout(function () { + self.open(); + }, this.socket.options['reopen delay']);*/ - /** - * Checks if the transport is ready to start a connection. - * - * @param {Socket} socket The socket instance that needs a transport - * @param {Function} fn The callback - * @api private - */ + this.open = false; + this.socket.onClose(); + this.onDisconnect(); + }; - Transport.prototype.ready = function (socket, fn) { - fn.call(this); - }; + /** + * Generates a connection url based on the Socket.IO URL Protocol. + * See for more details. + * + * @returns {String} Connection url + * @api private + */ + + Transport.prototype.prepareUrl = function () { + var options = this.socket.options; + + return this.scheme() + '://' + + options.host + ':' + options.port + '/' + + options.resource + '/' + io.protocol + + '/' + this.name + '/' + this.sessid; + }; + + /** + * Checks if the transport is ready to start a connection. + * + * @param {Socket} socket The socket instance that needs a transport + * @param {Function} fn The callback + * @api private + */ + + Transport.prototype.ready = function ( socket, fn ) { + fn.call( this ); + }; })( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports + 'undefined' != typeof io ? io : module.exports + , 'undefined' != typeof io ? io : module.parent.exports ); /** * socket.io @@ -1469,547 +1495,550 @@ * MIT Licensed */ -(function (exports, io, global) { - - /** - * Expose constructor. - */ - - exports.Socket = Socket; - - /** - * Create a new `Socket.IO client` which can establish a persistent - * connection with a Socket.IO enabled server. - * - * @api public - */ - - function Socket (options) { - this.options = { - port: 80 - , secure: false - , document: 'document' in global ? document : false - , resource: 'socket.io' - , transports: io.transports - , 'connect timeout': 10000 - , 'try multiple transports': true - , 'reconnect': true - , 'reconnection delay': 500 - , 'reconnection limit': Infinity - , 'reopen delay': 3000 - , 'max reconnection attempts': 10 - , 'sync disconnect on unload': true - , 'auto connect': true - , 'flash policy port': 10843 - }; - - io.util.merge(this.options, options); - - this.connected = false; - this.open = false; - this.connecting = false; - this.reconnecting = false; - this.namespaces = {}; - this.buffer = []; - this.doBuffer = false; - - if (this.options['sync disconnect on unload'] && - (!this.isXDomain() || io.util.ua.hasCORS)) { - var self = this; - - io.util.on(global, 'unload', function () { - self.disconnectSync(); - }, false); - } - - if (this.options['auto connect']) { - this.connect(); - } -}; - - /** - * Apply EventEmitter mixin. - */ - - io.util.mixin(Socket, io.EventEmitter); - - /** - * Returns a namespace listener/emitter for this socket - * - * @api public - */ - - Socket.prototype.of = function (name) { - if (!this.namespaces[name]) { - this.namespaces[name] = new io.SocketNamespace(this, name); - - if (name !== '') { - this.namespaces[name].packet({ type: 'connect' }); - } - } - - return this.namespaces[name]; - }; - - /** - * Emits the given event to the Socket and all namespaces - * - * @api private - */ - - Socket.prototype.publish = function () { - this.emit.apply(this, arguments); - - var nsp; - - for (var i in this.namespaces) { - if (this.namespaces.hasOwnProperty(i)) { - nsp = this.of(i); - nsp.$emit.apply(nsp, arguments); - } - } - }; - - /** - * Performs the handshake - * - * @api private - */ - - function empty () { }; - - Socket.prototype.handshake = function (fn) { - var self = this - , options = this.options; - - function complete (data) { - if (data instanceof Error) { - self.onError(data.message); - } else { - fn.apply(null, data.split(':')); - } - }; - - var url = [ - 'http' + (options.secure ? 's' : '') + ':/' - , options.host + ':' + options.port - , options.resource - , io.protocol - , io.util.query(this.options.query, 't=' + +new Date) - ].join('/'); - - if (this.isXDomain() && !io.util.ua.hasCORS) { - var insertAt = document.getElementsByTagName('script')[0] - , script = document.createElement('script'); - - script.src = url + '&jsonp=' + io.j.length; - insertAt.parentNode.insertBefore(script, insertAt); - - io.j.push(function (data) { - complete(data); - script.parentNode.removeChild(script); - }); - } else { - var xhr = io.util.request(); - - xhr.open('GET', url, true); - xhr.withCredentials = true; - xhr.onreadystatechange = function () { - if (xhr.readyState == 4) { - xhr.onreadystatechange = empty; - - if (xhr.status == 200) { - complete(xhr.responseText); - } else { - !self.reconnecting && self.onError(xhr.responseText); - } - } - }; - xhr.send(null); - } - }; - - /** - * Find an available transport based on the options supplied in the constructor. - * - * @api private - */ - - Socket.prototype.getTransport = function (override) { - var transports = override || this.transports, match; - - for (var i = 0, transport; transport = transports[i]; i++) { - if (io.Transport[transport] - && io.Transport[transport].check(this) - && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) { - return new io.Transport[transport](this, this.sessionid); - } - } - - return null; - }; - - /** - * Connects to the server. - * - * @param {Function} [fn] Callback. - * @returns {io.Socket} - * @api public - */ - - Socket.prototype.connect = function (fn) { - if (this.connecting) { - return this; - } - - var self = this; - - this.handshake(function (sid, heartbeat, close, transports) { - self.sessionid = sid; - self.closeTimeout = close * 1000; - self.heartbeatTimeout = heartbeat * 1000; - self.transports = transports ? io.util.intersect( - transports.split(',') - , self.options.transports - ) : self.options.transports; - - self.setHeartbeatTimeout(); - - function connect (transports){ - if (self.transport) self.transport.clearTimeouts(); - - self.transport = self.getTransport(transports); - if (!self.transport) return self.publish('connect_failed'); - - // once the transport is ready - self.transport.ready(self, function () { - self.connecting = true; - self.publish('connecting', self.transport.name); - self.transport.open(); - - if (self.options['connect timeout']) { - self.connectTimeoutTimer = setTimeout(function () { - if (!self.connected) { - self.connecting = false; - - if (self.options['try multiple transports']) { - if (!self.remainingTransports) { - self.remainingTransports = self.transports.slice(0); - } - - var remaining = self.remainingTransports; - - while (remaining.length > 0 && remaining.splice(0,1)[0] != - self.transport.name) {} - - if (remaining.length){ - connect(remaining); - } else { - self.publish('connect_failed'); - } - } - } - }, self.options['connect timeout']); - } - }); - } - - connect(self.transports); - - self.once('connect', function (){ - clearTimeout(self.connectTimeoutTimer); - - fn && typeof fn == 'function' && fn(); - }); - }); - - return this; - }; - - /** - * Clears and sets a new heartbeat timeout using the value given by the - * server during the handshake. - * - * @api private - */ - - Socket.prototype.setHeartbeatTimeout = function () { - clearTimeout(this.heartbeatTimeoutTimer); - - var self = this; - this.heartbeatTimeoutTimer = setTimeout(function () { - self.transport.onClose(); - }, this.heartbeatTimeout); - }; - - /** - * Sends a message. - * - * @param {Object} data packet. - * @returns {io.Socket} - * @api public - */ - - Socket.prototype.packet = function (data) { - if (this.connected && !this.doBuffer) { - this.transport.packet(data); - } else { - this.buffer.push(data); - } - - return this; - }; - - /** - * Sets buffer state - * - * @api private - */ - - Socket.prototype.setBuffer = function (v) { - this.doBuffer = v; - - if (!v && this.connected && this.buffer.length) { - this.transport.payload(this.buffer); - this.buffer = []; - } - }; - - /** - * Disconnect the established connect. - * - * @returns {io.Socket} - * @api public - */ - - Socket.prototype.disconnect = function () { - if (this.connected || this.connecting) { - if (this.open) { - this.of('').packet({ type: 'disconnect' }); - } - - // handle disconnection immediately - this.onDisconnect('booted'); - } - - return this; - }; - - /** - * Disconnects the socket with a sync XHR. - * - * @api private - */ - - Socket.prototype.disconnectSync = function () { - // ensure disconnection - var xhr = io.util.request() - , uri = this.resource + '/' + io.protocol + '/' + this.sessionid; - - xhr.open('GET', uri, true); - - // handle disconnection immediately - this.onDisconnect('booted'); - }; - - /** - * Check if we need to use cross domain enabled transports. Cross domain would - * be a different port or different domain name. - * - * @returns {Boolean} - * @api private - */ - - Socket.prototype.isXDomain = function () { - - var port = global.location.port || - ('https:' == global.location.protocol ? 443 : 80); - - return this.options.host !== global.location.hostname - || this.options.port != port; - }; - - /** - * Called upon handshake. - * - * @api private - */ - - Socket.prototype.onConnect = function () { - if (!this.connected) { - this.connected = true; - this.connecting = false; - if (!this.doBuffer) { - // make sure to flush the buffer - this.setBuffer(false); - } - this.emit('connect'); - } - }; - - /** - * Called when the transport opens - * - * @api private - */ - - Socket.prototype.onOpen = function () { - this.open = true; - }; - - /** - * Called when the transport closes. - * - * @api private - */ - - Socket.prototype.onClose = function () { - this.open = false; - clearTimeout(this.heartbeatTimeoutTimer); - }; - - /** - * Called when the transport first opens a connection - * - * @param text - */ - - Socket.prototype.onPacket = function (packet) { - this.of(packet.endpoint).onPacket(packet); - }; - - /** - * Handles an error. - * - * @api private - */ - - Socket.prototype.onError = function (err) { - if (err && err.advice) { - if (err.advice === 'reconnect' && (this.connected || this.connecting)) { - this.disconnect(); - if (this.options.reconnect) { - this.reconnect(); - } - } - } - - this.publish('error', err && err.reason ? err.reason : err); - }; - - /** - * Called when the transport disconnects. - * - * @api private - */ - - Socket.prototype.onDisconnect = function (reason) { - var wasConnected = this.connected - , wasConnecting = this.connecting; - - this.connected = false; - this.connecting = false; - this.open = false; - - if (wasConnected || wasConnecting) { - this.transport.close(); - this.transport.clearTimeouts(); - if (wasConnected) { - this.publish('disconnect', reason); - - if ('booted' != reason && this.options.reconnect && !this.reconnecting) { - this.reconnect(); - } - } - } - }; - - /** - * Called upon reconnection. - * - * @api private - */ - - Socket.prototype.reconnect = function () { - this.reconnecting = true; - this.reconnectionAttempts = 0; - this.reconnectionDelay = this.options['reconnection delay']; - - var self = this - , maxAttempts = this.options['max reconnection attempts'] - , tryMultiple = this.options['try multiple transports'] - , limit = this.options['reconnection limit']; - - function reset () { - if (self.connected) { - for (var i in self.namespaces) { - if (self.namespaces.hasOwnProperty(i) && '' !== i) { - self.namespaces[i].packet({ type: 'connect' }); - } - } - self.publish('reconnect', self.transport.name, self.reconnectionAttempts); - } - - clearTimeout(self.reconnectionTimer); - - self.removeListener('connect_failed', maybeReconnect); - self.removeListener('connect', maybeReconnect); - - self.reconnecting = false; - - delete self.reconnectionAttempts; - delete self.reconnectionDelay; - delete self.reconnectionTimer; - delete self.redoTransports; - - self.options['try multiple transports'] = tryMultiple; - }; - - function maybeReconnect () { - if (!self.reconnecting) { - return; - } - - if (self.connected) { - return reset(); - }; - - if (self.connecting && self.reconnecting) { - return self.reconnectionTimer = setTimeout(maybeReconnect, 1000); - } - - if (self.reconnectionAttempts++ >= maxAttempts) { - if (!self.redoTransports) { - self.on('connect_failed', maybeReconnect); - self.options['try multiple transports'] = true; - self.transport = self.getTransport(); - self.redoTransports = true; - self.connect(); - } else { - self.publish('reconnect_failed'); - reset(); - } - } else { - if (self.reconnectionDelay < limit) { - self.reconnectionDelay *= 2; // exponential back off - } - - self.connect(); - self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts); - self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay); - } - }; - - this.options['try multiple transports'] = false; - this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay); - - this.on('connect', maybeReconnect); - }; +(function ( exports, io, global ) { + + /** + * Expose constructor. + */ + + exports.Socket = Socket; + + /** + * Create a new `Socket.IO client` which can establish a persistent + * connection with a Socket.IO enabled server. + * + * @api public + */ + + function Socket( options ) { + this.options = { + port : 80, secure : false, document : 'document' in global ? document : false, resource : 'socket.io', transports : io.transports, 'connect timeout' : 10000, 'try multiple transports' : true, 'reconnect' : true, 'reconnection delay' : 500, 'reconnection limit' : Infinity, 'reopen delay' : 3000, 'max reconnection attempts' : 10, 'sync disconnect on unload' : true, 'auto connect' : true, 'flash policy port' : 10843 + }; + + io.util.merge( this.options, options ); + + this.connected = false; + this.open = false; + this.connecting = false; + this.reconnecting = false; + this.namespaces = {}; + this.buffer = []; + this.doBuffer = false; + + if ( this.options['sync disconnect on unload'] && + (!this.isXDomain() || io.util.ua.hasCORS) ) { + var self = this; + + io.util.on( global, 'unload', function () { + self.disconnectSync(); + }, false ); + } + + if ( this.options['auto connect'] ) { + this.connect(); + } + } + + ; + + /** + * Apply EventEmitter mixin. + */ + + io.util.mixin( Socket, io.EventEmitter ); + + /** + * Returns a namespace listener/emitter for this socket + * + * @api public + */ + + Socket.prototype.of = function ( name ) { + if ( !this.namespaces[name] ) { + this.namespaces[name] = new io.SocketNamespace( this, name ); + + if ( name !== '' ) { + this.namespaces[name].packet( { type : 'connect' } ); + } + } + + return this.namespaces[name]; + }; + + /** + * Emits the given event to the Socket and all namespaces + * + * @api private + */ + + Socket.prototype.publish = function () { + this.emit.apply( this, arguments ); + + var nsp; + + for ( var i in this.namespaces ) { + if ( this.namespaces.hasOwnProperty( i ) ) { + nsp = this.of( i ); + nsp.$emit.apply( nsp, arguments ); + } + } + }; + + /** + * Performs the handshake + * + * @api private + */ + + function empty() { + } + + ; + + Socket.prototype.handshake = function ( fn ) { + var self = this + , options = this.options; + + function complete( data ) { + if ( data instanceof Error ) { + self.onError( data.message ); + } else { + fn.apply( null, data.split( ':' ) ); + } + } + + ; + + var url = [ + 'http' + (options.secure ? 's' : '') + ':/' + , options.host + ':' + options.port + , options.resource + , io.protocol + , io.util.query( this.options.query, 't=' + +new Date ) + ].join( '/' ); + + if ( this.isXDomain() && !io.util.ua.hasCORS ) { + var insertAt = document.getElementsByTagName( 'script' )[0] + , script = document.createElement( 'script' ); + + script.src = url + '&jsonp=' + io.j.length; + insertAt.parentNode.insertBefore( script, insertAt ); + + io.j.push( function ( data ) { + complete( data ); + script.parentNode.removeChild( script ); + } ); + } else { + var xhr = io.util.request(); + + xhr.open( 'GET', url, true ); + xhr.withCredentials = true; + xhr.onreadystatechange = function () { + if ( xhr.readyState == 4 ) { + xhr.onreadystatechange = empty; + + if ( xhr.status == 200 ) { + complete( xhr.responseText ); + } else { + !self.reconnecting && self.onError( xhr.responseText ); + } + } + }; + xhr.send( null ); + } + }; + + /** + * Find an available transport based on the options supplied in the constructor. + * + * @api private + */ + + Socket.prototype.getTransport = function ( override ) { + var transports = override || this.transports, match; + + for ( var i = 0, transport; transport = transports[i]; i++ ) { + if ( io.Transport[transport] + && io.Transport[transport].check( this ) + && (!this.isXDomain() || io.Transport[transport].xdomainCheck()) ) { + return new io.Transport[transport]( this, this.sessionid ); + } + } + + return null; + }; + + /** + * Connects to the server. + * + * @param {Function} [fn] Callback. + * @returns {io.Socket} + * @api public + */ + + Socket.prototype.connect = function ( fn ) { + if ( this.connecting ) { + return this; + } + + var self = this; + + this.handshake( function ( sid, heartbeat, close, transports ) { + self.sessionid = sid; + self.closeTimeout = close * 1000; + self.heartbeatTimeout = heartbeat * 1000; + self.transports = transports ? io.util.intersect( + transports.split( ',' ) + , self.options.transports + ) : self.options.transports; + + self.setHeartbeatTimeout(); + + function connect( transports ) { + if ( self.transport ) { + self.transport.clearTimeouts(); + } + + self.transport = self.getTransport( transports ); + if ( !self.transport ) { + return self.publish( 'connect_failed' ); + } + + // once the transport is ready + self.transport.ready( self, function () { + self.connecting = true; + self.publish( 'connecting', self.transport.name ); + self.transport.open(); + + if ( self.options['connect timeout'] ) { + self.connectTimeoutTimer = setTimeout( function () { + if ( !self.connected ) { + self.connecting = false; + + if ( self.options['try multiple transports'] ) { + if ( !self.remainingTransports ) { + self.remainingTransports = self.transports.slice( 0 ); + } + + var remaining = self.remainingTransports; + + while ( remaining.length > 0 && remaining.splice( 0, 1 )[0] != + self.transport.name ) { + } + + if ( remaining.length ) { + connect( remaining ); + } else { + self.publish( 'connect_failed' ); + } + } + } + }, self.options['connect timeout'] ); + } + } ); + } + + connect( self.transports ); + + self.once( 'connect', function () { + clearTimeout( self.connectTimeoutTimer ); + + fn && typeof fn == 'function' && fn(); + } ); + } ); + + return this; + }; + + /** + * Clears and sets a new heartbeat timeout using the value given by the + * server during the handshake. + * + * @api private + */ + + Socket.prototype.setHeartbeatTimeout = function () { + clearTimeout( this.heartbeatTimeoutTimer ); + + var self = this; + this.heartbeatTimeoutTimer = setTimeout( function () { + self.transport.onClose(); + }, this.heartbeatTimeout ); + }; + + /** + * Sends a message. + * + * @param {Object} data packet. + * @returns {io.Socket} + * @api public + */ + + Socket.prototype.packet = function ( data ) { + if ( this.connected && !this.doBuffer ) { + this.transport.packet( data ); + } else { + this.buffer.push( data ); + } + + return this; + }; + + /** + * Sets buffer state + * + * @api private + */ + + Socket.prototype.setBuffer = function ( v ) { + this.doBuffer = v; + + if ( !v && this.connected && this.buffer.length ) { + this.transport.payload( this.buffer ); + this.buffer = []; + } + }; + + /** + * Disconnect the established connect. + * + * @returns {io.Socket} + * @api public + */ + + Socket.prototype.disconnect = function () { + if ( this.connected || this.connecting ) { + if ( this.open ) { + this.of( '' ).packet( { type : 'disconnect' } ); + } + + // handle disconnection immediately + this.onDisconnect( 'booted' ); + } + + return this; + }; + + /** + * Disconnects the socket with a sync XHR. + * + * @api private + */ + + Socket.prototype.disconnectSync = function () { + // ensure disconnection + var xhr = io.util.request() + , uri = this.resource + '/' + io.protocol + '/' + this.sessionid; + + xhr.open( 'GET', uri, true ); + + // handle disconnection immediately + this.onDisconnect( 'booted' ); + }; + + /** + * Check if we need to use cross domain enabled transports. Cross domain would + * be a different port or different domain name. + * + * @returns {Boolean} + * @api private + */ + + Socket.prototype.isXDomain = function () { + + var port = global.location.port || + ('https:' == global.location.protocol ? 443 : 80); + + return this.options.host !== global.location.hostname + || this.options.port != port; + }; + + /** + * Called upon handshake. + * + * @api private + */ + + Socket.prototype.onConnect = function () { + if ( !this.connected ) { + this.connected = true; + this.connecting = false; + if ( !this.doBuffer ) { + // make sure to flush the buffer + this.setBuffer( false ); + } + this.emit( 'connect' ); + } + }; + + /** + * Called when the transport opens + * + * @api private + */ + + Socket.prototype.onOpen = function () { + this.open = true; + }; + + /** + * Called when the transport closes. + * + * @api private + */ + + Socket.prototype.onClose = function () { + this.open = false; + clearTimeout( this.heartbeatTimeoutTimer ); + }; + + /** + * Called when the transport first opens a connection + * + * @param text + */ + + Socket.prototype.onPacket = function ( packet ) { + this.of( packet.endpoint ).onPacket( packet ); + }; + + /** + * Handles an error. + * + * @api private + */ + + Socket.prototype.onError = function ( err ) { + if ( err && err.advice ) { + if ( err.advice === 'reconnect' && (this.connected || this.connecting) ) { + this.disconnect(); + if ( this.options.reconnect ) { + this.reconnect(); + } + } + } + + this.publish( 'error', err && err.reason ? err.reason : err ); + }; + + /** + * Called when the transport disconnects. + * + * @api private + */ + + Socket.prototype.onDisconnect = function ( reason ) { + var wasConnected = this.connected + , wasConnecting = this.connecting; + + this.connected = false; + this.connecting = false; + this.open = false; + + if ( wasConnected || wasConnecting ) { + this.transport.close(); + this.transport.clearTimeouts(); + if ( wasConnected ) { + this.publish( 'disconnect', reason ); + + if ( 'booted' != reason && this.options.reconnect && !this.reconnecting ) { + this.reconnect(); + } + } + } + }; + + /** + * Called upon reconnection. + * + * @api private + */ + + Socket.prototype.reconnect = function () { + this.reconnecting = true; + this.reconnectionAttempts = 0; + this.reconnectionDelay = this.options['reconnection delay']; + + var self = this + , maxAttempts = this.options['max reconnection attempts'] + , tryMultiple = this.options['try multiple transports'] + , limit = this.options['reconnection limit']; + + function reset() { + if ( self.connected ) { + for ( var i in self.namespaces ) { + if ( self.namespaces.hasOwnProperty( i ) && '' !== i ) { + self.namespaces[i].packet( { type : 'connect' } ); + } + } + self.publish( 'reconnect', self.transport.name, self.reconnectionAttempts ); + } + + clearTimeout( self.reconnectionTimer ); + + self.removeListener( 'connect_failed', maybeReconnect ); + self.removeListener( 'connect', maybeReconnect ); + + self.reconnecting = false; + + delete self.reconnectionAttempts; + delete self.reconnectionDelay; + delete self.reconnectionTimer; + delete self.redoTransports; + + self.options['try multiple transports'] = tryMultiple; + } + + ; + + function maybeReconnect() { + if ( !self.reconnecting ) { + return; + } + + if ( self.connected ) { + return reset(); + } + ; + + if ( self.connecting && self.reconnecting ) { + return self.reconnectionTimer = setTimeout( maybeReconnect, 1000 ); + } + + if ( self.reconnectionAttempts++ >= maxAttempts ) { + if ( !self.redoTransports ) { + self.on( 'connect_failed', maybeReconnect ); + self.options['try multiple transports'] = true; + self.transport = self.getTransport(); + self.redoTransports = true; + self.connect(); + } else { + self.publish( 'reconnect_failed' ); + reset(); + } + } else { + if ( self.reconnectionDelay < limit ) { + self.reconnectionDelay *= 2; // exponential back off + } + + self.connect(); + self.publish( 'reconnecting', self.reconnectionDelay, self.reconnectionAttempts ); + self.reconnectionTimer = setTimeout( maybeReconnect, self.reconnectionDelay ); + } + } + + ; + + this.options['try multiple transports'] = false; + this.reconnectionTimer = setTimeout( maybeReconnect, this.reconnectionDelay ); + + this.on( 'connect', maybeReconnect ); + }; })( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports - , this + 'undefined' != typeof io ? io : module.exports + , 'undefined' != typeof io ? io : module.parent.exports + , this ); /** * socket.io @@ -2017,241 +2046,244 @@ * MIT Licensed */ -(function (exports, io) { +(function ( exports, io ) { - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports.SocketNamespace = SocketNamespace; + exports.SocketNamespace = SocketNamespace; - /** - * Socket namespace constructor. - * - * @constructor - * @api public - */ + /** + * Socket namespace constructor. + * + * @constructor + * @api public + */ - function SocketNamespace (socket, name) { - this.socket = socket; - this.name = name || ''; - this.flags = {}; - this.json = new Flag(this, 'json'); - this.ackPackets = 0; - this.acks = {}; - }; + function SocketNamespace( socket, name ) { + this.socket = socket; + this.name = name || ''; + this.flags = {}; + this.json = new Flag( this, 'json' ); + this.ackPackets = 0; + this.acks = {}; + } - /** - * Apply EventEmitter mixin. - */ + ; - io.util.mixin(SocketNamespace, io.EventEmitter); + /** + * Apply EventEmitter mixin. + */ - /** - * Copies emit since we override it - * - * @api private - */ + io.util.mixin( SocketNamespace, io.EventEmitter ); - SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit; + /** + * Copies emit since we override it + * + * @api private + */ - /** - * Creates a new namespace, by proxying the request to the socket. This - * allows us to use the synax as we do on the server. - * - * @api public - */ + SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit; - SocketNamespace.prototype.of = function () { - return this.socket.of.apply(this.socket, arguments); - }; + /** + * Creates a new namespace, by proxying the request to the socket. This + * allows us to use the synax as we do on the server. + * + * @api public + */ - /** - * Sends a packet. - * - * @api private - */ + SocketNamespace.prototype.of = function () { + return this.socket.of.apply( this.socket, arguments ); + }; - SocketNamespace.prototype.packet = function (packet) { - packet.endpoint = this.name; - this.socket.packet(packet); - this.flags = {}; - return this; - }; + /** + * Sends a packet. + * + * @api private + */ - /** - * Sends a message - * - * @api public - */ + SocketNamespace.prototype.packet = function ( packet ) { + packet.endpoint = this.name; + this.socket.packet( packet ); + this.flags = {}; + return this; + }; - SocketNamespace.prototype.send = function (data, fn) { - var packet = { - type: this.flags.json ? 'json' : 'message' - , data: data - }; + /** + * Sends a message + * + * @api public + */ - if ('function' == typeof fn) { - packet.id = ++this.ackPackets; - packet.ack = true; - this.acks[packet.id] = fn; - } + SocketNamespace.prototype.send = function ( data, fn ) { + var packet = { + type : this.flags.json ? 'json' : 'message', data : data + }; - return this.packet(packet); - }; + if ( 'function' == typeof fn ) { + packet.id = ++this.ackPackets; + packet.ack = true; + this.acks[packet.id] = fn; + } - /** - * Emits an event - * - * @api public - */ - - SocketNamespace.prototype.emit = function (name) { - var args = Array.prototype.slice.call(arguments, 1) - , lastArg = args[args.length - 1] - , packet = { - type: 'event' - , name: name - }; + return this.packet( packet ); + }; - if ('function' == typeof lastArg) { - packet.id = ++this.ackPackets; - packet.ack = 'data'; - this.acks[packet.id] = lastArg; - args = args.slice(0, args.length - 1); - } + /** + * Emits an event + * + * @api public + */ - packet.args = args; + SocketNamespace.prototype.emit = function ( name ) { + var args = Array.prototype.slice.call( arguments, 1 ) + , lastArg = args[args.length - 1] + , packet = { + type : 'event', name : name + }; - return this.packet(packet); - }; + if ( 'function' == typeof lastArg ) { + packet.id = ++this.ackPackets; + packet.ack = 'data'; + this.acks[packet.id] = lastArg; + args = args.slice( 0, args.length - 1 ); + } - /** - * Disconnects the namespace - * - * @api private - */ + packet.args = args; - SocketNamespace.prototype.disconnect = function () { - if (this.name === '') { - this.socket.disconnect(); - } else { - this.packet({ type: 'disconnect' }); - this.$emit('disconnect'); - } + return this.packet( packet ); + }; - return this; - }; + /** + * Disconnects the namespace + * + * @api private + */ - /** - * Handles a packet - * - * @api private - */ + SocketNamespace.prototype.disconnect = function () { + if ( this.name === '' ) { + this.socket.disconnect(); + } else { + this.packet( { type : 'disconnect' } ); + this.$emit( 'disconnect' ); + } - SocketNamespace.prototype.onPacket = function (packet) { - var self = this; + return this; + }; - function ack () { - self.packet({ - type: 'ack' - , args: io.util.toArray(arguments) - , ackId: packet.id - }); - }; + /** + * Handles a packet + * + * @api private + */ - switch (packet.type) { - case 'connect': - this.$emit('connect'); - break; + SocketNamespace.prototype.onPacket = function ( packet ) { + var self = this; - case 'disconnect': - if (this.name === '') { - this.socket.onDisconnect(packet.reason || 'booted'); - } else { - this.$emit('disconnect', packet.reason); - } - break; + function ack() { + self.packet( { + type : 'ack', args : io.util.toArray( arguments ), ackId : packet.id + } ); + } - case 'message': - case 'json': - var params = ['message', packet.data]; + ; - if (packet.ack == 'data') { - params.push(ack); - } else if (packet.ack) { - this.packet({ type: 'ack', ackId: packet.id }); - } + switch ( packet.type ) { + case 'connect': + this.$emit( 'connect' ); + break; - this.$emit.apply(this, params); - break; + case 'disconnect': + if ( this.name === '' ) { + this.socket.onDisconnect( packet.reason || 'booted' ); + } else { + this.$emit( 'disconnect', packet.reason ); + } + break; - case 'event': - var params = [packet.name].concat(packet.args); + case 'message': + case 'json': + var params = ['message', packet.data]; - if (packet.ack == 'data') - params.push(ack); + if ( packet.ack == 'data' ) { + params.push( ack ); + } else if ( packet.ack ) { + this.packet( { type : 'ack', ackId : packet.id } ); + } - this.$emit.apply(this, params); - break; + this.$emit.apply( this, params ); + break; - case 'ack': - if (this.acks[packet.ackId]) { - this.acks[packet.ackId].apply(this, packet.args); - delete this.acks[packet.ackId]; - } - break; + case 'event': + var params = [packet.name].concat( packet.args ); - case 'error': - if (packet.advice){ - this.socket.onError(packet); - } else { - if (packet.reason == 'unauthorized') { - this.$emit('connect_failed', packet.reason); - } else { - this.$emit('error', packet.reason); - } - } - break; - } - }; + if ( packet.ack == 'data' ) { + params.push( ack ); + } - /** - * Flag interface. - * - * @api private - */ + this.$emit.apply( this, params ); + break; - function Flag (nsp, name) { - this.namespace = nsp; - this.name = name; - }; + case 'ack': + if ( this.acks[packet.ackId] ) { + this.acks[packet.ackId].apply( this, packet.args ); + delete this.acks[packet.ackId]; + } + break; - /** - * Send a message - * - * @api public - */ + case 'error': + if ( packet.advice ) { + this.socket.onError( packet ); + } else { + if ( packet.reason == 'unauthorized' ) { + this.$emit( 'connect_failed', packet.reason ); + } else { + this.$emit( 'error', packet.reason ); + } + } + break; + } + }; - Flag.prototype.send = function () { - this.namespace.flags[this.name] = true; - this.namespace.send.apply(this.namespace, arguments); - }; + /** + * Flag interface. + * + * @api private + */ - /** - * Emit an event - * - * @api public - */ + function Flag( nsp, name ) { + this.namespace = nsp; + this.name = name; + } - Flag.prototype.emit = function () { - this.namespace.flags[this.name] = true; - this.namespace.emit.apply(this.namespace, arguments); - }; + ; + + /** + * Send a message + * + * @api public + */ + + Flag.prototype.send = function () { + this.namespace.flags[this.name] = true; + this.namespace.send.apply( this.namespace, arguments ); + }; + + /** + * Emit an event + * + * @api public + */ + + Flag.prototype.emit = function () { + this.namespace.flags[this.name] = true; + this.namespace.emit.apply( this.namespace, arguments ); + }; })( - 'undefined' != typeof io ? io : module.exports - , 'undefined' != typeof io ? io : module.parent.exports + 'undefined' != typeof io ? io : module.exports + , 'undefined' != typeof io ? io : module.parent.exports ); /** @@ -2260,176 +2292,178 @@ * MIT Licensed */ -(function (exports, io, global) { +(function ( exports, io, global ) { - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports.websocket = WS; + exports.websocket = WS; - /** - * The WebSocket transport uses the HTML5 WebSocket API to establish an - * persistent connection with the Socket.IO server. This transport will also - * be inherited by the FlashSocket fallback as it provides a API compatible - * polyfill for the WebSockets. - * - * @constructor - * @extends {io.Transport} - * @api public - */ + /** + * The WebSocket transport uses the HTML5 WebSocket API to establish an + * persistent connection with the Socket.IO server. This transport will also + * be inherited by the FlashSocket fallback as it provides a API compatible + * polyfill for the WebSockets. + * + * @constructor + * @extends {io.Transport} + * @api public + */ - function WS (socket) { - io.Transport.apply(this, arguments); - }; + function WS( socket ) { + io.Transport.apply( this, arguments ); + } - /** - * Inherits from Transport. - */ + ; - io.util.inherit(WS, io.Transport); + /** + * Inherits from Transport. + */ - /** - * Transport name - * - * @api public - */ + io.util.inherit( WS, io.Transport ); - WS.prototype.name = 'websocket'; + /** + * Transport name + * + * @api public + */ - /** - * Initializes a new `WebSocket` connection with the Socket.IO server. We attach - * all the appropriate listeners to handle the responses from the server. - * - * @returns {Transport} - * @api public - */ + WS.prototype.name = 'websocket'; - WS.prototype.open = function () { - var query = io.util.query(this.socket.options.query) - , self = this - , Socket + /** + * Initializes a new `WebSocket` connection with the Socket.IO server. We attach + * all the appropriate listeners to handle the responses from the server. + * + * @returns {Transport} + * @api public + */ + + WS.prototype.open = function () { + var query = io.util.query( this.socket.options.query ) + , self = this + , Socket - if (!Socket) { - Socket = global.MozWebSocket || global.WebSocket; - } + if ( !Socket ) { + Socket = global.MozWebSocket || global.WebSocket; + } - this.websocket = new Socket(this.prepareUrl() + query); + this.websocket = new Socket( this.prepareUrl() + query ); - this.websocket.onopen = function () { - self.onOpen(); - self.socket.setBuffer(false); - }; - this.websocket.onmessage = function (ev) { - self.onData(ev.data); - }; - this.websocket.onclose = function () { - self.onClose(); - self.socket.setBuffer(true); - }; - this.websocket.onerror = function (e) { - self.onError(e); - }; + this.websocket.onopen = function () { + self.onOpen(); + self.socket.setBuffer( false ); + }; + this.websocket.onmessage = function ( ev ) { + self.onData( ev.data ); + }; + this.websocket.onclose = function () { + self.onClose(); + self.socket.setBuffer( true ); + }; + this.websocket.onerror = function ( e ) { + self.onError( e ); + }; - return this; - }; + return this; + }; - /** - * Send a message to the Socket.IO server. The message will automatically be - * encoded in the correct message format. - * - * @returns {Transport} - * @api public - */ + /** + * Send a message to the Socket.IO server. The message will automatically be + * encoded in the correct message format. + * + * @returns {Transport} + * @api public + */ - WS.prototype.send = function (data) { - this.websocket.send(data); - return this; - }; + WS.prototype.send = function ( data ) { + this.websocket.send( data ); + return this; + }; - /** - * Payload - * - * @api private - */ + /** + * Payload + * + * @api private + */ - WS.prototype.payload = function (arr) { - for (var i = 0, l = arr.length; i < l; i++) { - this.packet(arr[i]); - } - return this; - }; + WS.prototype.payload = function ( arr ) { + for ( var i = 0, l = arr.length; i < l; i++ ) { + this.packet( arr[i] ); + } + return this; + }; - /** - * Disconnect the established `WebSocket` connection. - * - * @returns {Transport} - * @api public - */ + /** + * Disconnect the established `WebSocket` connection. + * + * @returns {Transport} + * @api public + */ - WS.prototype.close = function () { - this.websocket.close(); - return this; - }; + WS.prototype.close = function () { + this.websocket.close(); + return this; + }; - /** - * Handle the errors that `WebSocket` might be giving when we - * are attempting to connect or send messages. - * - * @param {Error} e The error. - * @api private - */ + /** + * Handle the errors that `WebSocket` might be giving when we + * are attempting to connect or send messages. + * + * @param {Error} e The error. + * @api private + */ - WS.prototype.onError = function (e) { - this.socket.onError(e); - }; + WS.prototype.onError = function ( e ) { + this.socket.onError( e ); + }; - /** - * Returns the appropriate scheme for the URI generation. - * - * @api private - */ - WS.prototype.scheme = function () { - return this.socket.options.secure ? 'wss' : 'ws'; - }; + /** + * Returns the appropriate scheme for the URI generation. + * + * @api private + */ + WS.prototype.scheme = function () { + return this.socket.options.secure ? 'wss' : 'ws'; + }; - /** - * Checks if the browser has support for native `WebSockets` and that - * it's not the polyfill created for the FlashSocket transport. - * - * @return {Boolean} - * @api public - */ + /** + * Checks if the browser has support for native `WebSockets` and that + * it's not the polyfill created for the FlashSocket transport. + * + * @return {Boolean} + * @api public + */ - WS.check = function () { - return ('WebSocket' in global && !('__addTask' in WebSocket)) - || 'MozWebSocket' in global; - }; + WS.check = function () { + return ('WebSocket' in global && !('__addTask' in WebSocket)) + || 'MozWebSocket' in global; + }; - /** - * Check if the `WebSocket` transport support cross domain communications. - * - * @returns {Boolean} - * @api public - */ + /** + * Check if the `WebSocket` transport support cross domain communications. + * + * @returns {Boolean} + * @api public + */ - WS.xdomainCheck = function () { - return true; - }; + WS.xdomainCheck = function () { + return true; + }; - /** - * Add the transport to your public io.transports array. - * - * @api private - */ + /** + * Add the transport to your public io.transports array. + * + * @api private + */ - io.transports.push('websocket'); + io.transports.push( 'websocket' ); })( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports - , this + 'undefined' != typeof io ? io.Transport : module.exports + , 'undefined' != typeof io ? io : module.parent.exports + , this ); /** @@ -2438,544 +2472,1220 @@ * MIT Licensed */ -(function (exports, io) { +(function ( exports, io ) { - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports.flashsocket = Flashsocket; + exports.flashsocket = Flashsocket; - /** - * The FlashSocket transport. This is a API wrapper for the HTML5 WebSocket - * specification. It uses a .swf file to communicate with the server. If you want - * to serve the .swf file from a other server than where the Socket.IO script is - * coming from you need to use the insecure version of the .swf. More information - * about this can be found on the github page. - * - * @constructor - * @extends {io.Transport.websocket} - * @api public - */ + /** + * The FlashSocket transport. This is a API wrapper for the HTML5 WebSocket + * specification. It uses a .swf file to communicate with the server. If you want + * to serve the .swf file from a other server than where the Socket.IO script is + * coming from you need to use the insecure version of the .swf. More information + * about this can be found on the github page. + * + * @constructor + * @extends {io.Transport.websocket} + * @api public + */ - function Flashsocket () { - io.Transport.websocket.apply(this, arguments); - }; + function Flashsocket() { + io.Transport.websocket.apply( this, arguments ); + } - /** - * Inherits from Transport. - */ + ; - io.util.inherit(Flashsocket, io.Transport.websocket); + /** + * Inherits from Transport. + */ - /** - * Transport name - * - * @api public - */ + io.util.inherit( Flashsocket, io.Transport.websocket ); - Flashsocket.prototype.name = 'flashsocket'; + /** + * Transport name + * + * @api public + */ - /** - * Disconnect the established `FlashSocket` connection. This is done by adding a - * new task to the FlashSocket. The rest will be handled off by the `WebSocket` - * transport. - * - * @returns {Transport} - * @api public - */ + Flashsocket.prototype.name = 'flashsocket'; - Flashsocket.prototype.open = function () { - var self = this - , args = arguments; + /** + * Disconnect the established `FlashSocket` connection. This is done by adding a + * new task to the FlashSocket. The rest will be handled off by the `WebSocket` + * transport. + * + * @returns {Transport} + * @api public + */ - WebSocket.__addTask(function () { - io.Transport.websocket.prototype.open.apply(self, args); - }); - return this; - }; - - /** - * Sends a message to the Socket.IO server. This is done by adding a new - * task to the FlashSocket. The rest will be handled off by the `WebSocket` - * transport. - * - * @returns {Transport} - * @api public - */ + Flashsocket.prototype.open = function () { + var self = this + , args = arguments; - Flashsocket.prototype.send = function () { - var self = this, args = arguments; - WebSocket.__addTask(function () { - io.Transport.websocket.prototype.send.apply(self, args); - }); - return this; - }; + WebSocket.__addTask( function () { + io.Transport.websocket.prototype.open.apply( self, args ); + } ); + return this; + }; - /** - * Disconnects the established `FlashSocket` connection. - * - * @returns {Transport} - * @api public - */ + /** + * Sends a message to the Socket.IO server. This is done by adding a new + * task to the FlashSocket. The rest will be handled off by the `WebSocket` + * transport. + * + * @returns {Transport} + * @api public + */ - Flashsocket.prototype.close = function () { - WebSocket.__tasks.length = 0; - io.Transport.websocket.prototype.close.call(this); - return this; - }; + Flashsocket.prototype.send = function () { + var self = this, args = arguments; + WebSocket.__addTask( function () { + io.Transport.websocket.prototype.send.apply( self, args ); + } ); + return this; + }; - /** - * The WebSocket fall back needs to append the flash container to the body - * element, so we need to make sure we have access to it. Or defer the call - * until we are sure there is a body element. - * - * @param {Socket} socket The socket instance that needs a transport - * @param {Function} fn The callback - * @api private - */ + /** + * Disconnects the established `FlashSocket` connection. + * + * @returns {Transport} + * @api public + */ - Flashsocket.prototype.ready = function (socket, fn) { - function init () { - var options = socket.options - , port = options['flash policy port'] - , path = [ - 'http' + (options.secure ? 's' : '') + ':/' - , options.host + ':' + options.port - , options.resource - , 'static/flashsocket' - , 'WebSocketMain' + (socket.isXDomain() ? 'Insecure' : '') + '.swf' - ]; + Flashsocket.prototype.close = function () { + WebSocket.__tasks.length = 0; + io.Transport.websocket.prototype.close.call( this ); + return this; + }; - // Only start downloading the swf file when the checked that this browser - // actually supports it - if (!Flashsocket.loaded) { - if (typeof WEB_SOCKET_SWF_LOCATION === 'undefined') { - // Set the correct file based on the XDomain settings - WEB_SOCKET_SWF_LOCATION = path.join('/'); - } + /** + * The WebSocket fall back needs to append the flash container to the body + * element, so we need to make sure we have access to it. Or defer the call + * until we are sure there is a body element. + * + * @param {Socket} socket The socket instance that needs a transport + * @param {Function} fn The callback + * @api private + */ - if (port !== 843) { - WebSocket.loadFlashPolicyFile('xmlsocket://' + options.host + ':' + port); - } + Flashsocket.prototype.ready = function ( socket, fn ) { + function init() { + var options = socket.options + , port = options['flash policy port'] + , path = [ + 'http' + (options.secure ? 's' : '') + ':/' + , options.host + ':' + options.port + , options.resource + , 'static/flashsocket' + , 'WebSocketMain' + (socket.isXDomain() ? 'Insecure' : '') + '.swf' + ]; - WebSocket.__initialize(); - Flashsocket.loaded = true; - } + // Only start downloading the swf file when the checked that this browser + // actually supports it + if ( !Flashsocket.loaded ) { + if ( typeof WEB_SOCKET_SWF_LOCATION === 'undefined' ) { + // Set the correct file based on the XDomain settings + WEB_SOCKET_SWF_LOCATION = path.join( '/' ); + } - fn.call(self); - } + if ( port !== 843 ) { + WebSocket.loadFlashPolicyFile( 'xmlsocket://' + options.host + ':' + port ); + } - var self = this; - if (document.body) return init(); + WebSocket.__initialize(); + Flashsocket.loaded = true; + } - io.util.load(init); - }; + fn.call( self ); + } - /** - * Check if the FlashSocket transport is supported as it requires that the Adobe - * Flash Player plug-in version `10.0.0` or greater is installed. And also check if - * the polyfill is correctly loaded. - * - * @returns {Boolean} - * @api public - */ + var self = this; + if ( document.body ) { + return init(); + } - Flashsocket.check = function () { - if ( - typeof WebSocket == 'undefined' - || !('__initialize' in WebSocket) || !swfobject - ) return false; + io.util.load( init ); + }; - return swfobject.getFlashPlayerVersion().major >= 10; - }; + /** + * Check if the FlashSocket transport is supported as it requires that the Adobe + * Flash Player plug-in version `10.0.0` or greater is installed. And also check if + * the polyfill is correctly loaded. + * + * @returns {Boolean} + * @api public + */ - /** - * Check if the FlashSocket transport can be used as cross domain / cross origin - * transport. Because we can't see which type (secure or insecure) of .swf is used - * we will just return true. - * - * @returns {Boolean} - * @api public - */ + Flashsocket.check = function () { + if ( + typeof WebSocket == 'undefined' + || !('__initialize' in WebSocket) || !swfobject + ) { + return false; + } - Flashsocket.xdomainCheck = function () { - return true; - }; + return swfobject.getFlashPlayerVersion().major >= 10; + }; - /** - * Disable AUTO_INITIALIZATION - */ + /** + * Check if the FlashSocket transport can be used as cross domain / cross origin + * transport. Because we can't see which type (secure or insecure) of .swf is used + * we will just return true. + * + * @returns {Boolean} + * @api public + */ - if (typeof window != 'undefined') { - WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true; - } + Flashsocket.xdomainCheck = function () { + return true; + }; - /** - * Add the transport to your public io.transports array. - * - * @api private - */ + /** + * Disable AUTO_INITIALIZATION + */ - io.transports.push('flashsocket'); + if ( typeof window != 'undefined' ) { + WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = true; + } + + /** + * Add the transport to your public io.transports array. + * + * @api private + */ + + io.transports.push( 'flashsocket' ); })( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports + 'undefined' != typeof io ? io.Transport : module.exports + , 'undefined' != typeof io ? io : module.parent.exports ); /* SWFObject v2.2 - is released under the MIT License -*/ -if ('undefined' != typeof window) { -var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O[(['Active'].concat('Object').join('X'))]!=D){try{var ad=new window[(['Active'].concat('Object').join('X'))](W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y0){for(var af=0;af0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad'}}aa.outerHTML='"+af+"";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab + */ +if ( 'undefined' != typeof window ) { + var swfobject = function () { + var D = "undefined", r = "object", S = "Shockwave Flash", W = "ShockwaveFlash.ShockwaveFlash", q = "application/x-shockwave-flash", R = "SWFObjectExprInst", x = "onreadystatechange", O = window, j = document, t = navigator, T = false, U = [h], o = [], N = [], I = [], l, Q, E, B, J = false, a = false, n, G, m = true, M = function () { + var aa = typeof j.getElementById != D && typeof j.getElementsByTagName != D && typeof j.createElement != D, ah = t.userAgent.toLowerCase(), Y = t.platform.toLowerCase(), ae = Y ? /win/.test( Y ) : /win/.test( ah ), ac = Y ? /mac/.test( Y ) : /mac/.test( ah ), af = /webkit/.test( ah ) ? parseFloat( ah.replace( /^.*webkit\/(\d+(\.\d+)?).*$/, "$1" ) ) : false, X = !+"\v1", ag = [0, 0, 0], ab = null; + if ( typeof t.plugins != D && typeof t.plugins[S] == r ) { + ab = t.plugins[S].description; + if ( ab && !(typeof t.mimeTypes != D && t.mimeTypes[q] && !t.mimeTypes[q].enabledPlugin) ) { + T = true; + X = false; + ab = ab.replace( /^.*\s+(\S+\s+\S+$)/, "$1" ); + ag[0] = parseInt( ab.replace( /^(.*)\..*$/, "$1" ), 10 ); + ag[1] = parseInt( ab.replace( /^.*\.(.*)\s.*$/, "$1" ), 10 ); + ag[2] = /[a-zA-Z]/.test( ab ) ? parseInt( ab.replace( /^.*[a-zA-Z]+(.*)$/, "$1" ), 10 ) : 0 + } + } else { + if ( typeof O[(['Active'].concat( 'Object' ).join( 'X' ))] != D ) { + try { + var ad = new window[(['Active'].concat( 'Object' ).join( 'X' ))]( W ); + if ( ad ) { + ab = ad.GetVariable( "$version" ); + if ( ab ) { + X = true; + ab = ab.split( " " )[1].split( "," ); + ag = [parseInt( ab[0], 10 ), parseInt( ab[1], 10 ), parseInt( ab[2], 10 )] + } + } + } catch ( Z ) { + } + } + } + return{w3 : aa, pv : ag, wk : af, ie : X, win : ae, mac : ac} + }(), k = function () { + if ( !M.w3 ) { + return + } + if ( (typeof j.readyState != D && j.readyState == "complete") || (typeof j.readyState == D && (j.getElementsByTagName( "body" )[0] || j.body)) ) { + f() + } + if ( !J ) { + if ( typeof j.addEventListener != D ) { + j.addEventListener( "DOMContentLoaded", f, false ) + } + if ( M.ie && M.win ) { + j.attachEvent( x, function () { + if ( j.readyState == "complete" ) { + j.detachEvent( x, arguments.callee ); + f() + } + } ); + if ( O == top ) { + (function () { + if ( J ) { + return + } + try { + j.documentElement.doScroll( "left" ) + } catch ( X ) { + setTimeout( arguments.callee, 0 ); + return + } + f() + })() + } + } + if ( M.wk ) { + (function () { + if ( J ) { + return + } + if ( !/loaded|complete/.test( j.readyState ) ) { + setTimeout( arguments.callee, 0 ); + return + } + f() + })() + } + s( f ) + } + }(); + + function f() { + if ( J ) { + return + } + try { + var Z = j.getElementsByTagName( "body" )[0].appendChild( C( "span" ) ); + Z.parentNode.removeChild( Z ) + } catch ( aa ) { + return + } + J = true; + var X = U.length; + for ( var Y = 0; Y < X; Y++ ) { + U[Y]() + } + } + + function K( X ) { + if ( J ) { + X() + } else { + U[U.length] = X + } + } + + function s( Y ) { + if ( typeof O.addEventListener != D ) { + O.addEventListener( "load", Y, false ) + } else { + if ( typeof j.addEventListener != D ) { + j.addEventListener( "load", Y, false ) + } else { + if ( typeof O.attachEvent != D ) { + i( O, "onload", Y ) + } else { + if ( typeof O.onload == "function" ) { + var X = O.onload; + O.onload = function () { + X(); + Y() + } + } else { + O.onload = Y + } + } + } + } + } + + function h() { + if ( T ) { + V() + } else { + H() + } + } + + function V() { + var X = j.getElementsByTagName( "body" )[0]; + var aa = C( r ); + aa.setAttribute( "type", q ); + var Z = X.appendChild( aa ); + if ( Z ) { + var Y = 0; + (function () { + if ( typeof Z.GetVariable != D ) { + var ab = Z.GetVariable( "$version" ); + if ( ab ) { + ab = ab.split( " " )[1].split( "," ); + M.pv = [parseInt( ab[0], 10 ), parseInt( ab[1], 10 ), parseInt( ab[2], 10 )] + } + } else { + if ( Y < 10 ) { + Y++; + setTimeout( arguments.callee, 10 ); + return + } + } + X.removeChild( aa ); + Z = null; + H() + })() + } else { + H() + } + } + + function H() { + var ag = o.length; + if ( ag > 0 ) { + for ( var af = 0; af < ag; af++ ) { + var Y = o[af].id; + var ab = o[af].callbackFn; + var aa = {success : false, id : Y}; + if ( M.pv[0] > 0 ) { + var ae = c( Y ); + if ( ae ) { + if ( F( o[af].swfVersion ) && !(M.wk && M.wk < 312) ) { + w( Y, true ); + if ( ab ) { + aa.success = true; + aa.ref = z( Y ); + ab( aa ) + } + } else { + if ( o[af].expressInstall && A() ) { + var ai = {}; + ai.data = o[af].expressInstall; + ai.width = ae.getAttribute( "width" ) || "0"; + ai.height = ae.getAttribute( "height" ) || "0"; + if ( ae.getAttribute( "class" ) ) { + ai.styleclass = ae.getAttribute( "class" ) + } + if ( ae.getAttribute( "align" ) ) { + ai.align = ae.getAttribute( "align" ) + } + var ah = {}; + var X = ae.getElementsByTagName( "param" ); + var ac = X.length; + for ( var ad = 0; ad < ac; ad++ ) { + if ( X[ad].getAttribute( "name" ).toLowerCase() != "movie" ) { + ah[X[ad].getAttribute( "name" )] = X[ad].getAttribute( "value" ) + } + } + P( ai, ah, Y, ab ) + } else { + p( ae ); + if ( ab ) { + ab( aa ) + } + } + } + } + } else { + w( Y, true ); + if ( ab ) { + var Z = z( Y ); + if ( Z && typeof Z.SetVariable != D ) { + aa.success = true; + aa.ref = Z + } + ab( aa ) + } + } + } + } + } + + function z( aa ) { + var X = null; + var Y = c( aa ); + if ( Y && Y.nodeName == "OBJECT" ) { + if ( typeof Y.SetVariable != D ) { + X = Y + } else { + var Z = Y.getElementsByTagName( r )[0]; + if ( Z ) { + X = Z + } + } + } + return X + } + + function A() { + return !a && F( "6.0.65" ) && (M.win || M.mac) && !(M.wk && M.wk < 312) + } + + function P( aa, ab, X, Z ) { + a = true; + E = Z || null; + B = {success : false, id : X}; + var ae = c( X ); + if ( ae ) { + if ( ae.nodeName == "OBJECT" ) { + l = g( ae ); + Q = null + } else { + l = ae; + Q = X + } + aa.id = R; + if ( typeof aa.width == D || (!/%$/.test( aa.width ) && parseInt( aa.width, 10 ) < 310) ) { + aa.width = "310" + } + if ( typeof aa.height == D || (!/%$/.test( aa.height ) && parseInt( aa.height, 10 ) < 137) ) { + aa.height = "137" + } + j.title = j.title.slice( 0, 47 ) + " - Flash Player Installation"; + var ad = M.ie && M.win ? (['Active'].concat( '' ).join( 'X' )) : "PlugIn", ac = "MMredirectURL=" + O.location.toString().replace( /&/g, "%26" ) + "&MMplayerType=" + ad + "&MMdoctitle=" + j.title; + if ( typeof ab.flashvars != D ) { + ab.flashvars += "&" + ac + } else { + ab.flashvars = ac + } + if ( M.ie && M.win && ae.readyState != 4 ) { + var Y = C( "div" ); + X += "SWFObjectNew"; + Y.setAttribute( "id", X ); + ae.parentNode.insertBefore( Y, ae ); + ae.style.display = "none"; + (function () { + if ( ae.readyState == 4 ) { + ae.parentNode.removeChild( ae ) + } else { + setTimeout( arguments.callee, 10 ) + } + })() + } + u( aa, ab, X ) + } + } + + function p( Y ) { + if ( M.ie && M.win && Y.readyState != 4 ) { + var X = C( "div" ); + Y.parentNode.insertBefore( X, Y ); + X.parentNode.replaceChild( g( Y ), X ); + Y.style.display = "none"; + (function () { + if ( Y.readyState == 4 ) { + Y.parentNode.removeChild( Y ) + } else { + setTimeout( arguments.callee, 10 ) + } + })() + } else { + Y.parentNode.replaceChild( g( Y ), Y ) + } + } + + function g( ab ) { + var aa = C( "div" ); + if ( M.win && M.ie ) { + aa.innerHTML = ab.innerHTML + } else { + var Y = ab.getElementsByTagName( r )[0]; + if ( Y ) { + var ad = Y.childNodes; + if ( ad ) { + var X = ad.length; + for ( var Z = 0; Z < X; Z++ ) { + if ( !(ad[Z].nodeType == 1 && ad[Z].nodeName == "PARAM") && !(ad[Z].nodeType == 8) ) { + aa.appendChild( ad[Z].cloneNode( true ) ) + } + } + } + } + } + return aa + } + + function u( ai, ag, Y ) { + var X, aa = c( Y ); + if ( M.wk && M.wk < 312 ) { + return X + } + if ( aa ) { + if ( typeof ai.id == D ) { + ai.id = Y + } + if ( M.ie && M.win ) { + var ah = ""; + for ( var ae in ai ) { + if ( ai[ae] != Object.prototype[ae] ) { + if ( ae.toLowerCase() == "data" ) { + ag.movie = ai[ae] + } else { + if ( ae.toLowerCase() == "styleclass" ) { + ah += ' class="' + ai[ae] + '"' + } else { + if ( ae.toLowerCase() != "classid" ) { + ah += " " + ae + '="' + ai[ae] + '"' + } + } + } + } + } + var af = ""; + for ( var ad in ag ) { + if ( ag[ad] != Object.prototype[ad] ) { + af += '' + } + } + aa.outerHTML = '" + af + ""; + N[N.length] = ai.id; + X = c( ai.id ) + } else { + var Z = C( r ); + Z.setAttribute( "type", q ); + for ( var ac in ai ) { + if ( ai[ac] != Object.prototype[ac] ) { + if ( ac.toLowerCase() == "styleclass" ) { + Z.setAttribute( "class", ai[ac] ) + } else { + if ( ac.toLowerCase() != "classid" ) { + Z.setAttribute( ac, ai[ac] ) + } + } + } + } + for ( var ab in ag ) { + if ( ag[ab] != Object.prototype[ab] && ab.toLowerCase() != "movie" ) { + e( Z, ab, ag[ab] ) + } + } + aa.parentNode.replaceChild( Z, aa ); + X = Z + } + } + return X + } + + function e( Z, X, Y ) { + var aa = C( "param" ); + aa.setAttribute( "name", X ); + aa.setAttribute( "value", Y ); + Z.appendChild( aa ) + } + + function y( Y ) { + var X = c( Y ); + if ( X && X.nodeName == "OBJECT" ) { + if ( M.ie && M.win ) { + X.style.display = "none"; + (function () { + if ( X.readyState == 4 ) { + b( Y ) + } else { + setTimeout( arguments.callee, 10 ) + } + })() + } else { + X.parentNode.removeChild( X ) + } + } + } + + function b( Z ) { + var Y = c( Z ); + if ( Y ) { + for ( var X in Y ) { + if ( typeof Y[X] == "function" ) { + Y[X] = null + } + } + Y.parentNode.removeChild( Y ) + } + } + + function c( Z ) { + var X = null; + try { + X = j.getElementById( Z ) + } catch ( Y ) { + } + return X + } + + function C( X ) { + return j.createElement( X ) + } + + function i( Z, X, Y ) { + Z.attachEvent( X, Y ); + I[I.length] = [Z, X, Y] + } + + function F( Z ) { + var Y = M.pv, X = Z.split( "." ); + X[0] = parseInt( X[0], 10 ); + X[1] = parseInt( X[1], 10 ) || 0; + X[2] = parseInt( X[2], 10 ) || 0; + return(Y[0] > X[0] || (Y[0] == X[0] && Y[1] > X[1]) || (Y[0] == X[0] && Y[1] == X[1] && Y[2] >= X[2])) ? true : false + } + + function v( ac, Y, ad, ab ) { + if ( M.ie && M.mac ) { + return + } + var aa = j.getElementsByTagName( "head" )[0]; + if ( !aa ) { + return + } + var X = (ad && typeof ad == "string") ? ad : "screen"; + if ( ab ) { + n = null; + G = null + } + if ( !n || G != X ) { + var Z = C( "style" ); + Z.setAttribute( "type", "text/css" ); + Z.setAttribute( "media", X ); + n = aa.appendChild( Z ); + if ( M.ie && M.win && typeof j.styleSheets != D && j.styleSheets.length > 0 ) { + n = j.styleSheets[j.styleSheets.length - 1] + } + G = X + } + if ( M.ie && M.win ) { + if ( n && typeof n.addRule == r ) { + n.addRule( ac, Y ) + } + } else { + if ( n && typeof j.createTextNode != D ) { + n.appendChild( j.createTextNode( ac + " {" + Y + "}" ) ) + } + } + } + + function w( Z, X ) { + if ( !m ) { + return + } + var Y = X ? "visible" : "hidden"; + if ( J && c( Z ) ) { + c( Z ).style.visibility = Y + } else { + v( "#" + Z, "visibility:" + Y ) + } + } + + function L( Y ) { + var Z = /[\\\"<>\.;]/; + var X = Z.exec( Y ) != null; + return X && typeof encodeURIComponent != D ? encodeURIComponent( Y ) : Y + } + + var d = function () { + if ( M.ie && M.win ) { + window.attachEvent( "onunload", function () { + var ac = I.length; + for ( var ab = 0; ab < ac; ab++ ) { + I[ab][0].detachEvent( I[ab][1], I[ab][2] ) + } + var Z = N.length; + for ( var aa = 0; aa < Z; aa++ ) { + y( N[aa] ) + } + for ( var Y in M ) { + M[Y] = null + } + M = null; + for ( var X in swfobject ) { + swfobject[X] = null + } + swfobject = null + } ) + } + }(); + return{registerObject : function ( ab, X, aa, Z ) { + if ( M.w3 && ab && X ) { + var Y = {}; + Y.id = ab; + Y.swfVersion = X; + Y.expressInstall = aa; + Y.callbackFn = Z; + o[o.length] = Y; + w( ab, false ) + } else { + if ( Z ) { + Z( {success : false, id : ab} ) + } + } + }, getObjectById : function ( X ) { + if ( M.w3 ) { + return z( X ) + } + }, embedSWF : function ( ab, ah, ae, ag, Y, aa, Z, ad, af, ac ) { + var X = {success : false, id : ah}; + if ( M.w3 && !(M.wk && M.wk < 312) && ab && ah && ae && ag && Y ) { + w( ah, false ); + K( function () { + ae += ""; + ag += ""; + var aj = {}; + if ( af && typeof af === r ) { + for ( var al in af ) { + aj[al] = af[al] + } + } + aj.data = ab; + aj.width = ae; + aj.height = ag; + var am = {}; + if ( ad && typeof ad === r ) { + for ( var ak in ad ) { + am[ak] = ad[ak] + } + } + if ( Z && typeof Z === r ) { + for ( var ai in Z ) { + if ( typeof am.flashvars != D ) { + am.flashvars += "&" + ai + "=" + Z[ai] + } else { + am.flashvars = ai + "=" + Z[ai] + } + } + } + if ( F( Y ) ) { + var an = u( aj, am, ah ); + if ( aj.id == ah ) { + w( ah, true ) + } + X.success = true; + X.ref = an + } else { + if ( aa && A() ) { + aj.data = aa; + P( aj, am, ah, ac ); + return + } else { + w( ah, true ) + } + } + if ( ac ) { + ac( X ) + } + } ) + } else { + if ( ac ) { + ac( X ) + } + } + }, switchOffAutoHideShow : function () { + m = false + }, ua : M, getFlashPlayerVersion : function () { + return{major : M.pv[0], minor : M.pv[1], release : M.pv[2]} + }, hasFlashPlayerVersion : F, createSWF : function ( Z, Y, X ) { + if ( M.w3 ) { + return u( Z, Y, X ) + } else { + return undefined + } + }, showExpressInstall : function ( Z, aa, X, Y ) { + if ( M.w3 && A() ) { + P( Z, aa, X, Y ) + } + }, removeSWF : function ( X ) { + if ( M.w3 ) { + y( X ) + } + }, createCSS : function ( aa, Z, Y, X ) { + if ( M.w3 ) { + v( aa, Z, Y, X ) + } + }, addDomLoadEvent : K, addLoadEvent : s, getQueryParamValue : function ( aa ) { + var Z = j.location.search || j.location.hash; + if ( Z ) { + if ( /\?/.test( Z ) ) { + Z = Z.split( "?" )[1] + } + if ( aa == null ) { + return L( Z ) + } + var Y = Z.split( "&" ); + for ( var X = 0; X < Y.length; X++ ) { + if ( Y[X].substring( 0, Y[X].indexOf( "=" ) ) == aa ) { + return L( Y[X].substring( (Y[X].indexOf( "=" ) + 1) ) ) + } + } + } + return"" + }, expressInstallCallback : function () { + if ( a ) { + var X = c( R ); + if ( X && l ) { + X.parentNode.replaceChild( l, X ); + if ( Q ) { + w( Q, true ); + if ( M.ie && M.win ) { + l.style.display = "block" + } + } + if ( E ) { + E( B ) + } + } + a = false + } + }} + }(); } // Copyright: Hiroshi Ichikawa // License: New BSD License // Reference: http://dev.w3.org/html5/websockets/ // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol -(function() { - - if ('undefined' == typeof window || window.WebSocket) return; +(function () { - var console = window.console; - if (!console || !console.log || !console.error) { - console = {log: function(){ }, error: function(){ }}; - } - - if (!swfobject.hasFlashPlayerVersion("10.0.0")) { - console.error("Flash Player >= 10.0.0 is required."); - return; - } - if (location.protocol == "file:") { - console.error( - "WARNING: web-socket-js doesn't work in file:///... URL " + - "unless you set Flash Security Settings properly. " + - "Open the page via Web server i.e. http://..."); - } + if ( 'undefined' == typeof window || window.WebSocket ) { + return; + } - /** - * This class represents a faux web socket. - * @param {string} url - * @param {array or string} protocols - * @param {string} proxyHost - * @param {int} proxyPort - * @param {string} headers - */ - WebSocket = function(url, protocols, proxyHost, proxyPort, headers) { - var self = this; - self.__id = WebSocket.__nextId++; - WebSocket.__instances[self.__id] = self; - self.readyState = WebSocket.CONNECTING; - self.bufferedAmount = 0; - self.__events = {}; - if (!protocols) { - protocols = []; - } else if (typeof protocols == "string") { - protocols = [protocols]; - } - // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc. - // Otherwise, when onopen fires immediately, onopen is called before it is set. - setTimeout(function() { - WebSocket.__addTask(function() { - WebSocket.__flash.create( - self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null); - }); - }, 0); - }; + var console = window.console; + if ( !console || !console.log || !console.error ) { + console = {log : function () { + }, error : function () { + }}; + } - /** - * Send data to the web socket. - * @param {string} data The data to send to the socket. - * @return {boolean} True for success, false for failure. - */ - WebSocket.prototype.send = function(data) { - if (this.readyState == WebSocket.CONNECTING) { - throw "INVALID_STATE_ERR: Web Socket connection has not been established"; - } - // We use encodeURIComponent() here, because FABridge doesn't work if - // the argument includes some characters. We don't use escape() here - // because of this: - // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions - // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't - // preserve all Unicode characters either e.g. "\uffff" in Firefox. - // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require - // additional testing. - var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data)); - if (result < 0) { // success - return true; - } else { - this.bufferedAmount += result; - return false; - } - }; + if ( !swfobject.hasFlashPlayerVersion( "10.0.0" ) ) { + console.error( "Flash Player >= 10.0.0 is required." ); + return; + } + if ( location.protocol == "file:" ) { + console.error( + "WARNING: web-socket-js doesn't work in file:///... URL " + + "unless you set Flash Security Settings properly. " + + "Open the page via Web server i.e. http://..." ); + } - /** - * Close this web socket gracefully. - */ - WebSocket.prototype.close = function() { - if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) { - return; - } - this.readyState = WebSocket.CLOSING; - WebSocket.__flash.close(this.__id); - }; + /** + * This class represents a faux web socket. + * @param {string} url + * @param {array or string} protocols + * @param {string} proxyHost + * @param {int} proxyPort + * @param {string} headers + */ + WebSocket = function ( url, protocols, proxyHost, proxyPort, headers ) { + var self = this; + self.__id = WebSocket.__nextId++; + WebSocket.__instances[self.__id] = self; + self.readyState = WebSocket.CONNECTING; + self.bufferedAmount = 0; + self.__events = {}; + if ( !protocols ) { + protocols = []; + } else if ( typeof protocols == "string" ) { + protocols = [protocols]; + } + // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc. + // Otherwise, when onopen fires immediately, onopen is called before it is set. + setTimeout( function () { + WebSocket.__addTask( function () { + WebSocket.__flash.create( + self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null ); + } ); + }, 0 ); + }; - /** - * Implementation of {@link DOM 2 EventTarget Interface} - * - * @param {string} type - * @param {function} listener - * @param {boolean} useCapture - * @return void - */ - WebSocket.prototype.addEventListener = function(type, listener, useCapture) { - if (!(type in this.__events)) { - this.__events[type] = []; - } - this.__events[type].push(listener); - }; + /** + * Send data to the web socket. + * @param {string} data The data to send to the socket. + * @return {boolean} True for success, false for failure. + */ + WebSocket.prototype.send = function ( data ) { + if ( this.readyState == WebSocket.CONNECTING ) { + throw "INVALID_STATE_ERR: Web Socket connection has not been established"; + } + // We use encodeURIComponent() here, because FABridge doesn't work if + // the argument includes some characters. We don't use escape() here + // because of this: + // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions + // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't + // preserve all Unicode characters either e.g. "\uffff" in Firefox. + // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require + // additional testing. + var result = WebSocket.__flash.send( this.__id, encodeURIComponent( data ) ); + if ( result < 0 ) { // success + return true; + } else { + this.bufferedAmount += result; + return false; + } + }; - /** - * Implementation of {@link DOM 2 EventTarget Interface} - * - * @param {string} type - * @param {function} listener - * @param {boolean} useCapture - * @return void - */ - WebSocket.prototype.removeEventListener = function(type, listener, useCapture) { - if (!(type in this.__events)) return; - var events = this.__events[type]; - for (var i = events.length - 1; i >= 0; --i) { - if (events[i] === listener) { - events.splice(i, 1); - break; - } - } - }; + /** + * Close this web socket gracefully. + */ + WebSocket.prototype.close = function () { + if ( this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING ) { + return; + } + this.readyState = WebSocket.CLOSING; + WebSocket.__flash.close( this.__id ); + }; - /** - * Implementation of {@link DOM 2 EventTarget Interface} - * - * @param {Event} event - * @return void - */ - WebSocket.prototype.dispatchEvent = function(event) { - var events = this.__events[event.type] || []; - for (var i = 0; i < events.length; ++i) { - events[i](event); - } - var handler = this["on" + event.type]; - if (handler) handler(event); - }; + /** + * Implementation of {@link DOM 2 EventTarget Interface} + * + * @param {string} type + * @param {function} listener + * @param {boolean} useCapture + * @return void + */ + WebSocket.prototype.addEventListener = function ( type, listener, useCapture ) { + if ( !(type in this.__events) ) { + this.__events[type] = []; + } + this.__events[type].push( listener ); + }; - /** - * Handles an event from Flash. - * @param {Object} flashEvent - */ - WebSocket.prototype.__handleEvent = function(flashEvent) { - if ("readyState" in flashEvent) { - this.readyState = flashEvent.readyState; - } - if ("protocol" in flashEvent) { - this.protocol = flashEvent.protocol; - } - - var jsEvent; - if (flashEvent.type == "open" || flashEvent.type == "error") { - jsEvent = this.__createSimpleEvent(flashEvent.type); - } else if (flashEvent.type == "close") { - // TODO implement jsEvent.wasClean - jsEvent = this.__createSimpleEvent("close"); - } else if (flashEvent.type == "message") { - var data = decodeURIComponent(flashEvent.message); - jsEvent = this.__createMessageEvent("message", data); - } else { - throw "unknown event type: " + flashEvent.type; - } - - this.dispatchEvent(jsEvent); - }; - - WebSocket.prototype.__createSimpleEvent = function(type) { - if (document.createEvent && window.Event) { - var event = document.createEvent("Event"); - event.initEvent(type, false, false); - return event; - } else { - return {type: type, bubbles: false, cancelable: false}; - } - }; - - WebSocket.prototype.__createMessageEvent = function(type, data) { - if (document.createEvent && window.MessageEvent && !window.opera) { - var event = document.createEvent("MessageEvent"); - event.initMessageEvent("message", false, false, data, null, null, window, null); - return event; - } else { - // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes. - return {type: type, data: data, bubbles: false, cancelable: false}; - } - }; - - /** - * Define the WebSocket readyState enumeration. - */ - WebSocket.CONNECTING = 0; - WebSocket.OPEN = 1; - WebSocket.CLOSING = 2; - WebSocket.CLOSED = 3; + /** + * Implementation of {@link DOM 2 EventTarget Interface} + * + * @param {string} type + * @param {function} listener + * @param {boolean} useCapture + * @return void + */ + WebSocket.prototype.removeEventListener = function ( type, listener, useCapture ) { + if ( !(type in this.__events) ) { + return; + } + var events = this.__events[type]; + for ( var i = events.length - 1; i >= 0; --i ) { + if ( events[i] === listener ) { + events.splice( i, 1 ); + break; + } + } + }; - WebSocket.__flash = null; - WebSocket.__instances = {}; - WebSocket.__tasks = []; - WebSocket.__nextId = 0; - - /** - * Load a new flash security policy file. - * @param {string} url - */ - WebSocket.loadFlashPolicyFile = function(url){ - WebSocket.__addTask(function() { - WebSocket.__flash.loadManualPolicyFile(url); - }); - }; + /** + * Implementation of {@link DOM 2 EventTarget Interface} + * + * @param {Event} event + * @return void + */ + WebSocket.prototype.dispatchEvent = function ( event ) { + var events = this.__events[event.type] || []; + for ( var i = 0; i < events.length; ++i ) { + events[i]( event ); + } + var handler = this["on" + event.type]; + if ( handler ) { + handler( event ); + } + }; + + /** + * Handles an event from Flash. + * @param {Object} flashEvent + */ + WebSocket.prototype.__handleEvent = function ( flashEvent ) { + if ( "readyState" in flashEvent ) { + this.readyState = flashEvent.readyState; + } + if ( "protocol" in flashEvent ) { + this.protocol = flashEvent.protocol; + } + + var jsEvent; + if ( flashEvent.type == "open" || flashEvent.type == "error" ) { + jsEvent = this.__createSimpleEvent( flashEvent.type ); + } else if ( flashEvent.type == "close" ) { + // TODO implement jsEvent.wasClean + jsEvent = this.__createSimpleEvent( "close" ); + } else if ( flashEvent.type == "message" ) { + var data = decodeURIComponent( flashEvent.message ); + jsEvent = this.__createMessageEvent( "message", data ); + } else { + throw "unknown event type: " + flashEvent.type; + } + + this.dispatchEvent( jsEvent ); + }; + + WebSocket.prototype.__createSimpleEvent = function ( type ) { + if ( document.createEvent && window.Event ) { + var event = document.createEvent( "Event" ); + event.initEvent( type, false, false ); + return event; + } else { + return {type : type, bubbles : false, cancelable : false}; + } + }; + + WebSocket.prototype.__createMessageEvent = function ( type, data ) { + if ( document.createEvent && window.MessageEvent && !window.opera ) { + var event = document.createEvent( "MessageEvent" ); + event.initMessageEvent( "message", false, false, data, null, null, window, null ); + return event; + } else { + // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes. + return {type : type, data : data, bubbles : false, cancelable : false}; + } + }; + + /** + * Define the WebSocket readyState enumeration. + */ + WebSocket.CONNECTING = 0; + WebSocket.OPEN = 1; + WebSocket.CLOSING = 2; + WebSocket.CLOSED = 3; + + WebSocket.__flash = null; + WebSocket.__instances = {}; + WebSocket.__tasks = []; + WebSocket.__nextId = 0; + + /** + * Load a new flash security policy file. + * @param {string} url + */ + WebSocket.loadFlashPolicyFile = function ( url ) { + WebSocket.__addTask( function () { + WebSocket.__flash.loadManualPolicyFile( url ); + } ); + }; + + /** + * Loads WebSocketMain.swf and creates WebSocketMain object in Flash. + */ + WebSocket.__initialize = function () { + if ( WebSocket.__flash ) { + return; + } + + if ( WebSocket.__swfLocation ) { + // For backword compatibility. + window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation; + } + if ( !window.WEB_SOCKET_SWF_LOCATION ) { + console.error( "[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf" ); + return; + } + var container = document.createElement( "div" ); + container.id = "webSocketContainer"; + // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents + // Flash from loading at least in IE. So we move it out of the screen at (-100, -100). + // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash + // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is + // the best we can do as far as we know now. + container.style.position = "absolute"; + if ( WebSocket.__isFlashLite() ) { + container.style.left = "0px"; + container.style.top = "0px"; + } else { + container.style.left = "-100px"; + container.style.top = "-100px"; + } + var holder = document.createElement( "div" ); + holder.id = "webSocketFlash"; + container.appendChild( holder ); + document.body.appendChild( container ); + // See this article for hasPriority: + // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html + swfobject.embedSWF( + WEB_SOCKET_SWF_LOCATION, + "webSocketFlash", + "1" /* width */, + "1" /* height */, + "10.0.0" /* SWF version */, + null, + null, + {hasPriority : true, swliveconnect : true, allowScriptAccess : "always"}, + null, + function ( e ) { + if ( !e.success ) { + console.error( "[WebSocket] swfobject.embedSWF failed" ); + } + } ); + }; + + /** + * Called by Flash to notify JS that it's fully loaded and ready + * for communication. + */ + WebSocket.__onFlashInitialized = function () { + // We need to set a timeout here to avoid round-trip calls + // to flash during the initialization process. + setTimeout( function () { + WebSocket.__flash = document.getElementById( "webSocketFlash" ); + WebSocket.__flash.setCallerUrl( location.href ); + WebSocket.__flash.setDebug( !!window.WEB_SOCKET_DEBUG ); + for ( var i = 0; i < WebSocket.__tasks.length; ++i ) { + WebSocket.__tasks[i](); + } + WebSocket.__tasks = []; + }, 0 ); + }; + + /** + * Called by Flash to notify WebSockets events are fired. + */ + WebSocket.__onFlashEvent = function () { + setTimeout( function () { + try { + // Gets events using receiveEvents() instead of getting it from event object + // of Flash event. This is to make sure to keep message order. + // It seems sometimes Flash events don't arrive in the same order as they are sent. + var events = WebSocket.__flash.receiveEvents(); + for ( var i = 0; i < events.length; ++i ) { + WebSocket.__instances[events[i].webSocketId].__handleEvent( events[i] ); + } + } catch ( e ) { + console.error( e ); + } + }, 0 ); + return true; + }; + + // Called by Flash. + WebSocket.__log = function ( message ) { + console.log( decodeURIComponent( message ) ); + }; + + // Called by Flash. + WebSocket.__error = function ( message ) { + console.error( decodeURIComponent( message ) ); + }; + + WebSocket.__addTask = function ( task ) { + if ( WebSocket.__flash ) { + task(); + } else { + WebSocket.__tasks.push( task ); + } + }; + + /** + * Test if the browser is running flash lite. + * @return {boolean} True if flash lite is running, false otherwise. + */ + WebSocket.__isFlashLite = function () { + if ( !window.navigator || !window.navigator.mimeTypes ) { + return false; + } + var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"]; + if ( !mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename ) { + return false; + } + return mimeType.enabledPlugin.filename.match( /flashlite/i ) ? true : false; + }; + + if ( !window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION ) { + if ( window.addEventListener ) { + window.addEventListener( "load", function () { + WebSocket.__initialize(); + }, false ); + } else { + window.attachEvent( "onload", function () { + WebSocket.__initialize(); + } ); + } + } - /** - * Loads WebSocketMain.swf and creates WebSocketMain object in Flash. - */ - WebSocket.__initialize = function() { - if (WebSocket.__flash) return; - - if (WebSocket.__swfLocation) { - // For backword compatibility. - window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation; - } - if (!window.WEB_SOCKET_SWF_LOCATION) { - console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf"); - return; - } - var container = document.createElement("div"); - container.id = "webSocketContainer"; - // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents - // Flash from loading at least in IE. So we move it out of the screen at (-100, -100). - // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash - // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is - // the best we can do as far as we know now. - container.style.position = "absolute"; - if (WebSocket.__isFlashLite()) { - container.style.left = "0px"; - container.style.top = "0px"; - } else { - container.style.left = "-100px"; - container.style.top = "-100px"; - } - var holder = document.createElement("div"); - holder.id = "webSocketFlash"; - container.appendChild(holder); - document.body.appendChild(container); - // See this article for hasPriority: - // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html - swfobject.embedSWF( - WEB_SOCKET_SWF_LOCATION, - "webSocketFlash", - "1" /* width */, - "1" /* height */, - "10.0.0" /* SWF version */, - null, - null, - {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"}, - null, - function(e) { - if (!e.success) { - console.error("[WebSocket] swfobject.embedSWF failed"); - } - }); - }; - - /** - * Called by Flash to notify JS that it's fully loaded and ready - * for communication. - */ - WebSocket.__onFlashInitialized = function() { - // We need to set a timeout here to avoid round-trip calls - // to flash during the initialization process. - setTimeout(function() { - WebSocket.__flash = document.getElementById("webSocketFlash"); - WebSocket.__flash.setCallerUrl(location.href); - WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG); - for (var i = 0; i < WebSocket.__tasks.length; ++i) { - WebSocket.__tasks[i](); - } - WebSocket.__tasks = []; - }, 0); - }; - - /** - * Called by Flash to notify WebSockets events are fired. - */ - WebSocket.__onFlashEvent = function() { - setTimeout(function() { - try { - // Gets events using receiveEvents() instead of getting it from event object - // of Flash event. This is to make sure to keep message order. - // It seems sometimes Flash events don't arrive in the same order as they are sent. - var events = WebSocket.__flash.receiveEvents(); - for (var i = 0; i < events.length; ++i) { - WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]); - } - } catch (e) { - console.error(e); - } - }, 0); - return true; - }; - - // Called by Flash. - WebSocket.__log = function(message) { - console.log(decodeURIComponent(message)); - }; - - // Called by Flash. - WebSocket.__error = function(message) { - console.error(decodeURIComponent(message)); - }; - - WebSocket.__addTask = function(task) { - if (WebSocket.__flash) { - task(); - } else { - WebSocket.__tasks.push(task); - } - }; - - /** - * Test if the browser is running flash lite. - * @return {boolean} True if flash lite is running, false otherwise. - */ - WebSocket.__isFlashLite = function() { - if (!window.navigator || !window.navigator.mimeTypes) { - return false; - } - var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"]; - if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) { - return false; - } - return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false; - }; - - if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) { - if (window.addEventListener) { - window.addEventListener("load", function(){ - WebSocket.__initialize(); - }, false); - } else { - window.attachEvent("onload", function(){ - WebSocket.__initialize(); - }); - } - } - })(); /** @@ -2984,215 +3694,226 @@ var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="Sho * MIT Licensed */ -(function (exports, io, global) { +(function ( exports, io, global ) { - /** - * Expose constructor. - * - * @api public - */ + /** + * Expose constructor. + * + * @api public + */ - exports.XHR = XHR; + exports.XHR = XHR; - /** - * XHR constructor - * - * @costructor - * @api public - */ + /** + * XHR constructor + * + * @costructor + * @api public + */ - function XHR (socket) { - if (!socket) return; + function XHR( socket ) { + if ( !socket ) { + return; + } - io.Transport.apply(this, arguments); - this.sendBuffer = []; - }; + io.Transport.apply( this, arguments ); + this.sendBuffer = []; + } - /** - * Inherits from Transport. - */ + ; - io.util.inherit(XHR, io.Transport); + /** + * Inherits from Transport. + */ - /** - * Establish a connection - * - * @returns {Transport} - * @api public - */ + io.util.inherit( XHR, io.Transport ); - XHR.prototype.open = function () { - this.socket.setBuffer(false); - this.onOpen(); - this.get(); + /** + * Establish a connection + * + * @returns {Transport} + * @api public + */ - // we need to make sure the request succeeds since we have no indication - // whether the request opened or not until it succeeded. - this.setCloseTimeout(); + XHR.prototype.open = function () { + this.socket.setBuffer( false ); + this.onOpen(); + this.get(); - return this; - }; + // we need to make sure the request succeeds since we have no indication + // whether the request opened or not until it succeeded. + this.setCloseTimeout(); - /** - * Check if we need to send data to the Socket.IO server, if we have data in our - * buffer we encode it and forward it to the `post` method. - * - * @api private - */ + return this; + }; - XHR.prototype.payload = function (payload) { - var msgs = []; + /** + * Check if we need to send data to the Socket.IO server, if we have data in our + * buffer we encode it and forward it to the `post` method. + * + * @api private + */ - for (var i = 0, l = payload.length; i < l; i++) { - msgs.push(io.parser.encodePacket(payload[i])); - } + XHR.prototype.payload = function ( payload ) { + var msgs = []; - this.send(io.parser.encodePayload(msgs)); - }; + for ( var i = 0, l = payload.length; i < l; i++ ) { + msgs.push( io.parser.encodePacket( payload[i] ) ); + } - /** - * Send data to the Socket.IO server. - * - * @param data The message - * @returns {Transport} - * @api public - */ + this.send( io.parser.encodePayload( msgs ) ); + }; - XHR.prototype.send = function (data) { - this.post(data); - return this; - }; + /** + * Send data to the Socket.IO server. + * + * @param data The message + * @returns {Transport} + * @api public + */ - /** - * Posts a encoded message to the Socket.IO server. - * - * @param {String} data A encoded message. - * @api private - */ + XHR.prototype.send = function ( data ) { + this.post( data ); + return this; + }; - function empty () { }; + /** + * Posts a encoded message to the Socket.IO server. + * + * @param {String} data A encoded message. + * @api private + */ - XHR.prototype.post = function (data) { - var self = this; - this.socket.setBuffer(true); + function empty() { + } - function stateChange () { - if (this.readyState == 4) { - this.onreadystatechange = empty; - self.posting = false; + ; - if (this.status == 200){ - self.socket.setBuffer(false); - } else { - self.onClose(); - } - } - } + XHR.prototype.post = function ( data ) { + var self = this; + this.socket.setBuffer( true ); - function onload () { - this.onload = empty; - self.socket.setBuffer(false); - }; + function stateChange() { + if ( this.readyState == 4 ) { + this.onreadystatechange = empty; + self.posting = false; - this.sendXHR = this.request('POST'); + if ( this.status == 200 ) { + self.socket.setBuffer( false ); + } else { + self.onClose(); + } + } + } - if (global.XDomainRequest && this.sendXHR instanceof XDomainRequest) { - this.sendXHR.onload = this.sendXHR.onerror = onload; - } else { - this.sendXHR.onreadystatechange = stateChange; - } + function onload() { + this.onload = empty; + self.socket.setBuffer( false ); + } - this.sendXHR.send(data); - }; + ; - /** - * Disconnects the established `XHR` connection. - * - * @returns {Transport} - * @api public - */ + this.sendXHR = this.request( 'POST' ); - XHR.prototype.close = function () { - this.onClose(); - return this; - }; + if ( global.XDomainRequest && this.sendXHR instanceof XDomainRequest ) { + this.sendXHR.onload = this.sendXHR.onerror = onload; + } else { + this.sendXHR.onreadystatechange = stateChange; + } - /** - * Generates a configured XHR request - * - * @param {String} url The url that needs to be requested. - * @param {String} method The method the request should use. - * @returns {XMLHttpRequest} - * @api private - */ + this.sendXHR.send( data ); + }; - XHR.prototype.request = function (method) { - var req = io.util.request(this.socket.isXDomain()) - , query = io.util.query(this.socket.options.query, 't=' + +new Date); + /** + * Disconnects the established `XHR` connection. + * + * @returns {Transport} + * @api public + */ - req.open(method || 'GET', this.prepareUrl() + query, true); + XHR.prototype.close = function () { + this.onClose(); + return this; + }; - if (method == 'POST') { - try { - if (req.setRequestHeader) { - req.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); - } else { - // XDomainRequest - req.contentType = 'text/plain'; - } - } catch (e) {} - } + /** + * Generates a configured XHR request + * + * @param {String} url The url that needs to be requested. + * @param {String} method The method the request should use. + * @returns {XMLHttpRequest} + * @api private + */ - return req; - }; + XHR.prototype.request = function ( method ) { + var req = io.util.request( this.socket.isXDomain() ) + , query = io.util.query( this.socket.options.query, 't=' + +new Date ); - /** - * Returns the scheme to use for the transport URLs. - * - * @api private - */ + req.open( method || 'GET', this.prepareUrl() + query, true ); - XHR.prototype.scheme = function () { - return this.socket.options.secure ? 'https' : 'http'; - }; + if ( method == 'POST' ) { + try { + if ( req.setRequestHeader ) { + req.setRequestHeader( 'Content-type', 'text/plain;charset=UTF-8' ); + } else { + // XDomainRequest + req.contentType = 'text/plain'; + } + } catch ( e ) { + } + } - /** - * Check if the XHR transports are supported - * - * @param {Boolean} xdomain Check if we support cross domain requests. - * @returns {Boolean} - * @api public - */ + return req; + }; - XHR.check = function (socket, xdomain) { - try { - var request = io.util.request(xdomain), - usesXDomReq = (global.XDomainRequest && request instanceof XDomainRequest), - socketProtocol = (socket && socket.options && socket.options.secure ? 'https:' : 'http:'), - isXProtocol = (socketProtocol != global.location.protocol); - if (request && !(usesXDomReq && isXProtocol)) { - return true; - } - } catch(e) {} + /** + * Returns the scheme to use for the transport URLs. + * + * @api private + */ - return false; - }; + XHR.prototype.scheme = function () { + return this.socket.options.secure ? 'https' : 'http'; + }; - /** - * Check if the XHR transport supports cross domain requests. - * - * @returns {Boolean} - * @api public - */ + /** + * Check if the XHR transports are supported + * + * @param {Boolean} xdomain Check if we support cross domain requests. + * @returns {Boolean} + * @api public + */ - XHR.xdomainCheck = function () { - return XHR.check(null, true); - }; + XHR.check = function ( socket, xdomain ) { + try { + var request = io.util.request( xdomain ), + usesXDomReq = (global.XDomainRequest && request instanceof XDomainRequest), + socketProtocol = (socket && socket.options && socket.options.secure ? 'https:' : 'http:'), + isXProtocol = (socketProtocol != global.location.protocol); + if ( request && !(usesXDomReq && isXProtocol) ) { + return true; + } + } catch ( e ) { + } + + return false; + }; + + /** + * Check if the XHR transport supports cross domain requests. + * + * @returns {Boolean} + * @api public + */ + + XHR.xdomainCheck = function () { + return XHR.check( null, true ); + }; })( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports - , this + 'undefined' != typeof io ? io.Transport : module.exports + , 'undefined' != typeof io ? io : module.parent.exports + , this ); /** * socket.io @@ -3200,170 +3921,175 @@ var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="Sho * MIT Licensed */ -(function (exports, io) { +(function ( exports, io ) { - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports.htmlfile = HTMLFile; + exports.htmlfile = HTMLFile; - /** - * The HTMLFile transport creates a `forever iframe` based transport - * for Internet Explorer. Regular forever iframe implementations will - * continuously trigger the browsers buzy indicators. If the forever iframe - * is created inside a `htmlfile` these indicators will not be trigged. - * - * @constructor - * @extends {io.Transport.XHR} - * @api public - */ + /** + * The HTMLFile transport creates a `forever iframe` based transport + * for Internet Explorer. Regular forever iframe implementations will + * continuously trigger the browsers buzy indicators. If the forever iframe + * is created inside a `htmlfile` these indicators will not be trigged. + * + * @constructor + * @extends {io.Transport.XHR} + * @api public + */ - function HTMLFile (socket) { - io.Transport.XHR.apply(this, arguments); - }; + function HTMLFile( socket ) { + io.Transport.XHR.apply( this, arguments ); + } - /** - * Inherits from XHR transport. - */ + ; - io.util.inherit(HTMLFile, io.Transport.XHR); + /** + * Inherits from XHR transport. + */ - /** - * Transport name - * - * @api public - */ + io.util.inherit( HTMLFile, io.Transport.XHR ); - HTMLFile.prototype.name = 'htmlfile'; + /** + * Transport name + * + * @api public + */ - /** - * Creates a new Ac...eX `htmlfile` with a forever loading iframe - * that can be used to listen to messages. Inside the generated - * `htmlfile` a reference will be made to the HTMLFile transport. - * - * @api private - */ + HTMLFile.prototype.name = 'htmlfile'; - HTMLFile.prototype.get = function () { - this.doc = new window[(['Active'].concat('Object').join('X'))]('htmlfile'); - this.doc.open(); - this.doc.write(''); - this.doc.close(); - this.doc.parentWindow.s = this; + /** + * Creates a new Ac...eX `htmlfile` with a forever loading iframe + * that can be used to listen to messages. Inside the generated + * `htmlfile` a reference will be made to the HTMLFile transport. + * + * @api private + */ - var iframeC = this.doc.createElement('div'); - iframeC.className = 'socketio'; + HTMLFile.prototype.get = function () { + this.doc = new window[(['Active'].concat( 'Object' ).join( 'X' ))]( 'htmlfile' ); + this.doc.open(); + this.doc.write( '' ); + this.doc.close(); + this.doc.parentWindow.s = this; - this.doc.body.appendChild(iframeC); - this.iframe = this.doc.createElement('iframe'); + var iframeC = this.doc.createElement( 'div' ); + iframeC.className = 'socketio'; - iframeC.appendChild(this.iframe); + this.doc.body.appendChild( iframeC ); + this.iframe = this.doc.createElement( 'iframe' ); - var self = this - , query = io.util.query(this.socket.options.query, 't='+ +new Date); + iframeC.appendChild( this.iframe ); - this.iframe.src = this.prepareUrl() + query; + var self = this + , query = io.util.query( this.socket.options.query, 't=' + +new Date ); - io.util.on(window, 'unload', function () { - self.destroy(); - }); - }; + this.iframe.src = this.prepareUrl() + query; - /** - * The Socket.IO server will write script tags inside the forever - * iframe, this function will be used as callback for the incoming - * information. - * - * @param {String} data The message - * @param {document} doc Reference to the context - * @api private - */ + io.util.on( window, 'unload', function () { + self.destroy(); + } ); + }; - HTMLFile.prototype._ = function (data, doc) { - this.onData(data); - try { - var script = doc.getElementsByTagName('script')[0]; - script.parentNode.removeChild(script); - } catch (e) { } - }; + /** + * The Socket.IO server will write script tags inside the forever + * iframe, this function will be used as callback for the incoming + * information. + * + * @param {String} data The message + * @param {document} doc Reference to the context + * @api private + */ - /** - * Destroy the established connection, iframe and `htmlfile`. - * And calls the `CollectGarbage` function of Internet Explorer - * to release the memory. - * - * @api private - */ + HTMLFile.prototype._ = function ( data, doc ) { + this.onData( data ); + try { + var script = doc.getElementsByTagName( 'script' )[0]; + script.parentNode.removeChild( script ); + } catch ( e ) { + } + }; - HTMLFile.prototype.destroy = function () { - if (this.iframe){ - try { - this.iframe.src = 'about:blank'; - } catch(e){} + /** + * Destroy the established connection, iframe and `htmlfile`. + * And calls the `CollectGarbage` function of Internet Explorer + * to release the memory. + * + * @api private + */ - this.doc = null; - this.iframe.parentNode.removeChild(this.iframe); - this.iframe = null; + HTMLFile.prototype.destroy = function () { + if ( this.iframe ) { + try { + this.iframe.src = 'about:blank'; + } catch ( e ) { + } - CollectGarbage(); - } - }; + this.doc = null; + this.iframe.parentNode.removeChild( this.iframe ); + this.iframe = null; - /** - * Disconnects the established connection. - * - * @returns {Transport} Chaining. - * @api public - */ + CollectGarbage(); + } + }; - HTMLFile.prototype.close = function () { - this.destroy(); - return io.Transport.XHR.prototype.close.call(this); - }; + /** + * Disconnects the established connection. + * + * @returns {Transport} Chaining. + * @api public + */ - /** - * Checks if the browser supports this transport. The browser - * must have an `Ac...eXObject` implementation. - * - * @return {Boolean} - * @api public - */ + HTMLFile.prototype.close = function () { + this.destroy(); + return io.Transport.XHR.prototype.close.call( this ); + }; - HTMLFile.check = function () { - if (typeof window != "undefined" && (['Active'].concat('Object').join('X')) in window){ - try { - var a = new window[(['Active'].concat('Object').join('X'))]('htmlfile'); - return a && io.Transport.XHR.check(); - } catch(e){} - } - return false; - }; + /** + * Checks if the browser supports this transport. The browser + * must have an `Ac...eXObject` implementation. + * + * @return {Boolean} + * @api public + */ - /** - * Check if cross domain requests are supported. - * - * @returns {Boolean} - * @api public - */ + HTMLFile.check = function () { + if ( typeof window != "undefined" && (['Active'].concat( 'Object' ).join( 'X' )) in window ) { + try { + var a = new window[(['Active'].concat( 'Object' ).join( 'X' ))]( 'htmlfile' ); + return a && io.Transport.XHR.check(); + } catch ( e ) { + } + } + return false; + }; - HTMLFile.xdomainCheck = function () { - // we can probably do handling for sub-domains, we should - // test that it's cross domain but a subdomain here - return false; - }; + /** + * Check if cross domain requests are supported. + * + * @returns {Boolean} + * @api public + */ - /** - * Add the transport to your public io.transports array. - * - * @api private - */ + HTMLFile.xdomainCheck = function () { + // we can probably do handling for sub-domains, we should + // test that it's cross domain but a subdomain here + return false; + }; - io.transports.push('htmlfile'); + /** + * Add the transport to your public io.transports array. + * + * @api private + */ + + io.transports.push( 'htmlfile' ); })( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports + 'undefined' != typeof io ? io.Transport : module.exports + , 'undefined' != typeof io ? io : module.parent.exports ); /** @@ -3372,159 +4098,173 @@ var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="Sho * MIT Licensed */ -(function (exports, io, global) { +(function ( exports, io, global ) { - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports['xhr-polling'] = XHRPolling; + exports['xhr-polling'] = XHRPolling; - /** - * The XHR-polling transport uses long polling XHR requests to create a - * "persistent" connection with the server. - * - * @constructor - * @api public - */ + /** + * The XHR-polling transport uses long polling XHR requests to create a + * "persistent" connection with the server. + * + * @constructor + * @api public + */ - function XHRPolling () { - io.Transport.XHR.apply(this, arguments); - }; + function XHRPolling() { + io.Transport.XHR.apply( this, arguments ); + } - /** - * Inherits from XHR transport. - */ + ; - io.util.inherit(XHRPolling, io.Transport.XHR); + /** + * Inherits from XHR transport. + */ - /** - * Merge the properties from XHR transport - */ + io.util.inherit( XHRPolling, io.Transport.XHR ); - io.util.merge(XHRPolling, io.Transport.XHR); + /** + * Merge the properties from XHR transport + */ - /** - * Transport name - * - * @api public - */ + io.util.merge( XHRPolling, io.Transport.XHR ); - XHRPolling.prototype.name = 'xhr-polling'; + /** + * Transport name + * + * @api public + */ - /** - * Establish a connection, for iPhone and Android this will be done once the page - * is loaded. - * - * @returns {Transport} Chaining. - * @api public - */ + XHRPolling.prototype.name = 'xhr-polling'; - XHRPolling.prototype.open = function () { - var self = this; + /** + * Establish a connection, for iPhone and Android this will be done once the page + * is loaded. + * + * @returns {Transport} Chaining. + * @api public + */ - io.Transport.XHR.prototype.open.call(self); - return false; - }; + XHRPolling.prototype.open = function () { + var self = this; - /** - * Starts a XHR request to wait for incoming messages. - * - * @api private - */ + io.Transport.XHR.prototype.open.call( self ); + return false; + }; - function empty () {}; + /** + * Starts a XHR request to wait for incoming messages. + * + * @api private + */ - XHRPolling.prototype.get = function () { - if (!this.open) return; + function empty() { + } - var self = this; + ; - function stateChange () { - if (this.readyState == 4) { - this.onreadystatechange = empty; + XHRPolling.prototype.get = function () { + if ( !this.open ) { + return; + } - if (this.status == 200) { - self.onData(this.responseText); - self.get(); - } else { - self.onClose(); - } - } - }; + var self = this; - function onload () { - this.onload = empty; - this.onerror = empty; - self.onData(this.responseText); - self.get(); - }; + function stateChange() { + if ( this.readyState == 4 ) { + this.onreadystatechange = empty; - function onerror () { - self.onClose(); - }; + if ( this.status == 200 ) { + self.onData( this.responseText ); + self.get(); + } else { + self.onClose(); + } + } + } - this.xhr = this.request(); + ; - if (global.XDomainRequest && this.xhr instanceof XDomainRequest) { - this.xhr.onload = onload; - this.xhr.onerror = onerror; - } else { - this.xhr.onreadystatechange = stateChange; - } + function onload() { + this.onload = empty; + this.onerror = empty; + self.onData( this.responseText ); + self.get(); + } - this.xhr.send(null); - }; + ; - /** - * Handle the unclean close behavior. - * - * @api private - */ + function onerror() { + self.onClose(); + } - XHRPolling.prototype.onClose = function () { - io.Transport.XHR.prototype.onClose.call(this); + ; - if (this.xhr) { - this.xhr.onreadystatechange = this.xhr.onload = this.xhr.onerror = empty; - try { - this.xhr.abort(); - } catch(e){} - this.xhr = null; - } - }; + this.xhr = this.request(); - /** - * Webkit based browsers show a infinit spinner when you start a XHR request - * before the browsers onload event is called so we need to defer opening of - * the transport until the onload event is called. Wrapping the cb in our - * defer method solve this. - * - * @param {Socket} socket The socket instance that needs a transport - * @param {Function} fn The callback - * @api private - */ + if ( global.XDomainRequest && this.xhr instanceof XDomainRequest ) { + this.xhr.onload = onload; + this.xhr.onerror = onerror; + } else { + this.xhr.onreadystatechange = stateChange; + } - XHRPolling.prototype.ready = function (socket, fn) { - var self = this; + this.xhr.send( null ); + }; - io.util.defer(function () { - fn.call(self); - }); - }; + /** + * Handle the unclean close behavior. + * + * @api private + */ - /** - * Add the transport to your public io.transports array. - * - * @api private - */ + XHRPolling.prototype.onClose = function () { + io.Transport.XHR.prototype.onClose.call( this ); - io.transports.push('xhr-polling'); + if ( this.xhr ) { + this.xhr.onreadystatechange = this.xhr.onload = this.xhr.onerror = empty; + try { + this.xhr.abort(); + } catch ( e ) { + } + this.xhr = null; + } + }; + + /** + * Webkit based browsers show a infinit spinner when you start a XHR request + * before the browsers onload event is called so we need to defer opening of + * the transport until the onload event is called. Wrapping the cb in our + * defer method solve this. + * + * @param {Socket} socket The socket instance that needs a transport + * @param {Function} fn The callback + * @api private + */ + + XHRPolling.prototype.ready = function ( socket, fn ) { + var self = this; + + io.util.defer( function () { + fn.call( self ); + } ); + }; + + /** + * Add the transport to your public io.transports array. + * + * @api private + */ + + io.transports.push( 'xhr-polling' ); })( - 'undefined' != typeof io ? io.Transport : module.exports - , 'undefined' != typeof io ? io : module.parent.exports - , this + 'undefined' != typeof io ? io.Transport : module.exports + , 'undefined' != typeof io ? io : module.parent.exports + , this ); /** @@ -3533,251 +4273,260 @@ var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="Sho * MIT Licensed */ -(function (exports, io, global) { - /** - * There is a way to hide the loading indicator in Firefox. If you create and - * remove a iframe it will stop showing the current loading indicator. - * Unfortunately we can't feature detect that and UA sniffing is evil. - * - * @api private - */ +(function ( exports, io, global ) { + /** + * There is a way to hide the loading indicator in Firefox. If you create and + * remove a iframe it will stop showing the current loading indicator. + * Unfortunately we can't feature detect that and UA sniffing is evil. + * + * @api private + */ - var indicator = global.document && "MozAppearance" in - global.document.documentElement.style; + var indicator = global.document && "MozAppearance" in + global.document.documentElement.style; - /** - * Expose constructor. - */ + /** + * Expose constructor. + */ - exports['jsonp-polling'] = JSONPPolling; + exports['jsonp-polling'] = JSONPPolling; - /** - * The JSONP transport creates an persistent connection by dynamically - * inserting a script tag in the page. This script tag will receive the - * information of the Socket.IO server. When new information is received - * it creates a new script tag for the new data stream. - * - * @constructor - * @extends {io.Transport.xhr-polling} - * @api public - */ + /** + * The JSONP transport creates an persistent connection by dynamically + * inserting a script tag in the page. This script tag will receive the + * information of the Socket.IO server. When new information is received + * it creates a new script tag for the new data stream. + * + * @constructor + * @extends {io.Transport.xhr-polling} + * @api public + */ - function JSONPPolling (socket) { - io.Transport['xhr-polling'].apply(this, arguments); + function JSONPPolling( socket ) { + io.Transport['xhr-polling'].apply( this, arguments ); - this.index = io.j.length; + this.index = io.j.length; - var self = this; + var self = this; - io.j.push(function (msg) { - self._(msg); - }); - }; + io.j.push( function ( msg ) { + self._( msg ); + } ); + } - /** - * Inherits from XHR polling transport. - */ + ; - io.util.inherit(JSONPPolling, io.Transport['xhr-polling']); + /** + * Inherits from XHR polling transport. + */ - /** - * Transport name - * - * @api public - */ + io.util.inherit( JSONPPolling, io.Transport['xhr-polling'] ); - JSONPPolling.prototype.name = 'jsonp-polling'; + /** + * Transport name + * + * @api public + */ - /** - * Posts a encoded message to the Socket.IO server using an iframe. - * The iframe is used because script tags can create POST based requests. - * The iframe is positioned outside of the view so the user does not - * notice it's existence. - * - * @param {String} data A encoded message. - * @api private - */ + JSONPPolling.prototype.name = 'jsonp-polling'; - JSONPPolling.prototype.post = function (data) { - var self = this - , query = io.util.query( - this.socket.options.query - , 't='+ (+new Date) + '&i=' + this.index - ); + /** + * Posts a encoded message to the Socket.IO server using an iframe. + * The iframe is used because script tags can create POST based requests. + * The iframe is positioned outside of the view so the user does not + * notice it's existence. + * + * @param {String} data A encoded message. + * @api private + */ - if (!this.form) { - var form = document.createElement('form') - , area = document.createElement('textarea') - , id = this.iframeId = 'socketio_iframe_' + this.index - , iframe; + JSONPPolling.prototype.post = function ( data ) { + var self = this + , query = io.util.query( + this.socket.options.query + , 't=' + (+new Date) + '&i=' + this.index + ); - form.className = 'socketio'; - form.style.position = 'absolute'; - form.style.top = '-1000px'; - form.style.left = '-1000px'; - form.target = id; - form.method = 'POST'; - form.setAttribute('accept-charset', 'utf-8'); - area.name = 'd'; - form.appendChild(area); - document.body.appendChild(form); + if ( !this.form ) { + var form = document.createElement( 'form' ) + , area = document.createElement( 'textarea' ) + , id = this.iframeId = 'socketio_iframe_' + this.index + , iframe; - this.form = form; - this.area = area; - } + form.className = 'socketio'; + form.style.position = 'absolute'; + form.style.top = '-1000px'; + form.style.left = '-1000px'; + form.target = id; + form.method = 'POST'; + form.setAttribute( 'accept-charset', 'utf-8' ); + area.name = 'd'; + form.appendChild( area ); + document.body.appendChild( form ); - this.form.action = this.prepareUrl() + query; + this.form = form; + this.area = area; + } - function complete () { - initIframe(); - self.socket.setBuffer(false); - }; + this.form.action = this.prepareUrl() + query; - function initIframe () { - if (self.iframe) { - self.form.removeChild(self.iframe); - } + function complete() { + initIframe(); + self.socket.setBuffer( false ); + } - try { - // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) - iframe = document.createElement(''; - } else { - if(ie6) { - $('select').css('visibility','hidden'); - } - msgbox +='
    '; - } - msgbox += '
    X
    '; - msgbox += '
    '; +(function ( $ ) { + $.prompt = function ( message, options ) { + options = $.extend( {}, $.prompt.defaults, options ); + $.prompt.currentPrefix = options.prefix; - var $jqib = $(msgbox).appendTo($body); - var $jqi = $jqib.children('#'+ options.prefix); - var $jqif = $jqib.children('#'+ options.prefix +'fade'); + var ie6 = ($.browser.msie && $.browser.version < 7); + var $body = $( document.body ); + var $window = $( window ); - //if a string was passed, convert to a single state - if(message.constructor == String){ - message = { - state0: { - html: message, - buttons: options.buttons, - focus: options.focus, - submit: options.submit - } - }; - } + options.classes = $.trim( options.classes ); + if ( options.classes != '' ) { + options.classes = ' ' + options.classes; + } - //build the states - var states = ""; + //build the box and fade + var msgbox = '
    '; + if ( options.useiframe && (($( 'object, applet' ).length > 0) || ie6) ) { + msgbox += ''; + } else { + if ( ie6 ) { + $( 'select' ).css( 'visibility', 'hidden' ); + } + msgbox += '
    '; + } + msgbox += '
    X
    '; + msgbox += '
    '; - $.each(message,function(statename,stateobj){ - stateobj = $.extend({},$.prompt.defaults.state,stateobj); - message[statename] = stateobj; + var $jqib = $( msgbox ).appendTo( $body ); + var $jqi = $jqib.children( '#' + options.prefix ); + var $jqif = $jqib.children( '#' + options.prefix + 'fade' ); - states += ''; - }); + //if a string was passed, convert to a single state + if ( message.constructor == String ) { + message = { + state0 : { + html : message, + buttons : options.buttons, + focus : options.focus, + submit : options.submit + } + }; + } - //insert the states... - $jqi.find('#'+ options.prefix +'states').html(states).children('.'+ options.prefix +'_state:first').css('display','block'); - $jqi.find('.'+ options.prefix +'buttons:empty').css('display','none'); - - //Events - $.each(message,function(statename,stateobj){ - var $state = $jqi.find('#'+ options.prefix +'_state_'+ statename); + //build the states + var states = ""; - $state.children('.'+ options.prefix +'buttons').children('button').click(function(){ - var msg = $state.children('.'+ options.prefix +'message'); - var clicked = stateobj.buttons[$(this).text()]; - if(clicked == undefined){ - for(var i in stateobj.buttons) - if(stateobj.buttons[i].title == $(this).text()) - clicked = stateobj.buttons[i].value; - } - - if(typeof clicked == 'object') - clicked = clicked.value; - var forminputs = {}; + $.each( message, function ( statename, stateobj ) { + stateobj = $.extend( {}, $.prompt.defaults.state, stateobj ); + message[statename] = stateobj; - //collect all form element values from all states - $.each($jqi.find('#'+ options.prefix +'states :input').serializeArray(),function(i,obj){ - if (forminputs[obj.name] === undefined) { - forminputs[obj.name] = obj.value; - } else if (typeof forminputs[obj.name] == Array || typeof forminputs[obj.name] == 'object') { - forminputs[obj.name].push(obj.value); - } else { - forminputs[obj.name] = [forminputs[obj.name],obj.value]; - } - }); + states += ''; + } ); - var close = stateobj.submit(clicked,msg,forminputs); - if(close === undefined || close) { - removePrompt(true,clicked,msg,forminputs); - } - }); - $state.find('.'+ options.prefix +'buttons button:eq('+ stateobj.focus +')').addClass(options.prefix +'defaultbutton'); + //insert the states... + $jqi.find( '#' + options.prefix + 'states' ).html( states ).children( '.' + options.prefix + '_state:first' ).css( 'display', 'block' ); + $jqi.find( '.' + options.prefix + 'buttons:empty' ).css( 'display', 'none' ); - }); + //Events + $.each( message, function ( statename, stateobj ) { + var $state = $jqi.find( '#' + options.prefix + '_state_' + statename ); - var ie6scroll = function(){ - $jqib.css({ top: $window.scrollTop() }); - }; + $state.children( '.' + options.prefix + 'buttons' ).children( 'button' ).click( function () { + var msg = $state.children( '.' + options.prefix + 'message' ); + var clicked = stateobj.buttons[$( this ).text()]; + if ( clicked == undefined ) { + for ( var i in stateobj.buttons ) { + if ( stateobj.buttons[i].title == $( this ).text() ) { + clicked = stateobj.buttons[i].value; + } + } + } - var fadeClicked = function(){ - if(options.persistent){ - var i = 0; - $jqib.addClass(options.prefix +'warning'); - var intervalid = setInterval(function(){ - $jqib.toggleClass(options.prefix +'warning'); - if(i++ > 1){ - clearInterval(intervalid); - $jqib.removeClass(options.prefix +'warning'); - } - }, 100); - } - else { - removePrompt(); - } - }; - - var keyPressEventHandler = function(e){ - var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox? - - //escape key closes - if(key==27) { - fadeClicked(); - } - - //constrain tabs - if (key == 9){ - var $inputels = $(':input:enabled:visible',$jqib); - var fwd = !e.shiftKey && e.target == $inputels[$inputels.length-1]; - var back = e.shiftKey && e.target == $inputels[0]; - if (fwd || back) { - setTimeout(function(){ - if (!$inputels) - return; - var el = $inputels[back===true ? $inputels.length-1 : 0]; + if ( typeof clicked == 'object' ) { + clicked = clicked.value; + } + var forminputs = {}; - if (el) - el.focus(); - },10); - return false; - } - } - }; - - var positionPrompt = function(){ - $jqib.css({ - position: (ie6) ? "absolute" : "fixed", - height: $window.height(), - width: "100%", - top: (ie6)? $window.scrollTop() : 0, - left: 0, - right: 0, - bottom: 0 - }); - $jqif.css({ - position: "absolute", - height: $window.height(), - width: "100%", - top: 0, - left: 0, - right: 0, - bottom: 0 - }); - $jqi.css({ - position: "absolute", - top: options.top, - left: "50%", - marginLeft: (($jqi.outerWidth()/2)*-1) - }); - }; + //collect all form element values from all states + $.each( $jqi.find( '#' + options.prefix + 'states :input' ).serializeArray(), function ( i, obj ) { + if ( forminputs[obj.name] === undefined ) { + forminputs[obj.name] = obj.value; + } else if ( typeof forminputs[obj.name] == Array || typeof forminputs[obj.name] == 'object' ) { + forminputs[obj.name].push( obj.value ); + } else { + forminputs[obj.name] = [forminputs[obj.name], obj.value]; + } + } ); - var stylePrompt = function(){ - $jqif.css({ - zIndex: options.zIndex, - display: "none", - opacity: options.opacity - }); - $jqi.css({ - zIndex: options.zIndex+1, - display: "none" - }); - $jqib.css({ - zIndex: options.zIndex - }); - }; + var close = stateobj.submit( clicked, msg, forminputs ); + if ( close === undefined || close ) { + removePrompt( true, clicked, msg, forminputs ); + } + } ); + $state.find( '.' + options.prefix + 'buttons button:eq(' + stateobj.focus + ')' ).addClass( options.prefix + 'defaultbutton' ); - var removePrompt = function(callCallback, clicked, msg, formvals){ - $jqi.remove(); - //ie6, remove the scroll event - if(ie6) { - $body.unbind('scroll',ie6scroll); - } - $window.unbind('resize',positionPrompt); - $jqif.fadeOut(options.overlayspeed,function(){ - $jqif.unbind('click',fadeClicked); - $jqif.remove(); - if(callCallback) { - options.callback(clicked,msg,formvals); - } - $jqib.unbind('keypress',keyPressEventHandler); - $jqib.remove(); - if(ie6 && !options.useiframe) { - $('select').css('visibility','visible'); - } - }); - }; + } ); - positionPrompt(); - stylePrompt(); - - //ie6, add a scroll event to fix position:fixed - if(ie6) { - $window.scroll(ie6scroll); - } - $jqif.click(fadeClicked); - $window.resize(positionPrompt); - $jqib.bind("keydown keypress",keyPressEventHandler); - $jqi.find('.'+ options.prefix +'close').click(removePrompt); + var ie6scroll = function () { + $jqib.css( { top : $window.scrollTop() } ); + }; - //Show it - $jqif.fadeIn(options.overlayspeed); - $jqi[options.show](options.promptspeed,options.loaded); - $jqi.find('#'+ options.prefix +'states .'+ options.prefix +'_state:first .'+ options.prefix +'defaultbutton').focus(); - - if(options.timeout > 0) - setTimeout($.prompt.close,options.timeout); + var fadeClicked = function () { + if ( options.persistent ) { + var i = 0; + $jqib.addClass( options.prefix + 'warning' ); + var intervalid = setInterval( function () { + $jqib.toggleClass( options.prefix + 'warning' ); + if ( i++ > 1 ) { + clearInterval( intervalid ); + $jqib.removeClass( options.prefix + 'warning' ); + } + }, 100 ); + } + else { + removePrompt(); + } + }; - return $jqib; - }; - - $.prompt.defaults = { - prefix:'jqi', - classes: '', - buttons: { - Ok: true - }, - loaded: function(){ + var keyPressEventHandler = function ( e ) { + var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox? - }, - submit: function(){ - return true; - }, - callback: function(){ + //escape key closes + if ( key == 27 ) { + fadeClicked(); + } - }, - opacity: 0.6, - zIndex: 999, - overlayspeed: 'slow', - promptspeed: 'fast', - show: 'fadeIn', - focus: 0, - useiframe: false, - top: "15%", - persistent: true, - timeout: 0, - state: { - html: '', - buttons: { - Ok: true - }, - focus: 0, - submit: function(){ - return true; - } - } - }; - - $.prompt.currentPrefix = $.prompt.defaults.prefix; + //constrain tabs + if ( key == 9 ) { + var $inputels = $( ':input:enabled:visible', $jqib ); + var fwd = !e.shiftKey && e.target == $inputels[$inputels.length - 1]; + var back = e.shiftKey && e.target == $inputels[0]; + if ( fwd || back ) { + setTimeout( function () { + if ( !$inputels ) { + return; + } + var el = $inputels[back === true ? $inputels.length - 1 : 0]; - $.prompt.setDefaults = function(o) { - $.prompt.defaults = $.extend({}, $.prompt.defaults, o); - }; - - $.prompt.setStateDefaults = function(o) { - $.prompt.defaults.state = $.extend({}, $.prompt.defaults.state, o); - }; - - $.prompt.getStateContent = function(state) { - return $('#'+ $.prompt.currentPrefix +'_state_'+ state); - }; - - $.prompt.getCurrentState = function() { - return $('.'+ $.prompt.currentPrefix +'_state:visible'); - }; - - $.prompt.getCurrentStateName = function() { - var stateid = $.prompt.getCurrentState().attr('id'); - - return stateid.replace($.prompt.currentPrefix +'_state_',''); - }; - - $.prompt.goToState = function(state, callback) { - $('.'+ $.prompt.currentPrefix +'_state').slideUp('slow'); - $('#'+ $.prompt.currentPrefix +'_state_'+ state).slideDown('slow',function(){ - $(this).find('.'+ $.prompt.currentPrefix +'defaultbutton').focus(); - if (typeof callback == 'function') - callback(); - }); - }; - - $.prompt.nextState = function(callback) { - var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').next(); + if ( el ) { + el.focus(); + } + }, 10 ); + return false; + } + } + }; - $('.'+ $.prompt.currentPrefix +'_state').slideUp('slow'); - - $next.slideDown('slow',function(){ - $next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus(); - if (typeof callback == 'function') - callback(); - }); - }; - - $.prompt.prevState = function(callback) { - var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').prev(); + var positionPrompt = function () { + $jqib.css( { + position : (ie6) ? "absolute" : "fixed", + height : $window.height(), + width : "100%", + top : (ie6) ? $window.scrollTop() : 0, + left : 0, + right : 0, + bottom : 0 + } ); + $jqif.css( { + position : "absolute", + height : $window.height(), + width : "100%", + top : 0, + left : 0, + right : 0, + bottom : 0 + } ); + $jqi.css( { + position : "absolute", + top : options.top, + left : "50%", + marginLeft : (($jqi.outerWidth() / 2) * -1) + } ); + }; - $('.'+ $.prompt.currentPrefix +'_state').slideUp('slow'); - - $next.slideDown('slow',function(){ - $next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus(); - if (typeof callback == 'function') - callback(); - }); - }; - - $.prompt.close = function() { - $('#'+ $.prompt.currentPrefix +'box').fadeOut('fast',function(){ - $(this).remove(); - }); - }; - - $.fn.prompt = function(options){ - if(options == undefined) - options = {}; - if(options.withDataAndEvents == undefined) - options.withDataAndEvents = false; - - $.prompt($(this).clone(options.withDataAndEvents).html(),options); - } - -})(jQuery); -(function($) { - $.fn.serializeToJson = function() { - attrs = {}; - this.find('[name]').each(function(i, field) { - $field = $(field); - if ($field.is(':checkbox')) { - val = $field.is(':checked'); - } else { - val = $field.val(); - } - attrs[$field.attr('name')] = val; - }); - return attrs; - }; -})(jQuery); + var stylePrompt = function () { + $jqif.css( { + zIndex : options.zIndex, + display : "none", + opacity : options.opacity + } ); + $jqi.css( { + zIndex : options.zIndex + 1, + display : "none" + } ); + $jqib.css( { + zIndex : options.zIndex + } ); + }; + + var removePrompt = function ( callCallback, clicked, msg, formvals ) { + $jqi.remove(); + //ie6, remove the scroll event + if ( ie6 ) { + $body.unbind( 'scroll', ie6scroll ); + } + $window.unbind( 'resize', positionPrompt ); + $jqif.fadeOut( options.overlayspeed, function () { + $jqif.unbind( 'click', fadeClicked ); + $jqif.remove(); + if ( callCallback ) { + options.callback( clicked, msg, formvals ); + } + $jqib.unbind( 'keypress', keyPressEventHandler ); + $jqib.remove(); + if ( ie6 && !options.useiframe ) { + $( 'select' ).css( 'visibility', 'visible' ); + } + } ); + }; + + positionPrompt(); + stylePrompt(); + + //ie6, add a scroll event to fix position:fixed + if ( ie6 ) { + $window.scroll( ie6scroll ); + } + $jqif.click( fadeClicked ); + $window.resize( positionPrompt ); + $jqib.bind( "keydown keypress", keyPressEventHandler ); + $jqi.find( '.' + options.prefix + 'close' ).click( removePrompt ); + + //Show it + $jqif.fadeIn( options.overlayspeed ); + $jqi[options.show]( options.promptspeed, options.loaded ); + $jqi.find( '#' + options.prefix + 'states .' + options.prefix + '_state:first .' + options.prefix + 'defaultbutton' ).focus(); + + if ( options.timeout > 0 ) { + setTimeout( $.prompt.close, options.timeout ); + } + + return $jqib; + }; + + $.prompt.defaults = { + prefix : 'jqi', + classes : '', + buttons : { + Ok : true + }, + loaded : function () { + + }, + submit : function () { + return true; + }, + callback : function () { + + }, + opacity : 0.6, + zIndex : 999, + overlayspeed : 'slow', + promptspeed : 'fast', + show : 'fadeIn', + focus : 0, + useiframe : false, + top : "15%", + persistent : true, + timeout : 0, + state : { + html : '', + buttons : { + Ok : true + }, + focus : 0, + submit : function () { + return true; + } + } + }; + + $.prompt.currentPrefix = $.prompt.defaults.prefix; + + $.prompt.setDefaults = function ( o ) { + $.prompt.defaults = $.extend( {}, $.prompt.defaults, o ); + }; + + $.prompt.setStateDefaults = function ( o ) { + $.prompt.defaults.state = $.extend( {}, $.prompt.defaults.state, o ); + }; + + $.prompt.getStateContent = function ( state ) { + return $( '#' + $.prompt.currentPrefix + '_state_' + state ); + }; + + $.prompt.getCurrentState = function () { + return $( '.' + $.prompt.currentPrefix + '_state:visible' ); + }; + + $.prompt.getCurrentStateName = function () { + var stateid = $.prompt.getCurrentState().attr( 'id' ); + + return stateid.replace( $.prompt.currentPrefix + '_state_', '' ); + }; + + $.prompt.goToState = function ( state, callback ) { + $( '.' + $.prompt.currentPrefix + '_state' ).slideUp( 'slow' ); + $( '#' + $.prompt.currentPrefix + '_state_' + state ).slideDown( 'slow', function () { + $( this ).find( '.' + $.prompt.currentPrefix + 'defaultbutton' ).focus(); + if ( typeof callback == 'function' ) { + callback(); + } + } ); + }; + + $.prompt.nextState = function ( callback ) { + var $next = $( '.' + $.prompt.currentPrefix + '_state:visible' ).next(); + + $( '.' + $.prompt.currentPrefix + '_state' ).slideUp( 'slow' ); + + $next.slideDown( 'slow', function () { + $next.find( '.' + $.prompt.currentPrefix + 'defaultbutton' ).focus(); + if ( typeof callback == 'function' ) { + callback(); + } + } ); + }; + + $.prompt.prevState = function ( callback ) { + var $next = $( '.' + $.prompt.currentPrefix + '_state:visible' ).prev(); + + $( '.' + $.prompt.currentPrefix + '_state' ).slideUp( 'slow' ); + + $next.slideDown( 'slow', function () { + $next.find( '.' + $.prompt.currentPrefix + 'defaultbutton' ).focus(); + if ( typeof callback == 'function' ) { + callback(); + } + } ); + }; + + $.prompt.close = function () { + $( '#' + $.prompt.currentPrefix + 'box' ).fadeOut( 'fast', function () { + $( this ).remove(); + } ); + }; + + $.fn.prompt = function ( options ) { + if ( options == undefined ) { + options = {}; + } + if ( options.withDataAndEvents == undefined ) { + options.withDataAndEvents = false; + } + + $.prompt( $( this ).clone( options.withDataAndEvents ).html(), options ); + } + +})( jQuery ); +(function ( $ ) { + $.fn.serializeToJson = function () { + attrs = {}; + this.find( '[name]' ).each( function ( i, field ) { + $field = $( field ); + if ( $field.is( ':checkbox' ) ) { + val = $field.is( ':checked' ); + } else { + val = $field.val(); + } + attrs[$field.attr( 'name' )] = val; + } ); + return attrs; + }; +})( jQuery ); /* - http://www.JSON.org/json2.js - 2011-02-23 + http://www.JSON.org/json2.js + 2011-02-23 - Public Domain. + Public Domain. - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - See http://www.JSON.org/js.html + See http://www.JSON.org/js.html - This code should be minified before deployment. - See http://javascript.crockford.com/jsmin.html + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html - USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO - NOT CONTROL. + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. - This file creates a global JSON object containing two methods: stringify - and parse. + This file creates a global JSON object containing two methods: stringify + and parse. - JSON.stringify(value, replacer, space) - value any JavaScript value, usually an object or array. + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. - replacer an optional parameter that determines how object - values are stringified for objects. It can be a - function or an array of strings. + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. - space an optional parameter that specifies the indentation - of nested structures. If it is omitted, the text will - be packed without extra whitespace. If it is a number, - it will specify the number of spaces to indent at each - level. If it is a string (such as '\t' or ' '), - it contains the characters used to indent at each level. + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. - This method produces a JSON text from a JavaScript value. + This method produces a JSON text from a JavaScript value. - When an object value is found, if the object contains a toJSON - method, its toJSON method will be called and the result will be - stringified. A toJSON method does not serialize: it returns the - value represented by the name/value pair that should be serialized, - or undefined if nothing should be serialized. The toJSON method - will be passed the key associated with the value, and this will be - bound to the value + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value - For example, this would serialize Dates as ISO strings. + For example, this would serialize Dates as ISO strings. - Date.prototype.toJSON = function (key) { - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } - return this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z'; - }; + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; - You can provide an optional replacer method. It will be passed the - key and value of each member, with this bound to the containing - object. The value that is returned from your method will be - serialized. If your method returns undefined, then the member will - be excluded from the serialization. + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. - If the replacer parameter is an array of strings, then it will be - used to select the members to be serialized. It filters the results - such that only members with keys listed in the replacer array are - stringified. + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. - Values that do not have JSON representations, such as undefined or - functions, will not be serialized. Such values in objects will be - dropped; in arrays they will be replaced with null. You can use - a replacer function to replace those with JSON values. - JSON.stringify(undefined) returns undefined. + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. - The optional space parameter produces a stringification of the - value that is filled with line breaks and indentation to make it - easier to read. + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. - If the space parameter is a non-empty string, then that string will - be used for indentation. If the space parameter is a number, then - the indentation will be that many spaces. + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. - Example: + Example: - text = JSON.stringify(['e', {pluribus: 'unum'}]); - // text is '["e",{"pluribus":"unum"}]' + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' - text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); - // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' - text = JSON.stringify([new Date()], function (key, value) { - return this[key] instanceof Date ? - 'Date(' + this[key] + ')' : value; - }); - // text is '["Date(---current time---)"]' + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' - JSON.parse(text, reviver) - This method parses a JSON text to produce an object or array. - It can throw a SyntaxError exception. + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. - The optional reviver parameter is a function that can filter and - transform the results. It receives each of the keys and values, - and its return value is used instead of the original value. - If it returns what it received, then the structure is not modified. - If it returns undefined then the member is deleted. + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. - Example: + Example: - // Parse the text. Values that look like ISO date strings will - // be converted to Date objects. + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. - myData = JSON.parse(text, function (key, value) { - var a; - if (typeof value === 'string') { - a = -/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); - if (a) { - return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], - +a[5], +a[6])); - } - } - return value; - }); + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); - myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { - var d; - if (typeof value === 'string' && - value.slice(0, 5) === 'Date(' && - value.slice(-1) === ')') { - d = new Date(value.slice(5, -1)); - if (d) { - return d; - } - } - return value; - }); + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); - This is a reference implementation. You are free to copy, modify, or - redistribute. -*/ + This is a reference implementation. You are free to copy, modify, or + redistribute. + */ /*jslint evil: true, strict: false, regexp: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, - call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, - getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, - lastIndex, length, parse, prototype, push, replace, slice, stringify, - test, toJSON, toString, valueOf -*/ + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf + */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON; -if (!JSON) { - JSON = {}; +if ( !JSON ) { + JSON = {}; } (function () { - "use strict"; + "use strict"; - function f(n) { - // Format integers to have at least two digits. - return n < 10 ? '0' + n : n; - } + function f( n ) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } - if (typeof Date.prototype.toJSON !== 'function') { + if ( typeof Date.prototype.toJSON !== 'function' ) { - Date.prototype.toJSON = function (key) { + Date.prototype.toJSON = function ( key ) { - return isFinite(this.valueOf()) ? - this.getUTCFullYear() + '-' + - f(this.getUTCMonth() + 1) + '-' + - f(this.getUTCDate()) + 'T' + - f(this.getUTCHours()) + ':' + - f(this.getUTCMinutes()) + ':' + - f(this.getUTCSeconds()) + 'Z' : null; - }; + return isFinite( this.valueOf() ) ? + this.getUTCFullYear() + '-' + + f( this.getUTCMonth() + 1 ) + '-' + + f( this.getUTCDate() ) + 'T' + + f( this.getUTCHours() ) + ':' + + f( this.getUTCMinutes() ) + ':' + + f( this.getUTCSeconds() ) + 'Z' : null; + }; - String.prototype.toJSON = - Number.prototype.toJSON = - Boolean.prototype.toJSON = function (key) { - return this.valueOf(); - }; - } + String.prototype.toJSON = + Number.prototype.toJSON = + Boolean.prototype.toJSON = function ( key ) { + return this.valueOf(); + }; + } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b' : '\\b', + '\t' : '\\t', + '\n' : '\\n', + '\f' : '\\f', + '\r' : '\\r', + '"' : '\\"', + '\\' : '\\\\' + }, + rep; - function quote(string) { + function quote( string ) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; - } + escapable.lastIndex = 0; + return escapable.test( string ) ? '"' + string.replace( escapable, function ( a ) { + var c = meta[a]; + return typeof c === 'string' ? c : + '\\u' + ('0000' + a.charCodeAt( 0 ).toString( 16 )).slice( -4 ); + } ) + '"' : '"' + string + '"'; + } - function str(key, holder) { + function str( key, holder ) { // Produce a string from holder[key]. - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } + if ( value && typeof value === 'object' && + typeof value.toJSON === 'function' ) { + value = value.toJSON( key ); + } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } + if ( typeof rep === 'function' ) { + value = rep.call( holder, key, value ); + } // What happens next depends on the value's type. - switch (typeof value) { - case 'string': - return quote(value); + switch ( typeof value ) { + case 'string': + return quote( value ); - case 'number': + case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. - return isFinite(value) ? String(value) : 'null'; + return isFinite( value ) ? String( value ) : 'null'; - case 'boolean': - case 'null': + case 'boolean': + case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. - return String(value); + return String( value ); // If the type is 'object', we might be dealing with an object or an array or // null. - case 'object': + case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. - if (!value) { - return 'null'; - } + if ( !value ) { + return 'null'; + } // Make an array to hold the partial results of stringifying this object value. - gap += indent; - partial = []; + gap += indent; + partial = []; // Is the value an array? - if (Object.prototype.toString.apply(value) === '[object Array]') { + if ( Object.prototype.toString.apply( value ) === '[object Array]' ) { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } + length = value.length; + for ( i = 0; i < length; i += 1 ) { + partial[i] = str( i, value ) || 'null'; + } // Join all of the elements together, separated with commas, and wrap them in // brackets. - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } + v = partial.length === 0 ? '[]' : gap ? + '[\n' + gap + partial.join( ',\n' + gap ) + '\n' + mind + ']' : + '[' + partial.join( ',' ) + ']'; + gap = mind; + return v; + } // If the replacer is an array, use it to select the members to be stringified. - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - if (typeof rep[i] === 'string') { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } else { + if ( rep && typeof rep === 'object' ) { + length = rep.length; + for ( i = 0; i < length; i += 1 ) { + if ( typeof rep[i] === 'string' ) { + k = rep[i]; + v = str( k, value ); + if ( v ) { + partial.push( quote( k ) + (gap ? ': ' : ':') + v ); + } + } + } + } else { // Otherwise, iterate through all of the keys in the object. - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } + for ( k in value ) { + if ( Object.prototype.hasOwnProperty.call( value, k ) ) { + v = str( k, value ); + if ( v ) { + partial.push( quote( k ) + (gap ? ': ' : ':') + v ); + } + } + } + } // Join all of the member texts together, separated with commas, // and wrap them in braces. - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } - } + v = partial.length === 0 ? '{}' : gap ? + '{\n' + gap + partial.join( ',\n' + gap ) + '\n' + mind + '}' : + '{' + partial.join( ',' ) + '}'; + gap = mind; + return v; + } + } // If the JSON object does not yet have a stringify method, give it one. - if (typeof JSON.stringify !== 'function') { - JSON.stringify = function (value, replacer, space) { + if ( typeof JSON.stringify !== 'function' ) { + JSON.stringify = function ( value, replacer, space ) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function @@ -15145,86 +20314,86 @@ if (!JSON) { // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. - var i; - gap = ''; - indent = ''; + var i; + gap = ''; + indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } + if ( typeof space === 'number' ) { + for ( i = 0; i < space; i += 1 ) { + indent += ' '; + } // If the space parameter is a string, it will be used as the indent string. - } else if (typeof space === 'string') { - indent = space; - } + } else if ( typeof space === 'string' ) { + indent = space; + } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. - rep = replacer; - if (replacer && typeof replacer !== 'function' && - (typeof replacer !== 'object' || - typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } + rep = replacer; + if ( replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number') ) { + throw new Error( 'JSON.stringify' ); + } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. - return str('', {'': value}); - }; - } + return str( '', {'' : value} ); + }; + } // If the JSON object does not yet have a parse method, give it one. - if (typeof JSON.parse !== 'function') { - JSON.parse = function (text, reviver) { + if ( typeof JSON.parse !== 'function' ) { + JSON.parse = function ( text, reviver ) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. - var j; + var j; - function walk(holder, key) { + function walk( holder, key ) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - } + var k, v, value = holder[key]; + if ( value && typeof value === 'object' ) { + for ( k in value ) { + if ( Object.prototype.hasOwnProperty.call( value, k ) ) { + v = walk( value, k ); + if ( v !== undefined ) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call( holder, key, value ); + } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. - text = String(text); - cx.lastIndex = 0; - if (cx.test(text)) { - text = text.replace(cx, function (a) { - return '\\u' + - ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }); - } + text = String( text ); + cx.lastIndex = 0; + if ( cx.test( text ) ) { + text = text.replace( cx, function ( a ) { + return '\\u' + + ('0000' + a.charCodeAt( 0 ).toString( 16 )).slice( -4 ); + } ); + } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' @@ -15239,214 +20408,202 @@ if (!JSON) { // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. - if (/^[\],:{}\s]*$/ - .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') - .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') - .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + if ( /^[\],:{}\s]*$/ + .test( text.replace( /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@' ) + .replace( /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']' ) + .replace( /(?:^|:|,)(?:\s*\[)+/g, '' ) ) ) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. - j = eval('(' + text + ')'); + j = eval( '(' + text + ')' ); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. - return typeof reviver === 'function' ? - walk({'': j}, '') : j; - } + return typeof reviver === 'function' ? + walk( {'' : j}, '' ) : j; + } // If the text is not JSON parseable, then a SyntaxError is thrown. - throw new SyntaxError('JSON.parse'); - }; - } + throw new SyntaxError( 'JSON.parse' ); + }; + } }()); - -jQuery.extend({ - - - createUploadIframe: function(id, uri) - { - //create frame - var frameId = 'jUploadFrame' + id; - var iframeHtml = '