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;
63 function onerror(event) {
70 this.onerror && this.onerror(this);
73 function onopen(event) {
80 function onclose(event) {
81 for (var id in this.pendings) {
82 var ferr = this.pendings[id].onerror;
83 ferr && ferr(null, this);
86 this.onclose && this.onclose();
89 function fire(awaitens, name, data) {
90 var a = awaitens[name];
92 a.forEach(function(handler){handler(data);});
93 var i = name.indexOf("/");
95 a = awaitens[name.substring(0,i)];
97 a.forEach(function(handler){handler(data);});
101 a.forEach(function(handler){handler(data);});
104 function reply(pendings, id, ans, offset) {
105 if (id in pendings) {
106 var p = pendings[id];
113 function onmessage(event) {
114 var obj = JSON.parse(event.data);
118 AFB_context.token = obj[3];
121 reply(this.pendings, id, ans, 0);
124 reply(this.pendings, id, ans, 1);
128 fire(this.awaitens, id, ans);
137 function call(method, request) {
138 return new Promise((function(resolve, reject){
141 id = String(this.counter = 4095 & (this.counter + 1));
142 } while (id in this.pendings);
143 this.pendings[id] = [ resolve, reject ];
144 arr = [CALL, id, method, request ];
145 if (AFB_context.token) arr.push(AFB_context.token);
146 this.ws.send(JSON.stringify(arr));
150 function onevent(name, handler) {
152 var list = this.awaitens[id] || (this.awaitens[id] = []);
156 AFB_websocket.prototype = {
162 /*********************************************/
166 /*********************************************/
168 context: AFB_context,