1 AFB = function(base, initialtoken){
3 if (typeof base != "object")
4 base = { base: base, token: initialtoken };
7 base: base.base || "api",
8 token: base.token || "hello",
9 host: base.host || window.location.host,
10 url: base.url || undefined
13 var urlws = initial.url || "ws://"+initial.host+"/"+initial.base;
15 /*********************************************/
17 /**** AFB_context ****/
19 /*********************************************/
23 var TOKEN = initial.token;
25 var context = function(token, uuid) {
31 get token() {return TOKEN;},
32 set token(tok) {if(tok) TOKEN=tok;},
33 get uuid() {return UUID;},
34 set uuid(id) {if(id) UUID=id;}
37 AFB_context = new context();
39 /*********************************************/
41 /**** AFB_websocket ****/
43 /*********************************************/
51 var PROTO1 = "x-afb-ws-json1";
53 AFB_websocket = function(onopen, onabort) {
55 if (AFB_context.token) {
56 u = u + '?x-afb-token=' + AFB_context.token;
58 u = u + '&x-afb-uuid=' + AFB_context.uuid;
60 this.ws = new WebSocket(u, [ PROTO1 ]);
65 this.ws.onopen = onopen.bind(this);
66 this.ws.onerror = onerror.bind(this);
67 this.ws.onclose = onclose.bind(this);
68 this.ws.onmessage = onmessage.bind(this);
70 this.onabort = onabort;
73 function onerror(event) {
80 this.onerror && this.onerror(this);
83 function onopen(event) {
90 function onclose(event) {
91 for (var id in this.pendings) {
92 var ferr = this.pendings[id].onerror;
93 ferr && ferr(null, this);
96 this.onclose && this.onclose();
99 function fire(awaitens, name, data) {
100 var a = awaitens[name];
102 a.forEach(function(handler){handler(data);});
103 var i = name.indexOf("/");
105 a = awaitens[name.substring(0,i)];
107 a.forEach(function(handler){handler(data);});
111 a.forEach(function(handler){handler(data);});
114 function reply(pendings, id, ans, offset) {
115 if (id in pendings) {
116 var p = pendings[id];
123 function onmessage(event) {
124 var obj = JSON.parse(event.data);
128 AFB_context.token = obj[3];
131 reply(this.pendings, id, ans, 0);
134 reply(this.pendings, id, ans, 1);
138 fire(this.awaitens, id, ans);
150 this.onabort = function(){};
153 function call(method, request) {
154 return new Promise((function(resolve, reject){
157 id = String(this.counter = 4095 & (this.counter + 1));
158 } while (id in this.pendings);
159 this.pendings[id] = [ resolve, reject ];
160 arr = [CALL, id, method, request ];
161 if (AFB_context.token) arr.push(AFB_context.token);
162 this.ws.send(JSON.stringify(arr));
166 function onevent(name, handler) {
168 var list = this.awaitens[id] || (this.awaitens[id] = []);
172 AFB_websocket.prototype = {
178 /*********************************************/
182 /*********************************************/
184 context: AFB_context,