gun.js 76 KB

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