1 AFB = function(base, initialtoken){
3 var urlws = "ws://"+window.location.host+"/"+base;
4 var urlhttp = "http://"+window.location.host+"/"+base;
6 /*********************************************/
8 /**** AFB_context ****/
10 /*********************************************/
14 var TOKEN = initialtoken;
16 var context = function(token, uuid) {
22 get token() {return TOKEN;},
23 set token(tok) {if(tok) TOKEN=tok;},
24 get uuid() {return UUID;},
25 set uuid(id) {if(id) UUID=id;}
28 AFB_context = new context();
30 /*********************************************/
32 /**** AFB_websocket ****/
34 /*********************************************/
42 var PROTO1 = "x-afb-ws-json1";
44 AFB_websocket = function(onopen, onabort) {
46 if (AFB_context.token) {
47 u = u + '?x-afb-token=' + AFB_context.token;
49 u = u + '&x-afb-uuid=' + AFB_context.uuid;
51 this.ws = new WebSocket(u, [ PROTO1 ]);
55 this.ws.onopen = onopen.bind(this);
56 this.ws.onerror = onerror.bind(this);
57 this.ws.onclose = onclose.bind(this);
58 this.ws.onmessage = onmessage.bind(this);
60 this.onabort = onabort;
61 this.onclose = onabort;
64 function onerror(event) {
71 this.onerror && this.onerror(this);
74 function onopen(event) {
81 function onclose(event) {
82 for (var id in this.pendings) {
83 var ferr = this.pendings[id].onerror;
84 ferr && ferr(null, this);
87 this.onclose && this.onclose();
90 function fire(awaitens, name, data) {
91 var a = awaitens[name];
93 a.forEach(function(handler){handler(data);});
94 var i = name.indexOf("/");
96 a = awaitens[name.substring(0,i)];
98 a.forEach(function(handler){handler(data);});
102 a.forEach(function(handler){handler(data);});
105 function reply(pendings, id, ans, offset) {
106 if (id in pendings) {
107 var p = pendings[id];
114 function onmessage(event) {
115 var obj = JSON.parse(event.data);
119 AFB_context.token = obj[3];
122 reply(this.pendings, id, ans, 0);
125 reply(this.pendings, id, ans, 1);
129 fire(this.awaitens, id, ans);
139 function call(method, request) {
140 return new Promise((function(resolve, reject){
143 id = String(this.counter = 4095 & (this.counter + 1));
144 } while (id in this.pendings);
145 this.pendings[id] = [ resolve, reject ];
146 arr = [CALL, id, method, request ];
147 if (AFB_context.token) arr.push(AFB_context.token);
148 this.ws.send(JSON.stringify(arr));
152 function onevent(name, handler) {
154 var list = this.awaitens[id] || (this.awaitens[id] = []);
158 AFB_websocket.prototype = {
164 /*********************************************/
168 /*********************************************/
170 context: AFB_context,