-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathlocal.min.js
3 lines (3 loc) · 87.1 KB
/
local.min.js
1
2
3
!function e(t,r,n){function i(o,a){if(!r[o]){if(!t[o]){var c="function"==typeof require&&require;if(!a&&c)return c(o,!0);if(s)return s(o,!0);throw new Error("Cannot find module '"+o+"'")}var u=r[o]={exports:{}};t[o][0].call(u.exports,function(e){var r=t[o][1][e];return i(r?r:e)},u,u.exports,e,t,r,n)}return r[o].exports}for(var s="function"==typeof require&&require,o=0;o<n.length;o++)i(n[o]);return i}({1:[function(e,t){var r=["null","self","console","atob","btoa","setTimeout","clearTimeout","setInterval","clearInterval","Proxy","importScripts","navigator","postMessage","addEventListener","removeEventListener","onmessage","onerror","onclose","dispatchEvent"],n=["XMLHttpRequest","WebSocket","EventSource","Worker"],i=["(function() {","var nulleds=[];",'var whitelist = ["'+r.join('", "')+'"];',"for (var k in self) {","if (whitelist.indexOf(k) === -1) {","Object.defineProperty(self, k, { value: null, configurable: false, writable: false });","nulleds.push(k);","}","}",'var blacklist = ["'+n.join('", "')+'"];',"blacklist.forEach(function(k) {","Object.defineProperty(self, k, { value: null, configurable: false, writable: false });","nulleds.push(k);","});",'if (typeof console != "undefined") { console.log("Nullified: "+nulleds.join(", ")); }',"})();\n"].join(""),s=["(function() {","var orgImportScripts = importScripts;","function joinRelPath(base, relpath) {","if (relpath.charAt(0) == '/') {",'return "{{HOST}}" + relpath;',"}","// totally relative, oh god","// (thanks to geoff parker for this)",'var hostpath = "{{HOST_DIR_PATH}}";',"var hostpathParts = hostpath.split('/');","var relpathParts = relpath.split('/');","for (var i=0, ii=relpathParts.length; i < ii; i++) {","if (relpathParts[i] == '.')","continue; // noop","if (relpathParts[i] == '..')","hostpathParts.pop();","else","hostpathParts.push(relpathParts[i]);","}","return \"{{HOST}}/\" + hostpathParts.join('/');","}","var isImportingAllowed = true;","setTimeout(function() { isImportingAllowed = false; },0);","importScripts = function() {",'if (!isImportingAllowed) { throw "Local.js - Imports disabled after initial load to prevent data-leaking"; }',"return orgImportScripts.apply(null, Array.prototype.map.call(arguments, function(v, i) {","return (v.indexOf('/') < v.indexOf(/[.:]/) || v.charAt(0) == '/' || v.charAt(0) == '.') ? joinRelPath('{{HOST_DIR_URL}}',v) : v;","}));","};","})();\n"].join("\n");t.exports={logAllExceptions:!1,workerBootstrapScript:i+s}},{}],2:[function(e,t){t.exports={LINK_NOT_FOUND:1}},{}],3:[function(e,t){var r=e("./util");t.exports={Request:e("./web/request.js"),Response:e("./web/response.js"),Server:e("./web/server.js"),Relay:e("./web/relay.js"),BridgeServer:e("./web/bridge-server.js"),WorkerBridgeServer:e("./web/worker-bridge-server.js"),RTCBridgeServer:e("./web/rtc-bridge-server.js"),UriTemplate:e("./web/uri-template.js"),util:r,schemes:e("./web/schemes.js"),httpHeaders:e("./web/http-headers.js"),contentTypes:e("./web/content-types.js"),worker:e("./worker")},r.mixin.call(t.exports,e("./constants.js")),r.mixin.call(t.exports,e("./config.js")),r.mixin.call(t.exports,e("./promises.js")),r.mixin.call(t.exports,e("./spawners.js")),r.mixin.call(t.exports,e("./request-event.js")),r.mixin.call(t.exports,e("./web/helpers.js")),r.mixin.call(t.exports,e("./web/httpl.js")),r.mixin.call(t.exports,e("./web/dispatch.js")),r.mixin.call(t.exports,e("./web/subscribe.js")),r.mixin.call(t.exports,e("./web/agent.js")),"undefined"!=typeof window?window.local=t.exports:"undefined"!=typeof self?self.local=t.exports:local=t.exports,local.addServer("hosts",function(e,t){var r=local.getServers();if("HEAD"!=e.method&&"GET"!=e.method)return t.writeHead(405,"bad method").end();if("GET"==e.method&&!local.preferredType(e,"application/json"))return t.writeHead(406,"bad accept - only provides application/json").end();var n=[],i=[],s=[];s.push({href:"/",rel:"self service via",id:"hosts",title:"Page Hosts"});for(var o in r)"hosts"!=o&&(i.push(o),n.push(local.dispatch({method:"HEAD",url:"local://"+o,timeout:500})));local.promise.bundle(n).then(function(r){return r.forEach(function(e,t){var r=local.queryLinks(e,{rel:"self"})[0];r||(r={rel:"service",id:i[t],href:"local://"+i[t]}),r.rel=r.rel?r.rel.replace(/(^|\b)(self|up|via)(\b|$)/gi,""):"service",s.push(r)}),t.setHeader("link",s),"HEAD"==e.method?t.writeHead(204,"ok, no content").end():(t.writeHead(200,"ok",{"content-type":"application/json"}),t.end({host_names:i}),void 0)})})},{"./config.js":1,"./constants.js":2,"./promises.js":4,"./request-event.js":5,"./spawners.js":6,"./util":9,"./web/agent.js":10,"./web/bridge-server.js":11,"./web/content-types.js":12,"./web/dispatch.js":13,"./web/helpers.js":14,"./web/http-headers.js":15,"./web/httpl.js":16,"./web/relay.js":17,"./web/request.js":18,"./web/response.js":19,"./web/rtc-bridge-server.js":20,"./web/schemes.js":21,"./web/server.js":22,"./web/subscribe.js":23,"./web/uri-template.js":24,"./web/worker-bridge-server.js":25,"./worker":27}],4:[function(e,t){function r(e){return e&&"function"==typeof e.then}function n(e){this.succeedCBs=[],this.failCBs=[],this.__hasValue=!1,this.__hasFailed=!1,this.value=void 0,e&&this.fulfill(e)}function i(e,t,n){if(null===n)e.isRejected()?t.reject(e.value):t.fulfill(e.value);else{var i;try{i=n(e.value)}catch(s){return(u.logAllExceptions||s instanceof Error)&&(console.error?console.error(s,s.stack):console.log("Promise exception thrown",s,s.stack)),t.reject(s)}r(i)?c(i).chain(t):t.fulfill(i)}}function s(e,t){Array.isArray(e)||(e=[e]);var r=c(),n=e.length,i=0;if(0===n)return r.fulfill([]),r;var s=[];s.length=n;for(var o=[],a=function(e,a,c){s[a]=e,c&&o.push(a),++i==n&&(t?t(s,o)?r.fulfill(s):r.reject(s):r.fulfill(s))},u=0;n>u;u++)c(e[u]).succeed(a,u,!1).fail(a,u,!0);return r}function o(e){return s(e,function(e,t){return 0===t.length})}function a(e){return s(e,function(e,t){return t.length<e.length})}function c(e){if(arguments.length>1)return s(Array.prototype.slice.call(arguments));if(e instanceof n)return e;if(r(e)){var t=c();return e.then(function(e){t.fulfill(e)},function(e){t.reject(e)}),t}return new n(e)}var u=e("./config.js"),l=e("./util");n.prototype.isUnfulfilled=function(){return!this.__hasValue},n.prototype.isRejected=function(){return this.__hasFailed},n.prototype.isFulfilled=function(){return this.__hasValue&&!this.__hasFailed},n.prototype.then=function(e,t){e=e&&"function"==typeof e?e:null,t=t&&"function"==typeof t?t:null;var r=c();if(this.isUnfulfilled())this.succeedCBs.push({p:r,fn:e}),this.failCBs.push({p:r,fn:t});else{var n=this;l.nextTick(function(){n.isFulfilled()?i(n,r,e):i(n,r,t)})}return r},n.prototype.succeed=function(e){if(this.isRejected())return this;var t=Array.prototype.slice.call(arguments,1);return this.then(function(r){return e.apply(null,[r].concat(t))})},n.prototype.fail=function(e){if(this.isFulfilled())return this;var t=Array.prototype.slice.call(arguments,1);return this.then(null,function(r){return e.apply(null,[r].concat(t))})},n.prototype.always=function(e){return this.then(e,e)},n.prototype.fulfill=function(e){if(this.isUnfulfilled()){this.value=e,this.__hasValue=!0;for(var t=0;t<this.succeedCBs.length;t++){var r=this.succeedCBs[t];i(this,r.p,r.fn)}this.succeedCBs.length=0,this.failCBs.length=0}return this},n.prototype.reject=function(e){if(this.isUnfulfilled()){this.value=e,this.__hasValue=!0,this.__hasFailed=!0;for(var t=0;t<this.failCBs.length;t++){var r=this.failCBs[t];i(this,r.p,r.fn)}this.succeedCBs.length=0,this.failCBs.length=0}return this},n.prototype.cancel=function(){var e;for(e=0;e<this.succeedCBs.length;e++)this.succeedCBs[e].p.cancel();for(e=0;e<this.failCBs.length;e++)this.failCBs[e].p.cancel();return this.succeedCBs.length=0,this.failCBs.length=0,this},n.prototype.chain=function(e){return this.then(function(t){return c(e).fulfill(t),t},function(t){return c(e).reject(t),t}),e},n.prototype.cb=function(e,t){e?this.reject(e):this.fulfill("undefined"==typeof t?null:t)},t.exports={Promise:n,promise:c,isPromiselike:r},c.bundle=s,c.all=o,c.any=a},{"./config.js":1,"./util":9}],5:[function(e,t){function r(e,t){e.__localEventHandlers=[],t=t||{};var r;t.links!==!1&&(r={name:"click",handleEvent:i,container:e},e.addEventListener("click",r,!1),e.__localEventHandlers.push(r)),t.forms!==!1&&(r={name:"click",handleEvent:s,container:e},e.addEventListener("click",r,!0),e.__localEventHandlers.push(r),r={name:"submit",handleEvent:o,container:e},e.addEventListener("submit",r,!1),e.__localEventHandlers.push(r))}function n(e){e.__localEventHandlers&&(e.__localEventHandlers.forEach(function(t){e.removeEventListener(t.name,t)}),delete e.__localEventHandlers)}function i(e){if(0===e.button){var t=a.extractRequest.fromAnchor(e.orgtarget||e.target);if(!t||-1===["_top","_blank"].indexOf(t.target))return t?(e.preventDefault(),e.stopPropagation(),a.dispatchRequestEvent(e.target,t),!1):void 0}}function s(e){0===e.button&&a.trackFormSubmitter(e.target)}function o(e){var t=a.extractRequest(e.target,this.container);if(!t||-1===["_top","_blank"].indexOf(t.target))return t?(e.preventDefault(),e.stopPropagation(),a.finishPayloadFileReads(t).then(function(){a.dispatchRequestEvent(e.target,t)}),!1):void 0}var a=e("./util");t.exports={bindRequestEvents:r,unbindRequestEvents:n}},{"./util":9}],6:[function(e,t){function r(e,t,r){"function"==typeof t&&(r=t,t=null),t||(t={}),t.src=e,t.serverFn=r;var n=t.domain;if(!n)if(local.isAbsUri(e)){var a=i.parseUri(e);n=a.authority+"("+a.path.slice(1)+")"}else{var c=e.split(/[\?#]/);n=window.location.host+"("+c[0].slice(1)+")"}if(s.getServer(n))throw"Worker already exists";var u=new o(t);return s.addServer(n,u),u}function n(e,t,r){return"function"==typeof t&&(r=t,t=null),t||(t={}),t.provider=e,t.serverFn=r,new a(t)}var i=e("./web/helpers.js"),s=e("./web/httpl.js"),o=e("./web/worker-bridge-server.js"),a=e("./web/relay.js");t.exports={spawnWorkerServer:r,joinRelay:n}},{"./web/helpers.js":14,"./web/httpl.js":16,"./web/relay.js":17,"./web/worker-bridge-server.js":25}],7:[function(e,t){function r(e,t){for(;e;){if(t(e))return e;e=e.parentNode}return null}function n(){for(var e,t=Array.prototype.slice.call(arguments),r={};t.length;)if(e=t.shift())for(var i in e)"undefined"!=typeof e[i]&&null!==e[i]&&(r[i]="object"!=typeof e[i]||Array.isArray(e[i])?e[i]:n(r[i],e[i]));return r}function i(e,t){var r=new CustomEvent("request",{bubbles:!0,cancelable:!0,detail:t});e.dispatchEvent(r)}function s(e){var t=r.thatisFormRelated(e);if(t){for(var n=0;n<t.form.length;n++)t.form[n].setAttribute("submitter",null);t.setAttribute("submitter","1")}}function o(e,t){var i={form:{},elem:{}},s=null;if("FORM"===e.tagName)s=e;else{var c=e.getAttribute("form");c&&(s=t.querySelector("#"+c)),s||(s=r.byTag(e,"FORM"))}var u=a(e,s);s&&(i.form=o.fromForm(s,e)),"A"===e.tagName?i.elem=o.fromAnchor(e):-1===["FORM","FIELDSET"].indexOf(e.tagName)&&(i.elem=o.fromFormElement(e));var l=n(i.form,i.elem),h={};return h[/GET/i.test(l.method)?"query":"body"]=u,n(l,h)}function a(e,t,n){n||(n={});var i={};n.nofiles||(i.__fileReads=[]);for(var s=0;s<t.length;s++){var o=t[s];if(o.name&&(!e||r.byElement(o,e))){var a="1"==o.getAttribute("submitter");if("BUTTON"===o.tagName)a&&(i[o.name]=o.value);else if("INPUT"===o.tagName)switch(o.type.toLowerCase()){case"button":case"submit":a&&(i[o.name]=o.value);break;case"checkbox":o.checked&&(i[o.name]=(i[o.name]||[]).concat(o.value));break;case"radio":null!==o.getAttribute("checked")&&(i[o.name]=o.value);break;case"file":if(n.nofiles)break;if(o.multiple){for(var u,s=0;u=o.files[s];s++)c(i,o,o.files[s],s);i[o.name]=[],i[o.name].length=s}else c(i,o,o.files[0]);break;default:i[o.name]=o.value}else i[o.name]=o.value}}return i}function c(e,t,r,n){if(r){var i=new FileReader;i.onloadend=u(e,t,r,n),i.readAsDataURL(r)}}function u(t,r,n,i){var s=e("../promises.js").promise();return t.__fileReads.push(s),function(e){var t={content:e.target.result||null,name:n.name,formattr:r.name,size:n.size,type:n.type,lastModifiedDate:n.lastModifiedDate};"undefined"!=typeof i&&(t.formindex=i),s.fulfill(t)}}function l(t){var r=t.body?t.body.__fileReads:t.query?t.query.__fileReads:[];return e("../promises.js").promise.bundle(r).then(function(e){return t.body&&delete t.body.__fileReads,t.query&&delete t.query.__fileReads,e.forEach(function(e){"undefined"!=typeof e.formindex?t.body[e.formattr][e.formindex]=e:t.body[e.formattr]=e}),t})}"undefined"==typeof CustomEvent&&(CustomEvent=function(e,t){var r=document.createEvent("CustomEvent");return r.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),r}),r.byTag=function(e,t){return r(e,function(e){return e.tagName==t})},r.byTagOrAlias=function(e,t){return r(e,function(e){return e.tagName==t||e.dataset&&e.dataset.localAlias&&e.dataset.localAlias.toUpperCase()==t})},r.byClass=function(e,t){return r(e,function(e){return e.classList&&e.classList.contains(t)})},r.byElement=function(e,t){return r(e,function(e){return e===t})},r.thatisFormRelated=function(e){return r(e,function(e){return!!e.form})},o.fromAnchor=function(e){if(e=r.byTagOrAlias(e,"A"),!e||!e.attributes.href||"#"==e.attributes.href.value.charAt(0))return null;var t={method:e.getAttribute("method"),url:e.attributes.href.value,target:e.getAttribute("target"),headers:{accept:e.getAttribute("type")}};return t},o.fromFormElement=function(e){var t={method:e.getAttribute("formmethod"),url:e.getAttribute("formaction"),target:e.getAttribute("formtarget"),headers:{"content-type":e.getAttribute("formenctype"),accept:e.getAttribute("formaccept")}};return t},o.fromForm=function(e,t){if(t&&!t.form)for(var i=0;i<e.length;i++){var s=e[i];if("1"==s.getAttribute("submitter")){t=s,s.setAttribute("submitter","0");break}}var a={submitter:{},fieldset:{},form:{}};if(t){a.submitter={method:t.getAttribute("formmethod"),url:t.getAttribute("formaction"),target:t.getAttribute("formtarget"),headers:{"content-type":t.getAttribute("formenctype"),accept:t.getAttribute("formaccept")}};for(var c=t,u=function(e){return"FIELDSET"==e.tagName||"FORM"==e.tagName};(c=r(c.parentNode,u))&&"FORM"!=c.tagName;)c&&(a.fieldset=n(o.fromFormElement(c),a.fieldset))}a.form={method:e.getAttribute("method"),url:e.getAttribute("action"),target:e.getAttribute("target"),headers:{"content-type":e.getAttribute("enctype")||e.enctype,accept:e.getAttribute("accept")}},e.acceptCharset&&(a.form.headers.accept=e.acceptCharset);var l=n(a.form,a.fieldset,a.submitter);return l},t.exports={findParentNode:r,trackFormSubmitter:s,dispatchRequestEvent:i,extractRequest:o,extractRequestPayload:a,finishPayloadFileReads:l}},{"../promises.js":4}],8:[function(e,t){function r(){Object.defineProperty(this,"_events",{value:{},configurable:!1,enumerable:!1,writable:!0}),Object.defineProperty(this,"_suspensions",{value:0,configurable:!1,enumerable:!1,writable:!0}),Object.defineProperty(this,"_history",{value:[],configurable:!1,enumerable:!1,writable:!0})}t.exports=r,r.prototype.suspendEvents=function(){this._suspensions++},r.prototype.resumeEvents=function(){this._suspensions--,this._suspensions<=0&&this.playbackHistory()},r.prototype.isSuspended=function(){return this._suspensions>0},r.prototype.playbackHistory=function(){for(var e;!this.isSuspended()&&(e=this._history.shift());)this.emit.apply(this,e)},r.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments);if(this.isSuspended())return this._history.push(t),void 0;var r=this._events[e];if(!r)return!1;t=t.slice(1);for(var n=0,i=r.length;i>n;n++)r[n].apply(this,t);return!0},r.prototype.addListener=function(e,t){if(Array.isArray(e))return e.forEach(function(e){this.addListener(e,t)},this),void 0;if("function"!=typeof t)throw new Error("addListener only takes instances of Function");return this.emit("newListener",e,t),this._events[e]?this._events[e].push(t):this._events[e]=[t],this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){var r=this;return r.on(e,function n(){r.removeListener(e,n),t.apply(this,arguments)}),this},r.prototype.removeListener=function(e,t){if("function"!=typeof t)throw new Error("removeListener only takes instances of Function");if(!this._events[e])return this;var r=this._events[e],n=r.indexOf(t);return 0>n?this:(r.splice(n,1),0===r.length&&delete this._events[e],this)},r.prototype.removeAllListeners=function(e){return e?this._events[e]=null:this._events={},this._history[e]&&(this._history[e]=null),this},r.prototype.listeners=function(e){return this._events[e]}},{}],9:[function(e,t){function r(e){for(var t in e)this[t]=e[t]}function n(e){o.call(e),r.call(e,o.prototype)}function i(e){return JSON.parse(JSON.stringify(e))}var s,o=e("./event-emitter.js"),a=e("./dom.js");if("undefined"==typeof window||window.ActiveXObject||!window.postMessage)s=function(e){setTimeout(e,0)};else{var c=0,u={};s=function(e){if("function"!=typeof e)throw"Invalid function provided to nextTick";window.postMessage("nextTick"+c,"*"),u["nextTick"+c]=e,c++},window.addEventListener("message",function(e){var t=u[e.data];t&&(delete u[e.data],t())},!0)}t.exports={EventEmitter:o,mixin:r,mixinEventEmitter:n,deepClone:i,nextTick:s},r.call(t.exports,a)},{"./dom.js":7,"./event-emitter.js":8}],10:[function(e,t){function r(e){this.query=e,this.resolveState=r.UNRESOLVED,this.error=null,this.queryIsAbsolute="string"==typeof e&&l.isAbsUri(e),this.queryIsAbsolute?(this.url=e,this.urld=l.parseUri(this.url)):(this.url=null,this.urld=null)}function n(e,t){this.context=e||null,this.parentAgent=t||null,this.links=null,this.proxyTmpl=null,this.requestDefaults=null}function i(e,t){for(var r in t)"headers"==r||e[r]||(e[r]="object"==typeof t[r]?c.deepClone(t[r]):t[r]);t.headers&&(e.headers||(e.headers={}),i(e.headers,t.headers))}function s(e){return function(t){var r=t||{};return r.method=e,this.dispatch(r)}}function o(e){return function(t,r){var n=r||{};return n.method=e,n.body=t,this.dispatch(n)}}var a=e("../constants.js"),c=e("../util"),u=e("../promises.js").promise,l=e("./helpers.js"),h=e("./uri-template.js"),f=e("./httpl.js"),p=e("./request.js"),d=e("./response.js"),g=e("./dispatch.js").dispatch,y=e("./subscribe.js").subscribe;r.UNRESOLVED=0,r.RESOLVED=1,r.FAILED=2,r.prototype.isResolved=function(){return this.resolveState===r.RESOLVED},r.prototype.isBad=function(){return this.resolveState===r.FAILED},r.prototype.isRelative=function(){return!this.queryIsAbsolute},r.prototype.isAbsolute=function(){return this.queryIsAbsolute},r.prototype.getUrl=function(){return this.url},r.prototype.getError=function(){return this.error},r.prototype.resetResolvedState=function(){this.resolveState=r.UNRESOLVED,this.error=null},r.prototype.setResolved=function(e){this.error=null,this.resolveState=r.RESOLVED,e&&(this.url=e,this.urld=l.parseUri(this.url))},r.prototype.setFailed=function(e){this.error=e,this.resolveState=r.FAILED},n.prototype.setRequestDefaults=function(e){this.requestDefaults=e},n.prototype.dispatch=function(e){e||(e={}),e.headers||(e.headers={});var t=this;return this.requestDefaults&&i(e,this.requestDefaults),e instanceof p&&e.suspendEvents(),(e.url?u(e.url):this.resolve({noretry:e.noretry,nohead:!0})).succeed(function(t){e.url=t;var r=g(e);return e instanceof p&&e.resumeEvents(),r}).succeed(function(e){return t.context.setResolved(),t.links=e.parsedHeaders.link?e.parsedHeaders.link:t.links||[],t.proxyTmpl=e.header("Proxy-Tmpl")?e.header("Proxy-Tmpl").split(" "):null,e}).fail(function(e){throw(e.status===a.LINK_NOT_FOUND||404===e.status)&&t.context.setFailed(e),e})},n.prototype.subscribe=function(e){var t,r=this;return e||(e={}),this.resolve({nohead:!0}).succeed(function(n){return e.url=n,r.requestDefaults&&i(e,r.requestDefaults),t=y(e),t.response_}).then(function(){return t})},n.prototype.follow=function(e){"string"==typeof e&&l.isNavSchemeUri(e)&&(e=l.parseNavUri(e)),Array.isArray(e)||(e=[e]);var t=this;do t=new n(new r(e.shift()),t),this.requestDefaults&&t.setRequestDefaults(this.requestDefaults);while(e[0]);return t},n.prototype.unresolve=function(){return this.context.resetResolvedState(),this.links=null,this.proxyTmpl=null,this},n.prototype.rebase=function(e){return this.unresolve(),this.context.query=e,this.context.queryIsAbsolute=!0,this.context.url=e,this.context.urld=l.parseUri(e),this},n.prototype.resolve=function(e){var t=this;e=e||{};var n=e.nohead;delete e.nohead;var i=u();if(null!==this.links&&(this.context.isResolved()||this.context.isAbsolute()&&this.context.isBad()===!1))i.fulfill(this.context.getUrl());else if(this.context.isBad()===!1||this.context.isBad()&&!e.noretry){if(this.context.resetResolvedState(),this.context.isRelative()&&!this.parentAgent){if("string"!=typeof this.context.query||!f.getServer(this.context.query))return t.context.setFailed({status:404,reason:"not found"}),i.reject(this.context.getError()),i;t.context=new r(t.context.query)}this.context.isRelative()?i=this.parentAgent.resolve(e).succeed(function(){var e=t.parentAgent.lookupLink(t.context);if(e)return t.context.setResolved(e),n?e:t.dispatch({method:"HEAD",url:e}).succeed(function(){return e});var r=new d;throw r.writeHead(a.LINK_NOT_FOUND,"Link Query Failed to Match").end(),r}).fail(function(e){throw t.context.setFailed(e),e}):n?i.fulfill(t.context.getUrl()):i=this.dispatch({method:"HEAD",url:t.context.getUrl()}).succeed(function(){return t.context.getUrl()})}else i.reject(this.context.getError());return i},n.prototype.lookupLink=function(e){if(e.query)if("object"==typeof e.query){var t=l.queryLinks(this.links,e.query)[0];if(t){var r=h.parse(t.href).expand(e.query);return this.proxyTmpl&&!t.noproxy&&(r=l.makeProxyUri(r,this.proxyTmpl)),r}}else if("string"==typeof e.query)return l.isAbsUri(e.query)?e.query:l.joinRelPath(this.context.urld,e.query);return console.log("Failed to find a link to resolve context. Link query:",e.query,"Agent:",this),null},n.prototype.SUBSCRIBE=s("SUBSCRIBE"),n.prototype.HEAD=n.prototype.head=s("HEAD"),n.prototype.GET=n.prototype.get=s("GET"),n.prototype.DELETE=n.prototype.delete=s("DELETE"),n.prototype.POST=n.prototype.post=o("POST"),n.prototype.PUT=n.prototype.put=o("PUT"),n.prototype.PATCH=n.prototype.patch=o("PATCH"),n.prototype.NOTIFY=n.prototype.notify=o("NOTIFY");var m=function(e){if(e instanceof n)return e;"string"==typeof e&&l.isNavSchemeUri(e)&&(e=l.parseNavUri(e)),Array.isArray(e)||(e=[e]);for(var t=new n(new r(e.shift()));e[0];)t=new n(new r(e.shift()),t);return t};t.exports={Agent:n,agent:m}},{"../constants.js":2,"../promises.js":4,"../util":9,"./dispatch.js":13,"./helpers.js":14,"./httpl.js":16,"./request.js":18,"./response.js":19,"./subscribe.js":23,"./uri-template.js":24}],11:[function(e,t){function r(e){a.call(this,e),this.sidCounter=1,this.incomingStreams={},this.incomingStreamsBuffer={},this.outgoingStreams={},this.msgBuffer=[],this.isReorderingMessages=!1}function n(e){return""===e?!1:(e=e.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""),/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(e))}function i(e){return e?isNaN(e.sid)?!1:!0:!1}var s=e("./request.js"),o=e("./response.js"),a=e("./server.js"),c=e("./content-types.js");r.prototype=Object.create(a.prototype),t.exports=r,r.prototype.useMessageReordering=function(e){this.debugLog("turning "+(e?"on":"off")+" reordering"),this.isReorderingMessages=!!e},r.prototype.isChannelActive=function(){return console.warn("isChannelActive not defined",this),!1},r.prototype.channelSendMsg=function(e){console.warn("channelSendMsg not defined",this,e)},r.prototype.handleRemoteRequest=function(e,t){console.warn("handleRemoteRequest not defined",this),t.writeHead(501,"server not implemented"),t.end()},r.prototype.flushBufferedMessages=function(){this.debugLog("FLUSHING MESSAGES",this,JSON.stringify(this.msgBuffer)),this.msgBuffer.forEach(function(e){this.channelSendMsg(e)},this),this.msgBuffer.length=0},r.prototype.channelSendMsgWhenReady=function(e){this.isChannelActive()?this.channelSendMsg(e):this.msgBuffer.push(e)},r.prototype.handleLocalRequest=function(e,t){var r=this.sidCounter++,n=c.serialize("application/x-www-form-urlencoded",e.query),i={sid:r,mid:this.isReorderingMessages?1:void 0,method:e.method,path:e.path+(n?"?"+n:""),headers:e.headers};this.outgoingStreams[i.sid]=e,this.incomingStreams[-i.sid]=t,this.channelSendMsgWhenReady(JSON.stringify(i));var s=this,o=i.mid;e.on("data",function(e){s.channelSendMsgWhenReady(JSON.stringify({sid:r,mid:o?++o:void 0,body:e}))}),e.on("end",function(){s.channelSendMsgWhenReady(JSON.stringify({sid:r,mid:o?++o:void 0,end:!0}))}),e.on("close",function(){s.channelSendMsgWhenReady(JSON.stringify({sid:r,mid:o?++o:void 0,close:!0})),delete s.outgoingStreams[i.sid]})},r.prototype.terminate=function(e,t){e=e||503,t=t||"Service Unavailable",a.prototype.terminate.call(this);for(var r in this.incomingStreams)this.incomingStreams[r]instanceof o&&!this.incomingStreams[r].status&&this.incomingStreams[r].writeHead(e,t),this.incomingStreams[r].end();for(r in this.outgoingStreams)this.outgoingStreams[r]instanceof o&&!this.outgoingStreams[r].status&&this.outgoingStreams[r].writeHead(e,t),this.outgoingStreams[r].end();this.incomingStreams={},this.outgoingStreams={}},r.prototype.onChannelMessage=function(e){if("string"==typeof e){if(!n(e))return console.warn("Dropping malformed HTTPL message",e,this),void 0;e=JSON.parse(e)}if(!i(e))return console.warn("Dropping malformed HTTPL message",e,this),void 0;if(e.mid&&(this.incomingStreamsBuffer[e.sid]||(this.incomingStreamsBuffer[e.sid]={nextMid:1,cache:{}}),this.incomingStreamsBuffer[e.sid].nextMid!=e.mid))return this.incomingStreamsBuffer[e.sid].cache[e.mid]=e,void 0;var t=this.incomingStreams[e.sid];if(!t){if(!(e.sid>0))return console.warn("Dropping unexpected HTTPL response message",e,this),void 0;var r=null,a=(e.path||"").split("?");e.path=a[0],a[1]&&(r=c.deserialize("application/x-www-form-urlencoded",a[1]));var u=new s({method:e.method,path:e.path,query:r,headers:e.headers});u.deserializeHeaders();var l=new o;u.on("close",function(){l.close()});var h=this,f=-e.sid,p=this.isReorderingMessages?1:void 0;l.on("headers",function(){h.channelSendMsg(JSON.stringify({sid:f,mid:p?p++:void 0,status:l.status,reason:l.reason,headers:l.headers}))}),l.on("data",function(e){h.channelSendMsg(JSON.stringify({sid:f,mid:p?p++:void 0,body:e}))}),l.on("end",function(){h.channelSendMsg(JSON.stringify({sid:f,mid:p?p++:void 0,end:!0}))}),l.on("close",function(){h.channelSendMsg(JSON.stringify({sid:f,mid:p?p++:void 0,close:!0})),delete h.outgoingStreams[f]}),t=this.incomingStreams[e.sid]=u,this.outgoingStreams[f]=l,this.handleRemoteRequest(u,l)}if(e.sid<0&&"undefined"!=typeof e.status&&t.writeHead(e.status,e.reason,e.headers),e.body&&t.write(e.body),e.end&&t.end(),e.close)return t.close(),delete this.incomingStreams[e.sid],delete this.incomingStreamsBuffer[e.sid],void 0;if(e.mid){var d=++this.incomingStreamsBuffer[e.sid].nextMid;if(this.incomingStreamsBuffer[e.sid].cache[d]){var g=this.incomingStreamsBuffer[e.sid].cache[d];delete this.incomingStreamsBuffer[e.sid].cache[d],this.onChannelMessage(g)}}}},{"./content-types.js":12,"./request.js":18,"./response.js":19,"./server.js":22}],12:[function(e,t){function r(e,t){if(!t||"object"!=typeof t||!e)return t;var r=o(e,"serializer");return r?r(t):t}function n(e,t){if(!t||"string"!=typeof t||!e)return t;var r=o(e,"deserializer");if(!r)return t;try{return r(t)}catch(n){return console.warn("Failed to deserialize content",e,t),t}}function i(e,t,r){u[e]={serializer:t,deserializer:r}}function s(e){var t=e.split(";"),r=t[0];if(t=r.split("/"),t[1]){var n=t[1].split("+");return n[1]?[r,t[0]+"/"+n[1],t[0]]:[r,t[0]]}return[r]}function o(e,t){for(var r=s(e),n=0;n<r.length;n++)if(r[n]in u)return u[r[n]][t];return null}function a(e){var t=e.indexOf(":");return[e.slice(0,t).trim(),e.slice(t+1).trim()]}var c={serialize:r,deserialize:n,register:i},u={};t.exports=c,c.register("application/json",function(e){try{return JSON.stringify(e)}catch(t){return t.message}},function(e){try{return JSON.parse(e)}catch(t){return t.message}}),c.register("application/x-www-form-urlencoded",function(e){var t=encodeURIComponent,r=[];for(var n in e)if(null===e[n])r.push(n+"=");else if(Array.isArray(e[n]))for(var i=0;i<e[n].length;i++)r.push(n+"[]="+t(e[n][i]));else if("object"==typeof e[n])for(var s in e[n])r.push(n+"["+s+"]="+t(e[n][s]));else r.push(n+"="+t(e[n]));return r.join("&")},function(e){for(var t=e.split("&"),r={},n=0;n<t.length;n++){var i=t[n].split("="),s=decodeURIComponent(i[0]),o=decodeURIComponent(i[1]),a=/\[\]$/.test(s),c=s.match(/^(.+)\[([^\]]+)\]$/);if("true"===o?o=!0:"false"===o?o=!1:+o==o&&(o=+o),c){s=c[1];var u=c[2];r[s]=r[s]||{},r[s][u]=o}else a?(s=s.substring(0,s.length-2),r[s]=r[s]||[],r[s].push(o)):r[s]=o}return r}),c.register("text/event-stream",function(e){var t="";return"undefined"!=typeof e.event&&(t+="event: "+e.event+"\r\n"),"undefined"!=typeof e.data&&(t+="data: "+JSON.stringify(e.data)+"\r\n"),t+"\r\n"},function(e){var t={};if(e.split("\r\n").forEach(function(e){/^[\s]*$/.test(e)||(e=a(e),e[0]&&(t[e[0]]=e[1]))}),t.data)try{t.data=JSON.parse(t.data)}catch(r){}return t})},{}],13:[function(e,t){function r(t){if(!t)throw new Error("No request provided to dispatch()");"string"==typeof t&&(t={url:t});var r=null,i=!1;if(!(t instanceof f)){i=!0;var o=t.timeout;t=new f(t),o&&t.setTimeout(o),r=t.body,t.body=""}if(!t.url)throw new Error("No url on request");var a=s(t.url);if("nav"==a){var g=new f(t),y=g.url;delete g.url;var m=e("./agent.js").agent(y).dispatch(g);return t.on("data",g.write.bind(g)),t.on("end",g.end.bind(g)),i&&t.end(r),m}if(Object.defineProperty(t,"urld",{value:l.parseUri(t.url),configurable:!0,enumerable:!1,writable:!0}),t.urld.query){var v=d.deserialize("application/x-www-form-urlencoded",t.urld.query);for(var b in v)t.query[b]=v[b];t.urld.relative=t.urld.path+(t.urld.anchor?"#"+t.urld.anchor:""),t.url=a+"://"+t.urld.authority+t.urld.relative}t.serializeHeaders();var w,E=new p,m=e("../promises.js").promise();t.on("close",function(){E.close()}),E.on("headers",function(){E.deserializeHeaders(),E.processHeaders(t)}),E.on("close",function(){E.latency=Date.now()-w,t.close()}),t.stream?E.on("headers",function(e){n(m,e)}):E.on("close",function(){n(m,E)}),t.suspendEvents(),E.suspendEvents();var j=function(e,t,n){return w=Date.now(),n=n||h.get(a),n?(n(e,t),e.resumeEvents(),t.resumeEvents(),i&&e.end(r)):(t.writeHead(0,'unsupported scheme "'+a+'"'),t.end(),e.resumeEvents(),t.resumeEvents()),m},S=Array.prototype.slice.call(arguments,1);return S.unshift(j),S.unshift(E),S.unshift(t),u.nextTick(function(){c.apply(null,S)}),m.request=t,m}function n(e,t){t.status>=200&&t.status<400?e.fulfill(t):t.status>=400&&t.status<600||0===t.status?e.reject(t):e.fulfill(t)}function i(e){c=e}function s(e){var t=/^([^.^:]*):/.exec(e);return t?t[1]:0===e.indexOf("//")?"http":0===e.indexOf("||")?"nav":"httpl"}function o(e){return function(t){var n=t||{};return"string"==typeof n&&(n={url:n}),n.method=e,r(n)}}function a(e){return function(t,n){var i=n||{};return"string"==typeof i&&(i={url:i}),i.method=e,i.body=t,r(i)}}var c,u=e("../util"),l=e("./helpers.js"),h=e("./schemes.js"),f=e("./request.js"),p=e("./response.js"),d=e("./content-types.js");i(function(e,t,r){r(e,t)}),t.exports={dispatch:r,fulfillResponsePromise:n,setDispatchWrapper:i,SUBSCRIBE:o("SUBSCRIBE"),HEAD:o("HEAD"),GET:o("GET"),DELETE:o("DELETE"),POST:a("POST"),PUT:a("PUT"),PATCH:a("PATCH"),NOTIFY:a("NOTIFY")}},{"../promises.js":4,"../util":9,"./agent.js":10,"./content-types.js":12,"./helpers.js":14,"./request.js":18,"./response.js":19,"./schemes.js":21}],14:[function(e,t){function r(e,t){t||(t={}),"undefined"==typeof t.links&&(t.links=!0);var r=[];return t.links&&(r=r.concat(Array.prototype.slice.call(e.querySelectorAll("link")))),t.anchors&&(r=r.concat(Array.prototype.slice.call(e.querySelectorAll("a")))),r.map(function(e){for(var t={},r=0;r<e.attributes.length;r++)t[e.attributes[r].name]=e.attributes[r].value;return t})}function n(e,t){return e?(e instanceof Document&&(e=r(e)),e.parsedHeaders&&(e=e.parsedHeaders.link),Array.isArray(e)?e.filter(function(e){return i(e,t)}):[]):[]}function i(e,t){for(var r in t)if("function"==typeof t[r]){if(!t[r].call(null,e[r],r))return!1
}else if("rel"==r)for(var n=t.rel.split(/\s+/),i=0;i<n.length;i++){var s=!0;if("!"==n[i].charAt(0)&&(n[i]=n[i].slice(1),s=!1),RegExp("(\\s|^)(.*//)?"+n[i]+"(\\s|$)","i").test(e.rel)!==s)return!1}else if("undefined"==typeof e[r]){if(RegExp(C+r+T,"i").test(e.href)===!0)continue;if(t[r])return!1}else if(t[r]&&t[r].indexOf&&0===t[r].indexOf("!")){if(e[r]==t[r].slice(1))return!1}else if(e[r]!=t[r])return!1;return!0}function s(e,t){var r=t.filter(function(t){return a(e,t)}).sort(function(e,t){return e.q>t.q?-1:1});return r[0]?r[0].q:0}function o(e,t){return"*"===e||e===t}function a(e,t){var r=c(e);if(t.params){var n=Object.keys(t.params);if(n.some(function(e){return!o(t.params[e],r.params[e])}))return null}return o(t.type,r.type)&&o(t.subtype,r.subtype)?t:void 0}function c(e){var t=e.match(/\s*(\S+)\/([^;\s]+)\s*(?:;(.*))?/);if(!t)return null;var r=t[1],n=t[2],i=""+r+"/"+n,s={},o=1;return t[3]&&(s=t[3].split(";").map(function(e){return e.trim().split("=")}).reduce(function(e,t){return e[t[0]]=t[1],e},s),null!==s.q&&(o=parseFloat(s.q),delete s.q)),{type:r,subtype:n,params:s,q:o,full:i}}function u(e){return e.split(",").map(function(e){return c(e.trim())}).filter(function(e){return e&&e.q>0})}function l(e,t){return"object"==typeof e&&(e=e.headers.accept),e=u(e||""),t?(Array.isArray(t)||(t=[t]),t.map(function(t){return[t,s(t,e)]}).filter(function(e){return e[1]>0}).sort(function(e,t){return e[1]===t[1]?0:e[1]>t[1]?-1:1}).map(function(e){return e[0]})):e.map(function(e){return e.full})}function h(e,t){return l(e,t)[0]}function f(){var e=Array.prototype.map.call(arguments,function(e,t){e=""+e;var r=0,n=e.length;return"/"==e?"":(0!==t&&"/"===e.charAt(0)&&(r+=1),"/"===e.charAt(n-1)&&(n-=1),e.substring(r,n))});return e.join("/")}function p(t){if(R.test(t))return!0;var r=y(t);return!!e("./httpl.js").getServer(r.authority)||!!v(r.authority)}function d(e){return A.test(e)}function g(e,t){"string"==typeof e&&(e=y(e));var r=e.protocol?e.protocol+"://":!1;if(r||(r=0===e.source.indexOf("//")?"//":0===e.source.indexOf("||")?"||":"local://"),"/"==t.charAt(0))return r+e.authority+t;for(var n=e.path,i=n.split("/"),s=t.split("/"),o=0,a=s.length;a>o;o++)"."!=s[o]&&(".."==s[o]?i.pop():i.push(s[o]));return f(r+e.authority,i.join("/"))}function y(e){if("object"==typeof e&&(e.url?e=e.url:(e.headers&&e.headers.host||e.path)&&(e=f(e.headers.host,e.path))),"data:"==e.slice(0,5))return{protocol:"data",source:e};if(-1!==e.indexOf("!")){var t=e.indexOf("//"),r=e.indexOf("/",t+2),n=e.slice(-1!==t?t+2:0,-1!==r?r:e.length),i=v(n);if(i){var s={};return-1!==r&&e.slice(r)&&(s=y(e.slice(r))),s.protocol="local",s.host=s.authority=n,s.port=s.password=s.user=s.userInfo="",s.source=e,s}}for(var o=y.options,a=o.parser[o.strictMode?"strict":"loose"].exec(e),c={},u=15;u--;)c[o.key[u]]=a[u]||"";return c[o.q.name]={},c[o.key[13]].replace(o.q.parser,function(e,t,r){t&&(c[o.q.name][t]=r)}),c}function m(e){if(!e)return[];var t=e.indexOf("||");-1!==t&&(e=e.slice(t+2));for(var r=e.split("|"),n=1;n<r.length;n++){for(var i={},s=r[n].split(","),o=0;o<s.length;o++){var a=s[o].split("=");0===o?(i.rel=a[0].replace(/\+/g," "),a[1]&&(i.id=a[1])):i[a[0]]=decodeURIComponent(a[1]).replace(/\+/g," ")}r[n]=i}return r.length>6&&(r.length=6),r[0]||r.shift(),r}function v(e){var t=O.exec(e);return t?{domain:e,user:t[1],relay:t[2],provider:t[2],app:t[3],stream:t[4]||0,sid:t[4]||0}:null}function b(e,t,r,n){return e+"@"+t+"!"+r+(n?"!"+n:"")}function w(e,t){Array.isArray(t)||(t=[t]);for(var r=t.length-1;r>=0;r--){var n=t[r];e=x.parse(n).expand({uri:e})}return e}function E(e,t,r,n){return r=r||function(e){return e},n=n||function(e){return e},S(t).always(function(t){return e.status||e.writeHead(t.status,t.reason,r(t.headers)),null!==t.body&&"undefined"!=typeof t.body&&e.write(n(t.body)),t.on&&t.isConnOpen?(t.on("data",function(t){e.write(n(t))}),t.on("end",function(){e.end()})):e.end(),e})}function j(){function t(){}var r=XMLHttpRequest;XMLHttpRequest.prototype,(window||self).XMLHttpRequest=t,t.UNSENT=0,t.OPENED=1,t.HEADERS_RECEIVED=2,t.LOADING=4,t.DONE=4,t.prototype.open=function(t,n,i,s,o){var a=y(n);if("httpl"!=a.protocol&&"local"!=a.protocol)return Object.defineProperty(this,"__xhr_request",{value:new r}),this.__xhr_request.open(t,n,i,s,o);var c=e("./request.js");Object.defineProperty(this,"__local_request",{value:new c({method:t,url:n,stream:!0})}),s&&this.__local_request.setHeader("Authorization","Basic "+btoa(s+":"+o)),this.readyState=1,this.onreadystatechange&&this.onreadystatechange()},t.prototype.send=function(t){var r=this;if(!this.__local_request)return this.__xhr_request.onreadystatechange=function(){for(var e in this)"function"!=typeof this[e]&&(r[e]=this[e]);r.onreadystatechange&&r.onreadystatechange()},this.__xhr_request.send(t);var n=e("./dispatch.js").dispatch(this.__local_request);this.__local_request.end(t),n.always(function(e){Object.defineProperty(r,"__local_response",{value:e}),r.readyState=2,r.status=e.status,r.statusText=e.status+" "+e.reason,r.responseText=null,r.onreadystatechange&&r.onreadystatechange(),e.on("data",function(e){r.readyState=3,null===r.responseText&&"string"==typeof e&&(r.responseText=""),r.responseText+=e,r.onreadystatechange&&r.onreadystatechange()}),e.on("end",function(){switch(r.readyState=4,r.responseType){case"json":r.response=e.body;break;case"text":default:r.response=r.responseText}r.onreadystatechange&&r.onreadystatechange(),r.onload&&r.onload()})})},t.prototype.abort=function(){return this.__local_request?this.__local_request.close():this.__xhr_request.abort()},t.prototype.setRequestHeader=function(e,t){return this.__local_request?this.__local_request.setHeader(e.toLowerCase(),t):this.__xhr_request.setRequestHeader(e,t)},t.prototype.getAllResponseHeaders=function(e){return this.__local_request?this.__local_response?this.__local_response.headers:null:this.__xhr_request.getAllResponseHeaders(e)},t.prototype.getResponseHeader=function(e){return this.__local_request?this.__local_response?this.__local_response.getHeader(e):null:this.__xhr_request.getResponseHeader(e)}}e("./http-headers.js");var S=e("../promises.js").promise,x=e("./uri-template.js"),C="\\{([^\\}]*)[\\+\\#\\.\\/\\;\\?\\&]?",T="(\\,|\\})",R=/^((http(s|l)?:)?\/\/)|(local:)|((nav:)?\|\|)|(data:)/,A=/^(nav:)?\|?\|/i;y.options={strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","srcPath","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@\/]*)(?::([^:@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@\/]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*)(?::([^:@\/]*))?)?@)?([^:\/\(?#]*)(?::(\d*))?(?:\(([^\)]+)\))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var O=/^(.+)@([^!]+)!([^!\/]+)(?:!([\d]+))?$/i;t.exports={extractDocumentLinks:r,queryLinks:n,queryLink:i,preferredTypes:l,preferredType:h,parseMediaType:c,parseAcceptHeader:u,joinUri:f,joinRelPath:g,isAbsUri:p,isNavSchemeUri:d,parseUri:y,parseNavUri:m,parsePeerDomain:v,makePeerDomain:b,makeProxyUri:w,pipe:E,patchXHR:j}},{"../promises.js":4,"./dispatch.js":13,"./http-headers.js":15,"./httpl.js":16,"./request.js":18,"./uri-template.js":24}],15:[function(e,t){function r(e,t){if(!t||"object"!=typeof t||!e)return t;var r=s(e,"serializer");if(!r)return t;try{return r(t)}catch(n){return console.warn("Failed to serialize header",e,t),t}}function n(e,t){if(!t||"string"!=typeof t||!e)return t;var r=s(e,"deserializer");if(!r)return t;try{return r(t)}catch(n){return console.warn("Failed to deserialize header",e,t),t}}function i(e,t,r){c[e.toLowerCase()]={serializer:t,deserializer:r}}function s(e,t){var r=c[e.toLowerCase()];return r?r[t]:null}var o=e("./helpers.js"),a={serialize:r,deserialize:n,register:i},c={};t.exports=a;var u=/<(.*?)>(?:;[\s]*(.*?)((,(?=[\s]*<))|$))/g,l=/([\-a-z0-9_\.]+)=?(?:(?:"([^"]+)")|([^;\s]+))?/g;a.register("link",function(e){var t=[];return e.forEach(function(e){var r=["<"+e.href+">"];for(var n in e)"href"!=n&&null!==e[n]&&("boolean"==typeof e[n]&&e[n]?r.push(n):r.push(n+'="'+e[n]+'"'));t.push(r.join("; "))}),t.join(", ")},function(e){for(var t,r,n,i=[];t=u.exec(e);){for(n={href:t[1]};r=l.exec(t[2]);)n[r[1]]=r[2]||r[3]||!0;i.push(n)}return i}),a.register("accept",function(e){return e.map(function(e){var t=[e.full];1!==e.q&&t.push("q="+e.q);for(var r in e.params)t.push(r+"="+e.params[r]);return t.join("; ")}).join(", ")},o.parseAcceptHeader);var h=/(?:([A-z]+)\/)?([\d\.]+) ([-A-z:\d\.@!]*)(?: ([^,]+))?/g;a.register("via",function(e){return e.map(function(e){return(e.proto.name?e.proto.name+"/":"")+e.proto.version+" "+e.hostname+(e.comment?" "+e.comment:"")}).join(", ")},function(e){for(var t,r=[];t=h.exec(e);){var n={proto:{name:t[1]||"http",version:t[2]},hostname:t[3],comment:t[4]};r.push(n)}return r})},{"./helpers.js":14}],16:[function(e,t){function r(e){h=e}function n(e,t,r){if(v[e])throw new Error("server already registered at domain given to addServer");var n=t instanceof g;return n&&(r=t,t=t.handleLocalRequest,r.config.domain=e),v[e]={fn:t,context:r},v[e]}function i(e){v[e]&&delete v[e]}function s(e){return v[e]}function o(){return v}function a(e,t){b[e]=t}function c(e){b[e]&&delete b[e]}function u(e){return b[e]}function l(){return b}var h,f=e("./schemes.js"),p=e("./helpers.js"),d=e("./content-types.js"),g=e("./server.js"),y=function(e,t){t.writeHead(404,"server not found"),t.end()},m=function(e,t){t.writeHead(407,"peer relay not authenticated"),t.end()};f.register(["local","httpl"],function(e,t){var r=s(e.urld.authority);if(r||(r=h(e,t),r||(r=y)),e.deserializeHeaders(),e.path=e.urld.path,e.headers.host=e.urld.authority,e.path=e.path?e.path.replace(/(.)\/$/,"$1"):"/",e.urld.query){var n=d.deserialize("application/x-www-form-urlencoded",e.urld.query);e.query||(e.query={});for(var i in n)e.query[i]=n[i]}if(e.binary&&console.warn("Got HTTPL request with binary=true - sorry, not currently supported",e),r.fn)r.fn.call(r.context,e,t);else if(r.handleLocalRequest)r.handleLocalRequest(e,t);else{if("function"!=typeof r)throw"Invalid server";r(e,t)}}),r(function(t){if(t.urld.srcPath)return console.log("Spawning temporary worker",t.urld.authority),e("../spawners.js").spawnWorkerServer(null,{domain:t.urld.authority,temp:!0});var r=p.parsePeerDomain(t.urld.authority);return r&&(0==r.sid&&("!0"==t.urld.authority.slice(-2)?server=s(t.urld.authority.slice(0,-2)):(t.urld.authority+="!0",server=s(t.urld.authority))),!server)?r.relay in b?(b[r.relay].connect(t.urld.authority),s(t.urld.authority)):m:!1});var v={},b={};t.exports={addServer:n,removeServer:i,getServer:s,getServers:o,addRelay:a,removeRelay:c,getRelay:u,getRelays:l,setHostLookup:r}},{"../spawners.js":6,"./content-types.js":12,"./helpers.js":14,"./schemes.js":21,"./server.js":22}],17:[function(e,t){function r(){return Math.round(1e4*Math.random())}function n(e){e||(e={}),e.app||(e.app=window.location.host),"undefined"==typeof e.sid&&(e.sid=r(),this.autoRetryStreamTaken=!0),"undefined"==typeof e.ping&&(e.ping=45e3),this.config=e,i.mixinEventEmitter(this),this.assignedDomain=null,this.connectionStatus=0,Object.defineProperty(this,"connectedToRelay",{get:function(){return this.connectionStatus==n.CONNECTED},set:function(e){this.connectionStatus=e?n.CONNECTED:n.DISCONNECTED}}),this.userId=null,this.accessToken=null,this.bridges={},this.pingInterval=null,this.registeredLinks=null,this.relayEventStream=null,this.messageFromAuthPopupHandler=null,this.relayService=null,this.usersCollection=null,this.relayItem=null,e.provider&&this.setProvider(e.provider),window.addEventListener("beforeunload",this.onPageClose.bind(this))}var i=e("../util"),s=e("./helpers.js"),o=e("./httpl.js"),a=e("./agent.js").agent,c=e("./rtc-bridge-server.js");t.exports=n,n.DISCONNECTED=0,n.CONNECTING=1,n.CONNECTED=2,n.prototype.setAccessToken=function(e){if("null"==e&&(e=null),e){var t=e.split(":");if(2!==t.length)throw new Error("Invalid access token");if(this.userId=t[0],this.accessToken=e,this.relayService){this.relayService.setRequestDefaults({headers:{authorization:"Bearer "+e}}),this.usersCollection.setRequestDefaults({headers:{authorization:"Bearer "+e}});var r=this;this.relayItem=this.relayService.follow({rel:"gwr.io/relay",user:this.getUserId(),app:this.getApp(),sid:this.getSid(),nc:Date.now()}),this.relayItem.resolve().then(function(){r.emit("accessGranted")},function(e){r.onRelayError({event:"error",data:e})})}}else{var n=!!this.accessToken;this.userId=null,this.accessToken=null,n&&this.emit("accessRemoved")}},n.prototype.isListening=function(){return this.connectedToRelay},n.prototype.getAssignedDomain=function(){return this.assignedDomain},n.prototype.getAssignedUrl=function(){return"local://"+this.assignedDomain},n.prototype.getUserId=function(){return this.userId},n.prototype.getApp=function(){return this.config.app},n.prototype.setApp=function(e){this.config.app=e},n.prototype.getStreamId=function(){return this.config.sid},n.prototype.getSid=n.prototype.getStreamId,n.prototype.setStreamId=function(e){this.config.sid=e},n.prototype.setSid=n.prototype.setStreamId,n.prototype.getAccessToken=function(){return this.accessToken},n.prototype.getServer=function(){return this.config.serverFn},n.prototype.setServer=function(e){this.config.serverFn=e},n.prototype.getRetryTimeout=function(){return this.config.retryTimeout},n.prototype.setRetryTimeout=function(e){this.config.retryTimeout=e},n.prototype.getProvider=function(){return this.config.provider},n.prototype.setProvider=function(e){if(this.connectedToRelay)throw new Error("Can not change provider while connected to the relay. Call stopListening() first.");this.config.provider=e,this.providerDomain=s.parseUri(e).authority,this.relayService=a(this.config.provider),this.usersCollection=this.relayService.follow({rel:"gwr.io/users"}),this.accessToken&&(this.relayService.setRequestDefaults({headers:{authorization:"Bearer "+this.accessToken}}),this.usersCollection.setRequestDefaults({headers:{authorization:"Bearer "+this.accessToken}}))},n.prototype.requestAccessToken=function(e){this.messageFromAuthPopupHandler||(this.messageFromAuthPopupHandler=function(e){var t=s.parseUri(e.origin),r=s.parseUri(this.config.provider);t.authority===r.authority&&(console.log("Received access token from "+e.origin),this.config.provider!=e.origin&&this.setProvider(e.origin),this.setAccessToken(e.data),e.data||this.emit("accessDenied"))}.bind(this),window.addEventListener("message",this.messageFromAuthPopupHandler));var t=this.getProvider()+"/session/"+this.config.app;e&&e.guestof&&(t+="?guestof="+encodeURIComponent(e.guestof)),window.open(t)},n.prototype.getUsers=function(e){var t=this.usersCollection;return e&&(e.rel="self",t=t.follow(e)),t.get({Accept:"application/json"})},n.prototype.getUser=function(e){return this.usersCollection.follow({rel:"gwr.io/user",id:e}).get({Accept:"application/json"})},n.prototype.registerLinks=function(e){this.registeredLinks=Array.isArray(e)?e:[e],this.relayItem&&this.relayItem.dispatch({method:"PATCH",body:{links:this.registeredLinks}})},n.prototype.agent=function(){return this.relayService?this.relayService.follow({rel:"gwr.io/relays",links:1}):a()},n.prototype.startListening=function(){var e=this;if(this.getAccessToken()){if(this.connectionStatus!==n.DISCONNECTED)return console.error("startListening() called when already connected or connecting to relay. Must call stopListening() first."),void 0;this.assignedDomain=this.makeDomain(this.getUserId(),this.config.app,this.config.sid),0===this.config.sid&&(this.assignedDomain+="!0"),this.relayItem=this.relayService.follow({rel:"gwr.io/relay",user:this.getUserId(),app:this.getApp(),sid:this.getSid(),nc:Date.now()}),this.connectionStatus=n.CONNECTING,this.relayItem.subscribe().then(function(t){o.addRelay(e.providerDomain,e),e.relayEventStream=t,e.connectionStatus=n.CONNECTED,t.response_.then(function(t){return e.registeredLinks&&e.registerLinks(e.registeredLinks),e.emit("listening"),t}),t.on("signal",e.onSignal.bind(e)),t.on("error",e.onRelayError.bind(e)),t.on("close",e.onRelayClose.bind(e)),e.pingInterval&&clearInterval(e.pingInterval),e.config.ping&&(e.pingInterval=setInterval(function(){e.signal(e.getAssignedDomain(),{type:"noop"})},e.config.ping))},function(t){e.onRelayError({event:"error",data:t})})}},n.prototype.stopListening=function(){if(this.connectedToRelay){for(var e in this.bridges)this.bridges[e].isConnecting&&this.bridges[e].terminate();this.connectedToRelay=!1,this.relayEventStream.close(),this.relayEventStream=null,o.removeRelay(this.providerDomain)}},n.prototype.connect=function(e,t){t||(t={}),"undefined"==typeof t.initiate&&(t.initiate=!0),e=s.parseUri(e).authority;var r=s.parsePeerDomain(e);if(!r)throw new Error("Invalid peer url given to connect(): "+e);if(0===r.sid&&"!0"!=e.slice(-2)&&(e+="!0"),e in this.bridges)return this.bridges[e];console.log("Initiating WebRTC session with",e);var n=new c({peer:e,initiate:t.initiate,relay:this,serverFn:this.config.serverFn,loopback:e==this.assignedDomain,retryTimeout:t.retryTimeout||this.config.retryTimeout,retries:t.retries||this.config.retries,log:this.config.log||!1});return n.on("connecting",this.emit.bind(this,"connecting")),n.on("connected",this.emit.bind(this,"connected")),n.on("disconnected",this.onBridgeDisconnected.bind(this)),n.on("disconnected",this.emit.bind(this,"disconnected")),n.on("error",this.emit.bind(this,"error")),this.bridges[e]=n,o.addServer(e,n),n},n.prototype.signal=function(e,t){if(!this.relayItem)return console.warn("Relay - signal() called before relay is connected"),void 0;var r=this,n=this.relayItem.dispatch({method:"notify",body:{src:this.assignedDomain,dst:e,msg:t}});return n.fail(function(e){if(401==e.status){if(!r.accessToken)return;r.setAccessToken(null),r.emit("accessInvalid")}}),n},n.prototype.onSignal=function(e){if(e.data&&e.data.src&&e.data.msg||console.warn("discarding faulty signal message",err),"noop"!=e.data.msg.type){var t=e.data.src,r=this.bridges[t]||this.bridges[t+"!0"];r?r.onSignal(e.data.msg):("offer"==e.data.msg.type||"httpl"==e.data.msg.type)&&(r=this.connect(t,{initiate:!1}),r.onSignal(e.data.msg))}},n.prototype.onRelayError=function(e){if(e.data&&423==e.data.status)this.relayEventStream=null,this.connectedToRelay=!1,this.autoRetryStreamTaken?(this.setSid(r()),this.startListening()):this.emit("streamTaken");else if(e.data&&420==e.data.status)this.relayEventStream=null,this.connectedToRelay=!1,this.emit("outOfStreams");else if(!e.data||401!=e.data.status&&403!=e.data.status)if(e.data&&(0===e.data.status||404==e.data.status||e.data.status>=500)){this.connectedToRelay&&this.onRelayClose(),this.connectedToRelay=!1,this.relayEventStream=null;var t=this;setTimeout(function(){t.startListening()},2e3)}else this.emit("error",{error:e.data});else this.setAccessToken(null),this.connectedToRelay=!1,this.emit("accessInvalid")},n.prototype.onRelayClose=function(){this.connectedToRelay=!1,self.pingInterval&&clearInterval(self.pingInterval),this.emit("notlistening")},n.prototype.onBridgeDisconnected=function(e){var t=this.bridges[e.domain];t&&(delete this.bridges[e.domain],o.removeServer(e.domain))},n.prototype.onPageClose=function(){var e=Object.keys(this.bridges);if(this.connectedToRelay&&0!==e.length){var t=[];for(var r in this.bridges)t.push(this.bridges[r].config.peer);var n=new XMLHttpRequest;n.open("NOTIFY",this.relayItem.context.url,!1),n.setRequestHeader("Authorization","Bearer "+this.accessToken),n.setRequestHeader("Content-type","application/json"),n.send(JSON.stringify({src:this.assignedDomain,dst:t,msg:{type:"disconnect"}}))}},n.prototype.makeDomain=function(e,t,r){return s.makePeerDomain(e,this.providerDomain,t,r)},"undefined"!=typeof window&&(window.logWebRTC=function(e){"undefined"==typeof e&&(e=!0);var t;for(t in o.getRelays())o.getRelay(t).config.log=e;for(t in o.getServers()){var r=o.getServer(t);r.context&&r.context instanceof c&&(r.context.config.log=e)}})},{"../util":9,"./agent.js":10,"./helpers.js":14,"./httpl.js":16,"./rtc-bridge-server.js":20}],18:[function(e,t){function r(e){s.EventEmitter.call(this),e||(e={}),"string"==typeof e&&(e={url:e});var t=e.headers||{};i(e,t),this.method=e.method?e.method.toUpperCase():"GET",this.url=e.url||null,this.path=e.path||null,this.query=e.query||{},this.headers=n(t),!this.headers.host&&e.host&&(this.headers.host=e.host),e.body&&!this.headers["content-type"]&&(this.headers["content-type"]="string"==typeof e.body?"text/plain":"application/json"),this.headers.accept||(this.headers.accept="*/*"),Object.defineProperty(this,"parsedHeaders",{value:{},configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"body",{value:e.body||"",configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"stream",{value:e.stream||!1,configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"binary",{value:e.binary||!1,configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"isConnOpen",{value:!0,configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"body_",{value:o(),configurable:!0,enumerable:!1,writable:!1}),function(e){e.on("data",function(t){e.body+=t}),e.on("end",function(){e.headers["content-type"]&&(e.body=a.deserialize(e.headers["content-type"],e.body)),e.body_.fulfill(e.body)})}(this)}function n(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r.toLowerCase()]=e[r]);return t}function i(e,t){for(var r in e){var n=r.charAt(0);if(e.hasOwnProperty(r)&&n===n.toUpperCase()){var i=r.replace(u,"-");t[i]=e[r],delete e[r]}}}var s=e("../util"),o=e("../promises.js").promise,a=e("./content-types.js"),c=e("./http-headers.js");t.exports=r,r.prototype=Object.create(s.EventEmitter.prototype),r.prototype.header=function(e,t){return"undefined"!=typeof t?this.setHeader(e,t):this.getHeader(e)},r.prototype.setHeader=function(e,t){this.headers[e.toLowerCase()]=t},r.prototype.getHeader=function(e){return this.headers[e.toLowerCase()]},r.prototype.removeHeader=function(e){delete this.headers[e.toLowerCase()]},r.prototype.setTimeout=function(e){var t=this;this.__timeoutId||Object.defineProperty(this,"__timeoutId",{value:setTimeout(function(){t.isConnOpen&&t.close(),delete t.__timeoutId},e),configurable:!0,enumerable:!1,writable:!0})},r.prototype.serializeHeaders=function(){for(var e in this.headers)this.headers[e]=c.serialize(e,this.headers[e])},r.prototype.deserializeHeaders=function(){for(var e in this.headers){var t=c.deserialize(e,this.headers[e]);t&&"string"!=typeof t&&(this.parsedHeaders[e]=t)}},r.prototype.write=function(e){return this.isConnOpen?("string"!=typeof e&&(e=a.serialize(this.headers["content-type"],e)),this.emit("data",e),this):this},r.prototype.end=function(e){return this.isConnOpen?("undefined"!=typeof e&&this.write(e),this.emit("end"),this):this},r.prototype.close=function(){return this.isConnOpen?(this.isConnOpen=!1,this.emit("close"),this):this};var u=/_/g},{"../promises.js":4,"../util":9,"./content-types.js":12,"./http-headers.js":15}],19:[function(e,t){function r(){var e=this;n.EventEmitter.call(this),this.status=0,this.reason=null,this.headers={},this.body="",Object.defineProperty(this,"parsedHeaders",{value:{},configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"isConnOpen",{value:!0,configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"latency",{value:void 0,configurable:!0,enumerable:!1,writable:!0}),Object.defineProperty(this,"body_",{value:i(),configurable:!0,enumerable:!1,writable:!1}),this.on("data",function(t){t instanceof ArrayBuffer?e.body=t:e.body+=t}),this.on("end",function(){e.headers["content-type"]&&(e.body=o.deserialize(e.headers["content-type"],e.body)),e.body_.fulfill(e.body)})}var n=e("../util"),i=e("../promises.js").promise,s=e("./helpers.js"),o=e("./content-types.js"),a=e("./http-headers.js");t.exports=r,r.prototype=Object.create(n.EventEmitter.prototype),r.prototype.header=function(e,t){return"undefined"!=typeof t?this.setHeader(e,t):this.getHeader(e)},r.prototype.setHeader=function(e,t){this.headers[e.toLowerCase()]=t},r.prototype.getHeader=function(e){return this.headers[e.toLowerCase()]},r.prototype.removeHeader=function(e){delete this.headers[e.toLowerCase()]},r.prototype.serializeHeaders=function(){for(var e in this.headers)this.headers[e]=a.serialize(e,this.headers[e])},r.prototype.deserializeHeaders=function(){for(var e in this.headers){var t=a.deserialize(e,this.headers[e]);t&&"string"!=typeof t&&(this.parsedHeaders[e]=t)}},r.prototype.processHeaders=function(e){var t=this;t.parsedHeaders.link&&t.parsedHeaders.link.forEach(function(t){s.isAbsUri(t.href)||(t.href=s.joinRelPath(e.urld,t.href));var r=s.parseUri(t.href).authority;Object.defineProperty(t,"host_domain",{enumerable:!1,configurable:!0,writable:!0,value:r});var n=s.parsePeerDomain(t.host_domain);n?(Object.defineProperty(t,"host_user",{enumerable:!1,configurable:!0,writable:!0,value:n.user}),Object.defineProperty(t,"host_relay",{enumerable:!1,configurable:!0,writable:!0,value:n.relay}),Object.defineProperty(t,"host_app",{enumerable:!1,configurable:!0,writable:!0,value:n.app}),Object.defineProperty(t,"host_sid",{enumerable:!1,configurable:!0,writable:!0,value:n.sid})):(delete t.host_user,delete t.host_relay,delete t.host_app,delete t.host_sid)})},r.prototype.writeHead=function(e,t,r){if(!this.isConnOpen)return this;if(this.status=e,this.reason=t,r)for(var n in r)r.hasOwnProperty(n)&&this.setHeader(n,r[n]);return this.serializeHeaders(),this.emit("headers",this),this},r.prototype.write=function(e){return this.isConnOpen?("string"!=typeof e&&(e=o.serialize(this.headers["content-type"],e)),this.emit("data",e),this):this},r.prototype.end=function(e){return this.isConnOpen?("undefined"!=typeof e&&this.write(e),this.emit("end"),this.close(),this):this},r.prototype.close=function(){return this.isConnOpen?(this.isConnOpen=!1,this.emit("close"),this):this}},{"../promises.js":4,"../util":9,"./content-types.js":12,"./helpers.js":14,"./http-headers.js":15}],20:[function(e,t){function r(e){if(e||(e={}),!e.peer)throw new Error("`config.peer` is required");if(!e.relay)throw new Error("`config.relay` is required");"undefined"==typeof e.retryTimeout&&(e.retryTimeout=15e3),"undefined"==typeof e.retries&&(e.retries=3),v.call(this,e),g.mixinEventEmitter(this);var t=y.parsePeerDomain(e.peer);if(!t)throw new Error("Invalid peer URL: "+e.peer);this.peerInfo=t,this.isConnecting=!0,this.isOfferExchanged=!1,this.isConnected=!1,this.isTerminated=!1,this.candidateQueue=[],this.offerNonce=0,this.retriesLeft=e.retries,this.rtcPeerConn=null,this.rtcDataChannel=null,this.createPeerConn(),this.config.loopback?(this.isOfferExchanged=!0,i.call(this)):this.config.initiate&&this.sendOffer()}function n(e){this.debugLog("HTTPL CHANNEL MSG",e),this.onChannelMessage(e.data)}function i(e){console.log("Successfully established WebRTC session with",this.config.peer),this.debugLog("HTTPL CHANNEL OPEN",e),this.isConnecting=!1,this.isConnected=!0,this.emit("connected",Object.create(this.peerInfo),this)}function s(e){console.log("Closed WebRTC session with",this.config.peer),this.debugLog("HTTPL CHANNEL CLOSE",e),this.terminate({noSignal:!0})}function o(e){this.debugLog("HTTPL CHANNEL ERR",e),this.emit("error",Object.create(this.peerInfo,{error:{value:e}}),this)}function a(){var e=this;setTimeout(function(){e.config.initiate&&e.isConnected===!1&&(e.retriesLeft>0?(e.retriesLeft--,e.debugLog("CONNECTION TIMED OUT, RESTARTING. TRIES LEFT:",e.retriesLeft),e.resetPeerConn(),e.sendOffer()):(console.log("Failed to establish WebRTC session with",e.config.peer," - Will continue bouncing traffic through the relay"),e.debugLog("CONNECTION TIMED OUT, GIVING UP"),e.resetPeerConn()))},this.config.retryTimeout)}function c(){var e=this;this.isOfferExchanged=!0,this.candidateQueue.forEach(function(t){e.rtcPeerConn.addIceCandidate(new x({candidate:t}))}),this.candidateQueue.length=0}function u(e){e&&e.candidate&&(this.debugLog("FOUND ICE CANDIDATE",e.candidate),this.signal({type:"candidate",candidate:e.candidate.candidate}))}function l(e){e.target&&"disconnected"===e.target.iceConnectionState&&(this.debugLog("ICE CONNECTION STATE CHANGE: DISCONNECTED",e),this.terminate({noSignal:!0}))}function h(e){e.target&&"closed"==e.target.signalingState&&(this.debugLog("SIGNALING STATE CHANGE: DISCONNECTED",e),this.terminate({noSignal:!0}))}function f(e){this.debugLog("DATA CHANNEL PROVIDED",e),this.rtcDataChannel=e.channel,this.rtcDataChannel.onopen=i.bind(this),this.rtcDataChannel.onclose=s.bind(this),this.rtcDataChannel.onerror=o.bind(this),this.rtcDataChannel.onmessage=n.bind(this)}function p(e){return e}var d="undefined"!=typeof self?self:"undefined"!=typeof window?window:{},g=e("../util"),y=e("./helpers.js"),m=e("./httpl.js"),v=e("./bridge-server.js"),b={optional:[{DtlsSrtpKeyAgreement:!0}]},w={iceServers:[{url:"stun:stun.l.google.com:19302"}]},E="undefined"!=typeof window?window:"undefined"!=typeof self?self:d,j=E.mozRTCSessionDescription||E.RTCSessionDescription,S=E.mozRTCPeerConnection||E.webkitRTCPeerConnection||E.RTCPeerConnection,x=E.mozRTCIceCandidate||E.RTCIceCandidate;r.prototype=Object.create(v.prototype),t.exports=r,r.prototype.getPeerInfo=function(){return this.peerInfo},r.prototype.terminate=function(e){v.prototype.terminate.call(this),this.isTerminated=!0,(this.isConnecting||this.isConnected)&&(e&&e.noSignal||this.signal({type:"disconnect"}),this.isConnecting=!1,this.isConnected=!1,this.destroyPeerConn(),this.emit("disconnected",Object.create(this.peerInfo),this))},r.prototype.isChannelActive=function(){return!0},r.prototype.channelSendMsg=function(e){if(this.config.loopback)this.onChannelMessage(e);else if(this.isConnected)try{this.rtcDataChannel.send(e),this.isReorderingMessages&&this.useMessageReordering(!1)}catch(t){this.debugLog("NETWORK ERROR, BOUNCING",t),this.signal({type:"httpl",data:e})}else this.signal({type:"httpl",data:e})},r.prototype.handleRemoteRequest=function(e,t){var r=this.config.relay.getServer();r&&"function"==typeof r?r.call(this,e,t,this):r&&r.handleRemoteRequest?r.handleRemoteRequest(e,t,this):(t.writeHead(501,"not implemented"),t.end())},r.prototype.onSignal=function(e){var t=this;switch(e.type){case"disconnect":this.terminate({noSignal:!0});break;case"candidate":this.debugLog("GOT CANDIDATE",e.candidate),this.isOfferExchanged?this.rtcPeerConn.addIceCandidate(new x({candidate:e.candidate})):this.candidateQueue.push(e.candidate);break;case"offer":if(this.debugLog("GOT OFFER",e),this.isConnected)return this.debugLog("RECEIVED AN OFFER WHEN BELIEVED TO BE CONNECTED, DROPPING"),void 0;if("undefined"==typeof j)return;if(this.isOfferExchanged||this.emit("connecting",Object.create(this.peerInfo),this),this.config.initiate&&(this.debugLog("LEADER CONFLICT DETECTED, COMPARING NONCES","MINE=",this.offerNonce,"THEIRS=",e.nonce),this.offerNonce<e.nonce&&(this.debugLog("RESETTING INTO FOLLOWER ROLE"),this.config.initiate=!1,this.resetPeerConn())),!this.config.initiate&&this.isOfferExchanged){if(!(this.retriesLeft>0))return this.debugLog("RECEIVED A NEW OFFER, NO RETRIES LEFT. GIVING UP."),this.terminate(),void 0;this.retriesLeft--,this.debugLog("RECEIVED A NEW OFFER, RESETTING AND RETRYING. RETRIES LEFT:",this.retriesLeft),this.resetPeerConn()}var r=new j({type:"offer",sdp:e.sdp});this.rtcPeerConn.setRemoteDescription(r),c.call(this),this.rtcPeerConn.createAnswer(function(e){t.debugLog("CREATED ANSWER",e),e.sdp=p(e.sdp),t.rtcPeerConn.setLocalDescription(e),t.signal({type:"answer",sdp:e.sdp})},function(e){t.emit("error",Object.create(this.peerInfo,{error:{value:e}}),t)});break;case"answer":this.debugLog("GOT ANSWER",e),this.rtcPeerConn.setRemoteDescription(new j({type:"answer",sdp:e.sdp})),c.call(this);break;case"httpl":this.debugLog("GOT HTTPL RELAY",e),this.onChannelMessage(e.data);break;default:console.warn("RTCBridgeServer - Unrecognized signal message from relay",e)}},r.prototype.signal=function(e){var t=this,r=this.config.relay.signal(this.config.peer,e);
return r.fail(function(e){if(404==e.status&&!t.isTerminated){for(var r in t.incomingStreams)try{t.incomingStreams[r].writeHead(404,"not found").end()}catch(n){console.error("That weird peer 404 error",n,t.incomingStreams[r])}t.terminate({noSignal:!0}),m.removeServer(t.config.domain)}}),r},r.prototype.createPeerConn=function(){if(!this.rtcPeerConn&&"undefined"!=typeof S){var e=this.config.iceServers||w;this.rtcPeerConn=new S(e,b),this.rtcPeerConn.onicecandidate=u.bind(this),this.rtcPeerConn.oniceconnectionstatechange=l.bind(this),this.rtcPeerConn.onsignalingstatechange=h.bind(this),this.rtcPeerConn.ondatachannel=f.bind(this),this.useMessageReordering(!0)}},r.prototype.destroyPeerConn=function(e){this.rtcDataChannel&&(this.rtcDataChannel.close(),e&&(this.rtcDataChannel.onopen=null,this.rtcDataChannel.onclose=null,this.rtcDataChannel.onerror=null,this.rtcDataChannel.onmessage=null),this.rtcDataChannel=null),this.rtcPeerConn&&(this.rtcPeerConn.close(),e&&(this.rtcPeerConn.onicecandidate=null,this.rtcPeerConn.oniceconnectionstatechange=null,this.rtcPeerConn.onsignalingstatechange=null,this.rtcPeerConn.ondatachannel=null),this.rtcPeerConn=null)},r.prototype.resetPeerConn=function(){this.destroyPeerConn(!0),this.createPeerConn(),this.candidateQueue.length=0,this.isOfferExchanged=!1},r.prototype.sendOffer=function(){var e=this;if("undefined"!=typeof S){try{this.rtcDataChannel=this.rtcPeerConn.createDataChannel("httpl",{reliable:!0}),this.rtcDataChannel.onopen=i.bind(this),this.rtcDataChannel.onclose=s.bind(this),this.rtcDataChannel.onerror=o.bind(this),this.rtcDataChannel.onmessage=n.bind(this)}catch(t){return}a.call(this),this.rtcPeerConn.createOffer(function(t){e.debugLog("CREATED OFFER",t),t.sdp=p(t.sdp),e.rtcPeerConn.setLocalDescription(t),e.offerNonce=Math.round(1e7*Math.random()),e.signal({type:"offer",sdp:t.sdp,nonce:e.offerNonce})},function(t){e.emit("error",Object.create(this.peerInfo,{error:{value:t}}),e)}),g.nextTick(function(){e.emit("connecting",Object.create(e.peerInfo),e)})}}},{"../util":9,"./bridge-server.js":11,"./helpers.js":14,"./httpl.js":16}],21:[function(e,t){function r(e,t){if(e&&Array.isArray(e))for(var n=0,i=e.length;i>n;n++)r(e[n],t);else u[e]=t}function n(e){delete u[e]}function i(e){return u[e]}var s=e("../util"),o=e("./helpers.js"),a=e("./content-types.js"),c={register:r,unregister:n,get:i},u={};t.exports=c,c.register(["http","https"],function(e,t){var r=o.parseUri(e.url);if(e.query){var n=a.serialize("application/x-www-form-urlencoded",e.query);n&&(r.query?(r.query+="&"+n,r.relative+="&"+n):(r.query=n,r.relative+="?"+n))}var i=(r.protocol?r.protocol+"://":"//")+r.authority+r.relative,s=new XMLHttpRequest;s.open(e.method,i,!0),e.binary&&(s.responseType="arraybuffer",e.stream&&console.warn("Got HTTP/S request with binary=true and stream=true - sorry, not supported, binary responses must be buffered (its a browser thing)",e)),e.serializeHeaders();for(var c in e.headers)null!==e.headers[c]&&e.headers.hasOwnProperty(c)&&s.setRequestHeader(c,e.headers[c]);var u="";e.on("data",function(e){u+=e}),e.on("end",function(){s.send(u)}),e.on("close",function(){s.readyState!==XMLHttpRequest.DONE&&(s.aborted=!0,s.abort())});var l=0,h=0,f=!1;s.onreadystatechange=function(){if(s.readyState>=XMLHttpRequest.HEADERS_RECEIVED&&!f){f=!0;var e={};if(0!==s.status)if(s.getAllResponseHeaders())s.getAllResponseHeaders().split("\n").forEach(function(t){if(t){var r=t.replace("\r","").split(": ");e[r[0].toLowerCase()]=r.slice(1).join(": ")}});else{var r=function(t){var r=s.getResponseHeader(t);r&&(e[t.toLowerCase()]=r.toLowerCase())};r("Accept-Ranges"),r("Age"),r("Allow"),r("Cache-Control"),r("Connection"),r("Content-Encoding"),r("Content-Language"),r("Content-Length"),r("Content-Location"),r("Content-MD5"),r("Content-Disposition"),r("Content-Range"),r("Content-Type"),r("Date"),r("ETag"),r("Expires"),r("Last-Modified"),r("Link"),r("Location"),r("Pragma"),r("Refresh"),r("Retry-After"),r("Server"),r("Set-Cookie"),r("Trailer"),r("Transfer-Encoding"),r("Vary"),r("Via"),r("Warning"),r("WWW-Authenticate")}t.writeHead(s.status,s.statusText,e),t.binary||(l=setInterval(function(){var e=s.response.length;if(e>h){var r=s.response.slice(h);h=e,t.write(r)}},50))}s.readyState===XMLHttpRequest.DONE&&(l&&clearInterval(l),0===t.status||0!==s.status||s.aborted?(s.response&&t.write(s.response.slice(h)),t.end()):(console.debug("XHR looks like it timed out; treating it as a premature close"),t.close()))}}),c.register("data",function(e,t){for(var r,n=e.url.indexOf(":"),i=e.url.indexOf(","),o=e.url.slice(n+1,i).split(";"),a=o.shift(),c=!1;r=o.shift();)"base64"==r&&(c=!0);var u=e.url.slice(i+1);u||(u=""),u=c?atob(u):decodeURIComponent(u),s.nextTick(function(){t.writeHead(200,"ok",{"content-type":a}),t.end(u)})})},{"../util":9,"./content-types.js":12,"./helpers.js":14}],22:[function(e,t){function r(e){if(this.config={domain:null,log:!1},e)for(var t in e)this.config[t]=e[t]}t.exports=r,r.prototype.getDomain=function(){return this.config.domain},r.prototype.getUrl=function(){return"local://"+this.config.domain},r.prototype.debugLog=function(){if(this.config.log){var e=[this.config.domain].concat([].slice.call(arguments));console.debug.apply(console,e)}},r.prototype.handleLocalRequest=function(e,t){console.warn("handleLocalRequest not defined",this),t.writeHead(501,"server not implemented"),t.end()},r.prototype.terminate=function(){}},{}],23:[function(e,t){function r(e){"string"==typeof e&&(e={url:e}),e.stream=!0,e.method||(e.method="SUBSCRIBE"),e.headers||(e.headers={accept:"text/event-stream"}),e.headers.accept||(e.headers.accept="text/event-stream");var t=c(e);return new n(t.request,t)}function n(e,t){a.EventEmitter.call(this),this.request=e,this.response=null,this.response_=null,this.lastEventId=-1,this.isConnOpen=!0,this.connect(t)}function i(e){this.emit("message",e),this.emit("error",e)}function s(e){e=h.deserialize("text/event-stream",e);var t=parseInt(e.id,10);"undefined"!=typeof t&&t>this.lastEventId&&(this.lastEventId=t),this.emit("message",e),this.emit(e.event,e)}function o(){this.streams=[]}var a=e("../util"),c=e("./dispatch.js").dispatch,u=e("./request.js"),l=e("./response.js"),h=e("./content-types.js");n.prototype=Object.create(a.EventEmitter.prototype),n.prototype.getUrl=function(){return this.request.url},n.prototype.connect=function(e){var t,r=this,n="";this.response_=e,e.then(function(e){return r.isConnOpen=!0,r.response=e,e.on("data",function(i){for(i=n+i;-1!==(t=i.indexOf("\r\n\r\n"));){var o=i.slice(0,t);s.call(r,o),i=i.slice(t+4)}n=i,e.body=""}),e.on("end",function(){r.close()}),e.on("close",function(){r.isConnOpen&&r.reconnect()}),e},function(e){throw r.response=e,i.call(r,{event:"error",data:e}),r.close(),e})},n.prototype.reconnect=function(){this.isConnOpen&&(this.isConnOpen=!1,this.request.close()),a.isAppClosing||(this.request=new u(this.request),this.request.headers||(this.request.headers={}),this.lastEventId&&(this.request.headers["last-event-id"]=this.lastEventId),this.connect(c(this.request)),this.request.end())},n.prototype.close=function(){this.isConnOpen&&(this.isConnOpen=!1,this.request.close(),this.emit("close"))},o.prototype.addStream=function(e){e.broadcastStreamId=this.streams.length,this.streams.push(e);var t=this;return e.on("close",function(){t.endStream(e)}),e.broadcastStreamId},o.prototype.endStream=function(e){"number"==typeof e&&(e=this.streams[e]),delete this.streams[e.broadcastStreamId],e.end()},o.prototype.endAllStreams=function(){this.streams.forEach(function(e){e.end()}),this.streams.length=0},o.prototype.emit=function(e,t,r){r||(r={}),r.exclude&&(Array.isArray(r.exclude)||(r.exclude=[r.exclude]),r.exclude=r.exclude.map(function(e){return e instanceof l?e.broadcastStreamId:e},this)),this.streams.forEach(function(n,i){r.exclude&&-1!==r.exclude.indexOf(i)||this.emitTo(n,e,t)},this)},o.prototype.emitTo=function(e,t,r){"number"==typeof e&&(e=this.streams[e]),e.write({event:t,data:r}),e.body=""},t.exports={subscribe:r,EventStream:n,EventHost:o}},{"../util":9,"./content-types.js":12,"./dispatch.js":13,"./request.js":18,"./response.js":19}],24:[function(e,t){!function(e){"use strict";function t(e){var r;if(null===e||void 0===e)return!1;if(n.isArray(e))return e.length>0;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return!0;for(r in e)if(e.hasOwnProperty(r)&&t(e[r]))return!0;return!1}var r=function(){function e(e){this.options=e}return e.prototype.toString=function(){return JSON&&JSON.stringify?JSON.stringify(this.options):this.options},e}(),n=function(){function e(e){return"[object Array]"===Object.prototype.toString.apply(e)}function t(e){return"[object String]"===Object.prototype.toString.apply(e)}function r(e){return"[object Number]"===Object.prototype.toString.apply(e)}function n(e){return"[object Boolean]"===Object.prototype.toString.apply(e)}function i(e,t){var r,n="",i=!0;for(r=0;r<e.length;r+=1)i?i=!1:n+=t,n+=e[r];return n}function s(e,t){for(var r=[],n=0;n<e.length;n+=1)r.push(t(e[n]));return r}function o(e,t){for(var r=[],n=0;n<e.length;n+=1)t(e[n])&&r.push(e[n]);return r}function a(e){if("object"!=typeof e||null===e)return e;Object.freeze(e);var t,r;for(r in e)e.hasOwnProperty(r)&&(t=e[r],"object"==typeof t&&c(t));return e}function c(e){return"function"==typeof Object.freeze?a(e):e}return{isArray:e,isString:t,isNumber:r,isBoolean:n,join:i,map:s,filter:o,deepFreeze:c}}(),i=function(){function e(e){return e>="a"&&"z">=e||e>="A"&&"Z">=e}function t(e){return e>="0"&&"9">=e}function r(e){return t(e)||e>="a"&&"f">=e||e>="A"&&"F">=e}return{isAlpha:e,isDigit:t,isHexDigit:r}}(),s=function(){function e(e){return e.length>1?e:"0"+e}function t(t){var r,n,i="",s=a.encode(t);for(n=0;n<s.length;n+=1)r=s.charCodeAt(n),i+="%"+e(r.toString(16).toUpperCase());return i}function r(e,t){return"%"===e.charAt(t)&&i.isHexDigit(e.charAt(t+1))&&i.isHexDigit(e.charAt(t+2))}function n(e,t){return parseInt(e.substr(t,2),16)}function s(e){if(!r(e,0))return!1;var t=n(e,1),i=a.numBytes(t);if(0===i)return!1;for(var s=1;i>s;s+=1)if(!r(e,3*s)||!a.isValidFollowingCharCode(n(e,3*s+1)))return!1;return!0}function o(e,t){var i=e.charAt(t);if(!r(e,t))return i;var s=n(e,t+1),o=a.numBytes(s);if(0===o)return i;for(var c=1;o>c;c+=1)if(!r(e,t+3*c)||!a.isValidFollowingCharCode(n(e,t+3*c+1)))return i;return e.substr(t,3*o)}var a={encode:function(e){return unescape(encodeURIComponent(e))},numBytes:function(e){return 127>=e?1:e>=194&&223>=e?2:e>=224&&239>=e?3:e>=240&&244>=e?4:0},isValidFollowingCharCode:function(e){return e>=128&&191>=e}};return{encodeCharacter:t,isPctEncoded:s,pctCharAt:o}}(),o=function(){function e(e){return i.isAlpha(e)||i.isDigit(e)||"_"===e||s.isPctEncoded(e)}function t(e){return i.isAlpha(e)||i.isDigit(e)||"-"===e||"."===e||"_"===e||"~"===e}function r(e){return":"===e||"/"===e||"?"===e||"#"===e||"["===e||"]"===e||"@"===e||"!"===e||"$"===e||"&"===e||"("===e||")"===e||"*"===e||"+"===e||","===e||";"===e||"="===e||"'"===e}return{isVarchar:e,isUnreserved:t,isReserved:r}}(),a=function(){function e(e,t){var r,n="",i="";for(("number"==typeof e||"boolean"==typeof e)&&(e=e.toString()),r=0;r<e.length;r+=i.length)i=e.charAt(r),n+=o.isUnreserved(i)||t&&o.isReserved(i)?i:s.encodeCharacter(i);return n}function t(t){return e(t,!0)}function r(e,t){var r=s.pctCharAt(e,t);return r.length>1?r:o.isReserved(r)||o.isUnreserved(r)?r:s.encodeCharacter(r)}function n(e){var t,r="",n="";for(t=0;t<e.length;t+=n.length)n=s.pctCharAt(e,t),r+=n.length>1?n:o.isReserved(n)||o.isUnreserved(n)?n:s.encodeCharacter(n);return r}return{encode:e,encodePassReserved:t,encodeLiteral:n,encodeLiteralCharacter:r}}(),c=function(){function e(e){t[e]={symbol:e,separator:"?"===e?"&":""===e||"+"===e||"#"===e?",":e,named:";"===e||"&"===e||"?"===e,ifEmpty:"&"===e||"?"===e?"=":"",first:"+"===e?"":e,encode:"+"===e||"#"===e?a.encodePassReserved:a.encode,toString:function(){return this.symbol}}}var t={};return e(""),e("+"),e("#"),e("."),e("/"),e(";"),e("?"),e("&"),{valueOf:function(e){return t[e]?t[e]:"=,!@|".indexOf(e)>=0?null:t[""]}}}(),u=function(){function e(e){this.literal=a.encodeLiteral(e)}return e.prototype.expand=function(){return this.literal},e.prototype.toString=e.prototype.expand,e}(),l=function(){function e(e){function t(){var t=e.substring(p,u);if(0===t.length)throw new r({expressionText:e,message:"a varname must be specified",position:u});f={varname:t,exploded:!1,maxLength:null},p=null}function n(){if(d===u)throw new r({expressionText:e,message:"after a ':' you have to specify the length",position:u});f.maxLength=parseInt(e.substring(d,u),10),d=null}var a,u,l=[],f=null,p=null,d=null,g="";for(a=function(t){var n=c.valueOf(t);if(null===n)throw new r({expressionText:e,message:"illegal use of reserved operator",position:u,operator:t});return n}(e.charAt(0)),u=a.symbol.length,p=u;u<e.length;u+=g.length){if(g=s.pctCharAt(e,u),null!==p){if("."===g){if(p===u)throw new r({expressionText:e,message:"a varname MUST NOT start with a dot",position:u});continue}if(o.isVarchar(g))continue;t()}if(null!==d){if(u===d&&"0"===g)throw new r({expressionText:e,message:"A :prefix must not start with digit 0",position:u});if(i.isDigit(g)){if(u-d>=4)throw new r({expressionText:e,message:"A :prefix must have max 4 digits",position:u});continue}n()}if(":"!==g)if("*"!==g){if(","!==g)throw new r({expressionText:e,message:"illegal character",character:g,position:u});l.push(f),f=null,p=u+1}else{if(null===f)throw new r({expressionText:e,message:"exploded without varspec",position:u});if(f.exploded)throw new r({expressionText:e,message:"exploded twice",position:u});if(f.maxLength)throw new r({expressionText:e,message:"an explode (*) MUST NOT follow to a prefix",position:u});f.exploded=!0}else{if(null!==f.maxLength)throw new r({expressionText:e,message:"only one :maxLength is allowed per varspec",position:u});if(f.exploded)throw new r({expressionText:e,message:"an exploeded varspec MUST NOT be varspeced",position:u});d=u+1}}return null!==p&&t(),null!==d&&n(),l.push(f),new h(e,a,l)}function t(t){var n,i,s=[],o=null,a=0;for(n=0;n<t.length;n+=1)if(i=t.charAt(n),null===a){if(null===o)throw new Error("reached unreachable code");if("{"===i)throw new r({templateText:t,message:"brace already opened",position:n});if("}"===i){if(o+1===n)throw new r({templateText:t,message:"empty braces",position:o});try{s.push(e(t.substring(o+1,n)))}catch(c){if(c.prototype===r.prototype)throw new r({templateText:t,message:c.options.message,position:o+c.options.position,details:c.options});throw c}o=null,a=n+1}}else{if("}"===i)throw new r({templateText:t,message:"unopened brace closed",position:n});"{"===i&&(n>a&&s.push(new u(t.substring(a,n))),a=null,o=n)}if(null!==o)throw new r({templateText:t,message:"unclosed brace",position:o});return a<t.length&&s.push(new u(t.substr(a))),new f(t,s)}return t}(),h=function(){function e(e){return JSON&&JSON.stringify?JSON.stringify(e):e}function r(e){if(!t(e))return!0;if(n.isString(e))return""===e;if(n.isNumber(e)||n.isBoolean(e))return!1;if(n.isArray(e))return 0===e.length;for(var r in e)if(e.hasOwnProperty(r))return!1;return!0}function i(e){var t,r=[];for(t in e)e.hasOwnProperty(t)&&r.push({name:t,value:e[t]});return r}function s(e,t,r){this.templateText=e,this.operator=t,this.varspecs=r}function o(e,t,r){var n="";if(r=r.toString(),t.named){if(n+=a.encodeLiteral(e.varname),""===r)return n+=t.ifEmpty;n+="="}return null!==e.maxLength&&(r=r.substr(0,e.maxLength)),n+=t.encode(r)}function c(e){return t(e.value)}function u(e,s,o){var u=[],l="";if(s.named){if(l+=a.encodeLiteral(e.varname),r(o))return l+=s.ifEmpty;l+="="}return n.isArray(o)?(u=o,u=n.filter(u,t),u=n.map(u,s.encode),l+=n.join(u,",")):(u=i(o),u=n.filter(u,c),u=n.map(u,function(e){return s.encode(e.name)+","+s.encode(e.value)}),l+=n.join(u,",")),l}function l(e,s,o){var u=n.isArray(o),l=[];return u?(l=o,l=n.filter(l,t),l=n.map(l,function(t){var n=a.encodeLiteral(e.varname);return n+=r(t)?s.ifEmpty:"="+s.encode(t)})):(l=i(o),l=n.filter(l,c),l=n.map(l,function(e){var t=a.encodeLiteral(e.name);return t+=r(e.value)?s.ifEmpty:"="+s.encode(e.value)})),n.join(l,s.separator)}function h(e,r){var s=[],o="";return n.isArray(r)?(s=r,s=n.filter(s,t),s=n.map(s,e.encode),o+=n.join(s,e.separator)):(s=i(r),s=n.filter(s,function(e){return t(e.value)}),s=n.map(s,function(t){return e.encode(t.name)+"="+e.encode(t.value)}),o+=n.join(s,e.separator)),o}return s.prototype.toString=function(){return this.templateText},s.prototype.expand=function(i){var s,a,c,f,p=[],d=!1,g=this.operator;for(s=0;s<this.varspecs.length;s+=1)if(a=this.varspecs[s],c=i[a.varname],null!==c&&void 0!==c)if(a.exploded&&(d=!0),f=n.isArray(c),"string"==typeof c||"number"==typeof c||"boolean"==typeof c)p.push(o(a,g,c));else{if(a.maxLength&&t(c))throw new Error("Prefix modifiers are not applicable to variables that have composite values. You tried to expand "+this+" with "+e(c));a.exploded?t(c)&&(g.named?p.push(l(a,g,c)):p.push(h(g,c))):(g.named||!r(c))&&p.push(u(a,g,c))}return 0===p.length?"":g.first+n.join(p,g.separator)},s}(),f=function(){function e(e,t){this.templateText=e,this.expressions=t,n.deepFreeze(this)}return e.prototype.toString=function(){return this.templateText},e.prototype.expand=function(e){var t,r="";for(t=0;t<this.expressions.length;t+=1)r+=this.expressions[t].expand(e);return r},e.parse=l,e.UriTemplateError=r,e}();e(f)}(function(e){t.exports=e})},{}],25:[function(e,t){function r(t){function r(t){var r=local.parseUri(t);if("data"!=r.protocol&&(!r.authority||"."==r.authority||-1===r.authority.indexOf("."))){var i=window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/")),o=window.location.protocol+"//"+window.location.hostname+i;t=s.joinRelPath(o,t),r=local.parseUri(t)}var c=r.protocol?t:"https://"+t;local.GET(c).fail(function(e){if(!r.protocol&&(0===e.status||404==e.status))return c="http://"+t,local.GET(c);throw e}).then(function(t){var n=e("../config.js").workerBootstrapScript,i=local.parseUri("data"!=r.protocol?c:window.location.protocol+"//"+window.location.hostname),s=i.protocol+"://"+i.authority;n=n.replace(/\{\{HOST\}\}/g,s),n=n.replace(/\{\{HOST_DIR_PATH\}\}/g,(i.directory||"").slice(0,-1)),n=n.replace(/\{\{HOST_DIR_URL\}\}/g,s+(i.directory||"").slice(0,-1));var o=new Blob([n+"(function(){"+t.body+"; if (main) { self.main = main; }})();"],{type:"text/javascript"});a.fulfill(window.URL.createObjectURL(o))}).fail(function(){a.reject(null),n.terminate(404,"Worker Not Found")})}var n=this;if(!t||!t.src&&!t.domain)throw new Error("WorkerBridgeServer requires config with `src` or `domain` attribute.");o.call(this,t),this.isActive=!1,this.hasHostPrivileges=!0,t.serverFn&&(this.configServerFn=t.serverFn,delete this.config.serverFn);var a=i();if(t.src)0===t.src.indexOf("blob:")?a.fulfill(t.src):r(t.src);else if(t.domain){var c=s.parseUri(t.domain);if(!c.srcPath)throw a.reject(null),this.terminate(404,"Worker Not Properly Constructed"),"Worker incorrectly constructed without src or a domain with a source-path";r(s.joinUri(c.host,c.srcPath))}a.then(function(e){n.config.src=e,n.config.domain||(n.config.domain="<"+n.config.src.slice(0,40)+">"),n.config.environmentHost=window.location.host,n.config.shared?(n.worker=new SharedWorker(e,t.namespace),n.worker.port.start()):n.worker=new Worker(e),"function"==typeof t.onerror&&(n.worker.onerror=t.onerror),n.getPort().addEventListener("message",function(e){var t=e.data;if(!t)return console.error("Invalid message from worker: Payload missing",n,e);switch(n.config.log&&n.debugLog("received from worker",t),t.op){case"ready":n.onWorkerReady(t.body);break;case"log":n.onWorkerLog(t.body);break;case"terminate":n.terminate();break;default:n.onChannelMessage(t)}})})}function n(){if(this.isActive){if(0!==Object.keys(this.incomingStreams).length){var t=e("./response.js");for(var r in this.incomingStreams)if(this.incomingStreams[r]instanceof t&&this.incomingStreams[r].isConnOpen)return}console.log("Closing temporary worker",this.config.domain),this.terminate(),e("./httpl").removeServer(this.config.domain)}}var i=e("../promises.js").promise,s=e("./helpers.js"),o=e("./bridge-server.js");r.prototype=Object.create(o.prototype),t.exports=r,r.prototype.getPort=function(){return this.worker.port?this.worker.port:this.worker},r.prototype.terminate=function(e,t){o.prototype.terminate.call(this,e,t),this.worker&&this.worker.terminate(),"string"==typeof this.config.src&&0===this.config.src.indexOf("blob:")&&window.URL.revokeObjectURL(this.config.src),this.worker=null,this.isActive=!1},r.prototype.isChannelActive=function(){return this.isActive},r.prototype.channelSendMsg=function(e){this.config.log&&this.debugLog("sending to worker",e),this.getPort().postMessage(e)},r.prototype.handleRemoteRequest=function(t,r){var n=e("./httpl.js");if(this.configServerFn)this.configServerFn.call(this,t,r,this);else if(n.getServer("worker-bridge")){var i=n.getServer("worker-bridge");i.fn.call(i.context,t,r,this)}else r.writeHead(501,"server not implemented"),r.end()},r.prototype.handleLocalRequest=function(e,t){o.prototype.handleLocalRequest.call(this,e,t),this.config.temp&&t.on("close",n.bind(this))},r.prototype.onWorkerReady=function(e){if(this.hasHostPrivileges=e.hostPrivileges,this.hasHostPrivileges){var t=JSON.parse(JSON.stringify(this.config));this.channelSendMsg({op:"configure",body:t})}this.isActive=!0,this.flushBufferedMessages()},r.prototype.onWorkerLog=function(e){if(e){if(!Array.isArray(e))return console.error('Received invalid "log" operation: Payload must be an array',e);var t=e.shift(),r=["["+this.config.domain+"]"].concat(e);switch(t){case"error":console.error.apply(console,r);break;case"warn":console.warn.apply(console,r);break;default:console.log.apply(console,r)}}}},{"../config.js":1,"../promises.js":4,"./bridge-server.js":11,"./helpers.js":14,"./httpl":16,"./httpl.js":16,"./response.js":19}],26:[function(e,t){t.exports={}},{}],27:[function(e,t){function r(e,r){var i=t.exports.hostPage;try{i.channelSendMsg({op:"log",body:[e].concat(r)})}catch(s){i.channelSendMsg({op:"log",body:[e].concat(r.map(n))})}}function n(e){return Array.isArray(e)?e.map(n):e&&"object"==typeof e?JSON.stringify(e):e}function i(e,t){var r=255&e.charCodeAt(t);return r}function s(e){var r=!t.exports.hostPage,n=new l(t.exports.pages.length,e,r);r&&(t.exports.hostPage=n,c.addServer("host.page",n)),t.exports.pages.push(n),c.addServer(n.id+".page",n),e.start&&e.start(),n.channelSendMsg({op:"ready",body:{hostPrivileges:r}}),t.exports.emit("connect",n)}if("undefined"!=typeof self&&"undefined"==typeof self.window){var o=e("../util"),a=e("../web/schemes.js"),c=e("../web/httpl.js"),u=e("./config.js"),l=e("./page-bridge-server.js");if(t.exports={config:u},o.mixinEventEmitter(t.exports),self.console={log:function(){var e=Array.prototype.slice.call(arguments);r("log",e)},dir:function(){var e=Array.prototype.slice.call(arguments);r("dir",e)},debug:function(){var e=Array.prototype.slice.call(arguments);r("debug",e)},warn:function(){var e=Array.prototype.slice.call(arguments);r("warn",e)},error:function(){var e=Array.prototype.slice.call(arguments);r("error",e)}},a.register(["http","https"],function(e,t){t.writeHead(0,"XHR Not Allowed in Workers for Security Reasons").end()}),!self.btoa){var h="=",f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";self.btoa=function(e){var t,r,n=h,s=f,o=[];e=""+e;var a=e.length-e.length%3;if(0===e.length)return e;for(t=0;a>t;t+=3)r=i(e,t)<<16|i(e,t+1)<<8|i(e,t+2),o.push(s.charAt(r>>18)),o.push(s.charAt(63&r>>12)),o.push(s.charAt(63&r>>6)),o.push(s.charAt(63&r));switch(e.length-a){case 1:r=i(e,t)<<16,o.push(s.charAt(r>>18)+s.charAt(63&r>>12)+n+n);break;case 2:r=i(e,t)<<16|i(e,t+1)<<8,o.push(s.charAt(r>>18)+s.charAt(63&r>>12)+s.charAt(63&r>>6)+n)}return o.join("")}}t.exports.setServer=function(e){self.main=e,c.addServer("self",e)},t.exports.pages=[],addEventListener("connect",function(e){s(e.ports[0])}),self.postMessage&&s(self)}},{"../util":9,"../web/httpl.js":16,"../web/schemes.js":21,"./config.js":26,"./page-bridge-server.js":28}],28:[function(e,t){function r(e,t,r){s.call(this),this.id=e,this.port=t,this.isHostPage=r,this.port.addEventListener("message",function(e){var t=e.data;if(!t)return console.error("Invalid message from page: Payload missing",e);switch(t.op){case"configure":this.onPageConfigure(t.body);break;case"terminate":this.terminate();break;default:this.onChannelMessage(t)}}.bind(this))}var n=e("../util"),i=e("./config.js"),s=e("../web/bridge-server.js");r.prototype=Object.create(s.prototype),t.exports=r,r.prototype.isChannelActive=function(){return!0},r.prototype.channelSendMsg=function(e){this.port.postMessage(e)},r.prototype.handleRemoteRequest=function(e,t){var r=self.main;r&&"function"==typeof r?r.call(this,e,t,this):r&&r.handleRemoteRequest?r.handleRemoteRequest(e,t,this):(t.writeHead(501,"not implemented"),t.end())},r.prototype.onPageConfigure=function(e){if(!this.isHostPage)return console.log('rejected "configure" from non-host connection'),void 0;var t=i.serverFn;n.mixin.call(i,e),i.serverFn=t}},{"../util":9,"../web/bridge-server.js":11,"./config.js":26}]},{},[3]);