luci-base: luci.js: rework error handling
[oweals/luci.git] / modules / luci-base / htdocs / luci-static / resources / luci.js
1 (function(window, document, undefined) {
2         'use strict';
3
4         /* Object.assign polyfill for IE */
5         if (typeof Object.assign !== 'function') {
6                 Object.defineProperty(Object, 'assign', {
7                         value: function assign(target, varArgs) {
8                                 if (target == null)
9                                         throw new TypeError('Cannot convert undefined or null to object');
10
11                                 var to = Object(target);
12
13                                 for (var index = 1; index < arguments.length; index++)
14                                         if (arguments[index] != null)
15                                                 for (var nextKey in arguments[index])
16                                                         if (Object.prototype.hasOwnProperty.call(arguments[index], nextKey))
17                                                                 to[nextKey] = arguments[index][nextKey];
18
19                                 return to;
20                         },
21                         writable: true,
22                         configurable: true
23                 });
24         }
25
26         /* Promise.finally polyfill */
27         if (typeof Promise.prototype.finally !== 'function') {
28                 Promise.prototype.finally = function(fn) {
29                         var onFinally = function(cb) {
30                                 return Promise.resolve(fn.call(this)).then(cb);
31                         };
32
33                         return this.then(
34                                 function(result) { return onFinally.call(this, function() { return result }) },
35                                 function(reason) { return onFinally.call(this, function() { return Promise.reject(reason) }) }
36                         );
37                 };
38         }
39
40         /*
41          * Class declaration and inheritance helper
42          */
43
44         var toCamelCase = function(s) {
45                 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
46         };
47
48         var superContext = null, Class = Object.assign(function() {}, {
49                 extend: function(properties) {
50                         var props = {
51                                 __base__: { value: this.prototype },
52                                 __name__: { value: properties.__name__ || 'anonymous' }
53                         };
54
55                         var ClassConstructor = function() {
56                                 if (!(this instanceof ClassConstructor))
57                                         throw new TypeError('Constructor must not be called without "new"');
58
59                                 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
60                                         if (typeof(this.__init__) != 'function')
61                                                 throw new TypeError('Class __init__ member is not a function');
62
63                                         this.__init__.apply(this, arguments)
64                                 }
65                                 else {
66                                         this.super('__init__', arguments);
67                                 }
68                         };
69
70                         for (var key in properties)
71                                 if (!props[key] && properties.hasOwnProperty(key))
72                                         props[key] = { value: properties[key], writable: true };
73
74                         ClassConstructor.prototype = Object.create(this.prototype, props);
75                         ClassConstructor.prototype.constructor = ClassConstructor;
76                         Object.assign(ClassConstructor, this);
77                         ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
78
79                         return ClassConstructor;
80                 },
81
82                 singleton: function(properties /*, ... */) {
83                         return Class.extend(properties)
84                                 .instantiate(Class.prototype.varargs(arguments, 1));
85                 },
86
87                 instantiate: function(args) {
88                         return new (Function.prototype.bind.apply(this,
89                                 Class.prototype.varargs(args, 0, null)))();
90                 },
91
92                 call: function(self, method) {
93                         if (typeof(this.prototype[method]) != 'function')
94                                 throw new ReferenceError(method + ' is not defined in class');
95
96                         return this.prototype[method].apply(self, self.varargs(arguments, 1));
97                 },
98
99                 isSubclass: function(_class) {
100                         return (_class != null &&
101                                 typeof(_class) == 'function' &&
102                                 _class.prototype instanceof this);
103                 },
104
105                 prototype: {
106                         varargs: function(args, offset /*, ... */) {
107                                 return Array.prototype.slice.call(arguments, 2)
108                                         .concat(Array.prototype.slice.call(args, offset));
109                         },
110
111                         super: function(key, callArgs) {
112                                 for (superContext = Object.getPrototypeOf(superContext ||
113                                                                           Object.getPrototypeOf(this));
114                                      superContext && !superContext.hasOwnProperty(key);
115                                      superContext = Object.getPrototypeOf(superContext)) { }
116
117                                 if (!superContext)
118                                         return null;
119
120                                 var res = superContext[key];
121
122                                 if (arguments.length > 1) {
123                                         if (typeof(res) != 'function')
124                                                 throw new ReferenceError(key + ' is not a function in base class');
125
126                                         if (typeof(callArgs) != 'object')
127                                                 callArgs = this.varargs(arguments, 1);
128
129                                         res = res.apply(this, callArgs);
130                                 }
131
132                                 superContext = null;
133
134                                 return res;
135                         },
136
137                         toString: function() {
138                                 var s = '[' + this.constructor.displayName + ']', f = true;
139                                 for (var k in this) {
140                                         if (this.hasOwnProperty(k)) {
141                                                 s += (f ? ' {\n' : '') + '  ' + k + ': ' + typeof(this[k]) + '\n';
142                                                 f = false;
143                                         }
144                                 }
145                                 return s + (f ? '' : '}');
146                         }
147                 }
148         });
149
150
151         /*
152          * HTTP Request helper
153          */
154
155         var Headers = Class.extend({
156                 __name__: 'LuCI.XHR.Headers',
157                 __init__: function(xhr) {
158                         var hdrs = this.headers = {};
159                         xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
160                                 var m = /^([^:]+):(.*)$/.exec(line);
161                                 if (m != null)
162                                         hdrs[m[1].trim().toLowerCase()] = m[2].trim();
163                         });
164                 },
165
166                 has: function(name) {
167                         return this.headers.hasOwnProperty(String(name).toLowerCase());
168                 },
169
170                 get: function(name) {
171                         var key = String(name).toLowerCase();
172                         return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
173                 }
174         });
175
176         var Response = Class.extend({
177                 __name__: 'LuCI.XHR.Response',
178                 __init__: function(xhr, url, duration, headers, content) {
179                         this.ok = (xhr.status >= 200 && xhr.status <= 299);
180                         this.status = xhr.status;
181                         this.statusText = xhr.statusText;
182                         this.headers = (headers != null) ? headers : new Headers(xhr);
183                         this.duration = duration;
184                         this.url = url;
185                         this.xhr = xhr;
186
187                         if (content != null && typeof(content) == 'object') {
188                                 this.responseJSON = content;
189                                 this.responseText = null;
190                         }
191                         else if (content != null) {
192                                 this.responseJSON = null;
193                                 this.responseText = String(content);
194                         }
195                         else {
196                                 this.responseJSON = null;
197                                 this.responseText = xhr.responseText;
198                         }
199                 },
200
201                 clone: function(content) {
202                         var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
203
204                         copy.ok = this.ok;
205                         copy.status = this.status;
206                         copy.statusText = this.statusText;
207
208                         return copy;
209                 },
210
211                 json: function() {
212                         if (this.responseJSON == null)
213                                 this.responseJSON = JSON.parse(this.responseText);
214
215                         return this.responseJSON;
216                 },
217
218                 text: function() {
219                         if (this.responseText == null && this.responseJSON != null)
220                                 this.responseText = JSON.stringify(this.responseJSON);
221
222                         return this.responseText;
223                 }
224         });
225
226
227         var requestQueue = [];
228
229         function isQueueableRequest(opt) {
230                 if (!classes.rpc)
231                         return false;
232
233                 if (opt.method != 'POST' || typeof(opt.content) != 'object')
234                         return false;
235
236                 if (opt.nobatch === true)
237                         return false;
238
239                 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
240
241                 return (rpcBaseURL != null && opt.url.indexOf(rpcBaseURL) == 0);
242         }
243
244         function flushRequestQueue() {
245                 if (!requestQueue.length)
246                         return;
247
248                 var reqopt = Object.assign({}, requestQueue[0][0], { content: [], nobatch: true }),
249                     batch = [];
250
251                 for (var i = 0; i < requestQueue.length; i++) {
252                         batch[i] = requestQueue[i];
253                         reqopt.content[i] = batch[i][0].content;
254                 }
255
256                 requestQueue.length = 0;
257
258                 Request.request(rpcBaseURL, reqopt).then(function(reply) {
259                         var json = null, req = null;
260
261                         try { json = reply.json() }
262                         catch(e) { }
263
264                         while ((req = batch.shift()) != null)
265                                 if (Array.isArray(json) && json.length)
266                                         req[2].call(reqopt, reply.clone(json.shift()));
267                                 else
268                                         req[1].call(reqopt, new Error('No related RPC reply'));
269                 }).catch(function(error) {
270                         var req = null;
271
272                         while ((req = batch.shift()) != null)
273                                 req[1].call(reqopt, error);
274                 });
275         }
276
277         var Request = Class.singleton({
278                 __name__: 'LuCI.Request',
279
280                 interceptors: [],
281
282                 expandURL: function(url) {
283                         if (!/^(?:[^/]+:)?\/\//.test(url))
284                                 url = location.protocol + '//' + location.host + url;
285
286                         return url;
287                 },
288
289                 request: function(target, options) {
290                         var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
291                             opt = Object.assign({}, options, state),
292                             content = null,
293                             contenttype = null,
294                             callback = this.handleReadyStateChange;
295
296                         return new Promise(function(resolveFn, rejectFn) {
297                                 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
298                                 opt.method = String(opt.method || 'GET').toUpperCase();
299
300                                 if ('query' in opt) {
301                                         var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
302                                                 if (opt.query[k] != null) {
303                                                         var v = (typeof(opt.query[k]) == 'object')
304                                                                 ? JSON.stringify(opt.query[k])
305                                                                 : String(opt.query[k]);
306
307                                                         return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
308                                                 }
309                                                 else {
310                                                         return encodeURIComponent(k);
311                                                 }
312                                         }).join('&') : '';
313
314                                         if (q !== '') {
315                                                 switch (opt.method) {
316                                                 case 'GET':
317                                                 case 'HEAD':
318                                                 case 'OPTIONS':
319                                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
320                                                         break;
321
322                                                 default:
323                                                         if (content == null) {
324                                                                 content = q;
325                                                                 contenttype = 'application/x-www-form-urlencoded';
326                                                         }
327                                                 }
328                                         }
329                                 }
330
331                                 if (!opt.cache)
332                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
333
334                                 if (isQueueableRequest(opt)) {
335                                         requestQueue.push([opt, rejectFn, resolveFn]);
336                                         requestAnimationFrame(flushRequestQueue);
337                                         return;
338                                 }
339
340                                 if ('username' in opt && 'password' in opt)
341                                         opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
342                                 else
343                                         opt.xhr.open(opt.method, opt.url, true);
344
345                                 opt.xhr.responseType = 'text';
346
347                                 if ('overrideMimeType' in opt.xhr)
348                                         opt.xhr.overrideMimeType('application/octet-stream');
349
350                                 if ('timeout' in opt)
351                                         opt.xhr.timeout = +opt.timeout;
352
353                                 if ('credentials' in opt)
354                                         opt.xhr.withCredentials = !!opt.credentials;
355
356                                 if (opt.content != null) {
357                                         switch (typeof(opt.content)) {
358                                         case 'function':
359                                                 content = opt.content(xhr);
360                                                 break;
361
362                                         case 'object':
363                                                 if (!(opt.content instanceof FormData)) {
364                                                         content = JSON.stringify(opt.content);
365                                                         contenttype = 'application/json';
366                                                 }
367                                                 else {
368                                                         content = opt.content;
369                                                 }
370                                                 break;
371
372                                         default:
373                                                 content = String(opt.content);
374                                         }
375                                 }
376
377                                 if ('headers' in opt)
378                                         for (var header in opt.headers)
379                                                 if (opt.headers.hasOwnProperty(header)) {
380                                                         if (header.toLowerCase() != 'content-type')
381                                                                 opt.xhr.setRequestHeader(header, opt.headers[header]);
382                                                         else
383                                                                 contenttype = opt.headers[header];
384                                                 }
385
386                                 if ('progress' in opt && 'upload' in opt.xhr)
387                                         opt.xhr.upload.addEventListener('progress', opt.progress);
388
389                                 if (contenttype != null)
390                                         opt.xhr.setRequestHeader('Content-Type', contenttype);
391
392                                 try {
393                                         opt.xhr.send(content);
394                                 }
395                                 catch (e) {
396                                         rejectFn.call(opt, e);
397                                 }
398                         });
399                 },
400
401                 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
402                         var xhr = this.xhr;
403
404                         if (xhr.readyState !== 4)
405                                 return;
406
407                         if (xhr.status === 0 && xhr.statusText === '') {
408                                 rejectFn.call(this, new Error('XHR request aborted by browser'));
409                         }
410                         else {
411                                 var response = new Response(
412                                         xhr, xhr.responseURL || this.url, Date.now() - this.start);
413
414                                 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
415                                         .then(resolveFn.bind(this, response))
416                                         .catch(rejectFn.bind(this));
417                         }
418                 },
419
420                 get: function(url, options) {
421                         return this.request(url, Object.assign({ method: 'GET' }, options));
422                 },
423
424                 post: function(url, data, options) {
425                         return this.request(url, Object.assign({ method: 'POST', content: data }, options));
426                 },
427
428                 addInterceptor: function(interceptorFn) {
429                         if (typeof(interceptorFn) == 'function')
430                                 this.interceptors.push(interceptorFn);
431                         return interceptorFn;
432                 },
433
434                 removeInterceptor: function(interceptorFn) {
435                         var oldlen = this.interceptors.length, i = oldlen;
436                         while (i--)
437                                 if (this.interceptors[i] === interceptorFn)
438                                         this.interceptors.splice(i, 1);
439                         return (this.interceptors.length < oldlen);
440                 },
441
442                 poll: {
443                         add: function(interval, url, options, callback) {
444                                 if (isNaN(interval) || interval <= 0)
445                                         throw new TypeError('Invalid poll interval');
446
447                                 var ival = interval >>> 0,
448                                     opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
449
450                                 return Poll.add(function() {
451                                         return Request.request(url, options).then(function(res) {
452                                                 if (!Poll.active())
453                                                         return;
454
455                                                 try {
456                                                         callback(res, res.json(), res.duration);
457                                                 }
458                                                 catch (err) {
459                                                         callback(res, null, res.duration);
460                                                 }
461                                         });
462                                 }, ival);
463                         },
464
465                         remove: function(entry) { return Poll.remove(entry) },
466                         start: function() { return Poll.start() },
467                         stop: function() { return Poll.stop() },
468                         active: function() { return Poll.active() }
469                 }
470         });
471
472         var Poll = Class.singleton({
473                 __name__: 'LuCI.Poll',
474
475                 queue: [],
476
477                 add: function(fn, interval) {
478                         if (interval == null || interval <= 0)
479                                 interval = window.L ? window.L.env.pollinterval : null;
480
481                         if (isNaN(interval) || typeof(fn) != 'function')
482                                 throw new TypeError('Invalid argument to LuCI.Poll.add()');
483
484                         for (var i = 0; i < this.queue.length; i++)
485                                 if (this.queue[i].fn === fn)
486                                         return false;
487
488                         var e = {
489                                 r: true,
490                                 i: interval >>> 0,
491                                 fn: fn
492                         };
493
494                         this.queue.push(e);
495
496                         if (this.tick != null && !this.active())
497                                 this.start();
498
499                         return true;
500                 },
501
502                 remove: function(fn) {
503                         if (typeof(fn) != 'function')
504                                 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
505
506                         var len = this.queue.length;
507
508                         for (var i = len; i > 0; i--)
509                                 if (this.queue[i-1].fn === fn)
510                                         this.queue.splice(i-1, 1);
511
512                         if (!this.queue.length && this.stop())
513                                 this.tick = 0;
514
515                         return (this.queue.length != len);
516                 },
517
518                 start: function() {
519                         if (this.active())
520                                 return false;
521
522                         this.tick = 0;
523
524                         if (this.queue.length) {
525                                 this.timer = window.setInterval(this.step, 1000);
526                                 this.step();
527                                 document.dispatchEvent(new CustomEvent('poll-start'));
528                         }
529
530                         return true;
531                 },
532
533                 stop: function() {
534                         if (!this.active())
535                                 return false;
536
537                         document.dispatchEvent(new CustomEvent('poll-stop'));
538                         window.clearInterval(this.timer);
539                         delete this.timer;
540                         delete this.tick;
541                         return true;
542                 },
543
544                 step: function() {
545                         for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
546                                 if ((Poll.tick % e.i) != 0)
547                                         continue;
548
549                                 if (!e.r)
550                                         continue;
551
552                                 e.r = false;
553
554                                 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
555                         }
556
557                         Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
558                 },
559
560                 active: function() {
561                         return (this.timer != null);
562                 }
563         });
564
565
566         var dummyElem = null,
567             domParser = null,
568             originalCBIInit = null,
569             rpcBaseURL = null,
570             sysFeatures = null,
571             classes = {};
572
573         var LuCI = Class.extend({
574                 __name__: 'LuCI',
575                 __init__: function(env) {
576
577                         document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
578                                 if (env.base_url == null || env.base_url == '')
579                                         env.base_url = s.getAttribute('src').replace(/\/luci\.js(?:\?v=[^?]+)?$/, '');
580                         });
581
582                         if (env.base_url == null)
583                                 this.error('InternalError', 'Cannot find url of luci.js');
584
585                         Object.assign(this.env, env);
586
587                         document.addEventListener('poll-start', function(ev) {
588                                 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
589                                         e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
590                                 });
591                         });
592
593                         document.addEventListener('poll-stop', function(ev) {
594                                 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
595                                         e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
596                                 });
597                         });
598
599                         var domReady = new Promise(function(resolveFn, rejectFn) {
600                                 document.addEventListener('DOMContentLoaded', resolveFn);
601                         });
602
603                         Promise.all([
604                                 domReady,
605                                 this.require('ui'),
606                                 this.require('rpc'),
607                                 this.require('form'),
608                                 this.probeRPCBaseURL()
609                         ]).then(this.setupDOM.bind(this)).catch(this.error);
610
611                         originalCBIInit = window.cbi_init;
612                         window.cbi_init = function() {};
613                 },
614
615                 raise: function(type, fmt /*, ...*/) {
616                         var e = null,
617                             msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
618                             stack = null;
619
620                         if (type instanceof Error) {
621                                 e = type;
622
623                                 if (msg)
624                                         e.message = msg + ': ' + e.message;
625                         }
626                         else {
627                                 try { throw new Error('stacktrace') }
628                                 catch (e2) { stack = (e2.stack || '').split(/\n/) }
629
630                                 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
631                                 e.name = type || 'Error';
632                         }
633
634                         stack = (stack || []).map(function(frame) {
635                                 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
636                                 return frame ? '  ' + frame : '';
637                         });
638
639                         if (!/^  at /.test(stack[0]))
640                                 stack.shift();
641
642                         if (/\braise /.test(stack[0]))
643                                 stack.shift();
644
645                         if (/\berror /.test(stack[0]))
646                                 stack.shift();
647
648                         if (stack.length)
649                                 e.message += '\n' + stack.join('\n');
650
651                         if (window.console && console.debug)
652                                 console.debug(e);
653
654                         throw e;
655                 },
656
657                 error: function(type, fmt /*, ...*/) {
658                         try {
659                                 L.raise.apply(L, Array.prototype.slice.call(arguments));
660                         }
661                         catch (e) {
662                                 if (!e.reported) {
663                                         if (L.ui)
664                                                 L.ui.addNotification(e.name || _('Runtime error'),
665                                                         E('pre', {}, e.message), 'danger');
666                                         else
667                                                 L.dom.content(document.querySelector('#maincontent'),
668                                                         E('pre', { 'class': 'alert-message error' }, e.message));
669
670                                         e.reported = true;
671                                 }
672
673                                 throw e;
674                         }
675                 },
676
677                 bind: function(fn, self /*, ... */) {
678                         return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
679                 },
680
681                 /* Class require */
682                 require: function(name, from) {
683                         var L = this, url = null, from = from || [];
684
685                         /* Class already loaded */
686                         if (classes[name] != null) {
687                                 /* Circular dependency */
688                                 if (from.indexOf(name) != -1)
689                                         L.raise('DependencyError',
690                                                 'Circular dependency: class "%s" depends on "%s"',
691                                                 name, from.join('" which depends on "'));
692
693                                 return classes[name];
694                         }
695
696                         url = '%s/%s.js'.format(L.env.base_url, name.replace(/\./g, '/'));
697                         from = [ name ].concat(from);
698
699                         var compileClass = function(res) {
700                                 if (!res.ok)
701                                         L.raise('NetworkError',
702                                                 'HTTP error %d while loading class file "%s"', res.status, url);
703
704                                 var source = res.text(),
705                                     requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
706                                     strictmatch = /^use[ \t]+strict$/,
707                                     depends = [],
708                                     args = '';
709
710                                 /* find require statements in source */
711                                 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
712                                         var chr = source.charCodeAt(i);
713
714                                         if (esc) {
715                                                 esc = false;
716                                         }
717                                         else if (chr == 92) {
718                                                 esc = true;
719                                         }
720                                         else if (chr == quote) {
721                                                 var s = source.substring(off, i),
722                                                     m = requirematch.exec(s);
723
724                                                 if (m) {
725                                                         var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
726                                                         depends.push(L.require(dep, from));
727                                                         args += ', ' + as;
728                                                 }
729                                                 else if (!strictmatch.exec(s)) {
730                                                         break;
731                                                 }
732
733                                                 off = -1;
734                                                 quote = -1;
735                                         }
736                                         else if (quote == -1 && (chr == 34 || chr == 39)) {
737                                                 off = i + 1;
738                                                 quote = chr;
739                                         }
740                                 }
741
742                                 /* load dependencies and instantiate class */
743                                 return Promise.all(depends).then(function(instances) {
744                                         var _factory, _class;
745
746                                         try {
747                                                 _factory = eval(
748                                                         '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
749                                                                 .format(args, source, res.url));
750                                         }
751                                         catch (error) {
752                                                 L.raise('SyntaxError', '%s\n  in %s:%s',
753                                                         error.message, res.url, error.lineNumber || '?');
754                                         }
755
756                                         _factory.displayName = toCamelCase(name + 'ClassFactory');
757                                         _class = _factory.apply(_factory, [window, document, L].concat(instances));
758
759                                         if (!Class.isSubclass(_class))
760                                             L.error('TypeError', '"%s" factory yields invalid constructor', name);
761
762                                         if (_class.displayName == 'AnonymousClass')
763                                                 _class.displayName = toCamelCase(name + 'Class');
764
765                                         var ptr = Object.getPrototypeOf(L),
766                                             parts = name.split(/\./),
767                                             instance = new _class();
768
769                                         for (var i = 0; ptr && i < parts.length - 1; i++)
770                                                 ptr = ptr[parts[i]];
771
772                                         if (ptr)
773                                                 ptr[parts[i]] = instance;
774
775                                         classes[name] = instance;
776
777                                         return instance;
778                                 });
779                         };
780
781                         /* Request class file */
782                         classes[name] = Request.get(url, { cache: true }).then(compileClass);
783
784                         return classes[name];
785                 },
786
787                 /* DOM setup */
788                 probeRPCBaseURL: function() {
789                         if (rpcBaseURL == null) {
790                                 try {
791                                         rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
792                                 }
793                                 catch (e) { }
794                         }
795
796                         if (rpcBaseURL == null) {
797                                 var rpcFallbackURL = this.url('admin/ubus');
798
799                                 rpcBaseURL = Request.get('/ubus/').then(function(res) {
800                                         return (rpcBaseURL = (res.status == 400) ? '/ubus/' : rpcFallbackURL);
801                                 }, function() {
802                                         return (rpcBaseURL = rpcFallbackURL);
803                                 }).then(function(url) {
804                                         try {
805                                                 window.sessionStorage.setItem('rpcBaseURL', url);
806                                         }
807                                         catch (e) { }
808
809                                         return url;
810                                 });
811                         }
812
813                         return Promise.resolve(rpcBaseURL);
814                 },
815
816                 probeSystemFeatures: function() {
817                         if (sysFeatures == null) {
818                                 try {
819                                         sysFeatures = JSON.parse(window.sessionStorage.getItem('sysFeatures'));
820                                 }
821                                 catch (e) {}
822                         }
823
824                         if (!this.isObject(sysFeatures)) {
825                                 sysFeatures = classes.rpc.declare({
826                                         object: 'luci',
827                                         method: 'getFeatures',
828                                         expect: { '': {} }
829                                 })().then(function(features) {
830                                         try {
831                                                 window.sessionStorage.setItem('sysFeatures', JSON.stringify(features));
832                                         }
833                                         catch (e) {}
834
835                                         sysFeatures = features;
836
837                                         return features;
838                                 });
839                         }
840
841                         return Promise.resolve(sysFeatures);
842                 },
843
844                 hasSystemFeature: function() {
845                         var ft = sysFeatures[arguments[0]];
846
847                         if (arguments.length == 2)
848                                 return this.isObject(ft) ? ft[arguments[1]] : null;
849
850                         return (ft != null && ft != false);
851                 },
852
853                 setupDOM: function(res) {
854                         var domEv = res[0],
855                             uiClass = res[1],
856                             rpcClass = res[2],
857                             formClass = res[3],
858                             rpcBaseURL = res[4];
859
860                         rpcClass.setBaseURL(rpcBaseURL);
861
862                         Request.addInterceptor(function(res) {
863                                 if (res.status != 403 || res.headers.get('X-LuCI-Login-Required') != 'yes')
864                                         return;
865
866                                 Poll.stop();
867
868                                 L.ui.showModal(_('Session expired'), [
869                                         E('div', { class: 'alert-message warning' },
870                                                 _('A new login is required since the authentication session expired.')),
871                                         E('div', { class: 'right' },
872                                                 E('div', {
873                                                         class: 'btn primary',
874                                                         click: function() {
875                                                                 var loc = window.location;
876                                                                 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
877                                                         }
878                                                 }, _('To login…')))
879                                 ]);
880
881                                 throw 'Session expired';
882                         });
883
884                         return this.probeSystemFeatures().finally(this.initDOM);
885                 },
886
887                 initDOM: function() {
888                         originalCBIInit();
889                         Poll.start();
890                         document.dispatchEvent(new CustomEvent('luci-loaded'));
891                 },
892
893                 env: {},
894
895                 /* URL construction helpers */
896                 path: function(prefix, parts) {
897                         var url = [ prefix || '' ];
898
899                         for (var i = 0; i < parts.length; i++)
900                                 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
901                                         url.push('/', parts[i]);
902
903                         if (url.length === 1)
904                                 url.push('/');
905
906                         return url.join('');
907                 },
908
909                 url: function() {
910                         return this.path(this.env.scriptname, arguments);
911                 },
912
913                 resource: function() {
914                         return this.path(this.env.resource, arguments);
915                 },
916
917                 location: function() {
918                         return this.path(this.env.scriptname, this.env.requestpath);
919                 },
920
921
922                 /* Data helpers */
923                 isObject: function(val) {
924                         return (val != null && typeof(val) == 'object');
925                 },
926
927                 sortedKeys: function(obj, key, sortmode) {
928                         if (obj == null || typeof(obj) != 'object')
929                                 return [];
930
931                         return Object.keys(obj).map(function(e) {
932                                 var v = (key != null) ? obj[e][key] : e;
933
934                                 switch (sortmode) {
935                                 case 'addr':
936                                         v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
937                                                 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
938                                         break;
939
940                                 case 'num':
941                                         v = (v != null) ? +v : null;
942                                         break;
943                                 }
944
945                                 return [ e, v ];
946                         }).filter(function(e) {
947                                 return (e[1] != null);
948                         }).sort(function(a, b) {
949                                 return (a[1] > b[1]);
950                         }).map(function(e) {
951                                 return e[0];
952                         });
953                 },
954
955                 toArray: function(val) {
956                         if (val == null)
957                                 return [];
958                         else if (Array.isArray(val))
959                                 return val;
960                         else if (typeof(val) == 'object')
961                                 return [ val ];
962
963                         var s = String(val).trim();
964
965                         if (s == '')
966                                 return [];
967
968                         return s.split(/\s+/);
969                 },
970
971
972                 /* HTTP resource fetching */
973                 get: function(url, args, cb) {
974                         return this.poll(null, url, args, cb, false);
975                 },
976
977                 post: function(url, args, cb) {
978                         return this.poll(null, url, args, cb, true);
979                 },
980
981                 poll: function(interval, url, args, cb, post) {
982                         if (interval !== null && interval <= 0)
983                                 interval = this.env.pollinterval;
984
985                         var data = post ? { token: this.env.token } : null,
986                             method = post ? 'POST' : 'GET';
987
988                         if (!/^(?:\/|\S+:\/\/)/.test(url))
989                                 url = this.url(url);
990
991                         if (args != null)
992                                 data = Object.assign(data || {}, args);
993
994                         if (interval !== null)
995                                 return Request.poll.add(interval, url, { method: method, query: data }, cb);
996                         else
997                                 return Request.request(url, { method: method, query: data })
998                                         .then(function(res) {
999                                                 var json = null;
1000                                                 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
1001                                                         try { json = res.json() } catch(e) {}
1002                                                 cb(res.xhr, json, res.duration);
1003                                         });
1004                 },
1005
1006                 stop: function(entry) { return Poll.remove(entry) },
1007                 halt: function() { return Poll.stop() },
1008                 run: function() { return Poll.start() },
1009
1010                 /* DOM manipulation */
1011                 dom: Class.singleton({
1012                         __name__: 'LuCI.DOM',
1013
1014                         elem: function(e) {
1015                                 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
1016                         },
1017
1018                         parse: function(s) {
1019                                 var elem;
1020
1021                                 try {
1022                                         domParser = domParser || new DOMParser();
1023                                         elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1024                                 }
1025                                 catch(e) {}
1026
1027                                 if (!elem) {
1028                                         try {
1029                                                 dummyElem = dummyElem || document.createElement('div');
1030                                                 dummyElem.innerHTML = s;
1031                                                 elem = dummyElem.firstChild;
1032                                         }
1033                                         catch (e) {}
1034                                 }
1035
1036                                 return elem || null;
1037                         },
1038
1039                         matches: function(node, selector) {
1040                                 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
1041                                 return m ? m.call(node, selector) : false;
1042                         },
1043
1044                         parent: function(node, selector) {
1045                                 if (this.elem(node) && node.closest)
1046                                         return node.closest(selector);
1047
1048                                 while (this.elem(node))
1049                                         if (this.matches(node, selector))
1050                                                 return node;
1051                                         else
1052                                                 node = node.parentNode;
1053
1054                                 return null;
1055                         },
1056
1057                         append: function(node, children) {
1058                                 if (!this.elem(node))
1059                                         return null;
1060
1061                                 if (Array.isArray(children)) {
1062                                         for (var i = 0; i < children.length; i++)
1063                                                 if (this.elem(children[i]))
1064                                                         node.appendChild(children[i]);
1065                                                 else if (children !== null && children !== undefined)
1066                                                         node.appendChild(document.createTextNode('' + children[i]));
1067
1068                                         return node.lastChild;
1069                                 }
1070                                 else if (typeof(children) === 'function') {
1071                                         return this.append(node, children(node));
1072                                 }
1073                                 else if (this.elem(children)) {
1074                                         return node.appendChild(children);
1075                                 }
1076                                 else if (children !== null && children !== undefined) {
1077                                         node.innerHTML = '' + children;
1078                                         return node.lastChild;
1079                                 }
1080
1081                                 return null;
1082                         },
1083
1084                         content: function(node, children) {
1085                                 if (!this.elem(node))
1086                                         return null;
1087
1088                                 var dataNodes = node.querySelectorAll('[data-idref]');
1089
1090                                 for (var i = 0; i < dataNodes.length; i++)
1091                                         delete this.registry[dataNodes[i].getAttribute('data-idref')];
1092
1093                                 while (node.firstChild)
1094                                         node.removeChild(node.firstChild);
1095
1096                                 return this.append(node, children);
1097                         },
1098
1099                         attr: function(node, key, val) {
1100                                 if (!this.elem(node))
1101                                         return null;
1102
1103                                 var attr = null;
1104
1105                                 if (typeof(key) === 'object' && key !== null)
1106                                         attr = key;
1107                                 else if (typeof(key) === 'string')
1108                                         attr = {}, attr[key] = val;
1109
1110                                 for (key in attr) {
1111                                         if (!attr.hasOwnProperty(key) || attr[key] == null)
1112                                                 continue;
1113
1114                                         switch (typeof(attr[key])) {
1115                                         case 'function':
1116                                                 node.addEventListener(key, attr[key]);
1117                                                 break;
1118
1119                                         case 'object':
1120                                                 node.setAttribute(key, JSON.stringify(attr[key]));
1121                                                 break;
1122
1123                                         default:
1124                                                 node.setAttribute(key, attr[key]);
1125                                         }
1126                                 }
1127                         },
1128
1129                         create: function() {
1130                                 var html = arguments[0],
1131                                     attr = arguments[1],
1132                                     data = arguments[2],
1133                                     elem;
1134
1135                                 if (!(attr instanceof Object) || Array.isArray(attr))
1136                                         data = attr, attr = null;
1137
1138                                 if (Array.isArray(html)) {
1139                                         elem = document.createDocumentFragment();
1140                                         for (var i = 0; i < html.length; i++)
1141                                                 elem.appendChild(this.create(html[i]));
1142                                 }
1143                                 else if (this.elem(html)) {
1144                                         elem = html;
1145                                 }
1146                                 else if (html.charCodeAt(0) === 60) {
1147                                         elem = this.parse(html);
1148                                 }
1149                                 else {
1150                                         elem = document.createElement(html);
1151                                 }
1152
1153                                 if (!elem)
1154                                         return null;
1155
1156                                 this.attr(elem, attr);
1157                                 this.append(elem, data);
1158
1159                                 return elem;
1160                         },
1161
1162                         registry: {},
1163
1164                         data: function(node, key, val) {
1165                                 var id = node.getAttribute('data-idref');
1166
1167                                 /* clear all data */
1168                                 if (arguments.length > 1 && key == null) {
1169                                         if (id != null) {
1170                                                 node.removeAttribute('data-idref');
1171                                                 val = this.registry[id]
1172                                                 delete this.registry[id];
1173                                                 return val;
1174                                         }
1175
1176                                         return null;
1177                                 }
1178
1179                                 /* clear a key */
1180                                 else if (arguments.length > 2 && key != null && val == null) {
1181                                         if (id != null) {
1182                                                 val = this.registry[id][key];
1183                                                 delete this.registry[id][key];
1184                                                 return val;
1185                                         }
1186
1187                                         return null;
1188                                 }
1189
1190                                 /* set a key */
1191                                 else if (arguments.length > 2 && key != null && val != null) {
1192                                         if (id == null) {
1193                                                 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1194                                                 while (this.registry.hasOwnProperty(id));
1195
1196                                                 node.setAttribute('data-idref', id);
1197                                                 this.registry[id] = {};
1198                                         }
1199
1200                                         return (this.registry[id][key] = val);
1201                                 }
1202
1203                                 /* get all data */
1204                                 else if (arguments.length == 1) {
1205                                         if (id != null)
1206                                                 return this.registry[id];
1207
1208                                         return null;
1209                                 }
1210
1211                                 /* get a key */
1212                                 else if (arguments.length == 2) {
1213                                         if (id != null)
1214                                                 return this.registry[id][key];
1215                                 }
1216
1217                                 return null;
1218                         },
1219
1220                         bindClassInstance: function(node, inst) {
1221                                 if (!(inst instanceof Class))
1222                                         L.error('TypeError', 'Argument must be a class instance');
1223
1224                                 return this.data(node, '_class', inst);
1225                         },
1226
1227                         findClassInstance: function(node) {
1228                                 var inst = null;
1229
1230                                 do {
1231                                         inst = this.data(node, '_class');
1232                                         node = node.parentNode;
1233                                 }
1234                                 while (!(inst instanceof Class) && node != null);
1235
1236                                 return inst;
1237                         },
1238
1239                         callClassMethod: function(node, method /*, ... */) {
1240                                 var inst = this.findClassInstance(node);
1241
1242                                 if (inst == null || typeof(inst[method]) != 'function')
1243                                         return null;
1244
1245                                 return inst[method].apply(inst, inst.varargs(arguments, 2));
1246                         },
1247
1248                         isEmpty: function(node, ignoreFn) {
1249                                 for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
1250                                         if (!child.classList.contains('hidden') && (!ignoreFn || !ignoreFn(child)))
1251                                                 return false;
1252
1253                                 return true;
1254                         }
1255                 }),
1256
1257                 Poll: Poll,
1258                 Class: Class,
1259                 Request: Request,
1260
1261                 view: Class.extend({
1262                         __name__: 'LuCI.View',
1263
1264                         __init__: function() {
1265                                 var vp = document.getElementById('view');
1266
1267                                 L.dom.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1268
1269                                 return Promise.resolve(this.load())
1270                                         .then(L.bind(this.render, this))
1271                                         .then(L.bind(function(nodes) {
1272                                                 var vp = document.getElementById('view');
1273
1274                                                 L.dom.content(vp, nodes);
1275                                                 L.dom.append(vp, this.addFooter());
1276                                         }, this)).catch(L.error);
1277                         },
1278
1279                         load: function() {},
1280                         render: function() {},
1281
1282                         handleSave: function(ev) {
1283                                 var tasks = [];
1284
1285                                 document.getElementById('maincontent')
1286                                         .querySelectorAll('.cbi-map').forEach(function(map) {
1287                                                 tasks.push(L.dom.callClassMethod(map, 'save'));
1288                                         });
1289
1290                                 return Promise.all(tasks);
1291                         },
1292
1293                         handleSaveApply: function(ev) {
1294                                 return this.handleSave(ev).then(function() {
1295                                         L.ui.changes.apply(true);
1296                                 });
1297                         },
1298
1299                         handleReset: function(ev) {
1300                                 var tasks = [];
1301
1302                                 document.getElementById('maincontent')
1303                                         .querySelectorAll('.cbi-map').forEach(function(map) {
1304                                                 tasks.push(L.dom.callClassMethod(map, 'reset'));
1305                                         });
1306
1307                                 return Promise.all(tasks);
1308                         },
1309
1310                         addFooter: function() {
1311                                 var footer = E([]),
1312                                     mc = document.getElementById('maincontent');
1313
1314                                 if (mc.querySelector('.cbi-map')) {
1315                                         footer.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
1316                                                 E('button', {
1317                                                         'class': 'cbi-button cbi-button-apply',
1318                                                         'click': L.ui.createHandlerFn(this, 'handleSaveApply')
1319                                                 }, _('Save & Apply')), ' ',
1320                                                 E('button', {
1321                                                         'class': 'cbi-button cbi-button-save',
1322                                                         'click': L.ui.createHandlerFn(this, 'handleSave')
1323                                                 }, _('Save')), ' ',
1324                                                 E('button', {
1325                                                         'class': 'cbi-button cbi-button-reset',
1326                                                         'click': L.ui.createHandlerFn(this, 'handleReset')
1327                                                 }, _('Reset'))
1328                                         ]));
1329                                 }
1330
1331                                 return footer;
1332                         }
1333                 })
1334         });
1335
1336         var XHR = Class.extend({
1337                 __name__: 'LuCI.XHR',
1338                 __init__: function() {
1339                         if (window.console && console.debug)
1340                                 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
1341                 },
1342
1343                 _response: function(cb, res, json, duration) {
1344                         if (this.active)
1345                                 cb(res, json, duration);
1346                         delete this.active;
1347                 },
1348
1349                 get: function(url, data, callback, timeout) {
1350                         this.active = true;
1351                         L.get(url, data, this._response.bind(this, callback), timeout);
1352                 },
1353
1354                 post: function(url, data, callback, timeout) {
1355                         this.active = true;
1356                         L.post(url, data, this._response.bind(this, callback), timeout);
1357                 },
1358
1359                 cancel: function() { delete this.active },
1360                 busy: function() { return (this.active === true) },
1361                 abort: function() {},
1362                 send_form: function() { L.error('InternalError', 'Not implemented') },
1363         });
1364
1365         XHR.get = function() { return window.L.get.apply(window.L, arguments) };
1366         XHR.post = function() { return window.L.post.apply(window.L, arguments) };
1367         XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
1368         XHR.stop = Request.poll.remove.bind(Request.poll);
1369         XHR.halt = Request.poll.stop.bind(Request.poll);
1370         XHR.run = Request.poll.start.bind(Request.poll);
1371         XHR.running = Request.poll.active.bind(Request.poll);
1372
1373         window.XHR = XHR;
1374         window.LuCI = LuCI;
1375 })(window, document);