gun.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  1. ;(function(){
  2. /* UNBUILD */
  3. var root;
  4. if(typeof window !== "undefined"){ root = window }
  5. if(typeof global !== "undefined"){ root = global }
  6. root = root || {};
  7. var console = root.console || {log: function(){}};
  8. function USE(arg, req){
  9. return req? require(arg) : arg.slice? USE[R(arg)] : function(mod, path){
  10. arg(mod = {exports: {}});
  11. USE[R(path)] = mod.exports;
  12. }
  13. function R(p){
  14. return p.split('/').slice(-1).toString().replace('.js','');
  15. }
  16. }
  17. if(typeof module !== "undefined"){ var common = module }
  18. /* UNBUILD */
  19. ;USE(function(module){
  20. // Generic javascript utilities.
  21. var Type = {};
  22. //Type.fns = Type.fn = {is: function(fn){ return (!!fn && fn instanceof Function) }}
  23. Type.fn = {is: function(fn){ return (!!fn && 'function' == typeof fn) }}
  24. Type.bi = {is: function(b){ return (b instanceof Boolean || typeof b == 'boolean') }}
  25. Type.num = {is: function(n){ return !list_is(n) && ((n - parseFloat(n) + 1) >= 0 || Infinity === n || -Infinity === n) }}
  26. Type.text = {is: function(t){ return (typeof t == 'string') }}
  27. Type.text.ify = function(t){
  28. if(Type.text.is(t)){ return t }
  29. if(typeof JSON !== "undefined"){ return JSON.stringify(t) }
  30. return (t && t.toString)? t.toString() : t;
  31. }
  32. Type.text.random = function(l, c){
  33. var s = '';
  34. l = l || 24; // you are not going to make a 0 length random number, so no need to check type
  35. c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz';
  36. while(l > 0){ s += c.charAt(Math.floor(Math.random() * c.length)); l-- }
  37. return s;
  38. }
  39. Type.text.match = function(t, o){ var r = false;
  40. t = t || '';
  41. o = Type.text.is(o)? {'=': o} : o || {}; // {'~', '=', '*', '<', '>', '+', '-', '?', '!'} // ignore case, exactly equal, anything after, lexically larger, lexically lesser, added in, subtacted from, questionable fuzzy match, and ends with.
  42. if(Type.obj.has(o,'~')){ t = t.toLowerCase(); o['='] = (o['='] || o['~']).toLowerCase() }
  43. if(Type.obj.has(o,'=')){ return t === o['='] }
  44. if(Type.obj.has(o,'*')){ if(t.slice(0, o['*'].length) === o['*']){ r = true; t = t.slice(o['*'].length) } else { return false }}
  45. if(Type.obj.has(o,'!')){ if(t.slice(-o['!'].length) === o['!']){ r = true } else { return false }}
  46. if(Type.obj.has(o,'+')){
  47. if(Type.list.map(Type.list.is(o['+'])? o['+'] : [o['+']], function(m){
  48. if(t.indexOf(m) >= 0){ r = true } else { return true }
  49. })){ return false }
  50. }
  51. if(Type.obj.has(o,'-')){
  52. if(Type.list.map(Type.list.is(o['-'])? o['-'] : [o['-']], function(m){
  53. if(t.indexOf(m) < 0){ r = true } else { return true }
  54. })){ return false }
  55. }
  56. if(Type.obj.has(o,'>')){ if(t > o['>']){ r = true } else { return false }}
  57. if(Type.obj.has(o,'<')){ if(t < o['<']){ r = true } else { return false }}
  58. function fuzzy(t,f){ var n = -1, i = 0, c; for(;c = f[i++];){ if(!~(n = t.indexOf(c, n+1))){ return false }} return true } // via http://stackoverflow.com/questions/9206013/javascript-fuzzy-search
  59. if(Type.obj.has(o,'?')){ if(fuzzy(t, o['?'])){ r = true } else { return false }} // change name!
  60. return r;
  61. }
  62. Type.list = {is: function(l){ return (l instanceof Array) }}
  63. Type.list.slit = Array.prototype.slice;
  64. Type.list.sort = function(k){ // creates a new sort function based off some key
  65. return function(A,B){
  66. if(!A || !B){ return 0 } A = A[k]; B = B[k];
  67. if(A < B){ return -1 }else if(A > B){ return 1 }
  68. else { return 0 }
  69. }
  70. }
  71. Type.list.map = function(l, c, _){ return obj_map(l, c, _) }
  72. Type.list.index = 1; // change this to 0 if you want non-logical, non-mathematical, non-matrix, non-convenient array notation
  73. Type.obj = {is: function(o){ return o? (o instanceof Object && o.constructor === Object) || Object.prototype.toString.call(o).match(/^\[object (\w+)\]$/)[1] === 'Object' : false }}
  74. Type.obj.put = function(o, k, v){ return (o||{})[k] = v, o }
  75. Type.obj.has = function(o, k){ return o && Object.prototype.hasOwnProperty.call(o, k) }
  76. Type.obj.del = function(o, k){
  77. if(!o){ return }
  78. o[k] = null;
  79. delete o[k];
  80. return o;
  81. }
  82. Type.obj.as = function(o, k, v, u){ return o[k] = o[k] || (u === v? {} : v) }
  83. Type.obj.ify = function(o){
  84. if(obj_is(o)){ return o }
  85. try{o = JSON.parse(o);
  86. }catch(e){o={}};
  87. return o;
  88. }
  89. ;(function(){ var u;
  90. function map(v,k){
  91. if(obj_has(this,k) && u !== this[k]){ return }
  92. this[k] = v;
  93. }
  94. Type.obj.to = function(from, to){
  95. to = to || {};
  96. obj_map(from, map, to);
  97. return to;
  98. }
  99. }());
  100. Type.obj.copy = function(o){ // because http://web.archive.org/web/20140328224025/http://jsperf.com/cloning-an-object/2
  101. return !o? o : JSON.parse(JSON.stringify(o)); // is shockingly faster than anything else, and our data has to be a subset of JSON anyways!
  102. }
  103. ;(function(){
  104. function empty(v,i){ var n = this.n;
  105. if(n && (i === n || (obj_is(n) && obj_has(n, i)))){ return }
  106. if(i){ return true }
  107. }
  108. Type.obj.empty = function(o, n){
  109. if(!o){ return true }
  110. return obj_map(o,empty,{n:n})? false : true;
  111. }
  112. }());
  113. ;(function(){
  114. function t(k,v){
  115. if(2 === arguments.length){
  116. t.r = t.r || {};
  117. t.r[k] = v;
  118. return;
  119. } t.r = t.r || [];
  120. t.r.push(k);
  121. };
  122. var keys = Object.keys;
  123. Type.obj.map = function(l, c, _){
  124. var u, i = 0, x, r, ll, lle, f = fn_is(c);
  125. t.r = null;
  126. if(keys && obj_is(l)){
  127. ll = keys(l); lle = true;
  128. }
  129. if(list_is(l) || ll){
  130. x = (ll || l).length;
  131. for(;i < x; i++){
  132. var ii = (i + Type.list.index);
  133. if(f){
  134. r = lle? c.call(_ || this, l[ll[i]], ll[i], t) : c.call(_ || this, l[i], ii, t);
  135. if(r !== u){ return r }
  136. } else {
  137. //if(Type.test.is(c,l[i])){ return ii } // should implement deep equality testing!
  138. if(c === l[lle? ll[i] : i]){ return ll? ll[i] : ii } // use this for now
  139. }
  140. }
  141. } else {
  142. for(i in l){
  143. if(f){
  144. if(obj_has(l,i)){
  145. r = _? c.call(_, l[i], i, t) : c(l[i], i, t);
  146. if(r !== u){ return r }
  147. }
  148. } else {
  149. //if(a.test.is(c,l[i])){ return i } // should implement deep equality testing!
  150. if(c === l[i]){ return i } // use this for now
  151. }
  152. }
  153. }
  154. return f? t.r : Type.list.index? 0 : -1;
  155. }
  156. }());
  157. Type.time = {};
  158. Type.time.is = function(t){ return t? t instanceof Date : (+new Date().getTime()) }
  159. var fn_is = Type.fn.is;
  160. var list_is = Type.list.is;
  161. var obj = Type.obj, obj_is = obj.is, obj_has = obj.has, obj_map = obj.map;
  162. module.exports = Type;
  163. })(USE, './type');
  164. ;USE(function(module){
  165. // On event emitter generic javascript utility.
  166. module.exports = function onto(tag, arg, as){
  167. if(!tag){ return {to: onto} }
  168. var u, tag = (this.tag || (this.tag = {}))[tag] ||
  169. (this.tag[tag] = {tag: tag, to: onto._ = {
  170. next: function(arg){ var tmp;
  171. if((tmp = this.to)){
  172. tmp.next(arg);
  173. }}
  174. }});
  175. if(arg instanceof Function){
  176. var be = {
  177. off: onto.off ||
  178. (onto.off = function(){
  179. if(this.next === onto._.next){ return !0 }
  180. if(this === this.the.last){
  181. this.the.last = this.back;
  182. }
  183. this.to.back = this.back;
  184. this.next = onto._.next;
  185. this.back.to = this.to;
  186. if(this.the.last === this.the){
  187. delete this.on.tag[this.the.tag];
  188. }
  189. }),
  190. to: onto._,
  191. next: arg,
  192. the: tag,
  193. on: this,
  194. as: as,
  195. };
  196. (be.back = tag.last || tag).to = be;
  197. return tag.last = be;
  198. }
  199. if((tag = tag.to) && u !== arg){ tag.next(arg) }
  200. return tag;
  201. };
  202. })(USE, './onto');
  203. ;USE(function(module){
  204. /* Based on the Hypothetical Amnesia Machine thought experiment */
  205. function HAM(machineState, incomingState, currentState, incomingValue, currentValue){
  206. if(machineState < incomingState){
  207. return {defer: true}; // the incoming value is outside the boundary of the machine's state, it must be reprocessed in another state.
  208. }
  209. if(incomingState < currentState){
  210. return {historical: true}; // the incoming value is within the boundary of the machine's state, but not within the range.
  211. }
  212. if(currentState < incomingState){
  213. return {converge: true, incoming: true}; // the incoming value is within both the boundary and the range of the machine's state.
  214. }
  215. if(incomingState === currentState){
  216. incomingValue = Lexical(incomingValue) || "";
  217. currentValue = Lexical(currentValue) || "";
  218. if(incomingValue === currentValue){ // Note: while these are practically the same, the deltas could be technically different
  219. return {state: true};
  220. }
  221. /*
  222. The following is a naive implementation, but will always work.
  223. Never change it unless you have specific needs that absolutely require it.
  224. If changed, your data will diverge unless you guarantee every peer's algorithm has also been changed to be the same.
  225. As a result, it is highly discouraged to modify despite the fact that it is naive,
  226. because convergence (data integrity) is generally more important.
  227. Any difference in this algorithm must be given a new and different name.
  228. */
  229. if(incomingValue < currentValue){ // Lexical only works on simple value types!
  230. return {converge: true, current: true};
  231. }
  232. if(currentValue < incomingValue){ // Lexical only works on simple value types!
  233. return {converge: true, incoming: true};
  234. }
  235. }
  236. return {err: "Invalid CRDT Data: "+ incomingValue +" to "+ currentValue +" at "+ incomingState +" to "+ currentState +"!"};
  237. }
  238. if(typeof JSON === 'undefined'){
  239. throw new Error(
  240. 'JSON is not included in this browser. Please load it first: ' +
  241. 'ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js'
  242. );
  243. }
  244. var Lexical = JSON.stringify, undefined;
  245. module.exports = HAM;
  246. })(USE, './HAM');
  247. ;USE(function(module){
  248. var Type = USE('./type');
  249. var Val = {};
  250. Val.is = function(v){ // Valid values are a subset of JSON: null, binary, number (!Infinity), text, or a soul relation. Arrays need special algorithms to handle concurrency, so they are not supported directly. Use an extension that supports them if needed but research their problems first.
  251. if(v === u){ return false }
  252. if(v === null){ return true } // "deletes", nulling out keys.
  253. if(v === Infinity){ return false } // we want this to be, but JSON does not support it, sad face.
  254. if(text_is(v) // by "text" we mean strings.
  255. || bi_is(v) // by "binary" we mean boolean.
  256. || num_is(v)){ // by "number" we mean integers or decimals.
  257. return true; // simple values are valid.
  258. }
  259. return Val.rel.is(v) || false; // is the value a soul relation? Then it is valid and return it. If not, everything else remaining is an invalid data type. Custom extensions can be built on top of these primitives to support other types.
  260. }
  261. Val.link = Val.rel = {_: '#'};
  262. ;(function(){
  263. Val.rel.is = function(v){ // this defines whether an object is a soul relation or not, they look like this: {'#': 'UUID'}
  264. if(v && v[rel_] && !v._ && obj_is(v)){ // must be an object.
  265. var o = {};
  266. obj_map(v, map, o);
  267. if(o.id){ // a valid id was found.
  268. return o.id; // yay! Return it.
  269. }
  270. }
  271. return false; // the value was not a valid soul relation.
  272. }
  273. function map(s, k){ var o = this; // map over the object...
  274. if(o.id){ return o.id = false } // if ID is already defined AND we're still looping through the object, it is considered invalid.
  275. if(k == rel_ && text_is(s)){ // the key should be '#' and have a text value.
  276. o.id = s; // we found the soul!
  277. } else {
  278. return o.id = false; // if there exists anything else on the object that isn't the soul, then it is considered invalid.
  279. }
  280. }
  281. }());
  282. Val.rel.ify = function(t){ return obj_put({}, rel_, t) } // convert a soul into a relation and return it.
  283. Type.obj.has._ = '.';
  284. var rel_ = Val.link._, u;
  285. var bi_is = Type.bi.is;
  286. var num_is = Type.num.is;
  287. var text_is = Type.text.is;
  288. var obj = Type.obj, obj_is = obj.is, obj_put = obj.put, obj_map = obj.map;
  289. module.exports = Val;
  290. })(USE, './val');
  291. ;USE(function(module){
  292. var Type = USE('./type');
  293. var Val = USE('./val');
  294. var Node = {_: '_'};
  295. Node.soul = function(n, o){ return (n && n._ && n._[o || soul_]) } // convenience function to check to see if there is a soul on a node and return it.
  296. Node.soul.ify = function(n, o){ // put a soul on an object.
  297. o = (typeof o === 'string')? {soul: o} : o || {};
  298. n = n || {}; // make sure it exists.
  299. n._ = n._ || {}; // make sure meta exists.
  300. n._[soul_] = o.soul || n._[soul_] || text_random(); // put the soul on it.
  301. return n;
  302. }
  303. Node.soul._ = Val.link._;
  304. ;(function(){
  305. Node.is = function(n, cb, as){ var s; // checks to see if an object is a valid node.
  306. if(!obj_is(n)){ return false } // must be an object.
  307. if(s = Node.soul(n)){ // must have a soul on it.
  308. return !obj_map(n, map, {as:as,cb:cb,s:s,n:n});
  309. }
  310. return false; // nope! This was not a valid node.
  311. }
  312. function map(v, k){ // we invert this because the way we check for this is via a negation.
  313. if(k === Node._){ return } // skip over the metadata.
  314. if(!Val.is(v)){ return true } // it is true that this is an invalid node.
  315. if(this.cb){ this.cb.call(this.as, v, k, this.n, this.s) } // optionally callback each key/value.
  316. }
  317. }());
  318. ;(function(){
  319. Node.ify = function(obj, o, as){ // returns a node from a shallow object.
  320. if(!o){ o = {} }
  321. else if(typeof o === 'string'){ o = {soul: o} }
  322. else if(o instanceof Function){ o = {map: o} }
  323. if(o.map){ o.node = o.map.call(as, obj, u, o.node || {}) }
  324. if(o.node = Node.soul.ify(o.node || {}, o)){
  325. obj_map(obj, map, {o:o,as:as});
  326. }
  327. return o.node; // This will only be a valid node if the object wasn't already deep!
  328. }
  329. function map(v, k){ var o = this.o, tmp, u; // iterate over each key/value.
  330. if(o.map){
  331. tmp = o.map.call(this.as, v, ''+k, o.node);
  332. if(u === tmp){
  333. obj_del(o.node, k);
  334. } else
  335. if(o.node){ o.node[k] = tmp }
  336. return;
  337. }
  338. if(Val.is(v)){
  339. o.node[k] = v;
  340. }
  341. }
  342. }());
  343. var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_map = obj.map;
  344. var text = Type.text, text_random = text.random;
  345. var soul_ = Node.soul._;
  346. var u;
  347. module.exports = Node;
  348. })(USE, './node');
  349. ;USE(function(module){
  350. var Type = USE('./type');
  351. var Node = USE('./node');
  352. function State(){
  353. var t;
  354. /*if(perf){
  355. t = start + perf.now(); // Danger: Accuracy decays significantly over time, even if precise.
  356. } else {*/
  357. t = time();
  358. //}
  359. if(last < t){
  360. return N = 0, last = t + State.drift;
  361. }
  362. return last = t + ((N += 1) / D) + State.drift;
  363. }
  364. var time = Type.time.is, last = -Infinity, N = 0, D = 1000; // WARNING! In the future, on machines that are D times faster than 2016AD machines, you will want to increase D by another several orders of magnitude so the processing speed never out paces the decimal resolution (increasing an integer effects the state accuracy).
  365. var perf = (typeof performance !== 'undefined')? (performance.timing && performance) : false, start = (perf && perf.timing && perf.timing.navigationStart) || (perf = false);
  366. State._ = '>';
  367. State.drift = 0;
  368. State.is = function(n, k, o){ // convenience function to get the state on a key on a node and return it.
  369. var tmp = (k && n && n[N_] && n[N_][State._]) || o;
  370. if(!tmp){ return }
  371. return num_is(tmp = tmp[k])? tmp : -Infinity;
  372. }
  373. State.lex = function(){ return State().toString(36).replace('.','') }
  374. State.ify = function(n, k, s, v, soul){ // put a key's state on a node.
  375. if(!n || !n[N_]){ // reject if it is not node-like.
  376. if(!soul){ // unless they passed a soul
  377. return;
  378. }
  379. n = Node.soul.ify(n, soul); // then make it so!
  380. }
  381. var tmp = obj_as(n[N_], State._); // grab the states data.
  382. if(u !== k && k !== N_){
  383. if(num_is(s)){
  384. tmp[k] = s; // add the valid state.
  385. }
  386. if(u !== v){ // Note: Not its job to check for valid values!
  387. n[k] = v;
  388. }
  389. }
  390. return n;
  391. }
  392. State.to = function(from, k, to){
  393. var val = from[k]; // BUGGY!
  394. if(obj_is(val)){
  395. val = obj_copy(val);
  396. }
  397. return State.ify(to, k, State.is(from, k), val, Node.soul(from));
  398. }
  399. ;(function(){
  400. State.map = function(cb, s, as){ var u; // for use with Node.ify
  401. var o = obj_is(o = cb || s)? o : null;
  402. cb = fn_is(cb = cb || s)? cb : null;
  403. if(o && !cb){
  404. s = num_is(s)? s : State();
  405. o[N_] = o[N_] || {};
  406. obj_map(o, map, {o:o,s:s});
  407. return o;
  408. }
  409. as = as || obj_is(s)? s : u;
  410. s = num_is(s)? s : State();
  411. return function(v, k, o, opt){
  412. if(!cb){
  413. map.call({o: o, s: s}, v,k);
  414. return v;
  415. }
  416. cb.call(as || this || {}, v, k, o, opt);
  417. if(obj_has(o,k) && u === o[k]){ return }
  418. map.call({o: o, s: s}, v,k);
  419. }
  420. }
  421. function map(v,k){
  422. if(N_ === k){ return }
  423. State.ify(this.o, k, this.s) ;
  424. }
  425. }());
  426. var obj = Type.obj, obj_as = obj.as, obj_has = obj.has, obj_is = obj.is, obj_map = obj.map, obj_copy = obj.copy;
  427. var num = Type.num, num_is = num.is;
  428. var fn = Type.fn, fn_is = fn.is;
  429. var N_ = Node._, u;
  430. module.exports = State;
  431. })(USE, './state');
  432. ;USE(function(module){
  433. var Type = USE('./type');
  434. var Val = USE('./val');
  435. var Node = USE('./node');
  436. var Graph = {};
  437. ;(function(){
  438. Graph.is = function(g, cb, fn, as){ // checks to see if an object is a valid graph.
  439. if(!g || !obj_is(g) || obj_empty(g)){ return false } // must be an object.
  440. return !obj_map(g, map, {cb:cb,fn:fn,as:as}); // makes sure it wasn't an empty object.
  441. }
  442. function map(n, s){ // we invert this because the way'? we check for this is via a negation.
  443. if(!n || s !== Node.soul(n) || !Node.is(n, this.fn, this.as)){ return true } // it is true that this is an invalid graph.
  444. if(!this.cb){ return }
  445. nf.n = n; nf.as = this.as; // sequential race conditions aren't races.
  446. this.cb.call(nf.as, n, s, nf);
  447. }
  448. function nf(fn){ // optional callback for each node.
  449. if(fn){ Node.is(nf.n, fn, nf.as) } // where we then have an optional callback for each key/value.
  450. }
  451. }());
  452. ;(function(){
  453. Graph.ify = function(obj, env, as){
  454. var at = {path: [], obj: obj};
  455. if(!env){
  456. env = {};
  457. } else
  458. if(typeof env === 'string'){
  459. env = {soul: env};
  460. } else
  461. if(env instanceof Function){
  462. env.map = env;
  463. }
  464. if(env.soul){
  465. at.rel = Val.rel.ify(env.soul);
  466. }
  467. env.shell = (as||{}).shell;
  468. env.graph = env.graph || {};
  469. env.seen = env.seen || [];
  470. env.as = env.as || as;
  471. node(env, at);
  472. env.root = at.node;
  473. return env.graph;
  474. }
  475. function node(env, at){ var tmp;
  476. if(tmp = seen(env, at)){ return tmp }
  477. at.env = env;
  478. at.soul = soul;
  479. if(Node.ify(at.obj, map, at)){
  480. at.rel = at.rel || Val.rel.ify(Node.soul(at.node));
  481. if(at.obj !== env.shell){
  482. env.graph[Val.rel.is(at.rel)] = at.node;
  483. }
  484. }
  485. return at;
  486. }
  487. function map(v,k,n){
  488. var at = this, env = at.env, is, tmp;
  489. if(Node._ === k && obj_has(v,Val.rel._)){
  490. return n._; // TODO: Bug?
  491. }
  492. if(!(is = valid(v,k,n, at,env))){ return }
  493. if(!k){
  494. at.node = at.node || n || {};
  495. if(obj_has(v, Node._) && Node.soul(v)){ // ? for safety ?
  496. at.node._ = obj_copy(v._);
  497. }
  498. at.node = Node.soul.ify(at.node, Val.rel.is(at.rel));
  499. at.rel = at.rel || Val.rel.ify(Node.soul(at.node));
  500. }
  501. if(tmp = env.map){
  502. tmp.call(env.as || {}, v,k,n, at);
  503. if(obj_has(n,k)){
  504. v = n[k];
  505. if(u === v){
  506. obj_del(n, k);
  507. return;
  508. }
  509. if(!(is = valid(v,k,n, at,env))){ return }
  510. }
  511. }
  512. if(!k){ return at.node }
  513. if(true === is){
  514. return v;
  515. }
  516. tmp = node(env, {obj: v, path: at.path.concat(k)});
  517. if(!tmp.node){ return }
  518. return tmp.rel; //{'#': Node.soul(tmp.node)};
  519. }
  520. function soul(id){ var at = this;
  521. var prev = Val.link.is(at.rel), graph = at.env.graph;
  522. at.rel = at.rel || Val.rel.ify(id);
  523. at.rel[Val.rel._] = id;
  524. if(at.node && at.node[Node._]){
  525. at.node[Node._][Val.rel._] = id;
  526. }
  527. if(obj_has(graph, prev)){
  528. graph[id] = graph[prev];
  529. obj_del(graph, prev);
  530. }
  531. }
  532. function valid(v,k,n, at,env){ var tmp;
  533. if(Val.is(v)){ return true }
  534. if(obj_is(v)){ return 1 }
  535. if(tmp = env.invalid){
  536. v = tmp.call(env.as || {}, v,k,n);
  537. return valid(v,k,n, at,env);
  538. }
  539. env.err = "Invalid value at '" + at.path.concat(k).join('.') + "'!";
  540. if(Type.list.is(v)){ env.err += " Use `.set(item)` instead of an Array." }
  541. }
  542. function seen(env, at){
  543. var arr = env.seen, i = arr.length, has;
  544. while(i--){ has = arr[i];
  545. if(at.obj === has.obj){ return has }
  546. }
  547. arr.push(at);
  548. }
  549. }());
  550. Graph.node = function(node){
  551. var soul = Node.soul(node);
  552. if(!soul){ return }
  553. return obj_put({}, soul, node);
  554. }
  555. ;(function(){
  556. Graph.to = function(graph, root, opt){
  557. if(!graph){ return }
  558. var obj = {};
  559. opt = opt || {seen: {}};
  560. obj_map(graph[root], map, {obj:obj, graph: graph, opt: opt});
  561. return obj;
  562. }
  563. function map(v,k){ var tmp, obj;
  564. if(Node._ === k){
  565. if(obj_empty(v, Val.rel._)){
  566. return;
  567. }
  568. this.obj[k] = obj_copy(v);
  569. return;
  570. }
  571. if(!(tmp = Val.rel.is(v))){
  572. this.obj[k] = v;
  573. return;
  574. }
  575. if(obj = this.opt.seen[tmp]){
  576. this.obj[k] = obj;
  577. return;
  578. }
  579. this.obj[k] = this.opt.seen[tmp] = Graph.to(this.graph, tmp, this.opt);
  580. }
  581. }());
  582. var fn_is = Type.fn.is;
  583. var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_has = obj.has, obj_empty = obj.empty, obj_put = obj.put, obj_map = obj.map, obj_copy = obj.copy;
  584. var u;
  585. module.exports = Graph;
  586. })(USE, './graph');
  587. ;USE(function(module){
  588. // request / response module, for asking and acking messages.
  589. USE('./onto'); // depends upon onto!
  590. module.exports = function ask(cb, as){
  591. if(!this.on){ return }
  592. if(!(cb instanceof Function)){
  593. if(!cb || !as){ return }
  594. var id = cb['#'] || cb, tmp = (this.tag||empty)[id];
  595. if(!tmp){ return }
  596. tmp = this.on(id, as);
  597. clearTimeout(tmp.err);
  598. return true;
  599. }
  600. var id = (as && as['#']) || Math.random().toString(36).slice(2);
  601. if(!cb){ return id }
  602. var to = this.on(id, cb, as);
  603. to.err = to.err || setTimeout(function(){
  604. to.next({err: "Error: No ACK received yet.", lack: true});
  605. to.off();
  606. }, (this.opt||{}).lack || 9000);
  607. return id;
  608. }
  609. })(USE, './ask');
  610. ;USE(function(module){
  611. var Type = USE('./type');
  612. function Dup(opt){
  613. var dup = {s:{}};
  614. opt = opt || {max: 1000, age: 1000 * 9};//1000 * 60 * 2};
  615. dup.check = function(id){ var tmp;
  616. if(!(tmp = dup.s[id])){ return false }
  617. if(tmp.pass){ return tmp.pass = false }
  618. return dup.track(id);
  619. }
  620. dup.track = function(id, pass){
  621. var it = dup.s[id] || (dup.s[id] = {});
  622. it.was = time_is();
  623. if(pass){ it.pass = true }
  624. if(!dup.to){
  625. dup.to = setTimeout(function(){
  626. var now = time_is();
  627. Type.obj.map(dup.s, function(it, id){
  628. if(opt.age > (now - it.was)){ return }
  629. Type.obj.del(dup.s, id);
  630. });
  631. dup.to = null;
  632. }, opt.age + 9);
  633. }
  634. return it;
  635. }
  636. return dup;
  637. }
  638. var time_is = Type.time.is;
  639. module.exports = Dup;
  640. })(USE, './dup');
  641. ;USE(function(module){
  642. function Gun(o){
  643. if(o instanceof Gun){ return (this._ = {gun: this, $: this}).$ }
  644. if(!(this instanceof Gun)){ return new Gun(o) }
  645. return Gun.create(this._ = {gun: this, $: this, opt: o});
  646. }
  647. Gun.is = function($){ return ($ instanceof Gun) || ($ && $._ && ($ === $._.$)) || false }
  648. Gun.version = 0.9;
  649. Gun.chain = Gun.prototype;
  650. Gun.chain.toJSON = function(){};
  651. var Type = USE('./type');
  652. Type.obj.to(Type, Gun);
  653. Gun.HAM = USE('./HAM');
  654. Gun.val = USE('./val');
  655. Gun.node = USE('./node');
  656. Gun.state = USE('./state');
  657. Gun.graph = USE('./graph');
  658. Gun.on = USE('./onto');
  659. Gun.ask = USE('./ask');
  660. Gun.dup = USE('./dup');
  661. ;(function(){
  662. Gun.create = function(at){
  663. at.root = at.root || at;
  664. at.graph = at.graph || {};
  665. at.on = at.on || Gun.on;
  666. at.ask = at.ask || Gun.ask;
  667. at.dup = at.dup || Gun.dup();
  668. var gun = at.$.opt(at.opt);
  669. if(!at.once){
  670. at.on('in', root, at);
  671. at.on('out', root, {at: at, out: root});
  672. Gun.on('create', at);
  673. at.on('create', at);
  674. }
  675. at.once = 1;
  676. return gun;
  677. }
  678. function root(msg){
  679. //add to.next(at); // TODO: MISSING FEATURE!!!
  680. var ev = this, as = ev.as, at = as.at || as, gun = at.$, dup, tmp;
  681. if(!(tmp = msg['#'])){ tmp = msg['#'] = text_rand(9) }
  682. if((dup = at.dup).check(tmp)){
  683. if(as.out === msg.out){
  684. msg.out = u;
  685. ev.to.next(msg);
  686. }
  687. return;
  688. }
  689. dup.track(tmp);
  690. if(!at.ask(msg['@'], msg)){
  691. if(msg.get){
  692. Gun.on.get(msg, gun); //at.on('get', get(msg));
  693. }
  694. if(msg.put){
  695. Gun.on.put(msg, gun); //at.on('put', put(msg));
  696. }
  697. }
  698. ev.to.next(msg);
  699. if(!as.out){
  700. msg.out = root;
  701. at.on('out', msg);
  702. }
  703. }
  704. }());
  705. ;(function(){
  706. Gun.on.put = function(msg, gun){
  707. var at = gun._, ctx = {$: gun, graph: at.graph, put: {}, map: {}, souls: {}, machine: Gun.state(), ack: msg['@'], cat: at, stop: {}};
  708. if(!Gun.graph.is(msg.put, null, verify, ctx)){ ctx.err = "Error: Invalid graph!" }
  709. if(ctx.err){ return at.on('in', {'@': msg['#'], err: Gun.log(ctx.err) }) }
  710. obj_map(ctx.put, merge, ctx);
  711. if(!ctx.async){ obj_map(ctx.map, map, ctx) }
  712. if(u !== ctx.defer){
  713. setTimeout(function(){
  714. Gun.on.put(msg, gun);
  715. }, ctx.defer - ctx.machine);
  716. }
  717. if(!ctx.diff){ return }
  718. at.on('put', obj_to(msg, {put: ctx.diff}));
  719. };
  720. function verify(val, key, node, soul){ var ctx = this;
  721. var state = Gun.state.is(node, key), tmp;
  722. if(!state){ return ctx.err = "Error: No state on '"+key+"' in node '"+soul+"'!" }
  723. var vertex = ctx.graph[soul] || empty, was = Gun.state.is(vertex, key, true), known = vertex[key];
  724. var HAM = Gun.HAM(ctx.machine, state, was, val, known);
  725. if(!HAM.incoming){
  726. if(HAM.defer){ // pick the lowest
  727. ctx.defer = (state < (ctx.defer || Infinity))? state : ctx.defer;
  728. }
  729. return;
  730. }
  731. ctx.put[soul] = Gun.state.to(node, key, ctx.put[soul]);
  732. (ctx.diff || (ctx.diff = {}))[soul] = Gun.state.to(node, key, ctx.diff[soul]);
  733. ctx.souls[soul] = true;
  734. }
  735. function merge(node, soul){
  736. var ctx = this, cat = ctx.$._, at = (cat.next || empty)[soul];
  737. if(!at){
  738. if(!(cat.opt||empty).super){
  739. ctx.souls[soul] = false;
  740. return;
  741. }
  742. at = (ctx.$.get(soul)._);
  743. }
  744. var msg = ctx.map[soul] = {
  745. put: node,
  746. get: soul,
  747. $: at.$
  748. }, as = {ctx: ctx, msg: msg};
  749. ctx.async = !!cat.tag.node;
  750. if(ctx.ack){ msg['@'] = ctx.ack }
  751. obj_map(node, each, as);
  752. if(!ctx.async){ return }
  753. if(!ctx.and){
  754. // If it is async, we only need to setup one listener per context (ctx)
  755. cat.on('node', function(m){
  756. this.to.next(m); // make sure to call other context's listeners.
  757. if(m !== ctx.map[m.get]){ return } // filter out events not from this context!
  758. ctx.souls[m.get] = false; // set our many-async flag
  759. obj_map(m.put, patch, m); // merge into view
  760. if(obj_map(ctx.souls, function(v){ if(v){ return v } })){ return } // if flag still outstanding, keep waiting.
  761. if(ctx.c){ return } ctx.c = 1; // failsafe for only being called once per context.
  762. this.off();
  763. obj_map(ctx.map, map, ctx); // all done, trigger chains.
  764. });
  765. }
  766. ctx.and = true;
  767. cat.on('node', msg); // each node on the current context's graph needs to be emitted though.
  768. }
  769. function each(val, key){
  770. var ctx = this.ctx, graph = ctx.graph, msg = this.msg, soul = msg.get, node = msg.put, at = (msg.$._), tmp;
  771. graph[soul] = Gun.state.to(node, key, graph[soul]);
  772. if(ctx.async){ return }
  773. at.put = Gun.state.to(node, key, at.put);
  774. }
  775. function patch(val, key){
  776. var msg = this, node = msg.put, at = (msg.$._);
  777. at.put = Gun.state.to(node, key, at.put);
  778. }
  779. function map(msg, soul){
  780. if(!msg.$){ return }
  781. this.cat.stop = this.stop; // temporary fix till a better solution?
  782. (msg.$._).on('in', msg);
  783. this.cat.stop = null; // temporary fix till a better solution?
  784. }
  785. Gun.on.get = function(msg, gun){
  786. var root = gun._, get = msg.get, soul = get[_soul], node = root.graph[soul], has = get[_has], tmp;
  787. var next = root.next || (root.next = {}), at = next[soul];
  788. if(obj_has(soul, '*')){ // TEMPORARY HACK FOR MARTTI, TESTING
  789. var graph = {};
  790. Gun.obj.map(root.graph, function(node, s){
  791. if(Gun.text.match(s, soul)){
  792. graph[s] = Gun.obj.copy(node);
  793. }
  794. });
  795. if(!Gun.obj.empty(graph)){
  796. root.on('in', {
  797. '@': msg['#'],
  798. how: '*',
  799. put: graph,
  800. $: gun
  801. });
  802. }
  803. } // TEMPORARY HACK FOR MARTTI, TESTING
  804. if(!node){ return root.on('get', msg) }
  805. if(has){
  806. if(!obj_has(node, has)){ return root.on('get', msg) }
  807. node = Gun.state.to(node, has);
  808. // If we have a key in-memory, do we really need to fetch?
  809. // Maybe... in case the in-memory key we have is a local write
  810. // we still need to trigger a pull/merge from peers.
  811. } else {
  812. node = Gun.obj.copy(node);
  813. }
  814. node = Gun.graph.node(node);
  815. tmp = (at||empty).ack;
  816. root.on('in', {
  817. '@': msg['#'],
  818. how: 'mem',
  819. put: node,
  820. $: gun
  821. });
  822. //if(0 < tmp){ return }
  823. root.on('get', msg);
  824. }
  825. }());
  826. ;(function(){
  827. Gun.chain.opt = function(opt){
  828. opt = opt || {};
  829. var gun = this, at = gun._, tmp = opt.peers || opt;
  830. if(!obj_is(opt)){ opt = {} }
  831. if(!obj_is(at.opt)){ at.opt = opt }
  832. if(text_is(tmp)){ tmp = [tmp] }
  833. if(list_is(tmp)){
  834. tmp = obj_map(tmp, function(url, i, map){
  835. map(url, {url: url});
  836. });
  837. if(!obj_is(at.opt.peers)){ at.opt.peers = {}}
  838. at.opt.peers = obj_to(tmp, at.opt.peers);
  839. }
  840. at.opt.peers = at.opt.peers || {};
  841. obj_to(opt, at.opt); // copies options on to `at.opt` only if not already taken.
  842. Gun.on('opt', at);
  843. at.opt.uuid = at.opt.uuid || function(){ return state_lex() + text_rand(12) }
  844. return gun;
  845. }
  846. }());
  847. var list_is = Gun.list.is;
  848. var text = Gun.text, text_is = text.is, text_rand = text.random;
  849. var obj = Gun.obj, obj_is = obj.is, obj_has = obj.has, obj_to = obj.to, obj_map = obj.map, obj_copy = obj.copy;
  850. var state_lex = Gun.state.lex, _soul = Gun.val.rel._, _has = '.', node_ = Gun.node._, rel_is = Gun.val.link.is;
  851. var empty = {}, u;
  852. console.debug = function(i, s){ return (console.debug.i && i === console.debug.i && console.debug.i++) && (console.log.apply(console, arguments) || s) };
  853. Gun.log = function(){ return (!Gun.log.off && console.log.apply(console, arguments)), [].slice.call(arguments).join(' ') }
  854. Gun.log.once = function(w,s,o){ return (o = Gun.log.once)[w] = o[w] || 0, o[w]++ || Gun.log(s) }
  855. ;"Please do not remove these messages unless you are paying for a monthly sponsorship, thanks!";
  856. Gun.log.once("welcome", "Hello wonderful person! :) Thanks for using GUN, feel free to ask for help on https://gitter.im/amark/gun and ask StackOverflow questions tagged with 'gun'!");
  857. ;"Please do not remove these messages unless you are paying for a monthly sponsorship, thanks!";
  858. if(typeof window !== "undefined"){ (window.Gun = Gun).window = window }
  859. try{ if(typeof common !== "undefined"){ common.exports = Gun } }catch(e){}
  860. module.exports = Gun;
  861. /*Gun.on('opt', function(ctx){ // FOR TESTING PURPOSES
  862. this.to.next(ctx);
  863. if(ctx.once){ return }
  864. ctx.on('node', function(msg){
  865. var to = this.to;
  866. //Gun.node.is(msg.put, function(v,k){ msg.put[k] = v + v });
  867. setTimeout(function(){
  868. to.next(msg);
  869. },1);
  870. });
  871. });*/
  872. })(USE, './root');
  873. ;USE(function(module){
  874. var Gun = USE('./root');
  875. Gun.chain.back = function(n, opt){ var tmp;
  876. n = n || 1;
  877. if(-1 === n || Infinity === n){
  878. return this._.root.$;
  879. } else
  880. if(1 === n){
  881. return (this._.back || this._).$;
  882. }
  883. var gun = this, at = gun._;
  884. if(typeof n === 'string'){
  885. n = n.split('.');
  886. }
  887. if(n instanceof Array){
  888. var i = 0, l = n.length, tmp = at;
  889. for(i; i < l; i++){
  890. tmp = (tmp||empty)[n[i]];
  891. }
  892. if(u !== tmp){
  893. return opt? gun : tmp;
  894. } else
  895. if((tmp = at.back)){
  896. return tmp.$.back(n, opt);
  897. }
  898. return;
  899. }
  900. if(n instanceof Function){
  901. var yes, tmp = {back: at};
  902. while((tmp = tmp.back)
  903. && u === (yes = n(tmp, opt))){}
  904. return yes;
  905. }
  906. if(Gun.num.is(n)){
  907. return (at.back || at).$.back(n - 1);
  908. }
  909. return this;
  910. }
  911. var empty = {}, u;
  912. })(USE, './back');
  913. ;USE(function(module){
  914. // WARNING: GUN is very simple, but the JavaScript chaining API around GUN
  915. // is complicated and was extremely hard to build. If you port GUN to another
  916. // language, consider implementing an easier API to build.
  917. var Gun = USE('./root');
  918. Gun.chain.chain = function(sub){
  919. var gun = this, at = gun._, chain = new (sub || gun).constructor(gun), cat = chain._, root;
  920. cat.root = root = at.root;
  921. cat.id = ++root.once;
  922. cat.back = gun._;
  923. cat.on = Gun.on;
  924. cat.on('in', input, cat); // For 'in' if I add my own listeners to each then I MUST do it before in gets called. If I listen globally for all incoming data instead though, regardless of individual listeners, I can transform the data there and then as well.
  925. cat.on('out', output, cat); // However for output, there isn't really the global option. I must listen by adding my own listener individually BEFORE this one is ever called.
  926. return chain;
  927. }
  928. function output(msg){
  929. var put, get, at = this.as, back = at.back, root = at.root, tmp;
  930. if(!msg.I){ msg.I = at.$ }
  931. if(!msg.$){ msg.$ = at.$ }
  932. this.to.next(msg);
  933. if(get = msg.get){
  934. /*if(u !== at.put){
  935. at.on('in', at);
  936. return;
  937. }*/
  938. if(get['#'] || at.soul){
  939. get['#'] = get['#'] || at.soul;
  940. msg['#'] || (msg['#'] = text_rand(9));
  941. back = (root.$.get(get['#'])._);
  942. if(!(get = get['.'])){
  943. tmp = back.ack;
  944. if(!tmp){ back.ack = -1 }
  945. if(obj_has(back, 'put')){
  946. back.on('in', back);
  947. }
  948. if(tmp){ return }
  949. msg.$ = back.$;
  950. } else
  951. if(obj_has(back.put, get)){
  952. put = (back.$.get(get)._);
  953. if(!(tmp = put.ack)){ put.ack = -1 }
  954. back.on('in', {
  955. $: back.$,
  956. put: Gun.state.to(back.put, get),
  957. get: back.get
  958. });
  959. if(tmp){ return }
  960. }
  961. root.ask(ack, msg);
  962. return root.on('in', msg);
  963. }
  964. if(root.now){ root.now[at.id] = root.now[at.id] || true; at.pass = {} }
  965. if(get['.']){
  966. if(at.get){
  967. msg = {get: {'.': at.get}, $: at.$};
  968. //if(back.ask || (back.ask = {})[at.get]){ return }
  969. (back.ask || (back.ask = {}));
  970. back.ask[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
  971. return back.on('out', msg);
  972. }
  973. msg = {get: {}, $: at.$};
  974. return back.on('out', msg);
  975. }
  976. at.ack = at.ack || -1;
  977. if(at.get){
  978. msg.$ = at.$;
  979. get['.'] = at.get;
  980. (back.ask || (back.ask = {}))[at.get] = msg.$._; // TODO: PERFORMANCE? More elegant way?
  981. return back.on('out', msg);
  982. }
  983. }
  984. return back.on('out', msg);
  985. }
  986. function input(msg){
  987. var eve = this, cat = eve.as, root = cat.root, gun = msg.$, at = (gun||empty)._ || empty, change = msg.put, rel, tmp;
  988. if(cat.get && msg.get !== cat.get){
  989. msg = obj_to(msg, {get: cat.get});
  990. }
  991. if(cat.has && at !== cat){
  992. msg = obj_to(msg, {$: cat.$});
  993. if(at.ack){
  994. cat.ack = at.ack;
  995. //cat.ack = cat.ack || at.ack;
  996. }
  997. }
  998. if(u === change){
  999. tmp = at.put;
  1000. eve.to.next(msg);
  1001. if(cat.soul){ return } // TODO: BUG, I believee the fresh input refactor caught an edge case that a `gun.get('soul').get('key')` that points to a soul that doesn't exist will not trigger val/get etc.
  1002. if(u === tmp && u !== at.put){ return }
  1003. echo(cat, msg, eve);
  1004. if(cat.has){
  1005. not(cat, msg);
  1006. }
  1007. obj_del(at.echo, cat.id);
  1008. obj_del(cat.map, at.id);
  1009. return;
  1010. }
  1011. if(cat.soul){
  1012. eve.to.next(msg);
  1013. echo(cat, msg, eve);
  1014. if(cat.next){ obj_map(change, map, {msg: msg, cat: cat}) }
  1015. return;
  1016. }
  1017. if(!(rel = Gun.val.link.is(change))){
  1018. if(Gun.val.is(change)){
  1019. if(cat.has || cat.soul){
  1020. not(cat, msg);
  1021. } else
  1022. if(at.has || at.soul){
  1023. (at.echo || (at.echo = {}))[cat.id] = at.echo[at.id] || cat;
  1024. (cat.map || (cat.map = {}))[at.id] = cat.map[at.id] || {at: at};
  1025. //if(u === at.put){ return } // Not necessary but improves performance. If we have it but at does not, that means we got things out of order and at will get it. Once at gets it, it will tell us again.
  1026. }
  1027. eve.to.next(msg);
  1028. echo(cat, msg, eve);
  1029. return;
  1030. }
  1031. if(cat.has && at !== cat && obj_has(at, 'put')){
  1032. cat.put = at.put;
  1033. };
  1034. if((rel = Gun.node.soul(change)) && at.has){
  1035. at.put = (cat.root.$.get(rel)._).put;
  1036. }
  1037. tmp = (root.stop || {})[at.id];
  1038. //if(tmp && tmp[cat.id]){ } else {
  1039. eve.to.next(msg);
  1040. //}
  1041. relate(cat, msg, at, rel);
  1042. echo(cat, msg, eve);
  1043. if(cat.next){ obj_map(change, map, {msg: msg, cat: cat}) }
  1044. return;
  1045. }
  1046. var was = root.stop;
  1047. tmp = root.stop || {};
  1048. tmp = tmp[at.id] || (tmp[at.id] = {});
  1049. //if(tmp[cat.id]){ return }
  1050. tmp.is = tmp.is || at.put;
  1051. tmp[cat.id] = at.put || true;
  1052. //if(root.stop){
  1053. eve.to.next(msg)
  1054. //}
  1055. relate(cat, msg, at, rel);
  1056. echo(cat, msg, eve);
  1057. }
  1058. var C = 0;
  1059. function relate(at, msg, from, rel){
  1060. if(!rel || node_ === at.get){ return }
  1061. var tmp = (at.root.$.get(rel)._);
  1062. if(at.has){
  1063. from = tmp;
  1064. } else
  1065. if(from.has){
  1066. relate(from, msg, from, rel);
  1067. }
  1068. if(from === at){ return }
  1069. if(!from.$){ from = {} }
  1070. (from.echo || (from.echo = {}))[at.id] = from.echo[at.id] || at;
  1071. if(at.has && !(at.map||empty)[from.id]){ // if we haven't seen this before.
  1072. not(at, msg);
  1073. }
  1074. tmp = from.id? ((at.map || (at.map = {}))[from.id] = at.map[from.id] || {at: from}) : {};
  1075. if(rel === tmp.link){
  1076. if(!(tmp.pass || at.pass)){
  1077. return;
  1078. }
  1079. }
  1080. if(at.pass){
  1081. Gun.obj.map(at.map, function(tmp){ tmp.pass = true })
  1082. obj_del(at, 'pass');
  1083. }
  1084. if(tmp.pass){ obj_del(tmp, 'pass') }
  1085. if(at.has){ at.link = rel }
  1086. ask(at, tmp.link = rel);
  1087. }
  1088. function echo(at, msg, ev){
  1089. if(!at.echo){ return } // || node_ === at.get ?
  1090. //if(at.has){ msg = obj_to(msg, {event: ev}) }
  1091. obj_map(at.echo, reverb, msg);
  1092. }
  1093. function reverb(to){
  1094. if(!to || !to.on){ return }
  1095. to.on('in', this);
  1096. }
  1097. function map(data, key){ // Map over only the changes on every update.
  1098. var cat = this.cat, next = cat.next || empty, via = this.msg, chain, at, tmp;
  1099. if(node_ === key && !next[key]){ return }
  1100. if(!(at = next[key])){
  1101. return;
  1102. }
  1103. //if(data && data[_soul] && (tmp = Gun.val.rel.is(data)) && (tmp = (cat.root.$.get(tmp)._)) && obj_has(tmp, 'put')){
  1104. // data = tmp.put;
  1105. //}
  1106. if(at.has){
  1107. //if(!(data && data[_soul] && Gun.val.rel.is(data) === Gun.node.soul(at.put))){
  1108. if(u === at.put || !Gun.val.link.is(data)){
  1109. at.put = data;
  1110. }
  1111. chain = at.$;
  1112. } else
  1113. if(tmp = via.$){
  1114. tmp = (chain = via.$.get(key))._;
  1115. if(u === tmp.put || !Gun.val.link.is(data)){
  1116. tmp.put = data;
  1117. }
  1118. }
  1119. at.on('in', {
  1120. put: data,
  1121. get: key,
  1122. $: chain,
  1123. via: via
  1124. });
  1125. }
  1126. function not(at, msg){
  1127. if(!(at.has || at.soul)){ return }
  1128. var tmp = at.map, root = at.root;
  1129. at.map = null;
  1130. if(at.has){ at.link = null }
  1131. //if(!root.now || !root.now[at.id]){
  1132. if(!at.pass){
  1133. if((!msg['@']) && null === tmp){ return }
  1134. //obj_del(at, 'pass');
  1135. }
  1136. if(u === tmp && Gun.val.link.is(at.put)){ return } // This prevents the very first call of a thing from triggering a "clean up" call. // TODO: link.is(at.put) || !val.is(at.put) ?
  1137. obj_map(tmp, function(proxy){
  1138. if(!(proxy = proxy.at)){ return }
  1139. obj_del(proxy.echo, at.id);
  1140. });
  1141. tmp = at.put;
  1142. obj_map(at.next, function(neat, key){
  1143. if(u === tmp && u !== at.put){ return true }
  1144. neat.put = u;
  1145. if(neat.ack){
  1146. neat.ack = -1;
  1147. }
  1148. neat.on('in', {
  1149. get: key,
  1150. $: neat.$,
  1151. put: u
  1152. });
  1153. });
  1154. }
  1155. function ask(at, soul){
  1156. var tmp = (at.root.$.get(soul)._);
  1157. if(at.ack){
  1158. tmp.on('out', {get: {'#': soul}});
  1159. if(!at.ask){ return } // TODO: PERFORMANCE? More elegant way?
  1160. }
  1161. tmp = at.ask; Gun.obj.del(at, 'ask');
  1162. obj_map(tmp || at.next, function(neat, key){
  1163. neat.on('out', {get: {'#': soul, '.': key}});
  1164. });
  1165. Gun.obj.del(at, 'ask'); // TODO: PERFORMANCE? More elegant way?
  1166. }
  1167. function ack(msg, ev){
  1168. var as = this.as, get = as.get || empty, at = as.$._, tmp = (msg.put||empty)[get['#']];
  1169. if(at.ack){ at.ack = (at.ack + 1) || 1; }
  1170. if(!msg.put || (get['.'] && !obj_has(tmp, at.get))){
  1171. if(at.put !== u){ return }
  1172. at.on('in', {
  1173. get: at.get,
  1174. put: at.put = u,
  1175. $: at.$,
  1176. '@': msg['@']
  1177. });
  1178. return;
  1179. }
  1180. if(node_ == get['.']){ // is this a security concern?
  1181. at.on('in', {get: at.get, put: Gun.val.link.ify(get['#']), $: at.$, '@': msg['@']});
  1182. return;
  1183. }
  1184. msg.$ = at.root.$;
  1185. Gun.on.put(msg, at.root.$);
  1186. }
  1187. var empty = {}, u;
  1188. var obj = Gun.obj, obj_has = obj.has, obj_put = obj.put, obj_del = obj.del, obj_to = obj.to, obj_map = obj.map;
  1189. var text_rand = Gun.text.random;
  1190. var _soul = Gun.val.rel._, node_ = Gun.node._;
  1191. })(USE, './chain');
  1192. ;USE(function(module){
  1193. var Gun = USE('./root');
  1194. Gun.chain.get = function(key, cb, as){
  1195. var gun, tmp;
  1196. if(typeof key === 'string'){
  1197. var back = this, cat = back._;
  1198. var next = cat.next || empty;
  1199. if(!(gun = next[key])){
  1200. gun = cache(key, back);
  1201. }
  1202. gun = gun.$;
  1203. } else
  1204. if(key instanceof Function){
  1205. if(true === cb){ return soul(this, key, cb, as) }
  1206. gun = this;
  1207. var at = gun._, root = at.root, tmp = root.now, ev;
  1208. as = cb || {};
  1209. as.at = at;
  1210. as.use = key;
  1211. as.out = as.out || {};
  1212. as.out.get = as.out.get || {};
  1213. (ev = at.on('in', use, as)).rid = rid;
  1214. (root.now = {$:1})[as.now = at.id] = ev;
  1215. var mum = root.mum; root.mum = {};
  1216. at.on('out', as.out);
  1217. root.mum = mum;
  1218. root.now = tmp;
  1219. return gun;
  1220. } else
  1221. if(num_is(key)){
  1222. return this.get(''+key, cb, as);
  1223. } else
  1224. if(tmp = rel.is(key)){
  1225. return this.get(tmp, cb, as);
  1226. } else {
  1227. (as = this.chain())._.err = {err: Gun.log('Invalid get request!', key)}; // CLEAN UP
  1228. if(cb){ cb.call(as, as._.err) }
  1229. return as;
  1230. }
  1231. if(tmp = cat.stun){ // TODO: Refactor?
  1232. gun._.stun = gun._.stun || tmp;
  1233. }
  1234. if(cb && cb instanceof Function){
  1235. gun.get(cb, as);
  1236. }
  1237. return gun;
  1238. }
  1239. function cache(key, back){
  1240. var cat = back._, next = cat.next, gun = back.chain(), at = gun._;
  1241. if(!next){ next = cat.next = {} }
  1242. next[at.get = key] = at;
  1243. if(back === cat.root.$){
  1244. at.soul = key;
  1245. } else
  1246. if(cat.soul || cat.has){
  1247. at.has = key;
  1248. //if(obj_has(cat.put, key)){
  1249. //at.put = cat.put[key];
  1250. //}
  1251. }
  1252. return at;
  1253. }
  1254. function soul(gun, cb, opt, as){
  1255. var cat = gun._, tmp;
  1256. if(tmp = cat.soul){ return cb(tmp, as, cat), gun }
  1257. if(tmp = cat.link){ return cb(tmp, as, cat), gun }
  1258. gun.get(function(msg, ev){
  1259. ev.rid(msg);
  1260. var at = ((at = msg.$) && at._) || {};
  1261. tmp = at.link || at.soul || rel.is(msg.put) || node_soul(msg.put);
  1262. cb(tmp, as, msg, ev);
  1263. }, {out: {get: {'.':true}}});
  1264. return gun;
  1265. }
  1266. function use(msg){
  1267. var eve = this, as = eve.as, cat = as.at, root = cat.root, gun = msg.$, at = (gun||{})._ || {}, data = msg.put || at.put, tmp;
  1268. if((tmp = root.now) && eve !== tmp[as.now]){ return eve.to.next(msg) }
  1269. //console.log("USE:", cat.id, cat.soul, cat.has, cat.get, msg, root.mum);
  1270. //if(at.async && msg.root){ return }
  1271. //if(at.async === 1 && cat.async !== true){ return }
  1272. //if(root.stop && root.stop[at.id]){ return } root.stop && (root.stop[at.id] = true);
  1273. //if(!at.async && !cat.async && at.put && msg.put === at.put){ return }
  1274. //else if(!cat.async && msg.put !== at.put && root.stop && root.stop[at.id]){ return } root.stop && (root.stop[at.id] = true);
  1275. //root.stop && (root.stop.ID = root.stop.ID || Gun.text.random(2));
  1276. //if((tmp = root.stop) && (tmp = tmp[at.id] || (tmp[at.id] = {})) && tmp[cat.id]){ return } tmp && (tmp[cat.id] = true);
  1277. if(eve.seen && at.id && eve.seen[at.id]){ return eve.to.next(msg) }
  1278. //if((tmp = root.stop)){ if(tmp[at.id]){ return } tmp[at.id] = msg.root; } // temporary fix till a better solution?
  1279. if((tmp = data) && tmp[rel._] && (tmp = rel.is(tmp))){
  1280. tmp = ((msg.$$ = at.root.gun.get(tmp))._);
  1281. if(u !== tmp.put){
  1282. msg = obj_to(msg, {put: data = tmp.put});
  1283. }
  1284. }
  1285. if((tmp = root.mum) && at.id){
  1286. if(tmp[at.id]){ return }
  1287. if(u !== data && !rel.is(data)){ tmp[at.id] = true; }
  1288. }
  1289. as.use(msg, eve);
  1290. if(eve.stun){
  1291. eve.stun = null;
  1292. return;
  1293. }
  1294. eve.to.next(msg);
  1295. }
  1296. function rid(at){
  1297. var cat = this.on;
  1298. if(!at || cat.soul || cat.has){ return this.off() }
  1299. if(!(at = (at = (at = at.$ || at)._ || at).id)){ return }
  1300. var map = cat.map, tmp, seen;
  1301. //if(!map || !(tmp = map[at]) || !(tmp = tmp.at)){ return }
  1302. if(tmp = (seen = this.seen || (this.seen = {}))[at]){ return true }
  1303. seen[at] = true;
  1304. return;
  1305. //tmp.echo[cat.id] = {}; // TODO: Warning: This unsubscribes ALL of this chain's listeners from this link, not just the one callback event.
  1306. //obj.del(map, at); // TODO: Warning: This unsubscribes ALL of this chain's listeners from this link, not just the one callback event.
  1307. return;
  1308. }
  1309. var obj = Gun.obj, obj_has = obj.has, obj_to = Gun.obj.to;
  1310. var num_is = Gun.num.is;
  1311. var rel = Gun.val.link, node_soul = Gun.node.soul, node_ = Gun.node._;
  1312. var empty = {}, u;
  1313. })(USE, './get');
  1314. ;USE(function(module){
  1315. var Gun = USE('./root');
  1316. Gun.chain.put = function(data, cb, as){
  1317. // #soul.has=value>state
  1318. // ~who#where.where=what>when@was
  1319. // TODO: BUG! Put probably cannot handle plural chains!
  1320. var gun = this, at = (gun._), root = at.root.$, tmp;
  1321. as = as || {};
  1322. as.data = data;
  1323. as.via = as.$ = as.via || as.$ || gun;
  1324. if(typeof cb === 'string'){
  1325. as.soul = cb;
  1326. } else {
  1327. as.ack = as.ack || cb;
  1328. }
  1329. if(at.soul){
  1330. as.soul = at.soul;
  1331. }
  1332. if(as.soul || root === gun){
  1333. if(!obj_is(as.data)){
  1334. (as.ack||noop).call(as, as.out = {err: Gun.log("Data saved to the root level of the graph must be a node (an object), not a", (typeof as.data), 'of "' + as.data + '"!')});
  1335. if(as.res){ as.res() }
  1336. return gun;
  1337. }
  1338. as.soul = as.soul || (as.not = Gun.node.soul(as.data) || (as.via.back('opt.uuid') || Gun.text.random)());
  1339. if(!as.soul){ // polyfill async uuid for SEA
  1340. as.via.back('opt.uuid')(function(err, soul){ // TODO: improve perf without anonymous callback
  1341. if(err){ return Gun.log(err) } // TODO: Handle error!
  1342. (as.ref||as.$).put(as.data, as.soul = soul, as);
  1343. });
  1344. return gun;
  1345. }
  1346. as.$ = gun = root.get(as.soul);
  1347. as.ref = as.$;
  1348. ify(as);
  1349. return gun;
  1350. }
  1351. if(Gun.is(data)){
  1352. data.get(function(soul, o, msg){
  1353. if(!soul && Gun.val.is(msg.put)){
  1354. return Gun.log("The reference you are saving is a", typeof msg.put, '"'+ msg.put +'", not a node (object)!');
  1355. }
  1356. gun.put(Gun.val.rel.ify(soul), cb, as);
  1357. }, true);
  1358. return gun;
  1359. }
  1360. as.ref = as.ref || (root._ === (tmp = at.back))? gun : tmp.$;
  1361. if(as.ref._.soul && Gun.val.is(as.data) && at.get){
  1362. as.data = obj_put({}, at.get, as.data);
  1363. as.ref.put(as.data, as.soul, as);
  1364. return gun;
  1365. }
  1366. as.ref.get(any, true, {as: as});
  1367. if(!as.out){
  1368. // TODO: Perf idea! Make a global lock, that blocks everything while it is on, but if it is on the lock it does the expensive lookup to see if it is a dependent write or not and if not then it proceeds full speed. Meh? For write heavy async apps that would be terrible.
  1369. as.res = as.res || stun; // Gun.on.stun(as.ref); // TODO: BUG! Deal with locking?
  1370. as.$._.stun = as.ref._.stun;
  1371. }
  1372. return gun;
  1373. };
  1374. function ify(as){
  1375. as.batch = batch;
  1376. var opt = as.opt||{}, env = as.env = Gun.state.map(map, opt.state);
  1377. env.soul = as.soul;
  1378. as.graph = Gun.graph.ify(as.data, env, as);
  1379. if(env.err){
  1380. (as.ack||noop).call(as, as.out = {err: Gun.log(env.err)});
  1381. if(as.res){ as.res() }
  1382. return;
  1383. }
  1384. as.batch();
  1385. }
  1386. function stun(cb){
  1387. if(cb){ cb() }
  1388. return;
  1389. var as = this;
  1390. if(!as.ref){ return }
  1391. if(cb){
  1392. as.after = as.ref._.tag;
  1393. as.now = as.ref._.tag = {};
  1394. cb();
  1395. return;
  1396. }
  1397. if(as.after){
  1398. as.ref._.tag = as.after;
  1399. }
  1400. }
  1401. function batch(){ var as = this;
  1402. if(!as.graph || obj_map(as.stun, no)){ return }
  1403. as.res = as.res || function(cb){ if(cb){ cb() } };
  1404. as.res(function(){
  1405. var cat = (as.$.back(-1)._), ask = cat.ask(function(ack){
  1406. cat.root.on('ack', ack);
  1407. if(ack.err){ Gun.log(ack) }
  1408. if(!ack.lack){ this.off() } // One response is good enough for us currently. Later we may want to adjust this.
  1409. if(!as.ack){ return }
  1410. as.ack(ack, this);
  1411. }, as.opt);
  1412. // NOW is a hack to get synchronous replies to correctly call.
  1413. // and STOP is a hack to get async behavior to correctly call.
  1414. // neither of these are ideal, need to be fixed without hacks,
  1415. // but for now, this works for current tests. :/
  1416. var tmp = cat.root.now; obj.del(cat.root, 'now');
  1417. var mum = cat.root.mum; cat.root.mum = {};
  1418. (as.ref._).on('out', {
  1419. $: as.ref, put: as.out = as.env.graph, opt: as.opt, '#': ask
  1420. });
  1421. cat.root.mum = mum? obj.to(mum, cat.root.mum) : mum;
  1422. cat.root.now = tmp;
  1423. }, as);
  1424. if(as.res){ as.res() }
  1425. } function no(v,k){ if(v){ return true } }
  1426. function map(v,k,n, at){ var as = this;
  1427. var is = Gun.is(v);
  1428. if(k || !at.path.length){ return }
  1429. (as.res||iife)(function(){
  1430. var path = at.path, ref = as.ref, opt = as.opt;
  1431. var i = 0, l = path.length;
  1432. for(i; i < l; i++){
  1433. ref = ref.get(path[i]);
  1434. }
  1435. if(is){ ref = v }
  1436. var id = (ref._).dub;
  1437. if(id || (id = Gun.node.soul(at.obj))){
  1438. ref.back(-1).get(id);
  1439. at.soul(id);
  1440. return;
  1441. }
  1442. (as.stun = as.stun || {})[path] = true;
  1443. ref.get(soul, true, {as: {at: at, as: as, p:path}});
  1444. }, {as: as, at: at});
  1445. //if(is){ return {} }
  1446. }
  1447. function soul(id, as, msg, eve){
  1448. var as = as.as, cat = as.at; as = as.as;
  1449. var at = ((msg || {}).$ || {})._ || {};
  1450. id = at.dub = at.dub || id || Gun.node.soul(cat.obj) || Gun.node.soul(msg.put || at.put) || Gun.val.rel.is(msg.put || at.put) || (as.via.back('opt.uuid') || Gun.text.random)(); // TODO: BUG!? Do we really want the soul of the object given to us? Could that be dangerous?
  1451. if(eve){ eve.stun = true }
  1452. if(!id){ // polyfill async uuid for SEA
  1453. at.via.back('opt.uuid')(function(err, id){ // TODO: improve perf without anonymous callback
  1454. if(err){ return Gun.log(err) } // TODO: Handle error.
  1455. solve(at, at.dub = at.dub || id, cat, as);
  1456. });
  1457. return;
  1458. }
  1459. solve(at, at.dub = id, cat, as);
  1460. }
  1461. function solve(at, id, cat, as){
  1462. at.$.back(-1).get(id);
  1463. cat.soul(id);
  1464. as.stun[cat.path] = false;
  1465. as.batch();
  1466. }
  1467. function any(soul, as, msg, eve){
  1468. as = as.as;
  1469. if(!msg.$ || !msg.$._){ return } // TODO: Handle
  1470. if(msg.err){ // TODO: Handle
  1471. console.log("Please report this as an issue! Put.any.err");
  1472. return;
  1473. }
  1474. var at = (msg.$._), data = at.put, opt = as.opt||{}, root, tmp;
  1475. if((tmp = as.ref) && tmp._.now){ return }
  1476. if(eve){ eve.stun = true }
  1477. if(as.ref !== as.$){
  1478. tmp = (as.$._).get || at.get;
  1479. if(!tmp){ // TODO: Handle
  1480. console.log("Please report this as an issue! Put.no.get"); // TODO: BUG!??
  1481. return;
  1482. }
  1483. as.data = obj_put({}, tmp, as.data);
  1484. tmp = null;
  1485. }
  1486. if(u === data){
  1487. if(!at.get){ return } // TODO: Handle
  1488. if(!soul){
  1489. tmp = at.$.back(function(at){
  1490. if(at.link || at.soul){ return at.link || at.soul }
  1491. as.data = obj_put({}, at.get, as.data);
  1492. });
  1493. }
  1494. tmp = tmp || at.get;
  1495. at = (at.root.$.get(tmp)._);
  1496. as.soul = tmp;
  1497. data = as.data;
  1498. }
  1499. if(!as.not && !(as.soul = as.soul || soul)){
  1500. if(as.path && obj_is(as.data)){
  1501. as.soul = (opt.uuid || as.via.back('opt.uuid') || Gun.text.random)();
  1502. } else {
  1503. //as.data = obj_put({}, as.$._.get, as.data);
  1504. if(node_ == at.get){
  1505. as.soul = (at.put||empty)['#'] || at.dub;
  1506. }
  1507. as.soul = as.soul || at.soul || at.soul || (opt.uuid || as.via.back('opt.uuid') || Gun.text.random)();
  1508. }
  1509. if(!as.soul){ // polyfill async uuid for SEA
  1510. as.via.back('opt.uuid')(function(err, soul){ // TODO: improve perf without anonymous callback
  1511. if(err){ return Gun.log(err) } // Handle error.
  1512. as.ref.put(as.data, as.soul = soul, as);
  1513. });
  1514. return;
  1515. }
  1516. }
  1517. as.ref.put(as.data, as.soul, as);
  1518. }
  1519. var obj = Gun.obj, obj_is = obj.is, obj_put = obj.put, obj_map = obj.map;
  1520. var u, empty = {}, noop = function(){}, iife = function(fn,as){fn.call(as||empty)};
  1521. var node_ = Gun.node._;
  1522. })(USE, './put');
  1523. ;USE(function(module){
  1524. var Gun = USE('./root');
  1525. USE('./chain');
  1526. USE('./back');
  1527. USE('./put');
  1528. USE('./get');
  1529. module.exports = Gun;
  1530. })(USE, './index');
  1531. ;USE(function(module){
  1532. var Gun = USE('./index');
  1533. Gun.chain.on = function(tag, arg, eas, as){
  1534. var gun = this, at = gun._, tmp, act, off;
  1535. if(typeof tag === 'string'){
  1536. if(!arg){ return at.on(tag) }
  1537. act = at.on(tag, arg, eas || at, as);
  1538. if(eas && eas.$){
  1539. (eas.subs || (eas.subs = [])).push(act);
  1540. }
  1541. return gun;
  1542. }
  1543. var opt = arg;
  1544. opt = (true === opt)? {change: true} : opt || {};
  1545. opt.at = at;
  1546. opt.ok = tag;
  1547. //opt.last = {};
  1548. gun.get(ok, opt); // TODO: PERF! Event listener leak!!!?
  1549. return gun;
  1550. }
  1551. function ok(msg, ev){ var opt = this;
  1552. var gun = msg.$, at = (gun||{})._ || {}, data = at.put || msg.put, cat = opt.at, tmp;
  1553. if(u === data){
  1554. return;
  1555. }
  1556. if(tmp = msg.$$){
  1557. tmp = (msg.$$._);
  1558. if(u === tmp.put){
  1559. return;
  1560. }
  1561. data = tmp.put;
  1562. }
  1563. if(opt.change){ // TODO: BUG? Move above the undef checks?
  1564. data = msg.put;
  1565. }
  1566. // DEDUPLICATE // TODO: NEEDS WORK! BAD PROTOTYPE
  1567. //if(tmp.put === data && tmp.get === id && !Gun.node.soul(data)){ return }
  1568. //tmp.put = data;
  1569. //tmp.get = id;
  1570. // DEDUPLICATE // TODO: NEEDS WORK! BAD PROTOTYPE
  1571. //at.last = data;
  1572. if(opt.as){
  1573. opt.ok.call(opt.as, msg, ev);
  1574. } else {
  1575. opt.ok.call(gun, data, msg.get, msg, ev);
  1576. }
  1577. }
  1578. Gun.chain.val = function(cb, opt){
  1579. Gun.log.once("onceval", "Future Breaking API Change: .val -> .once, apologies unexpected.");
  1580. return this.once(cb, opt);
  1581. }
  1582. Gun.chain.once = function(cb, opt){
  1583. var gun = this, at = gun._, data = at.put;
  1584. if(0 < at.ack && u !== data){
  1585. (cb || noop).call(gun, data, at.get);
  1586. return gun;
  1587. }
  1588. if(cb){
  1589. (opt = opt || {}).ok = cb;
  1590. opt.at = at;
  1591. opt.out = {'#': Gun.text.random(9)};
  1592. gun.get(val, {as: opt});
  1593. opt.async = true; //opt.async = at.stun? 1 : true;
  1594. } else {
  1595. Gun.log.once("valonce", "Chainable val is experimental, its behavior and API may change moving forward. Please play with it and report bugs and ideas on how to improve it.");
  1596. var chain = gun.chain();
  1597. chain._.nix = gun.once(function(){
  1598. chain._.on('in', gun._);
  1599. });
  1600. return chain;
  1601. }
  1602. return gun;
  1603. }
  1604. function val(msg, eve, to){
  1605. var opt = this.as, cat = opt.at, gun = msg.$, at = gun._, data = at.put || msg.put, link, tmp;
  1606. if(tmp = msg.$$){
  1607. link = tmp = (msg.$$._);
  1608. if(u === tmp.put){
  1609. return;
  1610. }
  1611. data = tmp.put;
  1612. }
  1613. if((tmp = eve.wait) && (tmp = tmp[at.id])){ clearTimeout(tmp) }
  1614. if((!to && (u === data || at.soul || at.link || (link && !(0 < link.ack))))
  1615. || (u === data && (tmp = (obj_map(at.root.opt.peers, function(v,k,t){t(k)})||[]).length) && (link||at).ack <= tmp)){
  1616. tmp = (eve.wait = {})[at.id] = setTimeout(function(){
  1617. val.call({as:opt}, msg, eve, tmp || 1);
  1618. }, opt.wait || 99);
  1619. return;
  1620. }
  1621. eve.rid(msg);
  1622. opt.ok.call(gun || opt.$, data, msg.get);
  1623. }
  1624. Gun.chain.off = function(){
  1625. // make off more aggressive. Warning, it might backfire!
  1626. var gun = this, at = gun._, tmp;
  1627. var cat = at.back;
  1628. if(!cat){ return }
  1629. if(tmp = cat.next){
  1630. if(tmp[at.get]){
  1631. obj_del(tmp, at.get);
  1632. } else {
  1633. }
  1634. }
  1635. if(tmp = cat.ask){
  1636. obj_del(tmp, at.get);
  1637. }
  1638. if(tmp = cat.put){
  1639. obj_del(tmp, at.get);
  1640. }
  1641. if(tmp = at.soul){
  1642. obj_del(cat.root.graph, tmp);
  1643. }
  1644. if(tmp = at.map){
  1645. obj_map(tmp, function(at){
  1646. if(at.link){
  1647. cat.root.$.get(at.link).off();
  1648. }
  1649. });
  1650. }
  1651. if(tmp = at.next){
  1652. obj_map(tmp, function(neat){
  1653. neat.$.off();
  1654. });
  1655. }
  1656. at.on('off', {});
  1657. return gun;
  1658. }
  1659. var obj = Gun.obj, obj_map = obj.map, obj_has = obj.has, obj_del = obj.del, obj_to = obj.to;
  1660. var rel = Gun.val.link;
  1661. var empty = {}, noop = function(){}, u;
  1662. })(USE, './on');
  1663. ;USE(function(module){
  1664. var Gun = USE('./index');
  1665. Gun.chain.map = function(cb, opt, t){
  1666. var gun = this, cat = gun._, chain;
  1667. if(!cb){
  1668. if(chain = cat.each){ return chain }
  1669. cat.each = chain = gun.chain();
  1670. chain._.nix = gun.back('nix');
  1671. gun.on('in', map, chain._);
  1672. return chain;
  1673. }
  1674. Gun.log.once("mapfn", "Map functions are experimental, their behavior and API may change moving forward. Please play with it and report bugs and ideas on how to improve it.");
  1675. chain = gun.chain();
  1676. gun.map().on(function(data, key, at, ev){
  1677. var next = (cb||noop).call(this, data, key, at, ev);
  1678. if(u === next){ return }
  1679. if(data === next){ return chain._.on('in', at) }
  1680. if(Gun.is(next)){ return chain._.on('in', next._) }
  1681. chain._.on('in', {get: key, put: next});
  1682. });
  1683. return chain;
  1684. }
  1685. function map(msg){
  1686. if(!msg.put || Gun.val.is(msg.put)){ return this.to.next(msg) }
  1687. if(this.as.nix){ this.off() } // TODO: Ugly hack!
  1688. obj_map(msg.put, each, {at: this.as, msg: msg});
  1689. this.to.next(msg);
  1690. }
  1691. function each(v,k){
  1692. if(n_ === k){ return }
  1693. var msg = this.msg, gun = msg.$, at = this.at, tmp = (gun.get(k)._);
  1694. (tmp.echo || (tmp.echo = {}))[at.id] = tmp.echo[at.id] || at;
  1695. }
  1696. var obj_map = Gun.obj.map, noop = function(){}, event = {stun: noop, off: noop}, n_ = Gun.node._, u;
  1697. })(USE, './map');
  1698. ;USE(function(module){
  1699. var Gun = USE('./index');
  1700. Gun.chain.set = function(item, cb, opt){
  1701. var gun = this, soul;
  1702. cb = cb || function(){};
  1703. opt = opt || {}; opt.item = opt.item || item;
  1704. if(soul = Gun.node.soul(item)){ return gun.set(gun.back(-1).get(soul), cb, opt) }
  1705. if(!Gun.is(item)){
  1706. var id = gun.back('opt.uuid')();
  1707. if(id && Gun.obj.is(item)){
  1708. return gun.set(gun._.root.$.put(item, id), cb, opt);
  1709. }
  1710. return gun.get((Gun.state.lex() + Gun.text.random(7))).put(item, cb, opt);
  1711. }
  1712. item.get(function(soul, o, msg){
  1713. if(!soul){ return cb.call(gun, {err: Gun.log('Only a node can be linked! Not "' + msg.put + '"!')}) }
  1714. gun.put(Gun.obj.put({}, soul, Gun.val.link.ify(soul)), cb, opt);
  1715. },true);
  1716. return item;
  1717. }
  1718. })(USE, './set');
  1719. ;USE(function(module){
  1720. if(typeof Gun === 'undefined'){ return } // TODO: localStorage is Browser only. But it would be nice if it could somehow plugin into NodeJS compatible localStorage APIs?
  1721. var root, noop = function(){}, u;
  1722. if(typeof window !== 'undefined'){ root = window }
  1723. var store = root.localStorage || {setItem: noop, removeItem: noop, getItem: noop};
  1724. /*
  1725. NOTE: Both `lib/file.js` and `lib/memdisk.js` are based on this design!
  1726. If you update anything here, consider updating the other adapters as well.
  1727. */
  1728. Gun.on('create', function(root){
  1729. // This code is used to queue offline writes for resync.
  1730. // See the next 'opt' code below for actual saving of data.
  1731. var ev = this.to, opt = root.opt;
  1732. if(root.once){ return ev.next(root) }
  1733. //if(false === opt.localStorage){ return ev.next(root) } // we want offline resynce queue regardless!
  1734. opt.prefix = opt.file || 'gun/';
  1735. var gap = Gun.obj.ify(store.getItem('gap/'+opt.prefix)) || {};
  1736. var empty = Gun.obj.empty, id, to, go;
  1737. // add re-sync command.
  1738. if(!empty(gap)){
  1739. var disk = Gun.obj.ify(store.getItem(opt.prefix)) || {}, send = {};
  1740. Gun.obj.map(gap, function(node, soul){
  1741. Gun.obj.map(node, function(val, key){
  1742. send[soul] = Gun.state.to(disk[soul], key, send[soul]);
  1743. });
  1744. });
  1745. setTimeout(function(){
  1746. root.on('out', {put: send, '#': root.ask(ack), I: root.$});
  1747. },1);
  1748. }
  1749. root.on('out', function(msg){
  1750. if(msg.lS){ return }
  1751. if(msg.I && msg.put && !msg['@'] && !empty(opt.peers)){
  1752. id = msg['#'];
  1753. Gun.graph.is(msg.put, null, map);
  1754. if(!to){ to = setTimeout(flush, opt.wait || 1) }
  1755. }
  1756. this.to.next(msg);
  1757. });
  1758. root.on('ack', ack);
  1759. function ack(ack){ // TODO: This is experimental, not sure if we should keep this type of event hook.
  1760. if(ack.err || !ack.ok){ return }
  1761. var id = ack['@'];
  1762. setTimeout(function(){
  1763. Gun.obj.map(gap, function(node, soul){
  1764. Gun.obj.map(node, function(val, key){
  1765. if(id !== val){ return }
  1766. delete node[key];
  1767. });
  1768. if(empty(node)){
  1769. delete gap[soul];
  1770. }
  1771. });
  1772. flush();
  1773. }, opt.wait || 1);
  1774. };
  1775. ev.next(root);
  1776. var map = function(val, key, node, soul){
  1777. (gap[soul] || (gap[soul] = {}))[key] = id;
  1778. }
  1779. var flush = function(){
  1780. clearTimeout(to);
  1781. to = false;
  1782. try{store.setItem('gap/'+opt.prefix, JSON.stringify(gap));
  1783. }catch(e){ Gun.log(err = e || "localStorage failure") }
  1784. }
  1785. });
  1786. Gun.on('create', function(root){
  1787. this.to.next(root);
  1788. var opt = root.opt;
  1789. if(root.once){ return }
  1790. if(false === opt.localStorage){ return }
  1791. opt.prefix = opt.file || 'gun/';
  1792. var graph = root.graph, acks = {}, count = 0, to;
  1793. var disk = Gun.obj.ify(store.getItem(opt.prefix)) || {};
  1794. var lS = function(){}, u;
  1795. root.on('localStorage', disk); // NON-STANDARD EVENT!
  1796. root.on('put', function(at){
  1797. this.to.next(at);
  1798. Gun.graph.is(at.put, null, map);
  1799. if(!at['@']){ acks[at['#']] = true; } // only ack non-acks.
  1800. count += 1;
  1801. if(count >= (opt.batch || 1000)){
  1802. return flush();
  1803. }
  1804. if(to){ return }
  1805. to = setTimeout(flush, opt.wait || 1);
  1806. });
  1807. root.on('get', function(msg){
  1808. this.to.next(msg);
  1809. var lex = msg.get, soul, data, u;
  1810. function to(){
  1811. if(!lex || !(soul = lex['#'])){ return }
  1812. //if(0 >= msg.cap){ return }
  1813. var has = lex['.'];
  1814. data = disk[soul] || u;
  1815. if(data && has){
  1816. data = Gun.state.to(data, has);
  1817. }
  1818. if(!data && !Gun.obj.empty(opt.peers)){ // if data not found, don't ack if there are peers.
  1819. return; // Hmm, what if we have peers but we are disconnected?
  1820. }
  1821. //console.log("lS get", lex, data);
  1822. root.on('in', {'@': msg['#'], put: Gun.graph.node(data), how: 'lS', lS: msg.I});
  1823. };
  1824. Gun.debug? setTimeout(to,1) : to();
  1825. });
  1826. var map = function(val, key, node, soul){
  1827. disk[soul] = Gun.state.to(node, key, disk[soul]);
  1828. }
  1829. var flush = function(data){
  1830. var err;
  1831. count = 0;
  1832. clearTimeout(to);
  1833. to = false;
  1834. var ack = acks;
  1835. acks = {};
  1836. if(data){ disk = data }
  1837. try{store.setItem(opt.prefix, JSON.stringify(disk));
  1838. }catch(e){
  1839. Gun.log(err = e || "localStorage failure");
  1840. root.on('localStorage:error', {err: err, file: opt.prefix, flush: disk, retry: flush});
  1841. }
  1842. if(!err && !Gun.obj.empty(opt.peers)){ return } // only ack if there are no peers.
  1843. Gun.obj.map(ack, function(yes, id){
  1844. root.on('in', {
  1845. '@': id,
  1846. err: err,
  1847. ok: 0 // localStorage isn't reliable, so make its `ok` code be a low number.
  1848. });
  1849. });
  1850. }
  1851. });
  1852. })(USE, './adapters/localStorage');
  1853. ;USE(function(module){
  1854. var Type = USE('../type');
  1855. function Mesh(ctx){
  1856. var mesh = function(){};
  1857. var opt = ctx.opt;
  1858. mesh.out = function(msg){ var tmp;
  1859. if(this.to){ this.to.next(msg) }
  1860. //if(mesh.last != msg['#']){ return mesh.last = msg['#'], this.to.next(msg) }
  1861. if((tmp = msg['@'])
  1862. && (tmp = ctx.dup.s[tmp])
  1863. && (tmp = tmp.it)
  1864. && tmp.mesh){
  1865. mesh.say(msg, tmp.mesh.via, 1);
  1866. tmp['##'] = msg['##'];
  1867. return;
  1868. }
  1869. // add hook for AXE?
  1870. mesh.say(msg);
  1871. }
  1872. ctx.on('create', function(root){
  1873. root.opt.pid = root.opt.pid || Type.text.random(9);
  1874. this.to.next(root);
  1875. ctx.on('out', mesh.out);
  1876. });
  1877. mesh.hear = function(raw, peer){
  1878. if(!raw){ return }
  1879. var dup = ctx.dup, id, hash, msg, tmp = raw[0];
  1880. try{msg = JSON.parse(raw);
  1881. }catch(e){console.log('DAM JSON parse error', e)}
  1882. if('{' === tmp){
  1883. if(!msg){ return }
  1884. if(dup.check(id = msg['#'])){ return }
  1885. dup.track(id, true).it = msg; // GUN core also dedups, so `true` is needed.
  1886. if((tmp = msg['@']) && msg.put){
  1887. hash = msg['##'] || (msg['##'] = mesh.hash(msg));
  1888. if((tmp = tmp + hash) != id){
  1889. if(dup.check(tmp)){ return }
  1890. (tmp = dup.s)[hash] = tmp[id];
  1891. }
  1892. }
  1893. (msg.mesh = function(){}).via = peer;
  1894. if((tmp = msg['><'])){
  1895. msg.mesh.to = Type.obj.map(tmp.split(','), function(k,i,m){m(k,true)});
  1896. }
  1897. if(msg.dam){
  1898. if(tmp = mesh.hear[msg.dam]){
  1899. tmp(msg, peer, ctx);
  1900. }
  1901. return;
  1902. }
  1903. ctx.on('in', msg);
  1904. return;
  1905. } else
  1906. if('[' === tmp){
  1907. if(!msg){ return }
  1908. var i = 0, m;
  1909. while(m = msg[i++]){
  1910. mesh.hear(m, peer);
  1911. }
  1912. return;
  1913. }
  1914. }
  1915. ;(function(){
  1916. mesh.say = function(msg, peer, o){
  1917. /*
  1918. TODO: Plenty of performance optimizations
  1919. that can be made just based off of ordering,
  1920. and reducing function calls for cached writes.
  1921. */
  1922. if(!peer){
  1923. Type.obj.map(opt.peers, function(peer){
  1924. mesh.say(msg, peer);
  1925. });
  1926. return;
  1927. }
  1928. var tmp, wire = peer.wire || ((opt.wire) && opt.wire(peer)), msh, raw;// || open(peer, ctx); // TODO: Reopen!
  1929. if(!wire){ return }
  1930. msh = msg.mesh || empty;
  1931. if(peer === msh.via){ return }
  1932. if(!(raw = msh.raw)){ raw = mesh.raw(msg) }
  1933. if((tmp = msg['@'])
  1934. && (tmp = ctx.dup.s[tmp])
  1935. && (tmp = tmp.it)){
  1936. if(tmp.get && tmp['##'] && tmp['##'] === msg['##']){ // PERF: move this condition outside say?
  1937. return; // TODO: this still needs to be tested in the browser!
  1938. }
  1939. }
  1940. if((tmp = msh.to) && (tmp[peer.url] || tmp[peer.id]) && !o){ return } // TODO: still needs to be tested
  1941. if(peer.batch){
  1942. peer.batch.push(raw);
  1943. return;
  1944. }
  1945. peer.batch = [];
  1946. setTimeout(function(){
  1947. var tmp = peer.batch;
  1948. if(!tmp){ return }
  1949. peer.batch = null;
  1950. if(!tmp.length){ return }
  1951. send(JSON.stringify(tmp), peer);
  1952. }, opt.gap || opt.wait || 1);
  1953. send(raw, peer);
  1954. }
  1955. function send(raw, peer){
  1956. var wire = peer.wire;
  1957. try{
  1958. if(wire.send){
  1959. wire.send(raw);
  1960. } else
  1961. if(peer.say){
  1962. peer.say(raw);
  1963. }
  1964. }catch(e){
  1965. (peer.queue = peer.queue || []).push(raw);
  1966. }
  1967. }
  1968. }());
  1969. ;(function(){
  1970. mesh.raw = function(msg){
  1971. if(!msg){ return '' }
  1972. var dup = ctx.dup, msh = msg.mesh || {}, put, hash, tmp;
  1973. if(tmp = msh.raw){ return tmp }
  1974. if(typeof msg === 'string'){ return msg }
  1975. if(msg['@'] && (tmp = msg.put)){
  1976. if(!(hash = msg['##'])){
  1977. put = $(tmp, sort) || '';
  1978. hash = mesh.hash(msg, put);
  1979. msg['##'] = hash;
  1980. }
  1981. (tmp = dup.s)[hash = msg['@']+hash] = tmp[msg['#']];
  1982. msg['#'] = hash || msg['#'];
  1983. if(put){ (msg = Type.obj.to(msg)).put = _ }
  1984. }
  1985. var i = 0, to = []; Type.obj.map(opt.peers, function(p){
  1986. to.push(p.url || p.id); if(++i > 9){ return true } // limit server, fast fix, improve later!
  1987. }); msg['><'] = to.join();
  1988. var raw = $(msg);
  1989. if(u !== put){
  1990. tmp = raw.indexOf(_, raw.indexOf('put'));
  1991. raw = raw.slice(0, tmp-1) + put + raw.slice(tmp + _.length + 1);
  1992. //raw = raw.replace('"'+ _ +'"', put); // https://github.com/amark/gun/wiki/@$$ Heisenbug
  1993. }
  1994. if(msh){
  1995. msh.raw = raw;
  1996. }
  1997. return raw;
  1998. }
  1999. mesh.hash = function(msg, hash){
  2000. return Mesh.hash(hash || $(msg.put, sort) || '') || msg['#'] || Type.text.random(9);
  2001. }
  2002. function sort(k, v){ var tmp;
  2003. if(!(v instanceof Object)){ return v }
  2004. Type.obj.map(Object.keys(v).sort(), map, {to: tmp = {}, on: v});
  2005. return tmp;
  2006. }
  2007. function map(k){
  2008. this.to[k] = this.on[k];
  2009. }
  2010. var $ = JSON.stringify, _ = ':])([:';
  2011. }());
  2012. mesh.hi = function(peer){
  2013. var tmp = peer.wire || {};
  2014. if(peer.id || peer.url){
  2015. opt.peers[peer.url || peer.id] = peer;
  2016. Type.obj.del(opt.peers, tmp.id);
  2017. } else {
  2018. tmp = tmp.id = tmp.id || Type.text.random(9);
  2019. mesh.say({dam: '?'}, opt.peers[tmp] = peer);
  2020. }
  2021. if(!tmp.hied){ ctx.on(tmp.hied = 'hi', peer) }
  2022. tmp = peer.queue; peer.queue = [];
  2023. Type.obj.map(tmp, function(msg){
  2024. mesh.say(msg, peer);
  2025. });
  2026. }
  2027. mesh.bye = function(peer){
  2028. Type.obj.del(opt.peers, peer.id); // assume if peer.url then reconnect
  2029. ctx.on('bye', peer);
  2030. }
  2031. mesh.hear['?'] = function(msg, peer){
  2032. if(!msg.pid){ return mesh.say({dam: '?', pid: opt.pid, '@': msg['#']}, peer) }
  2033. peer.id = peer.id || msg.pid;
  2034. mesh.hi(peer);
  2035. }
  2036. return mesh;
  2037. }
  2038. Mesh.hash = function(s){ // via SO
  2039. if(typeof s !== 'string'){ return {err: 1} }
  2040. var c = 0;
  2041. if(!s.length){ return c }
  2042. for(var i=0,l=s.length,n; i<l; ++i){
  2043. n = s.charCodeAt(i);
  2044. c = ((c<<5)-c)+n;
  2045. c |= 0;
  2046. }
  2047. return c; // Math.abs(c);
  2048. }
  2049. var empty = {}, u;
  2050. Object.keys = Object.keys || function(o){ return map(o, function(v,k,t){t(k)}) }
  2051. try{ module.exports = Mesh }catch(e){}
  2052. })(USE, './adapters/mesh');
  2053. ;USE(function(module){
  2054. var Gun = USE('../index');
  2055. Gun.Mesh = USE('./mesh');
  2056. Gun.on('opt', function(root){
  2057. this.to.next(root);
  2058. var opt = root.opt;
  2059. if(root.once){ return }
  2060. if(false === opt.WebSocket){ return }
  2061. var env;
  2062. if(typeof window !== "undefined"){ env = window }
  2063. if(typeof global !== "undefined"){ env = global }
  2064. env = env || {};
  2065. var websocket = opt.WebSocket || env.WebSocket || env.webkitWebSocket || env.mozWebSocket;
  2066. if(!websocket){ return }
  2067. opt.WebSocket = websocket;
  2068. var mesh = opt.mesh = opt.mesh || Gun.Mesh(root);
  2069. var wire = opt.wire;
  2070. opt.wire = open;
  2071. function open(peer){ try{
  2072. if(!peer || !peer.url){ return wire && wire(peer) }
  2073. var url = peer.url.replace('http', 'ws');
  2074. var wire = peer.wire = new opt.WebSocket(url);
  2075. wire.onclose = function(){
  2076. opt.mesh.bye(peer);
  2077. reconnect(peer);
  2078. };
  2079. wire.onerror = function(error){
  2080. reconnect(peer); // placement?
  2081. if(!error){ return }
  2082. if(error.code === 'ECONNREFUSED'){
  2083. //reconnect(peer, as);
  2084. }
  2085. };
  2086. wire.onopen = function(){
  2087. opt.mesh.hi(peer);
  2088. }
  2089. wire.onmessage = function(msg){
  2090. if(!msg){ return }
  2091. opt.mesh.hear(msg.data || msg, peer);
  2092. };
  2093. return wire;
  2094. }catch(e){}}
  2095. function reconnect(peer){
  2096. clearTimeout(peer.defer);
  2097. peer.defer = setTimeout(function(){
  2098. open(peer);
  2099. }, 2 * 1000);
  2100. }
  2101. });
  2102. var noop = function(){};
  2103. })(USE, './adapters/websocket');
  2104. }());