luci-base: luci.js: add ability to add "preload" classes
[oweals/luci.git] / modules / luci-base / htdocs / luci-static / resources / luci.js
1 /**
2  * @class LuCI
3  * @classdesc
4  *
5  * This is the LuCI base class. It is automatically instantiated and
6  * accessible using the global `L` variable.
7  *
8  * @param {Object} env
9  * The environment settings to use for the LuCI runtime.
10  */
11
12 (function(window, document, undefined) {
13         'use strict';
14
15         /* Object.assign polyfill for IE */
16         if (typeof Object.assign !== 'function') {
17                 Object.defineProperty(Object, 'assign', {
18                         value: function assign(target, varArgs) {
19                                 if (target == null)
20                                         throw new TypeError('Cannot convert undefined or null to object');
21
22                                 var to = Object(target);
23
24                                 for (var index = 1; index < arguments.length; index++)
25                                         if (arguments[index] != null)
26                                                 for (var nextKey in arguments[index])
27                                                         if (Object.prototype.hasOwnProperty.call(arguments[index], nextKey))
28                                                                 to[nextKey] = arguments[index][nextKey];
29
30                                 return to;
31                         },
32                         writable: true,
33                         configurable: true
34                 });
35         }
36
37         /* Promise.finally polyfill */
38         if (typeof Promise.prototype.finally !== 'function') {
39                 Promise.prototype.finally = function(fn) {
40                         var onFinally = function(cb) {
41                                 return Promise.resolve(fn.call(this)).then(cb);
42                         };
43
44                         return this.then(
45                                 function(result) { return onFinally.call(this, function() { return result }) },
46                                 function(reason) { return onFinally.call(this, function() { return Promise.reject(reason) }) }
47                         );
48                 };
49         }
50
51         /*
52          * Class declaration and inheritance helper
53          */
54
55         var toCamelCase = function(s) {
56                 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
57         };
58
59         /**
60          * @class baseclass
61          * @hideconstructor
62          * @memberof LuCI
63          * @classdesc
64          *
65          * `LuCI.baseclass` is the abstract base class all LuCI classes inherit from.
66          *
67          * It provides simple means to create subclasses of given classes and
68          * implements prototypal inheritance.
69          */
70         var superContext = {}, classIndex = 0, Class = Object.assign(function() {}, {
71                 /**
72                  * Extends this base class with the properties described in
73                  * `properties` and returns a new subclassed Class instance
74                  *
75                  * @memberof LuCI.baseclass
76                  *
77                  * @param {Object<string, *>} properties
78                  * An object describing the properties to add to the new
79                  * subclass.
80                  *
81                  * @returns {LuCI.baseclass}
82                  * Returns a new LuCI.baseclass sublassed from this class, extended
83                  * by the given properties and with its prototype set to this base
84                  * class to enable inheritance. The resulting value represents a
85                  * class constructor and can be instantiated with `new`.
86                  */
87                 extend: function(properties) {
88                         var props = {
89                                 __id__: { value: classIndex },
90                                 __base__: { value: this.prototype },
91                                 __name__: { value: properties.__name__ || 'anonymous' + classIndex++ }
92                         };
93
94                         var ClassConstructor = function() {
95                                 if (!(this instanceof ClassConstructor))
96                                         throw new TypeError('Constructor must not be called without "new"');
97
98                                 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
99                                         if (typeof(this.__init__) != 'function')
100                                                 throw new TypeError('Class __init__ member is not a function');
101
102                                         this.__init__.apply(this, arguments)
103                                 }
104                                 else {
105                                         this.super('__init__', arguments);
106                                 }
107                         };
108
109                         for (var key in properties)
110                                 if (!props[key] && properties.hasOwnProperty(key))
111                                         props[key] = { value: properties[key], writable: true };
112
113                         ClassConstructor.prototype = Object.create(this.prototype, props);
114                         ClassConstructor.prototype.constructor = ClassConstructor;
115                         Object.assign(ClassConstructor, this);
116                         ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
117
118                         return ClassConstructor;
119                 },
120
121                 /**
122                  * Extends this base class with the properties described in
123                  * `properties`, instantiates the resulting subclass using
124                  * the additional optional arguments passed to this function
125                  * and returns the resulting subclassed Class instance.
126                  *
127                  * This function serves as a convenience shortcut for
128                  * {@link LuCI.baseclass.extend Class.extend()} and subsequent
129                  * `new`.
130                  *
131                  * @memberof LuCI.baseclass
132                  *
133                  * @param {Object<string, *>} properties
134                  * An object describing the properties to add to the new
135                  * subclass.
136                  *
137                  * @param {...*} [new_args]
138                  * Specifies arguments to be passed to the subclass constructor
139                  * as-is in order to instantiate the new subclass.
140                  *
141                  * @returns {LuCI.baseclass}
142                  * Returns a new LuCI.baseclass instance extended by the given
143                  * properties with its prototype set to this base class to
144                  * enable inheritance.
145                  */
146                 singleton: function(properties /*, ... */) {
147                         return Class.extend(properties)
148                                 .instantiate(Class.prototype.varargs(arguments, 1));
149                 },
150
151                 /**
152                  * Calls the class constructor using `new` with the given argument
153                  * array being passed as variadic parameters to the constructor.
154                  *
155                  * @memberof LuCI.baseclass
156                  *
157                  * @param {Array<*>} params
158                  * An array of arbitrary values which will be passed as arguments
159                  * to the constructor function.
160                  *
161                  * @param {...*} [new_args]
162                  * Specifies arguments to be passed to the subclass constructor
163                  * as-is in order to instantiate the new subclass.
164                  *
165                  * @returns {LuCI.baseclass}
166                  * Returns a new LuCI.baseclass instance extended by the given
167                  * properties with its prototype set to this base class to
168                  * enable inheritance.
169                  */
170                 instantiate: function(args) {
171                         return new (Function.prototype.bind.apply(this,
172                                 Class.prototype.varargs(args, 0, null)))();
173                 },
174
175                 /* unused */
176                 call: function(self, method) {
177                         if (typeof(this.prototype[method]) != 'function')
178                                 throw new ReferenceError(method + ' is not defined in class');
179
180                         return this.prototype[method].apply(self, self.varargs(arguments, 1));
181                 },
182
183                 /**
184                  * Checks whether the given class value is a subclass of this class.
185                  *
186                  * @memberof LuCI.baseclass
187                  *
188                  * @param {LuCI.baseclass} classValue
189                  * The class object to test.
190                  *
191                  * @returns {boolean}
192                  * Returns `true` when the given `classValue` is a subclass of this
193                  * class or `false` if the given value is not a valid class or not
194                  * a subclass of this class'.
195                  */
196                 isSubclass: function(classValue) {
197                         return (classValue != null &&
198                                 typeof(classValue) == 'function' &&
199                                 classValue.prototype instanceof this);
200                 },
201
202                 prototype: {
203                         /**
204                          * Extract all values from the given argument array beginning from
205                          * `offset` and prepend any further given optional parameters to
206                          * the beginning of the resulting array copy.
207                          *
208                          * @memberof LuCI.baseclass
209                          * @instance
210                          *
211                          * @param {Array<*>} args
212                          * The array to extract the values from.
213                          *
214                          * @param {number} offset
215                          * The offset from which to extract the values. An offset of `0`
216                          * would copy all values till the end.
217                          *
218                          * @param {...*} [extra_args]
219                          * Extra arguments to add to prepend to the resultung array.
220                          *
221                          * @returns {Array<*>}
222                          * Returns a new array consisting of the optional extra arguments
223                          * and the values extracted from the `args` array beginning with
224                          * `offset`.
225                          */
226                         varargs: function(args, offset /*, ... */) {
227                                 return Array.prototype.slice.call(arguments, 2)
228                                         .concat(Array.prototype.slice.call(args, offset));
229                         },
230
231                         /**
232                          * Walks up the parent class chain and looks for a class member
233                          * called `key` in any of the parent classes this class inherits
234                          * from. Returns the member value of the superclass or calls the
235                          * member as function and returns its return value when the
236                          * optional `callArgs` array is given.
237                          *
238                          * This function has two signatures and is sensitive to the
239                          * amount of arguments passed to it:
240                          *  - `super('key')` -
241                          *    Returns the value of `key` when found within one of the
242                          *    parent classes.
243                          *  - `super('key', ['arg1', 'arg2'])` -
244                          *    Calls the `key()` method with parameters `arg1` and `arg2`
245                          *    when found within one of the parent classes.
246                          *
247                          * @memberof LuCI.baseclass
248                          * @instance
249                          *
250                          * @param {string} key
251                          * The name of the superclass member to retrieve.
252                          *
253                          * @param {Array<*>} [callArgs]
254                          * An optional array of function call parameters to use. When
255                          * this parameter is specified, the found member value is called
256                          * as function using the values of this array as arguments.
257                          *
258                          * @throws {ReferenceError}
259                          * Throws a `ReferenceError` when `callArgs` are specified and
260                          * the found member named by `key` is not a function value.
261                          *
262                          * @returns {*|null}
263                          * Returns the value of the found member or the return value of
264                          * the call to the found method. Returns `null` when no member
265                          * was found in the parent class chain or when the call to the
266                          * superclass method returned `null`.
267                          */
268                         super: function(key, callArgs) {
269                                 if (key == null)
270                                         return null;
271
272                                 var slotIdx = this.__id__ + '.' + key,
273                                     symStack = superContext[slotIdx],
274                                     protoCtx = null;
275
276                                 for (protoCtx = Object.getPrototypeOf(symStack ? symStack[0] : Object.getPrototypeOf(this));
277                                      protoCtx != null && !protoCtx.hasOwnProperty(key);
278                                      protoCtx = Object.getPrototypeOf(protoCtx)) {}
279
280                                 if (protoCtx == null)
281                                         return null;
282
283                                 var res = protoCtx[key];
284
285                                 if (arguments.length > 1) {
286                                         if (typeof(res) != 'function')
287                                                 throw new ReferenceError(key + ' is not a function in base class');
288
289                                         if (typeof(callArgs) != 'object')
290                                                 callArgs = this.varargs(arguments, 1);
291
292                                         if (symStack)
293                                                 symStack.unshift(protoCtx);
294                                         else
295                                                 superContext[slotIdx] = [ protoCtx ];
296
297                                         res = res.apply(this, callArgs);
298
299                                         if (symStack && symStack.length > 1)
300                                                 symStack.shift(protoCtx);
301                                         else
302                                                 delete superContext[slotIdx];
303                                 }
304
305                                 return res;
306                         },
307
308                         /**
309                          * Returns a string representation of this class.
310                          *
311                          * @returns {string}
312                          * Returns a string representation of this class containing the
313                          * constructor functions `displayName` and describing the class
314                          * members and their respective types.
315                          */
316                         toString: function() {
317                                 var s = '[' + this.constructor.displayName + ']', f = true;
318                                 for (var k in this) {
319                                         if (this.hasOwnProperty(k)) {
320                                                 s += (f ? ' {\n' : '') + '  ' + k + ': ' + typeof(this[k]) + '\n';
321                                                 f = false;
322                                         }
323                                 }
324                                 return s + (f ? '' : '}');
325                         }
326                 }
327         });
328
329
330         /**
331          * @class headers
332          * @memberof LuCI
333          * @hideconstructor
334          * @classdesc
335          *
336          * The `Headers` class is an internal utility class exposed in HTTP
337          * response objects using the `response.headers` property.
338          */
339         var Headers = Class.extend(/** @lends LuCI.headers.prototype */ {
340                 __name__: 'LuCI.headers',
341                 __init__: function(xhr) {
342                         var hdrs = this.headers = {};
343                         xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
344                                 var m = /^([^:]+):(.*)$/.exec(line);
345                                 if (m != null)
346                                         hdrs[m[1].trim().toLowerCase()] = m[2].trim();
347                         });
348                 },
349
350                 /**
351                  * Checks whether the given header name is present.
352                  * Note: Header-Names are case-insensitive.
353                  *
354                  * @instance
355                  * @memberof LuCI.headers
356                  * @param {string} name
357                  * The header name to check
358                  *
359                  * @returns {boolean}
360                  * Returns `true` if the header name is present, `false` otherwise
361                  */
362                 has: function(name) {
363                         return this.headers.hasOwnProperty(String(name).toLowerCase());
364                 },
365
366                 /**
367                  * Returns the value of the given header name.
368                  * Note: Header-Names are case-insensitive.
369                  *
370                  * @instance
371                  * @memberof LuCI.headers
372                  * @param {string} name
373                  * The header name to read
374                  *
375                  * @returns {string|null}
376                  * The value of the given header name or `null` if the header isn't present.
377                  */
378                 get: function(name) {
379                         var key = String(name).toLowerCase();
380                         return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
381                 }
382         });
383
384         /**
385          * @class response
386          * @memberof LuCI
387          * @hideconstructor
388          * @classdesc
389          *
390          * The `Response` class is an internal utility class representing HTTP responses.
391          */
392         var Response = Class.extend({
393                 __name__: 'LuCI.response',
394                 __init__: function(xhr, url, duration, headers, content) {
395                         /**
396                          * Describes whether the response is successful (status codes `200..299`) or not
397                          * @instance
398                          * @memberof LuCI.response
399                          * @name ok
400                          * @type {boolean}
401                          */
402                         this.ok = (xhr.status >= 200 && xhr.status <= 299);
403
404                         /**
405                          * The numeric HTTP status code of the response
406                          * @instance
407                          * @memberof LuCI.response
408                          * @name status
409                          * @type {number}
410                          */
411                         this.status = xhr.status;
412
413                         /**
414                          * The HTTP status description message of the response
415                          * @instance
416                          * @memberof LuCI.response
417                          * @name statusText
418                          * @type {string}
419                          */
420                         this.statusText = xhr.statusText;
421
422                         /**
423                          * The HTTP headers of the response
424                          * @instance
425                          * @memberof LuCI.response
426                          * @name headers
427                          * @type {LuCI.headers}
428                          */
429                         this.headers = (headers != null) ? headers : new Headers(xhr);
430
431                         /**
432                          * The total duration of the HTTP request in milliseconds
433                          * @instance
434                          * @memberof LuCI.response
435                          * @name duration
436                          * @type {number}
437                          */
438                         this.duration = duration;
439
440                         /**
441                          * The final URL of the request, i.e. after following redirects.
442                          * @instance
443                          * @memberof LuCI.response
444                          * @name url
445                          * @type {string}
446                          */
447                         this.url = url;
448
449                         /* privates */
450                         this.xhr = xhr;
451
452                         if (content instanceof Blob) {
453                                 this.responseBlob = content;
454                                 this.responseJSON = null;
455                                 this.responseText = null;
456                         }
457                         else if (content != null && typeof(content) == 'object') {
458                                 this.responseBlob = null;
459                                 this.responseJSON = content;
460                                 this.responseText = null;
461                         }
462                         else if (content != null) {
463                                 this.responseBlob = null;
464                                 this.responseJSON = null;
465                                 this.responseText = String(content);
466                         }
467                         else {
468                                 this.responseJSON = null;
469
470                                 if (xhr.responseType == 'blob') {
471                                         this.responseBlob = xhr.response;
472                                         this.responseText = null;
473                                 }
474                                 else {
475                                         this.responseBlob = null;
476                                         this.responseText = xhr.responseText;
477                                 }
478                         }
479                 },
480
481                 /**
482                  * Clones the given response object, optionally overriding the content
483                  * of the cloned instance.
484                  *
485                  * @instance
486                  * @memberof LuCI.response
487                  * @param {*} [content]
488                  * Override the content of the cloned response. Object values will be
489                  * treated as JSON response data, all other types will be converted
490                  * using `String()` and treated as response text.
491                  *
492                  * @returns {LuCI.response}
493                  * The cloned `Response` instance.
494                  */
495                 clone: function(content) {
496                         var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
497
498                         copy.ok = this.ok;
499                         copy.status = this.status;
500                         copy.statusText = this.statusText;
501
502                         return copy;
503                 },
504
505                 /**
506                  * Access the response content as JSON data.
507                  *
508                  * @instance
509                  * @memberof LuCI.response
510                  * @throws {SyntaxError}
511                  * Throws `SyntaxError` if the content isn't valid JSON.
512                  *
513                  * @returns {*}
514                  * The parsed JSON data.
515                  */
516                 json: function() {
517                         if (this.responseJSON == null)
518                                 this.responseJSON = JSON.parse(this.responseText);
519
520                         return this.responseJSON;
521                 },
522
523                 /**
524                  * Access the response content as string.
525                  *
526                  * @instance
527                  * @memberof LuCI.response
528                  * @returns {string}
529                  * The response content.
530                  */
531                 text: function() {
532                         if (this.responseText == null && this.responseJSON != null)
533                                 this.responseText = JSON.stringify(this.responseJSON);
534
535                         return this.responseText;
536                 },
537
538                 /**
539                  * Access the response content as blob.
540                  *
541                  * @instance
542                  * @memberof LuCI.response
543                  * @returns {Blob}
544                  * The response content as blob.
545                  */
546                 blob: function() {
547                         return this.responseBlob;
548                 }
549         });
550
551
552         var requestQueue = [];
553
554         function isQueueableRequest(opt) {
555                 if (!classes.rpc)
556                         return false;
557
558                 if (opt.method != 'POST' || typeof(opt.content) != 'object')
559                         return false;
560
561                 if (opt.nobatch === true)
562                         return false;
563
564                 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
565
566                 return (rpcBaseURL != null && opt.url.indexOf(rpcBaseURL) == 0);
567         }
568
569         function flushRequestQueue() {
570                 if (!requestQueue.length)
571                         return;
572
573                 var reqopt = Object.assign({}, requestQueue[0][0], { content: [], nobatch: true }),
574                     batch = [];
575
576                 for (var i = 0; i < requestQueue.length; i++) {
577                         batch[i] = requestQueue[i];
578                         reqopt.content[i] = batch[i][0].content;
579                 }
580
581                 requestQueue.length = 0;
582
583                 Request.request(rpcBaseURL, reqopt).then(function(reply) {
584                         var json = null, req = null;
585
586                         try { json = reply.json() }
587                         catch(e) { }
588
589                         while ((req = batch.shift()) != null)
590                                 if (Array.isArray(json) && json.length)
591                                         req[2].call(reqopt, reply.clone(json.shift()));
592                                 else
593                                         req[1].call(reqopt, new Error('No related RPC reply'));
594                 }).catch(function(error) {
595                         var req = null;
596
597                         while ((req = batch.shift()) != null)
598                                 req[1].call(reqopt, error);
599                 });
600         }
601
602         /**
603          * @class request
604          * @memberof LuCI
605          * @hideconstructor
606          * @classdesc
607          *
608          * The `Request` class allows initiating HTTP requests and provides utilities
609          * for dealing with responses.
610          */
611         var Request = Class.singleton(/** @lends LuCI.request.prototype */ {
612                 __name__: 'LuCI.request',
613
614                 interceptors: [],
615
616                 /**
617                  * Turn the given relative URL into an absolute URL if necessary.
618                  *
619                  * @instance
620                  * @memberof LuCI.request
621                  * @param {string} url
622                  * The URL to convert.
623                  *
624                  * @returns {string}
625                  * The absolute URL derived from the given one, or the original URL
626                  * if it already was absolute.
627                  */
628                 expandURL: function(url) {
629                         if (!/^(?:[^/]+:)?\/\//.test(url))
630                                 url = location.protocol + '//' + location.host + url;
631
632                         return url;
633                 },
634
635                 /**
636                  * @typedef {Object} RequestOptions
637                  * @memberof LuCI.request
638                  *
639                  * @property {string} [method=GET]
640                  * The HTTP method to use, e.g. `GET` or `POST`.
641                  *
642                  * @property {Object<string, Object|string>} [query]
643                  * Query string data to append to the URL. Non-string values of the
644                  * given object will be converted to JSON.
645                  *
646                  * @property {boolean} [cache=false]
647                  * Specifies whether the HTTP response may be retrieved from cache.
648                  *
649                  * @property {string} [username]
650                  * Provides a username for HTTP basic authentication.
651                  *
652                  * @property {string} [password]
653                  * Provides a password for HTTP basic authentication.
654                  *
655                  * @property {number} [timeout]
656                  * Specifies the request timeout in seconds.
657                  *
658                  * @property {boolean} [credentials=false]
659                  * Whether to include credentials such as cookies in the request.
660                  *
661                  * @property {string} [responseType=text]
662                  * Overrides the request response type. Valid values or `text` to
663                  * interpret the response as UTF-8 string or `blob` to handle the
664                  * response as binary `Blob` data.
665                  *
666                  * @property {*} [content]
667                  * Specifies the HTTP message body to send along with the request.
668                  * If the value is a function, it is invoked and the return value
669                  * used as content, if it is a FormData instance, it is used as-is,
670                  * if it is an object, it will be converted to JSON, in all other
671                  * cases it is converted to a string.
672                  *
673              * @property {Object<string, string>} [header]
674              * Specifies HTTP headers to set for the request.
675              *
676              * @property {function} [progress]
677              * An optional request callback function which receives ProgressEvent
678              * instances as sole argument during the HTTP request transfer.
679                  */
680
681                 /**
682                  * Initiate an HTTP request to the given target.
683                  *
684                  * @instance
685                  * @memberof LuCI.request
686                  * @param {string} target
687                  * The URL to request.
688                  *
689                  * @param {LuCI.request.RequestOptions} [options]
690                  * Additional options to configure the request.
691                  *
692                  * @returns {Promise<LuCI.response>}
693                  * The resulting HTTP response.
694                  */
695                 request: function(target, options) {
696                         var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
697                             opt = Object.assign({}, options, state),
698                             content = null,
699                             contenttype = null,
700                             callback = this.handleReadyStateChange;
701
702                         return new Promise(function(resolveFn, rejectFn) {
703                                 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
704                                 opt.method = String(opt.method || 'GET').toUpperCase();
705
706                                 if ('query' in opt) {
707                                         var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
708                                                 if (opt.query[k] != null) {
709                                                         var v = (typeof(opt.query[k]) == 'object')
710                                                                 ? JSON.stringify(opt.query[k])
711                                                                 : String(opt.query[k]);
712
713                                                         return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
714                                                 }
715                                                 else {
716                                                         return encodeURIComponent(k);
717                                                 }
718                                         }).join('&') : '';
719
720                                         if (q !== '') {
721                                                 switch (opt.method) {
722                                                 case 'GET':
723                                                 case 'HEAD':
724                                                 case 'OPTIONS':
725                                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
726                                                         break;
727
728                                                 default:
729                                                         if (content == null) {
730                                                                 content = q;
731                                                                 contenttype = 'application/x-www-form-urlencoded';
732                                                         }
733                                                 }
734                                         }
735                                 }
736
737                                 if (!opt.cache)
738                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
739
740                                 if (isQueueableRequest(opt)) {
741                                         requestQueue.push([opt, rejectFn, resolveFn]);
742                                         requestAnimationFrame(flushRequestQueue);
743                                         return;
744                                 }
745
746                                 if ('username' in opt && 'password' in opt)
747                                         opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
748                                 else
749                                         opt.xhr.open(opt.method, opt.url, true);
750
751                                 opt.xhr.responseType = opt.responseType || 'text';
752
753                                 if ('overrideMimeType' in opt.xhr)
754                                         opt.xhr.overrideMimeType('application/octet-stream');
755
756                                 if ('timeout' in opt)
757                                         opt.xhr.timeout = +opt.timeout;
758
759                                 if ('credentials' in opt)
760                                         opt.xhr.withCredentials = !!opt.credentials;
761
762                                 if (opt.content != null) {
763                                         switch (typeof(opt.content)) {
764                                         case 'function':
765                                                 content = opt.content(xhr);
766                                                 break;
767
768                                         case 'object':
769                                                 if (!(opt.content instanceof FormData)) {
770                                                         content = JSON.stringify(opt.content);
771                                                         contenttype = 'application/json';
772                                                 }
773                                                 else {
774                                                         content = opt.content;
775                                                 }
776                                                 break;
777
778                                         default:
779                                                 content = String(opt.content);
780                                         }
781                                 }
782
783                                 if ('headers' in opt)
784                                         for (var header in opt.headers)
785                                                 if (opt.headers.hasOwnProperty(header)) {
786                                                         if (header.toLowerCase() != 'content-type')
787                                                                 opt.xhr.setRequestHeader(header, opt.headers[header]);
788                                                         else
789                                                                 contenttype = opt.headers[header];
790                                                 }
791
792                                 if ('progress' in opt && 'upload' in opt.xhr)
793                                         opt.xhr.upload.addEventListener('progress', opt.progress);
794
795                                 if (contenttype != null)
796                                         opt.xhr.setRequestHeader('Content-Type', contenttype);
797
798                                 try {
799                                         opt.xhr.send(content);
800                                 }
801                                 catch (e) {
802                                         rejectFn.call(opt, e);
803                                 }
804                         });
805                 },
806
807                 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
808                         var xhr = this.xhr,
809                             duration = Date.now() - this.start;
810
811                         if (xhr.readyState !== 4)
812                                 return;
813
814                         if (xhr.status === 0 && xhr.statusText === '') {
815                                 if (duration >= this.timeout)
816                                         rejectFn.call(this, new Error('XHR request timed out'));
817                                 else
818                                         rejectFn.call(this, new Error('XHR request aborted by browser'));
819                         }
820                         else {
821                                 var response = new Response(
822                                         xhr, xhr.responseURL || this.url, duration);
823
824                                 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
825                                         .then(resolveFn.bind(this, response))
826                                         .catch(rejectFn.bind(this));
827                         }
828                 },
829
830                 /**
831                  * Initiate an HTTP GET request to the given target.
832                  *
833                  * @instance
834                  * @memberof LuCI.request
835                  * @param {string} target
836                  * The URL to request.
837                  *
838                  * @param {LuCI.request.RequestOptions} [options]
839                  * Additional options to configure the request.
840                  *
841                  * @returns {Promise<LuCI.response>}
842                  * The resulting HTTP response.
843                  */
844                 get: function(url, options) {
845                         return this.request(url, Object.assign({ method: 'GET' }, options));
846                 },
847
848                 /**
849                  * Initiate an HTTP POST request to the given target.
850                  *
851                  * @instance
852                  * @memberof LuCI.request
853                  * @param {string} target
854                  * The URL to request.
855                  *
856                  * @param {*} [data]
857                  * The request data to send, see {@link LuCI.request.RequestOptions} for details.
858                  *
859                  * @param {LuCI.request.RequestOptions} [options]
860                  * Additional options to configure the request.
861                  *
862                  * @returns {Promise<LuCI.response>}
863                  * The resulting HTTP response.
864                  */
865                 post: function(url, data, options) {
866                         return this.request(url, Object.assign({ method: 'POST', content: data }, options));
867                 },
868
869                 /**
870                  * Interceptor functions are invoked whenever an HTTP reply is received, in the order
871                  * these functions have been registered.
872                  * @callback LuCI.request.interceptorFn
873                  * @param {LuCI.response} res
874                  * The HTTP response object
875                  */
876
877                 /**
878                  * Register an HTTP response interceptor function. Interceptor
879                  * functions are useful to perform default actions on incoming HTTP
880                  * responses, such as checking for expired authentication or for
881                  * implementing request retries before returning a failure.
882                  *
883                  * @instance
884                  * @memberof LuCI.request
885                  * @param {LuCI.request.interceptorFn} interceptorFn
886                  * The interceptor function to register.
887                  *
888                  * @returns {LuCI.request.interceptorFn}
889                  * The registered function.
890                  */
891                 addInterceptor: function(interceptorFn) {
892                         if (typeof(interceptorFn) == 'function')
893                                 this.interceptors.push(interceptorFn);
894                         return interceptorFn;
895                 },
896
897                 /**
898                  * Remove an HTTP response interceptor function. The passed function
899                  * value must be the very same value that was used to register the
900                  * function.
901                  *
902                  * @instance
903                  * @memberof LuCI.request
904                  * @param {LuCI.request.interceptorFn} interceptorFn
905                  * The interceptor function to remove.
906                  *
907                  * @returns {boolean}
908                  * Returns `true` if any function has been removed, else `false`.
909                  */
910                 removeInterceptor: function(interceptorFn) {
911                         var oldlen = this.interceptors.length, i = oldlen;
912                         while (i--)
913                                 if (this.interceptors[i] === interceptorFn)
914                                         this.interceptors.splice(i, 1);
915                         return (this.interceptors.length < oldlen);
916                 },
917
918                 /**
919                  * @class
920                  * @memberof LuCI.request
921                  * @hideconstructor
922                  * @classdesc
923                  *
924                  * The `Request.poll` class provides some convience wrappers around
925                  * {@link LuCI.poll} mainly to simplify registering repeating HTTP
926                  * request calls as polling functions.
927                  */
928                 poll: {
929                         /**
930                          * The callback function is invoked whenever an HTTP reply to a
931                          * polled request is received or when the polled request timed
932                          * out.
933                          *
934                          * @callback LuCI.request.poll~callbackFn
935                          * @param {LuCI.response} res
936                          * The HTTP response object.
937                          *
938                          * @param {*} data
939                          * The response JSON if the response could be parsed as such,
940                          * else `null`.
941                          *
942                          * @param {number} duration
943                          * The total duration of the request in milliseconds.
944                          */
945
946                         /**
947                          * Register a repeating HTTP request with an optional callback
948                          * to invoke whenever a response for the request is received.
949                          *
950                          * @instance
951                          * @memberof LuCI.request.poll
952                          * @param {number} interval
953                          * The poll interval in seconds.
954                          *
955                          * @param {string} url
956                          * The URL to request on each poll.
957                          *
958                          * @param {LuCI.request.RequestOptions} [options]
959                          * Additional options to configure the request.
960                          *
961                          * @param {LuCI.request.poll~callbackFn} [callback]
962                          * {@link LuCI.request.poll~callbackFn Callback} function to
963                          * invoke for each HTTP reply.
964                          *
965                          * @throws {TypeError}
966                          * Throws `TypeError` when an invalid interval was passed.
967                          *
968                          * @returns {function}
969                          * Returns the internally created poll function.
970                          */
971                         add: function(interval, url, options, callback) {
972                                 if (isNaN(interval) || interval <= 0)
973                                         throw new TypeError('Invalid poll interval');
974
975                                 var ival = interval >>> 0,
976                                     opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
977
978                                 var fn = function() {
979                                         return Request.request(url, options).then(function(res) {
980                                                 if (!Poll.active())
981                                                         return;
982
983                                                 try {
984                                                         callback(res, res.json(), res.duration);
985                                                 }
986                                                 catch (err) {
987                                                         callback(res, null, res.duration);
988                                                 }
989                                         });
990                                 };
991
992                                 return (Poll.add(fn, ival) ? fn : null);
993                         },
994
995                         /**
996                          * Remove a polling request that has been previously added using `add()`.
997                          * This function is essentially a wrapper around
998                          * {@link LuCI.poll.remove LuCI.poll.remove()}.
999                          *
1000                          * @instance
1001                          * @memberof LuCI.request.poll
1002                          * @param {function} entry
1003                          * The poll function returned by {@link LuCI.request.poll#add add()}.
1004                          *
1005                          * @returns {boolean}
1006                          * Returns `true` if any function has been removed, else `false`.
1007                          */
1008                         remove: function(entry) { return Poll.remove(entry) },
1009
1010                         /**
1011                           * Alias for {@link LuCI.poll.start LuCI.poll.start()}.
1012                           *
1013                           * @instance
1014                           * @memberof LuCI.request.poll
1015                           */
1016                         start: function() { return Poll.start() },
1017
1018                         /**
1019                           * Alias for {@link LuCI.poll.stop LuCI.poll.stop()}.
1020                           *
1021                           * @instance
1022                           * @memberof LuCI.request.poll
1023                           */
1024                         stop: function() { return Poll.stop() },
1025
1026                         /**
1027                           * Alias for {@link LuCI.poll.active LuCI.poll.active()}.
1028                           *
1029                           * @instance
1030                           * @memberof LuCI.request.poll
1031                           */
1032                         active: function() { return Poll.active() }
1033                 }
1034         });
1035
1036         /**
1037          * @class poll
1038          * @memberof LuCI
1039          * @hideconstructor
1040          * @classdesc
1041          *
1042          * The `Poll` class allows registering and unregistering poll actions,
1043          * as well as starting, stopping and querying the state of the polling
1044          * loop.
1045          */
1046         var Poll = Class.singleton(/** @lends LuCI.poll.prototype */ {
1047                 __name__: 'LuCI.poll',
1048
1049                 queue: [],
1050
1051                 /**
1052                  * Add a new operation to the polling loop. If the polling loop is not
1053                  * already started at this point, it will be implicitely started.
1054                  *
1055                  * @instance
1056                  * @memberof LuCI.poll
1057                  * @param {function} fn
1058                  * The function to invoke on each poll interval.
1059                  *
1060                  * @param {number} interval
1061                  * The poll interval in seconds.
1062                  *
1063                  * @throws {TypeError}
1064                  * Throws `TypeError` when an invalid interval was passed.
1065                  *
1066                  * @returns {boolean}
1067                  * Returns `true` if the function has been added or `false` if it
1068                  * already is registered.
1069                  */
1070                 add: function(fn, interval) {
1071                         if (interval == null || interval <= 0)
1072                                 interval = window.L ? window.L.env.pollinterval : null;
1073
1074                         if (isNaN(interval) || typeof(fn) != 'function')
1075                                 throw new TypeError('Invalid argument to LuCI.poll.add()');
1076
1077                         for (var i = 0; i < this.queue.length; i++)
1078                                 if (this.queue[i].fn === fn)
1079                                         return false;
1080
1081                         var e = {
1082                                 r: true,
1083                                 i: interval >>> 0,
1084                                 fn: fn
1085                         };
1086
1087                         this.queue.push(e);
1088
1089                         if (this.tick != null && !this.active())
1090                                 this.start();
1091
1092                         return true;
1093                 },
1094
1095                 /**
1096                  * Remove an operation from the polling loop. If no further operatons
1097                  * are registered, the polling loop is implicitely stopped.
1098                  *
1099                  * @instance
1100                  * @memberof LuCI.poll
1101                  * @param {function} fn
1102                  * The function to remove.
1103                  *
1104                  * @throws {TypeError}
1105                  * Throws `TypeError` when the given argument isn't a function.
1106                  *
1107                  * @returns {boolean}
1108                  * Returns `true` if the function has been removed or `false` if it
1109                  * wasn't found.
1110                  */
1111                 remove: function(fn) {
1112                         if (typeof(fn) != 'function')
1113                                 throw new TypeError('Invalid argument to LuCI.poll.remove()');
1114
1115                         var len = this.queue.length;
1116
1117                         for (var i = len; i > 0; i--)
1118                                 if (this.queue[i-1].fn === fn)
1119                                         this.queue.splice(i-1, 1);
1120
1121                         if (!this.queue.length && this.stop())
1122                                 this.tick = 0;
1123
1124                         return (this.queue.length != len);
1125                 },
1126
1127                 /**
1128                  * (Re)start the polling loop. Dispatches a custom `poll-start` event
1129                  * to the `document` object upon successful start.
1130                  *
1131                  * @instance
1132                  * @memberof LuCI.poll
1133                  * @returns {boolean}
1134                  * Returns `true` if polling has been started (or if no functions
1135                  * where registered) or `false` when the polling loop already runs.
1136                  */
1137                 start: function() {
1138                         if (this.active())
1139                                 return false;
1140
1141                         this.tick = 0;
1142
1143                         if (this.queue.length) {
1144                                 this.timer = window.setInterval(this.step, 1000);
1145                                 this.step();
1146                                 document.dispatchEvent(new CustomEvent('poll-start'));
1147                         }
1148
1149                         return true;
1150                 },
1151
1152                 /**
1153                  * Stop the polling loop. Dispatches a custom `poll-stop` event
1154                  * to the `document` object upon successful stop.
1155                  *
1156                  * @instance
1157                  * @memberof LuCI.poll
1158                  * @returns {boolean}
1159                  * Returns `true` if polling has been stopped or `false` if it din't
1160                  * run to begin with.
1161                  */
1162                 stop: function() {
1163                         if (!this.active())
1164                                 return false;
1165
1166                         document.dispatchEvent(new CustomEvent('poll-stop'));
1167                         window.clearInterval(this.timer);
1168                         delete this.timer;
1169                         delete this.tick;
1170                         return true;
1171                 },
1172
1173                 /* private */
1174                 step: function() {
1175                         for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
1176                                 if ((Poll.tick % e.i) != 0)
1177                                         continue;
1178
1179                                 if (!e.r)
1180                                         continue;
1181
1182                                 e.r = false;
1183
1184                                 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
1185                         }
1186
1187                         Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
1188                 },
1189
1190                 /**
1191                  * Test whether the polling loop is running.
1192                  *
1193                  * @instance
1194                  * @memberof LuCI.poll
1195                  * @returns {boolean} - Returns `true` if polling is active, else `false`.
1196                  */
1197                 active: function() {
1198                         return (this.timer != null);
1199                 }
1200         });
1201
1202         /**
1203          * @class dom
1204          * @memberof LuCI
1205          * @hideconstructor
1206          * @classdesc
1207          *
1208          * The `dom` class provides convenience method for creating and
1209          * manipulating DOM elements.
1210          *
1211          * To import the class in views, use `'require dom'`, to import it in
1212          * external JavaScript, use `L.require("dom").then(...)`.
1213          */
1214         var DOM = Class.singleton(/* @lends LuCI.dom.prototype */ {
1215                 __name__: 'LuCI.dom',
1216
1217                 /**
1218                  * Tests whether the given argument is a valid DOM `Node`.
1219                  *
1220                  * @instance
1221                  * @memberof LuCI.dom
1222                  * @param {*} e
1223                  * The value to test.
1224                  *
1225                  * @returns {boolean}
1226                  * Returns `true` if the value is a DOM `Node`, else `false`.
1227                  */
1228                 elem: function(e) {
1229                         return (e != null && typeof(e) == 'object' && 'nodeType' in e);
1230                 },
1231
1232                 /**
1233                  * Parses a given string as HTML and returns the first child node.
1234                  *
1235                  * @instance
1236                  * @memberof LuCI.dom
1237                  * @param {string} s
1238                  * A string containing an HTML fragment to parse. Note that only
1239                  * the first result of the resulting structure is returned, so an
1240                  * input value of `<div>foo</div> <div>bar</div>` will only return
1241                  * the first `div` element node.
1242                  *
1243                  * @returns {Node}
1244                  * Returns the first DOM `Node` extracted from the HTML fragment or
1245                  * `null` on parsing failures or if no element could be found.
1246                  */
1247                 parse: function(s) {
1248                         var elem;
1249
1250                         try {
1251                                 domParser = domParser || new DOMParser();
1252                                 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1253                         }
1254                         catch(e) {}
1255
1256                         if (!elem) {
1257                                 try {
1258                                         dummyElem = dummyElem || document.createElement('div');
1259                                         dummyElem.innerHTML = s;
1260                                         elem = dummyElem.firstChild;
1261                                 }
1262                                 catch (e) {}
1263                         }
1264
1265                         return elem || null;
1266                 },
1267
1268                 /**
1269                  * Tests whether a given `Node` matches the given query selector.
1270                  *
1271                  * This function is a convenience wrapper around the standard
1272                  * `Node.matches("selector")` function with the added benefit that
1273                  * the `node` argument may be a non-`Node` value, in which case
1274                  * this function simply returns `false`.
1275                  *
1276                  * @instance
1277                  * @memberof LuCI.dom
1278                  * @param {*} node
1279                  * The `Node` argument to test the selector against.
1280                  *
1281                  * @param {string} [selector]
1282                  * The query selector expression to test against the given node.
1283                  *
1284                  * @returns {boolean}
1285                  * Returns `true` if the given node matches the specified selector
1286                  * or `false` when the node argument is no valid DOM `Node` or the
1287                  * selector didn't match.
1288                  */
1289                 matches: function(node, selector) {
1290                         var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
1291                         return m ? m.call(node, selector) : false;
1292                 },
1293
1294                 /**
1295                  * Returns the closest parent node that matches the given query
1296                  * selector expression.
1297                  *
1298                  * This function is a convenience wrapper around the standard
1299                  * `Node.closest("selector")` function with the added benefit that
1300                  * the `node` argument may be a non-`Node` value, in which case
1301                  * this function simply returns `null`.
1302                  *
1303                  * @instance
1304                  * @memberof LuCI.dom
1305                  * @param {*} node
1306                  * The `Node` argument to find the closest parent for.
1307                  *
1308                  * @param {string} [selector]
1309                  * The query selector expression to test against each parent.
1310                  *
1311                  * @returns {Node|null}
1312                  * Returns the closest parent node matching the selector or
1313                  * `null` when the node argument is no valid DOM `Node` or the
1314                  * selector didn't match any parent.
1315                  */
1316                 parent: function(node, selector) {
1317                         if (this.elem(node) && node.closest)
1318                                 return node.closest(selector);
1319
1320                         while (this.elem(node))
1321                                 if (this.matches(node, selector))
1322                                         return node;
1323                                 else
1324                                         node = node.parentNode;
1325
1326                         return null;
1327                 },
1328
1329                 /**
1330                  * Appends the given children data to the given node.
1331                  *
1332                  * @instance
1333                  * @memberof LuCI.dom
1334                  * @param {*} node
1335                  * The `Node` argument to append the children to.
1336                  *
1337                  * @param {*} [children]
1338                  * The childrens to append to the given node.
1339                  *
1340                  * When `children` is an array, then each item of the array
1341                  * will be either appended as child element or text node,
1342                  * depending on whether the item is a DOM `Node` instance or
1343                  * some other non-`null` value. Non-`Node`, non-`null` values
1344                  * will be converted to strings first before being passed as
1345                  * argument to `createTextNode()`.
1346                  *
1347                  * When `children` is a function, it will be invoked with
1348                  * the passed `node` argument as sole parameter and the `append`
1349                  * function will be invoked again, with the given `node` argument
1350                  * as first and the return value of the `children` function as
1351                  * second parameter.
1352                  *
1353                  * When `children` is is a DOM `Node` instance, it will be
1354                  * appended to the given `node`.
1355                  *
1356                  * When `children` is any other non-`null` value, it will be
1357                  * converted to a string and appened to the `innerHTML` property
1358                  * of the given `node`.
1359                  *
1360                  * @returns {Node|null}
1361                  * Returns the last children `Node` appended to the node or `null`
1362                  * if either the `node` argument was no valid DOM `node` or if the
1363                  * `children` was `null` or didn't result in further DOM nodes.
1364                  */
1365                 append: function(node, children) {
1366                         if (!this.elem(node))
1367                                 return null;
1368
1369                         if (Array.isArray(children)) {
1370                                 for (var i = 0; i < children.length; i++)
1371                                         if (this.elem(children[i]))
1372                                                 node.appendChild(children[i]);
1373                                         else if (children !== null && children !== undefined)
1374                                                 node.appendChild(document.createTextNode('' + children[i]));
1375
1376                                 return node.lastChild;
1377                         }
1378                         else if (typeof(children) === 'function') {
1379                                 return this.append(node, children(node));
1380                         }
1381                         else if (this.elem(children)) {
1382                                 return node.appendChild(children);
1383                         }
1384                         else if (children !== null && children !== undefined) {
1385                                 node.innerHTML = '' + children;
1386                                 return node.lastChild;
1387                         }
1388
1389                         return null;
1390                 },
1391
1392                 /**
1393                  * Replaces the content of the given node with the given children.
1394                  *
1395                  * This function first removes any children of the given DOM
1396                  * `Node` and then adds the given given children following the
1397                  * rules outlined below.
1398                  *
1399                  * @instance
1400                  * @memberof LuCI.dom
1401                  * @param {*} node
1402                  * The `Node` argument to replace the children of.
1403                  *
1404                  * @param {*} [children]
1405                  * The childrens to replace into the given node.
1406                  *
1407                  * When `children` is an array, then each item of the array
1408                  * will be either appended as child element or text node,
1409                  * depending on whether the item is a DOM `Node` instance or
1410                  * some other non-`null` value. Non-`Node`, non-`null` values
1411                  * will be converted to strings first before being passed as
1412                  * argument to `createTextNode()`.
1413                  *
1414                  * When `children` is a function, it will be invoked with
1415                  * the passed `node` argument as sole parameter and the `append`
1416                  * function will be invoked again, with the given `node` argument
1417                  * as first and the return value of the `children` function as
1418                  * second parameter.
1419                  *
1420                  * When `children` is is a DOM `Node` instance, it will be
1421                  * appended to the given `node`.
1422                  *
1423                  * When `children` is any other non-`null` value, it will be
1424                  * converted to a string and appened to the `innerHTML` property
1425                  * of the given `node`.
1426                  *
1427                  * @returns {Node|null}
1428                  * Returns the last children `Node` appended to the node or `null`
1429                  * if either the `node` argument was no valid DOM `node` or if the
1430                  * `children` was `null` or didn't result in further DOM nodes.
1431                  */
1432                 content: function(node, children) {
1433                         if (!this.elem(node))
1434                                 return null;
1435
1436                         var dataNodes = node.querySelectorAll('[data-idref]');
1437
1438                         for (var i = 0; i < dataNodes.length; i++)
1439                                 delete this.registry[dataNodes[i].getAttribute('data-idref')];
1440
1441                         while (node.firstChild)
1442                                 node.removeChild(node.firstChild);
1443
1444                         return this.append(node, children);
1445                 },
1446
1447                 /**
1448                  * Sets attributes or registers event listeners on element nodes.
1449                  *
1450                  * @instance
1451                  * @memberof LuCI.dom
1452                  * @param {*} node
1453                  * The `Node` argument to set the attributes or add the event
1454                  * listeners for. When the given `node` value is not a valid
1455                  * DOM `Node`, the function returns and does nothing.
1456                  *
1457                  * @param {string|Object<string, *>} key
1458                  * Specifies either the attribute or event handler name to use,
1459                  * or an object containing multiple key, value pairs which are
1460                  * each added to the node as either attribute or event handler,
1461                  * depending on the respective value.
1462                  *
1463                  * @param {*} [val]
1464                  * Specifies the attribute value or event handler function to add.
1465                  * If the `key` parameter is an `Object`, this parameter will be
1466                  * ignored.
1467                  *
1468                  * When `val` is of type function, it will be registered as event
1469                  * handler on the given `node` with the `key` parameter being the
1470                  * event name.
1471                  *
1472                  * When `val` is of type object, it will be serialized as JSON and
1473                  * added as attribute to the given `node`, using the given `key`
1474                  * as attribute name.
1475                  *
1476                  * When `val` is of any other type, it will be added as attribute
1477                  * to the given `node` as-is, with the underlying `setAttribute()`
1478                  * call implicitely turning it into a string.
1479                  */
1480                 attr: function(node, key, val) {
1481                         if (!this.elem(node))
1482                                 return null;
1483
1484                         var attr = null;
1485
1486                         if (typeof(key) === 'object' && key !== null)
1487                                 attr = key;
1488                         else if (typeof(key) === 'string')
1489                                 attr = {}, attr[key] = val;
1490
1491                         for (key in attr) {
1492                                 if (!attr.hasOwnProperty(key) || attr[key] == null)
1493                                         continue;
1494
1495                                 switch (typeof(attr[key])) {
1496                                 case 'function':
1497                                         node.addEventListener(key, attr[key]);
1498                                         break;
1499
1500                                 case 'object':
1501                                         node.setAttribute(key, JSON.stringify(attr[key]));
1502                                         break;
1503
1504                                 default:
1505                                         node.setAttribute(key, attr[key]);
1506                                 }
1507                         }
1508                 },
1509
1510                 /**
1511                  * Creates a new DOM `Node` from the given `html`, `attr` and
1512                  * `data` parameters.
1513                  *
1514                  * This function has multiple signatures, it can be either invoked
1515                  * in the form `create(html[, attr[, data]])` or in the form
1516                  * `create(html[, data])`. The used variant is determined from the
1517                  * type of the second argument.
1518                  *
1519                  * @instance
1520                  * @memberof LuCI.dom
1521                  * @param {*} html
1522                  * Describes the node to create.
1523                  *
1524                  * When the value of `html` is of type array, a `DocumentFragment`
1525                  * node is created and each item of the array is first converted
1526                  * to a DOM `Node` by passing it through `create()` and then added
1527                  * as child to the fragment.
1528                  *
1529                  * When the value of `html` is a DOM `Node` instance, no new
1530                  * element will be created but the node will be used as-is.
1531                  *
1532                  * When the value of `html` is a string starting with `<`, it will
1533                  * be passed to `dom.parse()` and the resulting value is used.
1534                  *
1535                  * When the value of `html` is any other string, it will be passed
1536                  * to `document.createElement()` for creating a new DOM `Node` of
1537                  * the given name.
1538                  *
1539                  * @param {Object<string, *>} [attr]
1540                  * Specifies an Object of key, value pairs to set as attributes
1541                  * or event handlers on the created node. Refer to
1542                  * {@link LuCI.dom#attr dom.attr()} for details.
1543                  *
1544                  * @param {*} [data]
1545                  * Specifies children to append to the newly created element.
1546                  * Refer to {@link LuCI.dom#append dom.append()} for details.
1547                  *
1548                  * @throws {InvalidCharacterError}
1549                  * Throws an `InvalidCharacterError` when the given `html`
1550                  * argument contained malformed markup (such as not escaped
1551                  * `&` characters in XHTML mode) or when the given node name
1552                  * in `html` contains characters which are not legal in DOM
1553                  * element names, such as spaces.
1554                  *
1555                  * @returns {Node}
1556                  * Returns the newly created `Node`.
1557                  */
1558                 create: function() {
1559                         var html = arguments[0],
1560                             attr = arguments[1],
1561                             data = arguments[2],
1562                             elem;
1563
1564                         if (!(attr instanceof Object) || Array.isArray(attr))
1565                                 data = attr, attr = null;
1566
1567                         if (Array.isArray(html)) {
1568                                 elem = document.createDocumentFragment();
1569                                 for (var i = 0; i < html.length; i++)
1570                                         elem.appendChild(this.create(html[i]));
1571                         }
1572                         else if (this.elem(html)) {
1573                                 elem = html;
1574                         }
1575                         else if (html.charCodeAt(0) === 60) {
1576                                 elem = this.parse(html);
1577                         }
1578                         else {
1579                                 elem = document.createElement(html);
1580                         }
1581
1582                         if (!elem)
1583                                 return null;
1584
1585                         this.attr(elem, attr);
1586                         this.append(elem, data);
1587
1588                         return elem;
1589                 },
1590
1591                 registry: {},
1592
1593                 /**
1594                  * Attaches or detaches arbitrary data to and from a DOM `Node`.
1595                  *
1596                  * This function is useful to attach non-string values or runtime
1597                  * data that is not serializable to DOM nodes. To decouple data
1598                  * from the DOM, values are not added directly to nodes, but
1599                  * inserted into a registry instead which is then referenced by a
1600                  * string key stored as `data-idref` attribute in the node.
1601                  *
1602                  * This function has multiple signatures and is sensitive to the
1603                  * number of arguments passed to it.
1604                  *
1605                  *  - `dom.data(node)` -
1606                  *     Fetches all data associated with the given node.
1607                  *  - `dom.data(node, key)` -
1608                  *     Fetches a specific key associated with the given node.
1609                  *  - `dom.data(node, key, val)` -
1610                  *     Sets a specific key to the given value associated with the
1611                  *     given node.
1612                  *  - `dom.data(node, null)` -
1613                  *     Clears any data associated with the node.
1614                  *  - `dom.data(node, key, null)` -
1615                  *     Clears the given key associated with the node.
1616                  *
1617                  * @instance
1618                  * @memberof LuCI.dom
1619                  * @param {Node} node
1620                  * The DOM `Node` instance to set or retrieve the data for.
1621                  *
1622                  * @param {string|null} [key]
1623                  * This is either a string specifying the key to retrieve, or
1624                  * `null` to unset the entire node data.
1625                  *
1626                  * @param {*|null} [val]
1627                  * This is either a non-`null` value to set for a given key or
1628                  * `null` to remove the given `key` from the specified node.
1629                  *
1630                  * @returns {*}
1631                  * Returns the get or set value, or `null` when no value could
1632                  * be found.
1633                  */
1634                 data: function(node, key, val) {
1635                         if (!node || !node.getAttribute)
1636                                 return null;
1637
1638                         var id = node.getAttribute('data-idref');
1639
1640                         /* clear all data */
1641                         if (arguments.length > 1 && key == null) {
1642                                 if (id != null) {
1643                                         node.removeAttribute('data-idref');
1644                                         val = this.registry[id]
1645                                         delete this.registry[id];
1646                                         return val;
1647                                 }
1648
1649                                 return null;
1650                         }
1651
1652                         /* clear a key */
1653                         else if (arguments.length > 2 && key != null && val == null) {
1654                                 if (id != null) {
1655                                         val = this.registry[id][key];
1656                                         delete this.registry[id][key];
1657                                         return val;
1658                                 }
1659
1660                                 return null;
1661                         }
1662
1663                         /* set a key */
1664                         else if (arguments.length > 2 && key != null && val != null) {
1665                                 if (id == null) {
1666                                         do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1667                                         while (this.registry.hasOwnProperty(id));
1668
1669                                         node.setAttribute('data-idref', id);
1670                                         this.registry[id] = {};
1671                                 }
1672
1673                                 return (this.registry[id][key] = val);
1674                         }
1675
1676                         /* get all data */
1677                         else if (arguments.length == 1) {
1678                                 if (id != null)
1679                                         return this.registry[id];
1680
1681                                 return null;
1682                         }
1683
1684                         /* get a key */
1685                         else if (arguments.length == 2) {
1686                                 if (id != null)
1687                                         return this.registry[id][key];
1688                         }
1689
1690                         return null;
1691                 },
1692
1693                 /**
1694                  * Binds the given class instance ot the specified DOM `Node`.
1695                  *
1696                  * This function uses the `dom.data()` facility to attach the
1697                  * passed instance of a Class to a node. This is needed for
1698                  * complex widget elements or similar where the corresponding
1699                  * class instance responsible for the element must be retrieved
1700                  * from DOM nodes obtained by `querySelector()` or similar means.
1701                  *
1702                  * @instance
1703                  * @memberof LuCI.dom
1704                  * @param {Node} node
1705                  * The DOM `Node` instance to bind the class to.
1706                  *
1707                  * @param {Class} inst
1708                  * The Class instance to bind to the node.
1709                  *
1710                  * @throws {TypeError}
1711                  * Throws a `TypeError` when the given instance argument isn't
1712                  * a valid Class instance.
1713                  *
1714                  * @returns {Class}
1715                  * Returns the bound class instance.
1716                  */
1717                 bindClassInstance: function(node, inst) {
1718                         if (!(inst instanceof Class))
1719                                 L.error('TypeError', 'Argument must be a class instance');
1720
1721                         return this.data(node, '_class', inst);
1722                 },
1723
1724                 /**
1725                  * Finds a bound class instance on the given node itself or the
1726                  * first bound instance on its closest parent node.
1727                  *
1728                  * @instance
1729                  * @memberof LuCI.dom
1730                  * @param {Node} node
1731                  * The DOM `Node` instance to start from.
1732                  *
1733                  * @returns {Class|null}
1734                  * Returns the founds class instance if any or `null` if no bound
1735                  * class could be found on the node itself or any of its parents.
1736                  */
1737                 findClassInstance: function(node) {
1738                         var inst = null;
1739
1740                         do {
1741                                 inst = this.data(node, '_class');
1742                                 node = node.parentNode;
1743                         }
1744                         while (!(inst instanceof Class) && node != null);
1745
1746                         return inst;
1747                 },
1748
1749                 /**
1750                  * Finds a bound class instance on the given node itself or the
1751                  * first bound instance on its closest parent node and invokes
1752                  * the specified method name on the found class instance.
1753                  *
1754                  * @instance
1755                  * @memberof LuCI.dom
1756                  * @param {Node} node
1757                  * The DOM `Node` instance to start from.
1758                  *
1759                  * @param {string} method
1760                  * The name of the method to invoke on the found class instance.
1761                  *
1762                  * @param {...*} params
1763                  * Additional arguments to pass to the invoked method as-is.
1764                  *
1765                  * @returns {*|null}
1766                  * Returns the return value of the invoked method if a class
1767                  * instance and method has been found. Returns `null` if either
1768                  * no bound class instance could be found, or if the found
1769                  * instance didn't have the requested `method`.
1770                  */
1771                 callClassMethod: function(node, method /*, ... */) {
1772                         var inst = this.findClassInstance(node);
1773
1774                         if (inst == null || typeof(inst[method]) != 'function')
1775                                 return null;
1776
1777                         return inst[method].apply(inst, inst.varargs(arguments, 2));
1778                 },
1779
1780                 /**
1781                  * The ignore callback function is invoked by `isEmpty()` for each
1782                  * child node to decide whether to ignore a child node or not.
1783                  *
1784                  * When this function returns `false`, the node passed to it is
1785                  * ignored, else not.
1786                  *
1787                  * @callback LuCI.dom~ignoreCallbackFn
1788                  * @param {Node} node
1789                  * The child node to test.
1790                  *
1791                  * @returns {boolean}
1792                  * Boolean indicating whether to ignore the node or not.
1793                  */
1794
1795                 /**
1796                  * Tests whether a given DOM `Node` instance is empty or appears
1797                  * empty.
1798                  *
1799                  * Any element child nodes which have the CSS class `hidden` set
1800                  * or for which the optionally passed `ignoreFn` callback function
1801                  * returns `false` are ignored.
1802                  *
1803                  * @instance
1804                  * @memberof LuCI.dom
1805                  * @param {Node} node
1806                  * The DOM `Node` instance to test.
1807                  *
1808                  * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
1809                  * Specifies an optional function which is invoked for each child
1810                  * node to decide whether the child node should be ignored or not.
1811                  *
1812                  * @returns {boolean}
1813                  * Returns `true` if the node does not have any children or if
1814                  * any children node either has a `hidden` CSS class or a `false`
1815                  * result when testing it using the given `ignoreFn`.
1816                  */
1817                 isEmpty: function(node, ignoreFn) {
1818                         for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
1819                                 if (!child.classList.contains('hidden') && (!ignoreFn || !ignoreFn(child)))
1820                                         return false;
1821
1822                         return true;
1823                 }
1824         });
1825
1826         /**
1827          * @class view
1828          * @memberof LuCI
1829          * @hideconstructor
1830          * @classdesc
1831          *
1832          * The `view` class forms the basis of views and provides a standard
1833          * set of methods to inherit from.
1834          */
1835         var View = Class.extend(/* @lends LuCI.view.prototype */ {
1836                 __name__: 'LuCI.view',
1837
1838                 __init__: function() {
1839                         var vp = document.getElementById('view');
1840
1841                         DOM.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1842
1843                         return Promise.resolve(this.load())
1844                                 .then(L.bind(this.render, this))
1845                                 .then(L.bind(function(nodes) {
1846                                         var vp = document.getElementById('view');
1847
1848                                         DOM.content(vp, nodes);
1849                                         DOM.append(vp, this.addFooter());
1850                                 }, this)).catch(L.error);
1851                 },
1852
1853                 /**
1854                  * The load function is invoked before the view is rendered.
1855                  *
1856                  * The invocation of this function is wrapped by
1857                  * `Promise.resolve()` so it may return Promises if needed.
1858                  *
1859                  * The return value of the function (or the resolved values
1860                  * of the promise returned by it) will be passed as first
1861                  * argument to `render()`.
1862                  *
1863                  * This function is supposed to be overwritten by subclasses,
1864                  * the default implementation does nothing.
1865                  *
1866                  * @instance
1867                  * @abstract
1868                  * @memberof LuCI.view
1869                  *
1870                  * @returns {*|Promise<*>}
1871                  * May return any value or a Promise resolving to any value.
1872                  */
1873                 load: function() {},
1874
1875                 /**
1876                  * The render function is invoked after the
1877                  * {@link LuCI.view#load load()} function and responsible
1878                  * for setting up the view contents. It must return a DOM
1879                  * `Node` or `DocumentFragment` holding the contents to
1880                  * insert into the view area.
1881                  *
1882                  * The invocation of this function is wrapped by
1883                  * `Promise.resolve()` so it may return Promises if needed.
1884                  *
1885                  * The return value of the function (or the resolved values
1886                  * of the promise returned by it) will be inserted into the
1887                  * main content area using
1888                  * {@link LuCI.dom#append dom.append()}.
1889                  *
1890                  * This function is supposed to be overwritten by subclasses,
1891                  * the default implementation does nothing.
1892                  *
1893                  * @instance
1894                  * @abstract
1895                  * @memberof LuCI.view
1896                  * @param {*|null} load_results
1897                  * This function will receive the return value of the
1898                  * {@link LuCI.view#load view.load()} function as first
1899                  * argument.
1900                  *
1901                  * @returns {Node|Promise<Node>}
1902                  * Should return a DOM `Node` value or a `Promise` resolving
1903                  * to a `Node` value.
1904                  */
1905                 render: function() {},
1906
1907                 /**
1908                  * The handleSave function is invoked when the user clicks
1909                  * the `Save` button in the page action footer.
1910                  *
1911                  * The default implementation should be sufficient for most
1912                  * views using {@link form#Map form.Map()} based forms - it
1913                  * will iterate all forms present in the view and invoke
1914                  * the {@link form#Map#save Map.save()} method on each form.
1915                  *
1916                  * Views not using `Map` instances or requiring other special
1917                  * logic should overwrite `handleSave()` with a custom
1918                  * implementation.
1919                  *
1920                  * To disable the `Save` page footer button, views extending
1921                  * this base class should overwrite the `handleSave` function
1922                  * with `null`.
1923                  *
1924                  * The invocation of this function is wrapped by
1925                  * `Promise.resolve()` so it may return Promises if needed.
1926                  *
1927                  * @instance
1928                  * @memberof LuCI.view
1929                  * @param {Event} ev
1930                  * The DOM event that triggered the function.
1931                  *
1932                  * @returns {*|Promise<*>}
1933                  * Any return values of this function are discarded, but
1934                  * passed through `Promise.resolve()` to ensure that any
1935                  * returned promise runs to completion before the button
1936                  * is reenabled.
1937                  */
1938                 handleSave: function(ev) {
1939                         var tasks = [];
1940
1941                         document.getElementById('maincontent')
1942                                 .querySelectorAll('.cbi-map').forEach(function(map) {
1943                                         tasks.push(DOM.callClassMethod(map, 'save'));
1944                                 });
1945
1946                         return Promise.all(tasks);
1947                 },
1948
1949                 /**
1950                  * The handleSaveApply function is invoked when the user clicks
1951                  * the `Save & Apply` button in the page action footer.
1952                  *
1953                  * The default implementation should be sufficient for most
1954                  * views using {@link form#Map form.Map()} based forms - it
1955                  * will first invoke
1956                  * {@link LuCI.view.handleSave view.handleSave()} and then
1957                  * call {@link ui#changes#apply ui.changes.apply()} to start the
1958                  * modal config apply and page reload flow.
1959                  *
1960                  * Views not using `Map` instances or requiring other special
1961                  * logic should overwrite `handleSaveApply()` with a custom
1962                  * implementation.
1963                  *
1964                  * To disable the `Save & Apply` page footer button, views
1965                  * extending this base class should overwrite the
1966                  * `handleSaveApply` function with `null`.
1967                  *
1968                  * The invocation of this function is wrapped by
1969                  * `Promise.resolve()` so it may return Promises if needed.
1970                  *
1971                  * @instance
1972                  * @memberof LuCI.view
1973                  * @param {Event} ev
1974                  * The DOM event that triggered the function.
1975                  *
1976                  * @returns {*|Promise<*>}
1977                  * Any return values of this function are discarded, but
1978                  * passed through `Promise.resolve()` to ensure that any
1979                  * returned promise runs to completion before the button
1980                  * is reenabled.
1981                  */
1982                 handleSaveApply: function(ev, mode) {
1983                         return this.handleSave(ev).then(function() {
1984                                 L.ui.changes.apply(mode == '0');
1985                         });
1986                 },
1987
1988                 /**
1989                  * The handleReset function is invoked when the user clicks
1990                  * the `Reset` button in the page action footer.
1991                  *
1992                  * The default implementation should be sufficient for most
1993                  * views using {@link form#Map form.Map()} based forms - it
1994                  * will iterate all forms present in the view and invoke
1995                  * the {@link form#Map#save Map.reset()} method on each form.
1996                  *
1997                  * Views not using `Map` instances or requiring other special
1998                  * logic should overwrite `handleReset()` with a custom
1999                  * implementation.
2000                  *
2001                  * To disable the `Reset` page footer button, views extending
2002                  * this base class should overwrite the `handleReset` function
2003                  * with `null`.
2004                  *
2005                  * The invocation of this function is wrapped by
2006                  * `Promise.resolve()` so it may return Promises if needed.
2007                  *
2008                  * @instance
2009                  * @memberof LuCI.view
2010                  * @param {Event} ev
2011                  * The DOM event that triggered the function.
2012                  *
2013                  * @returns {*|Promise<*>}
2014                  * Any return values of this function are discarded, but
2015                  * passed through `Promise.resolve()` to ensure that any
2016                  * returned promise runs to completion before the button
2017                  * is reenabled.
2018                  */
2019                 handleReset: function(ev) {
2020                         var tasks = [];
2021
2022                         document.getElementById('maincontent')
2023                                 .querySelectorAll('.cbi-map').forEach(function(map) {
2024                                         tasks.push(DOM.callClassMethod(map, 'reset'));
2025                                 });
2026
2027                         return Promise.all(tasks);
2028                 },
2029
2030                 /**
2031                  * Renders a standard page action footer if any of the
2032                  * `handleSave()`, `handleSaveApply()` or `handleReset()`
2033                  * functions are defined.
2034                  *
2035                  * The default implementation should be sufficient for most
2036                  * views - it will render a standard page footer with action
2037                  * buttons labeled `Save`, `Save & Apply` and `Reset`
2038                  * triggering the `handleSave()`, `handleSaveApply()` and
2039                  * `handleReset()` functions respectively.
2040                  *
2041                  * When any of these `handle*()` functions is overwritten
2042                  * with `null` by a view extending this class, the
2043                  * corresponding button will not be rendered.
2044                  *
2045                  * @instance
2046                  * @memberof LuCI.view
2047                  * @returns {DocumentFragment}
2048                  * Returns a `DocumentFragment` containing the footer bar
2049                  * with buttons for each corresponding `handle*()` action
2050                  * or an empty `DocumentFragment` if all three `handle*()`
2051                  * methods are overwritten with `null`.
2052                  */
2053                 addFooter: function() {
2054                         var footer = E([]);
2055
2056                         var saveApplyBtn = this.handleSaveApply ? new L.ui.ComboButton('0', {
2057                                 0: [ _('Save & Apply') ],
2058                                 1: [ _('Apply unchecked') ]
2059                         }, {
2060                                 classes: {
2061                                         0: 'btn cbi-button cbi-button-apply important',
2062                                         1: 'btn cbi-button cbi-button-negative important'
2063                                 },
2064                                 click: L.ui.createHandlerFn(this, 'handleSaveApply')
2065                         }).render() : E([]);
2066
2067                         if (this.handleSaveApply || this.handleSave || this.handleReset) {
2068                                 footer.appendChild(E('div', { 'class': 'cbi-page-actions control-group' }, [
2069                                         saveApplyBtn, ' ',
2070                                         this.handleSave ? E('button', {
2071                                                 'class': 'cbi-button cbi-button-save',
2072                                                 'click': L.ui.createHandlerFn(this, 'handleSave')
2073                                         }, [ _('Save') ]) : '', ' ',
2074                                         this.handleReset ? E('button', {
2075                                                 'class': 'cbi-button cbi-button-reset',
2076                                                 'click': L.ui.createHandlerFn(this, 'handleReset')
2077                                         }, [ _('Reset') ]) : ''
2078                                 ]));
2079                         }
2080
2081                         return footer;
2082                 }
2083         });
2084
2085
2086         var dummyElem = null,
2087             domParser = null,
2088             originalCBIInit = null,
2089             rpcBaseURL = null,
2090             sysFeatures = null,
2091             preloadClasses = null;
2092
2093         /* "preload" builtin classes to make the available via require */
2094         var classes = {
2095                 baseclass: Class,
2096                 dom: DOM,
2097                 poll: Poll,
2098                 request: Request,
2099                 view: View
2100         };
2101
2102         var LuCI = Class.extend(/** @lends LuCI.prototype */ {
2103                 __name__: 'LuCI',
2104                 __init__: function(env) {
2105
2106                         document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
2107                                 if (env.base_url == null || env.base_url == '') {
2108                                         var m = (s.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
2109                                         if (m) {
2110                                                 env.base_url = m[1];
2111                                                 env.resource_version = m[2];
2112                                         }
2113                                 }
2114                         });
2115
2116                         if (env.base_url == null)
2117                                 this.error('InternalError', 'Cannot find url of luci.js');
2118
2119                         env.cgi_base = env.scriptname.replace(/\/[^\/]+$/, '');
2120
2121                         Object.assign(this.env, env);
2122
2123                         document.addEventListener('poll-start', function(ev) {
2124                                 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
2125                                         e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
2126                                 });
2127                         });
2128
2129                         document.addEventListener('poll-stop', function(ev) {
2130                                 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
2131                                         e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
2132                                 });
2133                         });
2134
2135                         var domReady = new Promise(function(resolveFn, rejectFn) {
2136                                 document.addEventListener('DOMContentLoaded', resolveFn);
2137                         });
2138
2139                         Promise.all([
2140                                 domReady,
2141                                 this.require('ui'),
2142                                 this.require('rpc'),
2143                                 this.require('form'),
2144                                 this.probeRPCBaseURL()
2145                         ]).then(this.setupDOM.bind(this)).catch(this.error);
2146
2147                         originalCBIInit = window.cbi_init;
2148                         window.cbi_init = function() {};
2149                 },
2150
2151                 /**
2152                  * Captures the current stack trace and throws an error of the
2153                  * specified type as a new exception. Also logs the exception as
2154                  * error to the debug console if it is available.
2155                  *
2156                  * @instance
2157                  * @memberof LuCI
2158                  *
2159                  * @param {Error|string} [type=Error]
2160                  * Either a string specifying the type of the error to throw or an
2161                  * existing `Error` instance to copy.
2162                  *
2163                  * @param {string} [fmt=Unspecified error]
2164                  * A format string which is used to form the error message, together
2165                  * with all subsequent optional arguments.
2166                  *
2167                  * @param {...*} [args]
2168                  * Zero or more variable arguments to the supplied format string.
2169                  *
2170                  * @throws {Error}
2171                  * Throws the created error object with the captured stack trace
2172                  * appended to the message and the type set to the given type
2173                  * argument or copied from the given error instance.
2174                  */
2175                 raise: function(type, fmt /*, ...*/) {
2176                         var e = null,
2177                             msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
2178                             stack = null;
2179
2180                         if (type instanceof Error) {
2181                                 e = type;
2182
2183                                 if (msg)
2184                                         e.message = msg + ': ' + e.message;
2185                         }
2186                         else {
2187                                 try { throw new Error('stacktrace') }
2188                                 catch (e2) { stack = (e2.stack || '').split(/\n/) }
2189
2190                                 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
2191                                 e.name = type || 'Error';
2192                         }
2193
2194                         stack = (stack || []).map(function(frame) {
2195                                 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
2196                                 return frame ? '  ' + frame : '';
2197                         });
2198
2199                         if (!/^  at /.test(stack[0]))
2200                                 stack.shift();
2201
2202                         if (/\braise /.test(stack[0]))
2203                                 stack.shift();
2204
2205                         if (/\berror /.test(stack[0]))
2206                                 stack.shift();
2207
2208                         if (stack.length)
2209                                 e.message += '\n' + stack.join('\n');
2210
2211                         if (window.console && console.debug)
2212                                 console.debug(e);
2213
2214                         throw e;
2215                 },
2216
2217                 /**
2218                  * A wrapper around {@link LuCI#raise raise()} which also renders
2219                  * the error either as modal overlay when `ui.js` is already loaed
2220                  * or directly into the view body.
2221                  *
2222                  * @instance
2223                  * @memberof LuCI
2224                  *
2225                  * @param {Error|string} [type=Error]
2226                  * Either a string specifying the type of the error to throw or an
2227                  * existing `Error` instance to copy.
2228                  *
2229                  * @param {string} [fmt=Unspecified error]
2230                  * A format string which is used to form the error message, together
2231                  * with all subsequent optional arguments.
2232                  *
2233                  * @param {...*} [args]
2234                  * Zero or more variable arguments to the supplied format string.
2235                  *
2236                  * @throws {Error}
2237                  * Throws the created error object with the captured stack trace
2238                  * appended to the message and the type set to the given type
2239                  * argument or copied from the given error instance.
2240                  */
2241                 error: function(type, fmt /*, ...*/) {
2242                         try {
2243                                 L.raise.apply(L, Array.prototype.slice.call(arguments));
2244                         }
2245                         catch (e) {
2246                                 if (!e.reported) {
2247                                         if (L.ui)
2248                                                 L.ui.addNotification(e.name || _('Runtime error'),
2249                                                         E('pre', {}, e.message), 'danger');
2250                                         else
2251                                                 DOM.content(document.querySelector('#maincontent'),
2252                                                         E('pre', { 'class': 'alert-message error' }, e.message));
2253
2254                                         e.reported = true;
2255                                 }
2256
2257                                 throw e;
2258                         }
2259                 },
2260
2261                 /**
2262                  * Return a bound function using the given `self` as `this` context
2263                  * and any further arguments as parameters to the bound function.
2264                  *
2265                  * @instance
2266                  * @memberof LuCI
2267                  *
2268                  * @param {function} fn
2269                  * The function to bind.
2270                  *
2271                  * @param {*} self
2272                  * The value to bind as `this` context to the specified function.
2273                  *
2274                  * @param {...*} [args]
2275                  * Zero or more variable arguments which are bound to the function
2276                  * as parameters.
2277                  *
2278                  * @returns {function}
2279                  * Returns the bound function.
2280                  */
2281                 bind: function(fn, self /*, ... */) {
2282                         return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
2283                 },
2284
2285                 /**
2286                  * Load an additional LuCI JavaScript class and its dependencies,
2287                  * instantiate it and return the resulting class instance. Each
2288                  * class is only loaded once. Subsequent attempts to load the same
2289                  * class will return the already instantiated class.
2290                  *
2291                  * @instance
2292                  * @memberof LuCI
2293                  *
2294                  * @param {string} name
2295                  * The name of the class to load in dotted notation. Dots will
2296                  * be replaced by spaces and joined with the runtime-determined
2297                  * base URL of LuCI.js to form an absolute URL to load the class
2298                  * file from.
2299                  *
2300                  * @throws {DependencyError}
2301                  * Throws a `DependencyError` when the class to load includes
2302                  * circular dependencies.
2303                  *
2304                  * @throws {NetworkError}
2305                  * Throws `NetworkError` when the underlying {@link LuCI.request}
2306                  * call failed.
2307                  *
2308                  * @throws {SyntaxError}
2309                  * Throws `SyntaxError` when the loaded class file code cannot
2310                  * be interpreted by `eval`.
2311                  *
2312                  * @throws {TypeError}
2313                  * Throws `TypeError` when the class file could be loaded and
2314                  * interpreted, but when invoking its code did not yield a valid
2315                  * class instance.
2316                  *
2317                  * @returns {Promise<LuCI.baseclass>}
2318                  * Returns the instantiated class.
2319                  */
2320                 require: function(name, from) {
2321                         var L = this, url = null, from = from || [];
2322
2323                         /* Class already loaded */
2324                         if (classes[name] != null) {
2325                                 /* Circular dependency */
2326                                 if (from.indexOf(name) != -1)
2327                                         L.raise('DependencyError',
2328                                                 'Circular dependency: class "%s" depends on "%s"',
2329                                                 name, from.join('" which depends on "'));
2330
2331                                 return Promise.resolve(classes[name]);
2332                         }
2333
2334                         url = '%s/%s.js%s'.format(L.env.base_url, name.replace(/\./g, '/'), (L.env.resource_version ? '?v=' + L.env.resource_version : ''));
2335                         from = [ name ].concat(from);
2336
2337                         var compileClass = function(res) {
2338                                 if (!res.ok)
2339                                         L.raise('NetworkError',
2340                                                 'HTTP error %d while loading class file "%s"', res.status, url);
2341
2342                                 var source = res.text(),
2343                                     requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
2344                                     strictmatch = /^use[ \t]+strict$/,
2345                                     depends = [],
2346                                     args = '';
2347
2348                                 /* find require statements in source */
2349                                 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
2350                                         var chr = source.charCodeAt(i);
2351
2352                                         if (esc) {
2353                                                 esc = false;
2354                                         }
2355                                         else if (chr == 92) {
2356                                                 esc = true;
2357                                         }
2358                                         else if (chr == quote) {
2359                                                 var s = source.substring(off, i),
2360                                                     m = requirematch.exec(s);
2361
2362                                                 if (m) {
2363                                                         var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
2364                                                         depends.push(L.require(dep, from));
2365                                                         args += ', ' + as;
2366                                                 }
2367                                                 else if (!strictmatch.exec(s)) {
2368                                                         break;
2369                                                 }
2370
2371                                                 off = -1;
2372                                                 quote = -1;
2373                                         }
2374                                         else if (quote == -1 && (chr == 34 || chr == 39)) {
2375                                                 off = i + 1;
2376                                                 quote = chr;
2377                                         }
2378                                 }
2379
2380                                 /* load dependencies and instantiate class */
2381                                 return Promise.all(depends).then(function(instances) {
2382                                         var _factory, _class;
2383
2384                                         try {
2385                                                 _factory = eval(
2386                                                         '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
2387                                                                 .format(args, source, res.url));
2388                                         }
2389                                         catch (error) {
2390                                                 L.raise('SyntaxError', '%s\n  in %s:%s',
2391                                                         error.message, res.url, error.lineNumber || '?');
2392                                         }
2393
2394                                         _factory.displayName = toCamelCase(name + 'ClassFactory');
2395                                         _class = _factory.apply(_factory, [window, document, L].concat(instances));
2396
2397                                         if (!Class.isSubclass(_class))
2398                                             L.error('TypeError', '"%s" factory yields invalid constructor', name);
2399
2400                                         if (_class.displayName == 'AnonymousClass')
2401                                                 _class.displayName = toCamelCase(name + 'Class');
2402
2403                                         var ptr = Object.getPrototypeOf(L),
2404                                             parts = name.split(/\./),
2405                                             instance = new _class();
2406
2407                                         for (var i = 0; ptr && i < parts.length - 1; i++)
2408                                                 ptr = ptr[parts[i]];
2409
2410                                         if (ptr)
2411                                                 ptr[parts[i]] = instance;
2412
2413                                         classes[name] = instance;
2414
2415                                         return instance;
2416                                 });
2417                         };
2418
2419                         /* Request class file */
2420                         classes[name] = Request.get(url, { cache: true }).then(compileClass);
2421
2422                         return classes[name];
2423                 },
2424
2425                 /* DOM setup */
2426                 probeRPCBaseURL: function() {
2427                         if (rpcBaseURL == null) {
2428                                 try {
2429                                         rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
2430                                 }
2431                                 catch (e) { }
2432                         }
2433
2434                         if (rpcBaseURL == null) {
2435                                 var rpcFallbackURL = this.url('admin/ubus');
2436
2437                                 rpcBaseURL = Request.get('/ubus/').then(function(res) {
2438                                         return (rpcBaseURL = (res.status == 400) ? '/ubus/' : rpcFallbackURL);
2439                                 }, function() {
2440                                         return (rpcBaseURL = rpcFallbackURL);
2441                                 }).then(function(url) {
2442                                         try {
2443                                                 window.sessionStorage.setItem('rpcBaseURL', url);
2444                                         }
2445                                         catch (e) { }
2446
2447                                         return url;
2448                                 });
2449                         }
2450
2451                         return Promise.resolve(rpcBaseURL);
2452                 },
2453
2454                 probeSystemFeatures: function() {
2455                         var sessionid = classes.rpc.getSessionID();
2456
2457                         if (sysFeatures == null) {
2458                                 try {
2459                                         var data = JSON.parse(window.sessionStorage.getItem('sysFeatures'));
2460
2461                                         if (this.isObject(data) && this.isObject(data[sessionid]))
2462                                                 sysFeatures = data[sessionid];
2463                                 }
2464                                 catch (e) {}
2465                         }
2466
2467                         if (!this.isObject(sysFeatures)) {
2468                                 sysFeatures = classes.rpc.declare({
2469                                         object: 'luci',
2470                                         method: 'getFeatures',
2471                                         expect: { '': {} }
2472                                 })().then(function(features) {
2473                                         try {
2474                                                 var data = {};
2475                                                     data[sessionid] = features;
2476
2477                                                 window.sessionStorage.setItem('sysFeatures', JSON.stringify(data));
2478                                         }
2479                                         catch (e) {}
2480
2481                                         sysFeatures = features;
2482
2483                                         return features;
2484                                 });
2485                         }
2486
2487                         return Promise.resolve(sysFeatures);
2488                 },
2489
2490                 probePreloadClasses: function() {
2491                         var sessionid = classes.rpc.getSessionID();
2492
2493                         if (preloadClasses == null) {
2494                                 try {
2495                                         var data = JSON.parse(window.sessionStorage.getItem('preloadClasses'));
2496
2497                                         if (this.isObject(data) && this.isObject(data[sessionid]))
2498                                                 preloadClasses = data[sessionid];
2499                                 }
2500                                 catch (e) {}
2501                         }
2502
2503                         if (!Array.isArray(preloadClasses)) {
2504                                 preloadClasses = this.resolveDefault(classes.rpc.declare({
2505                                         object: 'file',
2506                                         method: 'list',
2507                                         params: [ 'path' ],
2508                                         expect: { 'entries': [] }
2509                                 })(this.fspath(this.resource('preload'))), []).then(function(entries) {
2510                                         var classes = [];
2511
2512                                         for (var i = 0; i < entries.length; i++) {
2513                                                 if (entries[i].type != 'file')
2514                                                         continue;
2515
2516                                                 var m = entries[i].name.match(/(.+)\.js$/);
2517
2518                                                 if (m)
2519                                                         classes.push('preload.%s'.format(m[1]));
2520                                         }
2521
2522                                         try {
2523                                                 var data = {};
2524                                                     data[sessionid] = classes;
2525
2526                                                 window.sessionStorage.setItem('preloadClasses', JSON.stringify(data));
2527                                         }
2528                                         catch (e) {}
2529
2530                                         preloadClasses = classes;
2531
2532                                         return classes;
2533                                 });
2534                         }
2535
2536                         return Promise.resolve(preloadClasses);
2537                 },
2538
2539                 /**
2540                  * Test whether a particular system feature is available, such as
2541                  * hostapd SAE support or an installed firewall. The features are
2542                  * queried once at the beginning of the LuCI session and cached in
2543                  * `SessionStorage` throughout the lifetime of the associated tab or
2544                  * browser window.
2545                  *
2546                  * @instance
2547                  * @memberof LuCI
2548                  *
2549                  * @param {string} feature
2550                  * The feature to test. For detailed list of known feature flags,
2551                  * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
2552                  *
2553                  * @param {string} [subfeature]
2554                  * Some feature classes like `hostapd` provide sub-feature flags,
2555                  * such as `sae` or `11w` support. The `subfeature` argument can
2556                  * be used to query these.
2557                  *
2558                  * @return {boolean|null}
2559                  * Return `true` if the queried feature (and sub-feature) is available
2560                  * or `false` if the requested feature isn't present or known.
2561                  * Return `null` when a sub-feature was queried for a feature which
2562                  * has no sub-features.
2563                  */
2564                 hasSystemFeature: function() {
2565                         var ft = sysFeatures[arguments[0]];
2566
2567                         if (arguments.length == 2)
2568                                 return this.isObject(ft) ? ft[arguments[1]] : null;
2569
2570                         return (ft != null && ft != false);
2571                 },
2572
2573                 /* private */
2574                 notifySessionExpiry: function() {
2575                         Poll.stop();
2576
2577                         L.ui.showModal(_('Session expired'), [
2578                                 E('div', { class: 'alert-message warning' },
2579                                         _('A new login is required since the authentication session expired.')),
2580                                 E('div', { class: 'right' },
2581                                         E('div', {
2582                                                 class: 'btn primary',
2583                                                 click: function() {
2584                                                         var loc = window.location;
2585                                                         window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
2586                                                 }
2587                                         }, _('To login…')))
2588                         ]);
2589
2590                         L.raise('SessionError', 'Login session is expired');
2591                 },
2592
2593                 /* private */
2594                 setupDOM: function(res) {
2595                         var domEv = res[0],
2596                             uiClass = res[1],
2597                             rpcClass = res[2],
2598                             formClass = res[3],
2599                             rpcBaseURL = res[4];
2600
2601                         rpcClass.setBaseURL(rpcBaseURL);
2602
2603                         rpcClass.addInterceptor(function(msg, req) {
2604                                 if (!L.isObject(msg) || !L.isObject(msg.error) || msg.error.code != -32002)
2605                                         return;
2606
2607                                 if (!L.isObject(req) || (req.object == 'session' && req.method == 'access'))
2608                                         return;
2609
2610                                 return rpcClass.declare({
2611                                         'object': 'session',
2612                                         'method': 'access',
2613                                         'params': [ 'scope', 'object', 'function' ],
2614                                         'expect': { access: true }
2615                                 })('uci', 'luci', 'read').catch(L.notifySessionExpiry);
2616                         });
2617
2618                         Request.addInterceptor(function(res) {
2619                                 var isDenied = false;
2620
2621                                 if (res.status == 403 && res.headers.get('X-LuCI-Login-Required') == 'yes')
2622                                         isDenied = true;
2623
2624                                 if (!isDenied)
2625                                         return;
2626
2627                                 L.notifySessionExpiry();
2628                         });
2629
2630                         return Promise.all([
2631                                 this.probeSystemFeatures(),
2632                                 this.probePreloadClasses()
2633                         ]).finally(L.bind(function() {
2634                                 var tasks = [];
2635
2636                                 if (Array.isArray(preloadClasses))
2637                                         for (var i = 0; i < preloadClasses.length; i++)
2638                                                 tasks.push(this.require(preloadClasses[i]));
2639
2640                                 return Promise.all(tasks);
2641                         }, this)).finally(this.initDOM);
2642                 },
2643
2644                 /* private */
2645                 initDOM: function() {
2646                         originalCBIInit();
2647                         Poll.start();
2648                         document.dispatchEvent(new CustomEvent('luci-loaded'));
2649                 },
2650
2651                 /**
2652                  * The `env` object holds environment settings used by LuCI, such
2653                  * as request timeouts, base URLs etc.
2654                  *
2655                  * @instance
2656                  * @memberof LuCI
2657                  */
2658                 env: {},
2659
2660                 /**
2661                  * Construct an absolute filesystem path relative to the server
2662                  * document root.
2663                  *
2664                  * @instance
2665                  * @memberof LuCI
2666                  *
2667                  * @param {...string} [parts]
2668                  * An array of parts to join into a path.
2669                  *
2670                  * @return {string}
2671                  * Return the joined path.
2672                  */
2673                 fspath: function(/* ... */) {
2674                         var path = this.env.documentroot;
2675
2676                         for (var i = 0; i < arguments.length; i++)
2677                                 path += '/' + arguments[i];
2678
2679                         var p = path.replace(/\/+$/, '').replace(/\/+/g, '/').split(/\//),
2680                             res = [];
2681
2682                         for (var i = 0; i < p.length; i++)
2683                                 if (p[i] == '..')
2684                                         res.pop();
2685                                 else if (p[i] != '.')
2686                                         res.push(p[i]);
2687
2688                         return res.join('/');
2689                 },
2690
2691                 /**
2692                  * Construct a relative URL path from the given prefix and parts.
2693                  * The resulting URL is guaranteed to only contain the characters
2694                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2695                  * as `/` for the path separator.
2696                  *
2697                  * @instance
2698                  * @memberof LuCI
2699                  *
2700                  * @param {string} [prefix]
2701                  * The prefix to join the given parts with. If the `prefix` is
2702                  * omitted, it defaults to an empty string.
2703                  *
2704                  * @param {string[]} [parts]
2705                  * An array of parts to join into an URL path. Parts may contain
2706                  * slashes and any of the other characters mentioned above.
2707                  *
2708                  * @return {string}
2709                  * Return the joined URL path.
2710                  */
2711                 path: function(prefix, parts) {
2712                         var url = [ prefix || '' ];
2713
2714                         for (var i = 0; i < parts.length; i++)
2715                                 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
2716                                         url.push('/', parts[i]);
2717
2718                         if (url.length === 1)
2719                                 url.push('/');
2720
2721                         return url.join('');
2722                 },
2723
2724                 /**
2725                  * Construct an URL  pathrelative to the script path of the server
2726                  * side LuCI application (usually `/cgi-bin/luci`).
2727                  *
2728                  * The resulting URL is guaranteed to only contain the characters
2729                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2730                  * as `/` for the path separator.
2731                  *
2732                  * @instance
2733                  * @memberof LuCI
2734                  *
2735                  * @param {string[]} [parts]
2736                  * An array of parts to join into an URL path. Parts may contain
2737                  * slashes and any of the other characters mentioned above.
2738                  *
2739                  * @return {string}
2740                  * Returns the resulting URL path.
2741                  */
2742                 url: function() {
2743                         return this.path(this.env.scriptname, arguments);
2744                 },
2745
2746                 /**
2747                  * Construct an URL path relative to the global static resource path
2748                  * of the LuCI ui (usually `/luci-static/resources`).
2749                  *
2750                  * The resulting URL is guaranteed to only contain the characters
2751                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2752                  * as `/` for the path separator.
2753                  *
2754                  * @instance
2755                  * @memberof LuCI
2756                  *
2757                  * @param {string[]} [parts]
2758                  * An array of parts to join into an URL path. Parts may contain
2759                  * slashes and any of the other characters mentioned above.
2760                  *
2761                  * @return {string}
2762                  * Returns the resulting URL path.
2763                  */
2764                 resource: function() {
2765                         return this.path(this.env.resource, arguments);
2766                 },
2767
2768                 /**
2769                  * Construct an URL path relative to the media resource path of the
2770                  * LuCI ui (usually `/luci-static/$theme_name`).
2771                  *
2772                  * The resulting URL is guaranteed to only contain the characters
2773                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2774                  * as `/` for the path separator.
2775                  *
2776                  * @instance
2777                  * @memberof LuCI
2778                  *
2779                  * @param {string[]} [parts]
2780                  * An array of parts to join into an URL path. Parts may contain
2781                  * slashes and any of the other characters mentioned above.
2782                  *
2783                  * @return {string}
2784                  * Returns the resulting URL path.
2785                  */
2786                 media: function() {
2787                         return this.path(this.env.media, arguments);
2788                 },
2789
2790                 /**
2791                  * Return the complete URL path to the current view.
2792                  *
2793                  * @instance
2794                  * @memberof LuCI
2795                  *
2796                  * @return {string}
2797                  * Returns the URL path to the current view.
2798                  */
2799                 location: function() {
2800                         return this.path(this.env.scriptname, this.env.requestpath);
2801                 },
2802
2803
2804                 /**
2805                  * Tests whether the passed argument is a JavaScript object.
2806                  * This function is meant to be an object counterpart to the
2807                  * standard `Array.isArray()` function.
2808                  *
2809                  * @instance
2810                  * @memberof LuCI
2811                  *
2812                  * @param {*} [val]
2813                  * The value to test
2814                  *
2815                  * @return {boolean}
2816                  * Returns `true` if the given value is of type object and
2817                  * not `null`, else returns `false`.
2818                  */
2819                 isObject: function(val) {
2820                         return (val != null && typeof(val) == 'object');
2821                 },
2822
2823                 /**
2824                  * Return an array of sorted object keys, optionally sorted by
2825                  * a different key or a different sorting mode.
2826                  *
2827                  * @instance
2828                  * @memberof LuCI
2829                  *
2830                  * @param {object} obj
2831                  * The object to extract the keys from. If the given value is
2832                  * not an object, the function will return an empty array.
2833                  *
2834                  * @param {string} [key]
2835                  * Specifies the key to order by. This is mainly useful for
2836                  * nested objects of objects or objects of arrays when sorting
2837                  * shall not be performed by the primary object keys but by
2838                  * some other key pointing to a value within the nested values.
2839                  *
2840                  * @param {string} [sortmode]
2841                  * May be either `addr` or `num` to override the natural
2842                  * lexicographic sorting with a sorting suitable for IP/MAC style
2843                  * addresses or numeric values respectively.
2844                  *
2845                  * @return {string[]}
2846                  * Returns an array containing the sorted keys of the given object.
2847                  */
2848                 sortedKeys: function(obj, key, sortmode) {
2849                         if (obj == null || typeof(obj) != 'object')
2850                                 return [];
2851
2852                         return Object.keys(obj).map(function(e) {
2853                                 var v = (key != null) ? obj[e][key] : e;
2854
2855                                 switch (sortmode) {
2856                                 case 'addr':
2857                                         v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
2858                                                 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
2859                                         break;
2860
2861                                 case 'num':
2862                                         v = (v != null) ? +v : null;
2863                                         break;
2864                                 }
2865
2866                                 return [ e, v ];
2867                         }).filter(function(e) {
2868                                 return (e[1] != null);
2869                         }).sort(function(a, b) {
2870                                 return (a[1] > b[1]);
2871                         }).map(function(e) {
2872                                 return e[0];
2873                         });
2874                 },
2875
2876                 /**
2877                  * Converts the given value to an array. If the given value is of
2878                  * type array, it is returned as-is, values of type object are
2879                  * returned as one-element array containing the object, empty
2880                  * strings and `null` values are returned as empty array, all other
2881                  * values are converted using `String()`, trimmed, split on white
2882                  * space and returned as array.
2883                  *
2884                  * @instance
2885                  * @memberof LuCI
2886                  *
2887                  * @param {*} val
2888                  * The value to convert into an array.
2889                  *
2890                  * @return {Array<*>}
2891                  * Returns the resulting array.
2892                  */
2893                 toArray: function(val) {
2894                         if (val == null)
2895                                 return [];
2896                         else if (Array.isArray(val))
2897                                 return val;
2898                         else if (typeof(val) == 'object')
2899                                 return [ val ];
2900
2901                         var s = String(val).trim();
2902
2903                         if (s == '')
2904                                 return [];
2905
2906                         return s.split(/\s+/);
2907                 },
2908
2909                 /**
2910                  * Returns a promise resolving with either the given value or or with
2911                  * the given default in case the input value is a rejecting promise.
2912                  *
2913                  * @instance
2914                  * @memberof LuCI
2915                  *
2916                  * @param {*} value
2917                  * The value to resolve the promise with.
2918                  *
2919                  * @param {*} defvalue
2920                  * The default value to resolve the promise with in case the given
2921                  * input value is a rejecting promise.
2922                  *
2923                  * @returns {Promise<*>}
2924                  * Returns a new promise resolving either to the given input value or
2925                  * to the given default value on error.
2926                  */
2927                 resolveDefault: function(value, defvalue) {
2928                         return Promise.resolve(value).catch(function() { return defvalue });
2929                 },
2930
2931                 /**
2932                  * The request callback function is invoked whenever an HTTP
2933                  * reply to a request made using the `L.get()`, `L.post()` or
2934                  * `L.poll()` function is timed out or received successfully.
2935                  *
2936                  * @instance
2937                  * @memberof LuCI
2938                  *
2939                  * @callback LuCI.requestCallbackFn
2940                  * @param {XMLHTTPRequest} xhr
2941                  * The XMLHTTPRequest instance used to make the request.
2942                  *
2943                  * @param {*} data
2944                  * The response JSON if the response could be parsed as such,
2945                  * else `null`.
2946                  *
2947                  * @param {number} duration
2948                  * The total duration of the request in milliseconds.
2949                  */
2950
2951                 /**
2952                  * Issues a GET request to the given url and invokes the specified
2953                  * callback function. The function is a wrapper around
2954                  * {@link LuCI.request#request Request.request()}.
2955                  *
2956                  * @deprecated
2957                  * @instance
2958                  * @memberof LuCI
2959                  *
2960                  * @param {string} url
2961                  * The URL to request.
2962                  *
2963                  * @param {Object<string, string>} [args]
2964                  * Additional query string arguments to append to the URL.
2965                  *
2966                  * @param {LuCI.requestCallbackFn} cb
2967                  * The callback function to invoke when the request finishes.
2968                  *
2969                  * @return {Promise<null>}
2970                  * Returns a promise resolving to `null` when concluded.
2971                  */
2972                 get: function(url, args, cb) {
2973                         return this.poll(null, url, args, cb, false);
2974                 },
2975
2976                 /**
2977                  * Issues a POST request to the given url and invokes the specified
2978                  * callback function. The function is a wrapper around
2979                  * {@link LuCI.request#request Request.request()}. The request is
2980                  * sent using `application/x-www-form-urlencoded` encoding and will
2981                  * contain a field `token` with the current value of `LuCI.env.token`
2982                  * by default.
2983                  *
2984                  * @deprecated
2985                  * @instance
2986                  * @memberof LuCI
2987                  *
2988                  * @param {string} url
2989                  * The URL to request.
2990                  *
2991                  * @param {Object<string, string>} [args]
2992                  * Additional post arguments to append to the request body.
2993                  *
2994                  * @param {LuCI.requestCallbackFn} cb
2995                  * The callback function to invoke when the request finishes.
2996                  *
2997                  * @return {Promise<null>}
2998                  * Returns a promise resolving to `null` when concluded.
2999                  */
3000                 post: function(url, args, cb) {
3001                         return this.poll(null, url, args, cb, true);
3002                 },
3003
3004                 /**
3005                  * Register a polling HTTP request that invokes the specified
3006                  * callback function. The function is a wrapper around
3007                  * {@link LuCI.request.poll#add Request.poll.add()}.
3008                  *
3009                  * @deprecated
3010                  * @instance
3011                  * @memberof LuCI
3012                  *
3013                  * @param {number} interval
3014                  * The poll interval to use. If set to a value less than or equal
3015                  * to `0`, it will default to the global poll interval configured
3016                  * in `LuCI.env.pollinterval`.
3017                  *
3018                  * @param {string} url
3019                  * The URL to request.
3020                  *
3021                  * @param {Object<string, string>} [args]
3022                  * Specifies additional arguments for the request. For GET requests,
3023                  * the arguments are appended to the URL as query string, for POST
3024                  * requests, they'll be added to the request body.
3025                  *
3026                  * @param {LuCI.requestCallbackFn} cb
3027                  * The callback function to invoke whenever a request finishes.
3028                  *
3029                  * @param {boolean} [post=false]
3030                  * When set to `false` or not specified, poll requests will be made
3031                  * using the GET method. When set to `true`, POST requests will be
3032                  * issued. In case of POST requests, the request body will contain
3033                  * an argument `token` with the current value of `LuCI.env.token` by
3034                  * default, regardless of the parameters specified with `args`.
3035                  *
3036                  * @return {function}
3037                  * Returns the internally created function that has been passed to
3038                  * {@link LuCI.request.poll#add Request.poll.add()}. This value can
3039                  * be passed to {@link LuCI.poll.remove Poll.remove()} to remove the
3040                  * polling request.
3041                  */
3042                 poll: function(interval, url, args, cb, post) {
3043                         if (interval !== null && interval <= 0)
3044                                 interval = this.env.pollinterval;
3045
3046                         var data = post ? { token: this.env.token } : null,
3047                             method = post ? 'POST' : 'GET';
3048
3049                         if (!/^(?:\/|\S+:\/\/)/.test(url))
3050                                 url = this.url(url);
3051
3052                         if (args != null)
3053                                 data = Object.assign(data || {}, args);
3054
3055                         if (interval !== null)
3056                                 return Request.poll.add(interval, url, { method: method, query: data }, cb);
3057                         else
3058                                 return Request.request(url, { method: method, query: data })
3059                                         .then(function(res) {
3060                                                 var json = null;
3061                                                 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
3062                                                         try { json = res.json() } catch(e) {}
3063                                                 cb(res.xhr, json, res.duration);
3064                                         });
3065                 },
3066
3067                 /**
3068                  * Deprecated wrapper around {@link LuCI.poll.remove Poll.remove()}.
3069                  *
3070                  * @deprecated
3071                  * @instance
3072                  * @memberof LuCI
3073                  *
3074                  * @param {function} entry
3075                  * The polling function to remove.
3076                  *
3077                  * @return {boolean}
3078                  * Returns `true` when the function has been removed or `false` if
3079                  * it could not be found.
3080                  */
3081                 stop: function(entry) { return Poll.remove(entry) },
3082
3083                 /**
3084                  * Deprecated wrapper around {@link LuCI.poll.stop Poll.stop()}.
3085                  *
3086                  * @deprecated
3087                  * @instance
3088                  * @memberof LuCI
3089                  *
3090                  * @return {boolean}
3091                  * Returns `true` when the polling loop has been stopped or `false`
3092                  * when it didn't run to begin with.
3093                  */
3094                 halt: function() { return Poll.stop() },
3095
3096                 /**
3097                  * Deprecated wrapper around {@link LuCI.poll.start Poll.start()}.
3098                  *
3099                  * @deprecated
3100                  * @instance
3101                  * @memberof LuCI
3102                  *
3103                  * @return {boolean}
3104                  * Returns `true` when the polling loop has been started or `false`
3105                  * when it was already running.
3106                  */
3107                 run: function() { return Poll.start() },
3108
3109                 /**
3110                  * Legacy `L.dom` class alias. New view code should use `'require dom';`
3111                  * to request the `LuCI.dom` class.
3112                  *
3113                  * @instance
3114                  * @memberof LuCI
3115                  * @deprecated
3116                  */
3117                 dom: DOM,
3118
3119                 /**
3120                  * Legacy `L.view` class alias. New view code should use `'require view';`
3121                  * to request the `LuCI.view` class.
3122                  *
3123                  * @instance
3124                  * @memberof LuCI
3125                  * @deprecated
3126                  */
3127                 view: View,
3128
3129                 /**
3130                  * Legacy `L.Poll` class alias. New view code should use `'require poll';`
3131                  * to request the `LuCI.poll` class.
3132                  *
3133                  * @instance
3134                  * @memberof LuCI
3135                  * @deprecated
3136                  */
3137                 Poll: Poll,
3138
3139                 /**
3140                  * Legacy `L.Request` class alias. New view code should use `'require request';`
3141                  * to request the `LuCI.request` class.
3142                  *
3143                  * @instance
3144                  * @memberof LuCI
3145                  * @deprecated
3146                  */
3147                 Request: Request,
3148
3149                 /**
3150                  * Legacy `L.Class` class alias. New view code should use `'require baseclass';`
3151                  * to request the `LuCI.baseclass` class.
3152                  *
3153                  * @instance
3154                  * @memberof LuCI
3155                  * @deprecated
3156                  */
3157                 Class: Class
3158         });
3159
3160         /**
3161          * @class xhr
3162          * @memberof LuCI
3163          * @deprecated
3164          * @classdesc
3165          *
3166          * The `LuCI.xhr` class is a legacy compatibility shim for the
3167          * functionality formerly provided by `xhr.js`. It is registered as global
3168          * `window.XHR` symbol for compatibility with legacy code.
3169          *
3170          * New code should use {@link LuCI.request} instead to implement HTTP
3171          * request handling.
3172          */
3173         var XHR = Class.extend(/** @lends LuCI.xhr.prototype */ {
3174                 __name__: 'LuCI.xhr',
3175                 __init__: function() {
3176                         if (window.console && console.debug)
3177                                 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
3178                 },
3179
3180                 _response: function(cb, res, json, duration) {
3181                         if (this.active)
3182                                 cb(res, json, duration);
3183                         delete this.active;
3184                 },
3185
3186                 /**
3187                  * This function is a legacy wrapper around
3188                  * {@link LuCI#get LuCI.get()}.
3189                  *
3190                  * @instance
3191                  * @deprecated
3192                  * @memberof LuCI.xhr
3193                  *
3194                  * @param {string} url
3195                  * The URL to request
3196                  *
3197                  * @param {Object} [data]
3198                  * Additional query string data
3199                  *
3200                  * @param {LuCI.requestCallbackFn} [callback]
3201                  * Callback function to invoke on completion
3202                  *
3203                  * @param {number} [timeout]
3204                  * Request timeout to use
3205                  *
3206                  * @return {Promise<null>}
3207                  */
3208                 get: function(url, data, callback, timeout) {
3209                         this.active = true;
3210                         L.get(url, data, this._response.bind(this, callback), timeout);
3211                 },
3212
3213                 /**
3214                  * This function is a legacy wrapper around
3215                  * {@link LuCI#post LuCI.post()}.
3216                  *
3217                  * @instance
3218                  * @deprecated
3219                  * @memberof LuCI.xhr
3220                  *
3221                  * @param {string} url
3222                  * The URL to request
3223                  *
3224                  * @param {Object} [data]
3225                  * Additional data to append to the request body.
3226                  *
3227                  * @param {LuCI.requestCallbackFn} [callback]
3228                  * Callback function to invoke on completion
3229                  *
3230                  * @param {number} [timeout]
3231                  * Request timeout to use
3232                  *
3233                  * @return {Promise<null>}
3234                  */
3235                 post: function(url, data, callback, timeout) {
3236                         this.active = true;
3237                         L.post(url, data, this._response.bind(this, callback), timeout);
3238                 },
3239
3240                 /**
3241                  * Cancels a running request.
3242                  *
3243                  * This function does not actually cancel the underlying
3244                  * `XMLHTTPRequest` request but it sets a flag which prevents the
3245                  * invocation of the callback function when the request eventually
3246                  * finishes or timed out.
3247                  *
3248                  * @instance
3249                  * @deprecated
3250                  * @memberof LuCI.xhr
3251                  */
3252                 cancel: function() { delete this.active },
3253
3254                 /**
3255                  * Checks the running state of the request.
3256                  *
3257                  * @instance
3258                  * @deprecated
3259                  * @memberof LuCI.xhr
3260                  *
3261                  * @returns {boolean}
3262                  * Returns `true` if the request is still running or `false` if it
3263                  * already completed.
3264                  */
3265                 busy: function() { return (this.active === true) },
3266
3267                 /**
3268                  * Ignored for backwards compatibility.
3269                  *
3270                  * This function does nothing.
3271                  *
3272                  * @instance
3273                  * @deprecated
3274                  * @memberof LuCI.xhr
3275                  */
3276                 abort: function() {},
3277
3278                 /**
3279                  * Existing for backwards compatibility.
3280                  *
3281                  * This function simply throws an `InternalError` when invoked.
3282                  *
3283                  * @instance
3284                  * @deprecated
3285                  * @memberof LuCI.xhr
3286                  *
3287                  * @throws {InternalError}
3288                  * Throws an `InternalError` with the message `Not implemented`
3289                  * when invoked.
3290                  */
3291                 send_form: function() { L.error('InternalError', 'Not implemented') },
3292         });
3293
3294         XHR.get = function() { return window.L.get.apply(window.L, arguments) };
3295         XHR.post = function() { return window.L.post.apply(window.L, arguments) };
3296         XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
3297         XHR.stop = Request.poll.remove.bind(Request.poll);
3298         XHR.halt = Request.poll.stop.bind(Request.poll);
3299         XHR.run = Request.poll.start.bind(Request.poll);
3300         XHR.running = Request.poll.active.bind(Request.poll);
3301
3302         window.XHR = XHR;
3303         window.LuCI = LuCI;
3304 })(window, document);