Revert "build: luci.mk: gracefully handle missing or unversioned po subdirectories"
[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                         var domReady = new Promise(function(resolveFn, rejectFn) {
2124                                 document.addEventListener('DOMContentLoaded', resolveFn);
2125                         });
2126
2127                         Promise.all([
2128                                 domReady,
2129                                 this.require('ui'),
2130                                 this.require('rpc'),
2131                                 this.require('form'),
2132                                 this.probeRPCBaseURL()
2133                         ]).then(this.setupDOM.bind(this)).catch(this.error);
2134
2135                         originalCBIInit = window.cbi_init;
2136                         window.cbi_init = function() {};
2137                 },
2138
2139                 /**
2140                  * Captures the current stack trace and throws an error of the
2141                  * specified type as a new exception. Also logs the exception as
2142                  * error to the debug console if it is available.
2143                  *
2144                  * @instance
2145                  * @memberof LuCI
2146                  *
2147                  * @param {Error|string} [type=Error]
2148                  * Either a string specifying the type of the error to throw or an
2149                  * existing `Error` instance to copy.
2150                  *
2151                  * @param {string} [fmt=Unspecified error]
2152                  * A format string which is used to form the error message, together
2153                  * with all subsequent optional arguments.
2154                  *
2155                  * @param {...*} [args]
2156                  * Zero or more variable arguments to the supplied format string.
2157                  *
2158                  * @throws {Error}
2159                  * Throws the created error object with the captured stack trace
2160                  * appended to the message and the type set to the given type
2161                  * argument or copied from the given error instance.
2162                  */
2163                 raise: function(type, fmt /*, ...*/) {
2164                         var e = null,
2165                             msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
2166                             stack = null;
2167
2168                         if (type instanceof Error) {
2169                                 e = type;
2170
2171                                 if (msg)
2172                                         e.message = msg + ': ' + e.message;
2173                         }
2174                         else {
2175                                 try { throw new Error('stacktrace') }
2176                                 catch (e2) { stack = (e2.stack || '').split(/\n/) }
2177
2178                                 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
2179                                 e.name = type || 'Error';
2180                         }
2181
2182                         stack = (stack || []).map(function(frame) {
2183                                 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
2184                                 return frame ? '  ' + frame : '';
2185                         });
2186
2187                         if (!/^  at /.test(stack[0]))
2188                                 stack.shift();
2189
2190                         if (/\braise /.test(stack[0]))
2191                                 stack.shift();
2192
2193                         if (/\berror /.test(stack[0]))
2194                                 stack.shift();
2195
2196                         if (stack.length)
2197                                 e.message += '\n' + stack.join('\n');
2198
2199                         if (window.console && console.debug)
2200                                 console.debug(e);
2201
2202                         throw e;
2203                 },
2204
2205                 /**
2206                  * A wrapper around {@link LuCI#raise raise()} which also renders
2207                  * the error either as modal overlay when `ui.js` is already loaed
2208                  * or directly into the view body.
2209                  *
2210                  * @instance
2211                  * @memberof LuCI
2212                  *
2213                  * @param {Error|string} [type=Error]
2214                  * Either a string specifying the type of the error to throw or an
2215                  * existing `Error` instance to copy.
2216                  *
2217                  * @param {string} [fmt=Unspecified error]
2218                  * A format string which is used to form the error message, together
2219                  * with all subsequent optional arguments.
2220                  *
2221                  * @param {...*} [args]
2222                  * Zero or more variable arguments to the supplied format string.
2223                  *
2224                  * @throws {Error}
2225                  * Throws the created error object with the captured stack trace
2226                  * appended to the message and the type set to the given type
2227                  * argument or copied from the given error instance.
2228                  */
2229                 error: function(type, fmt /*, ...*/) {
2230                         try {
2231                                 L.raise.apply(L, Array.prototype.slice.call(arguments));
2232                         }
2233                         catch (e) {
2234                                 if (!e.reported) {
2235                                         if (L.ui)
2236                                                 L.ui.addNotification(e.name || _('Runtime error'),
2237                                                         E('pre', {}, e.message), 'danger');
2238                                         else
2239                                                 DOM.content(document.querySelector('#maincontent'),
2240                                                         E('pre', { 'class': 'alert-message error' }, e.message));
2241
2242                                         e.reported = true;
2243                                 }
2244
2245                                 throw e;
2246                         }
2247                 },
2248
2249                 /**
2250                  * Return a bound function using the given `self` as `this` context
2251                  * and any further arguments as parameters to the bound function.
2252                  *
2253                  * @instance
2254                  * @memberof LuCI
2255                  *
2256                  * @param {function} fn
2257                  * The function to bind.
2258                  *
2259                  * @param {*} self
2260                  * The value to bind as `this` context to the specified function.
2261                  *
2262                  * @param {...*} [args]
2263                  * Zero or more variable arguments which are bound to the function
2264                  * as parameters.
2265                  *
2266                  * @returns {function}
2267                  * Returns the bound function.
2268                  */
2269                 bind: function(fn, self /*, ... */) {
2270                         return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
2271                 },
2272
2273                 /**
2274                  * Load an additional LuCI JavaScript class and its dependencies,
2275                  * instantiate it and return the resulting class instance. Each
2276                  * class is only loaded once. Subsequent attempts to load the same
2277                  * class will return the already instantiated class.
2278                  *
2279                  * @instance
2280                  * @memberof LuCI
2281                  *
2282                  * @param {string} name
2283                  * The name of the class to load in dotted notation. Dots will
2284                  * be replaced by spaces and joined with the runtime-determined
2285                  * base URL of LuCI.js to form an absolute URL to load the class
2286                  * file from.
2287                  *
2288                  * @throws {DependencyError}
2289                  * Throws a `DependencyError` when the class to load includes
2290                  * circular dependencies.
2291                  *
2292                  * @throws {NetworkError}
2293                  * Throws `NetworkError` when the underlying {@link LuCI.request}
2294                  * call failed.
2295                  *
2296                  * @throws {SyntaxError}
2297                  * Throws `SyntaxError` when the loaded class file code cannot
2298                  * be interpreted by `eval`.
2299                  *
2300                  * @throws {TypeError}
2301                  * Throws `TypeError` when the class file could be loaded and
2302                  * interpreted, but when invoking its code did not yield a valid
2303                  * class instance.
2304                  *
2305                  * @returns {Promise<LuCI.baseclass>}
2306                  * Returns the instantiated class.
2307                  */
2308                 require: function(name, from) {
2309                         var L = this, url = null, from = from || [];
2310
2311                         /* Class already loaded */
2312                         if (classes[name] != null) {
2313                                 /* Circular dependency */
2314                                 if (from.indexOf(name) != -1)
2315                                         L.raise('DependencyError',
2316                                                 'Circular dependency: class "%s" depends on "%s"',
2317                                                 name, from.join('" which depends on "'));
2318
2319                                 return Promise.resolve(classes[name]);
2320                         }
2321
2322                         url = '%s/%s.js%s'.format(L.env.base_url, name.replace(/\./g, '/'), (L.env.resource_version ? '?v=' + L.env.resource_version : ''));
2323                         from = [ name ].concat(from);
2324
2325                         var compileClass = function(res) {
2326                                 if (!res.ok)
2327                                         L.raise('NetworkError',
2328                                                 'HTTP error %d while loading class file "%s"', res.status, url);
2329
2330                                 var source = res.text(),
2331                                     requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
2332                                     strictmatch = /^use[ \t]+strict$/,
2333                                     depends = [],
2334                                     args = '';
2335
2336                                 /* find require statements in source */
2337                                 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
2338                                         var chr = source.charCodeAt(i);
2339
2340                                         if (esc) {
2341                                                 esc = false;
2342                                         }
2343                                         else if (chr == 92) {
2344                                                 esc = true;
2345                                         }
2346                                         else if (chr == quote) {
2347                                                 var s = source.substring(off, i),
2348                                                     m = requirematch.exec(s);
2349
2350                                                 if (m) {
2351                                                         var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
2352                                                         depends.push(L.require(dep, from));
2353                                                         args += ', ' + as;
2354                                                 }
2355                                                 else if (!strictmatch.exec(s)) {
2356                                                         break;
2357                                                 }
2358
2359                                                 off = -1;
2360                                                 quote = -1;
2361                                         }
2362                                         else if (quote == -1 && (chr == 34 || chr == 39)) {
2363                                                 off = i + 1;
2364                                                 quote = chr;
2365                                         }
2366                                 }
2367
2368                                 /* load dependencies and instantiate class */
2369                                 return Promise.all(depends).then(function(instances) {
2370                                         var _factory, _class;
2371
2372                                         try {
2373                                                 _factory = eval(
2374                                                         '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
2375                                                                 .format(args, source, res.url));
2376                                         }
2377                                         catch (error) {
2378                                                 L.raise('SyntaxError', '%s\n  in %s:%s',
2379                                                         error.message, res.url, error.lineNumber || '?');
2380                                         }
2381
2382                                         _factory.displayName = toCamelCase(name + 'ClassFactory');
2383                                         _class = _factory.apply(_factory, [window, document, L].concat(instances));
2384
2385                                         if (!Class.isSubclass(_class))
2386                                             L.error('TypeError', '"%s" factory yields invalid constructor', name);
2387
2388                                         if (_class.displayName == 'AnonymousClass')
2389                                                 _class.displayName = toCamelCase(name + 'Class');
2390
2391                                         var ptr = Object.getPrototypeOf(L),
2392                                             parts = name.split(/\./),
2393                                             instance = new _class();
2394
2395                                         for (var i = 0; ptr && i < parts.length - 1; i++)
2396                                                 ptr = ptr[parts[i]];
2397
2398                                         if (ptr)
2399                                                 ptr[parts[i]] = instance;
2400
2401                                         classes[name] = instance;
2402
2403                                         return instance;
2404                                 });
2405                         };
2406
2407                         /* Request class file */
2408                         classes[name] = Request.get(url, { cache: true }).then(compileClass);
2409
2410                         return classes[name];
2411                 },
2412
2413                 /* DOM setup */
2414                 probeRPCBaseURL: function() {
2415                         if (rpcBaseURL == null) {
2416                                 try {
2417                                         rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
2418                                 }
2419                                 catch (e) { }
2420                         }
2421
2422                         if (rpcBaseURL == null) {
2423                                 var rpcFallbackURL = this.url('admin/ubus');
2424
2425                                 rpcBaseURL = Request.get(this.env.ubuspath).then(function(res) {
2426                                         return (rpcBaseURL = (res.status == 400) ? L.env.ubuspath : rpcFallbackURL);
2427                                 }, function() {
2428                                         return (rpcBaseURL = rpcFallbackURL);
2429                                 }).then(function(url) {
2430                                         try {
2431                                                 window.sessionStorage.setItem('rpcBaseURL', url);
2432                                         }
2433                                         catch (e) { }
2434
2435                                         return url;
2436                                 });
2437                         }
2438
2439                         return Promise.resolve(rpcBaseURL);
2440                 },
2441
2442                 probeSystemFeatures: function() {
2443                         var sessionid = classes.rpc.getSessionID();
2444
2445                         if (sysFeatures == null) {
2446                                 try {
2447                                         var data = JSON.parse(window.sessionStorage.getItem('sysFeatures'));
2448
2449                                         if (this.isObject(data) && this.isObject(data[sessionid]))
2450                                                 sysFeatures = data[sessionid];
2451                                 }
2452                                 catch (e) {}
2453                         }
2454
2455                         if (!this.isObject(sysFeatures)) {
2456                                 sysFeatures = classes.rpc.declare({
2457                                         object: 'luci',
2458                                         method: 'getFeatures',
2459                                         expect: { '': {} }
2460                                 })().then(function(features) {
2461                                         try {
2462                                                 var data = {};
2463                                                     data[sessionid] = features;
2464
2465                                                 window.sessionStorage.setItem('sysFeatures', JSON.stringify(data));
2466                                         }
2467                                         catch (e) {}
2468
2469                                         sysFeatures = features;
2470
2471                                         return features;
2472                                 });
2473                         }
2474
2475                         return Promise.resolve(sysFeatures);
2476                 },
2477
2478                 probePreloadClasses: function() {
2479                         var sessionid = classes.rpc.getSessionID();
2480
2481                         if (preloadClasses == null) {
2482                                 try {
2483                                         var data = JSON.parse(window.sessionStorage.getItem('preloadClasses'));
2484
2485                                         if (this.isObject(data) && this.isObject(data[sessionid]))
2486                                                 preloadClasses = data[sessionid];
2487                                 }
2488                                 catch (e) {}
2489                         }
2490
2491                         if (!Array.isArray(preloadClasses)) {
2492                                 preloadClasses = this.resolveDefault(classes.rpc.declare({
2493                                         object: 'file',
2494                                         method: 'list',
2495                                         params: [ 'path' ],
2496                                         expect: { 'entries': [] }
2497                                 })(this.fspath(this.resource('preload'))), []).then(function(entries) {
2498                                         var classes = [];
2499
2500                                         for (var i = 0; i < entries.length; i++) {
2501                                                 if (entries[i].type != 'file')
2502                                                         continue;
2503
2504                                                 var m = entries[i].name.match(/(.+)\.js$/);
2505
2506                                                 if (m)
2507                                                         classes.push('preload.%s'.format(m[1]));
2508                                         }
2509
2510                                         try {
2511                                                 var data = {};
2512                                                     data[sessionid] = classes;
2513
2514                                                 window.sessionStorage.setItem('preloadClasses', JSON.stringify(data));
2515                                         }
2516                                         catch (e) {}
2517
2518                                         preloadClasses = classes;
2519
2520                                         return classes;
2521                                 });
2522                         }
2523
2524                         return Promise.resolve(preloadClasses);
2525                 },
2526
2527                 /**
2528                  * Test whether a particular system feature is available, such as
2529                  * hostapd SAE support or an installed firewall. The features are
2530                  * queried once at the beginning of the LuCI session and cached in
2531                  * `SessionStorage` throughout the lifetime of the associated tab or
2532                  * browser window.
2533                  *
2534                  * @instance
2535                  * @memberof LuCI
2536                  *
2537                  * @param {string} feature
2538                  * The feature to test. For detailed list of known feature flags,
2539                  * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
2540                  *
2541                  * @param {string} [subfeature]
2542                  * Some feature classes like `hostapd` provide sub-feature flags,
2543                  * such as `sae` or `11w` support. The `subfeature` argument can
2544                  * be used to query these.
2545                  *
2546                  * @return {boolean|null}
2547                  * Return `true` if the queried feature (and sub-feature) is available
2548                  * or `false` if the requested feature isn't present or known.
2549                  * Return `null` when a sub-feature was queried for a feature which
2550                  * has no sub-features.
2551                  */
2552                 hasSystemFeature: function() {
2553                         var ft = sysFeatures[arguments[0]];
2554
2555                         if (arguments.length == 2)
2556                                 return this.isObject(ft) ? ft[arguments[1]] : null;
2557
2558                         return (ft != null && ft != false);
2559                 },
2560
2561                 /* private */
2562                 notifySessionExpiry: function() {
2563                         Poll.stop();
2564
2565                         L.ui.showModal(_('Session expired'), [
2566                                 E('div', { class: 'alert-message warning' },
2567                                         _('A new login is required since the authentication session expired.')),
2568                                 E('div', { class: 'right' },
2569                                         E('div', {
2570                                                 class: 'btn primary',
2571                                                 click: function() {
2572                                                         var loc = window.location;
2573                                                         window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
2574                                                 }
2575                                         }, _('To login…')))
2576                         ]);
2577
2578                         L.raise('SessionError', 'Login session is expired');
2579                 },
2580
2581                 /* private */
2582                 setupDOM: function(res) {
2583                         var domEv = res[0],
2584                             uiClass = res[1],
2585                             rpcClass = res[2],
2586                             formClass = res[3],
2587                             rpcBaseURL = res[4];
2588
2589                         rpcClass.setBaseURL(rpcBaseURL);
2590
2591                         rpcClass.addInterceptor(function(msg, req) {
2592                                 if (!L.isObject(msg) || !L.isObject(msg.error) || msg.error.code != -32002)
2593                                         return;
2594
2595                                 if (!L.isObject(req) || (req.object == 'session' && req.method == 'access'))
2596                                         return;
2597
2598                                 return rpcClass.declare({
2599                                         'object': 'session',
2600                                         'method': 'access',
2601                                         'params': [ 'scope', 'object', 'function' ],
2602                                         'expect': { access: true }
2603                                 })('uci', 'luci', 'read').catch(L.notifySessionExpiry);
2604                         });
2605
2606                         Request.addInterceptor(function(res) {
2607                                 var isDenied = false;
2608
2609                                 if (res.status == 403 && res.headers.get('X-LuCI-Login-Required') == 'yes')
2610                                         isDenied = true;
2611
2612                                 if (!isDenied)
2613                                         return;
2614
2615                                 L.notifySessionExpiry();
2616                         });
2617
2618                         document.addEventListener('poll-start', function(ev) {
2619                                 uiClass.showIndicator('poll-status', _('Refreshing'), function(ev) {
2620                                         Request.poll.active() ? Request.poll.stop() : Request.poll.start();
2621                                 });
2622                         });
2623
2624                         document.addEventListener('poll-stop', function(ev) {
2625                                 uiClass.showIndicator('poll-status', _('Paused'), null, 'inactive');
2626                         });
2627
2628                         return Promise.all([
2629                                 this.probeSystemFeatures(),
2630                                 this.probePreloadClasses()
2631                         ]).finally(L.bind(function() {
2632                                 var tasks = [];
2633
2634                                 if (Array.isArray(preloadClasses))
2635                                         for (var i = 0; i < preloadClasses.length; i++)
2636                                                 tasks.push(this.require(preloadClasses[i]));
2637
2638                                 return Promise.all(tasks);
2639                         }, this)).finally(this.initDOM);
2640                 },
2641
2642                 /* private */
2643                 initDOM: function() {
2644                         originalCBIInit();
2645                         Poll.start();
2646                         document.dispatchEvent(new CustomEvent('luci-loaded'));
2647                 },
2648
2649                 /**
2650                  * The `env` object holds environment settings used by LuCI, such
2651                  * as request timeouts, base URLs etc.
2652                  *
2653                  * @instance
2654                  * @memberof LuCI
2655                  */
2656                 env: {},
2657
2658                 /**
2659                  * Construct an absolute filesystem path relative to the server
2660                  * document root.
2661                  *
2662                  * @instance
2663                  * @memberof LuCI
2664                  *
2665                  * @param {...string} [parts]
2666                  * An array of parts to join into a path.
2667                  *
2668                  * @return {string}
2669                  * Return the joined path.
2670                  */
2671                 fspath: function(/* ... */) {
2672                         var path = this.env.documentroot;
2673
2674                         for (var i = 0; i < arguments.length; i++)
2675                                 path += '/' + arguments[i];
2676
2677                         var p = path.replace(/\/+$/, '').replace(/\/+/g, '/').split(/\//),
2678                             res = [];
2679
2680                         for (var i = 0; i < p.length; i++)
2681                                 if (p[i] == '..')
2682                                         res.pop();
2683                                 else if (p[i] != '.')
2684                                         res.push(p[i]);
2685
2686                         return res.join('/');
2687                 },
2688
2689                 /**
2690                  * Construct a relative URL path from the given prefix and parts.
2691                  * The resulting URL is guaranteed to only contain the characters
2692                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2693                  * as `/` for the path separator.
2694                  *
2695                  * @instance
2696                  * @memberof LuCI
2697                  *
2698                  * @param {string} [prefix]
2699                  * The prefix to join the given parts with. If the `prefix` is
2700                  * omitted, it defaults to an empty string.
2701                  *
2702                  * @param {string[]} [parts]
2703                  * An array of parts to join into an URL path. Parts may contain
2704                  * slashes and any of the other characters mentioned above.
2705                  *
2706                  * @return {string}
2707                  * Return the joined URL path.
2708                  */
2709                 path: function(prefix, parts) {
2710                         var url = [ prefix || '' ];
2711
2712                         for (var i = 0; i < parts.length; i++)
2713                                 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
2714                                         url.push('/', parts[i]);
2715
2716                         if (url.length === 1)
2717                                 url.push('/');
2718
2719                         return url.join('');
2720                 },
2721
2722                 /**
2723                  * Construct an URL  pathrelative to the script path of the server
2724                  * side LuCI application (usually `/cgi-bin/luci`).
2725                  *
2726                  * The resulting URL is guaranteed to only contain the characters
2727                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2728                  * as `/` for the path separator.
2729                  *
2730                  * @instance
2731                  * @memberof LuCI
2732                  *
2733                  * @param {string[]} [parts]
2734                  * An array of parts to join into an URL path. Parts may contain
2735                  * slashes and any of the other characters mentioned above.
2736                  *
2737                  * @return {string}
2738                  * Returns the resulting URL path.
2739                  */
2740                 url: function() {
2741                         return this.path(this.env.scriptname, arguments);
2742                 },
2743
2744                 /**
2745                  * Construct an URL path relative to the global static resource path
2746                  * of the LuCI ui (usually `/luci-static/resources`).
2747                  *
2748                  * The resulting URL is guaranteed to only contain the characters
2749                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2750                  * as `/` for the path separator.
2751                  *
2752                  * @instance
2753                  * @memberof LuCI
2754                  *
2755                  * @param {string[]} [parts]
2756                  * An array of parts to join into an URL path. Parts may contain
2757                  * slashes and any of the other characters mentioned above.
2758                  *
2759                  * @return {string}
2760                  * Returns the resulting URL path.
2761                  */
2762                 resource: function() {
2763                         return this.path(this.env.resource, arguments);
2764                 },
2765
2766                 /**
2767                  * Construct an URL path relative to the media resource path of the
2768                  * LuCI ui (usually `/luci-static/$theme_name`).
2769                  *
2770                  * The resulting URL is guaranteed to only contain the characters
2771                  * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2772                  * as `/` for the path separator.
2773                  *
2774                  * @instance
2775                  * @memberof LuCI
2776                  *
2777                  * @param {string[]} [parts]
2778                  * An array of parts to join into an URL path. Parts may contain
2779                  * slashes and any of the other characters mentioned above.
2780                  *
2781                  * @return {string}
2782                  * Returns the resulting URL path.
2783                  */
2784                 media: function() {
2785                         return this.path(this.env.media, arguments);
2786                 },
2787
2788                 /**
2789                  * Return the complete URL path to the current view.
2790                  *
2791                  * @instance
2792                  * @memberof LuCI
2793                  *
2794                  * @return {string}
2795                  * Returns the URL path to the current view.
2796                  */
2797                 location: function() {
2798                         return this.path(this.env.scriptname, this.env.requestpath);
2799                 },
2800
2801
2802                 /**
2803                  * Tests whether the passed argument is a JavaScript object.
2804                  * This function is meant to be an object counterpart to the
2805                  * standard `Array.isArray()` function.
2806                  *
2807                  * @instance
2808                  * @memberof LuCI
2809                  *
2810                  * @param {*} [val]
2811                  * The value to test
2812                  *
2813                  * @return {boolean}
2814                  * Returns `true` if the given value is of type object and
2815                  * not `null`, else returns `false`.
2816                  */
2817                 isObject: function(val) {
2818                         return (val != null && typeof(val) == 'object');
2819                 },
2820
2821                 /**
2822                  * Return an array of sorted object keys, optionally sorted by
2823                  * a different key or a different sorting mode.
2824                  *
2825                  * @instance
2826                  * @memberof LuCI
2827                  *
2828                  * @param {object} obj
2829                  * The object to extract the keys from. If the given value is
2830                  * not an object, the function will return an empty array.
2831                  *
2832                  * @param {string} [key]
2833                  * Specifies the key to order by. This is mainly useful for
2834                  * nested objects of objects or objects of arrays when sorting
2835                  * shall not be performed by the primary object keys but by
2836                  * some other key pointing to a value within the nested values.
2837                  *
2838                  * @param {string} [sortmode]
2839                  * May be either `addr` or `num` to override the natural
2840                  * lexicographic sorting with a sorting suitable for IP/MAC style
2841                  * addresses or numeric values respectively.
2842                  *
2843                  * @return {string[]}
2844                  * Returns an array containing the sorted keys of the given object.
2845                  */
2846                 sortedKeys: function(obj, key, sortmode) {
2847                         if (obj == null || typeof(obj) != 'object')
2848                                 return [];
2849
2850                         return Object.keys(obj).map(function(e) {
2851                                 var v = (key != null) ? obj[e][key] : e;
2852
2853                                 switch (sortmode) {
2854                                 case 'addr':
2855                                         v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
2856                                                 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
2857                                         break;
2858
2859                                 case 'num':
2860                                         v = (v != null) ? +v : null;
2861                                         break;
2862                                 }
2863
2864                                 return [ e, v ];
2865                         }).filter(function(e) {
2866                                 return (e[1] != null);
2867                         }).sort(function(a, b) {
2868                                 return (a[1] > b[1]);
2869                         }).map(function(e) {
2870                                 return e[0];
2871                         });
2872                 },
2873
2874                 /**
2875                  * Converts the given value to an array. If the given value is of
2876                  * type array, it is returned as-is, values of type object are
2877                  * returned as one-element array containing the object, empty
2878                  * strings and `null` values are returned as empty array, all other
2879                  * values are converted using `String()`, trimmed, split on white
2880                  * space and returned as array.
2881                  *
2882                  * @instance
2883                  * @memberof LuCI
2884                  *
2885                  * @param {*} val
2886                  * The value to convert into an array.
2887                  *
2888                  * @return {Array<*>}
2889                  * Returns the resulting array.
2890                  */
2891                 toArray: function(val) {
2892                         if (val == null)
2893                                 return [];
2894                         else if (Array.isArray(val))
2895                                 return val;
2896                         else if (typeof(val) == 'object')
2897                                 return [ val ];
2898
2899                         var s = String(val).trim();
2900
2901                         if (s == '')
2902                                 return [];
2903
2904                         return s.split(/\s+/);
2905                 },
2906
2907                 /**
2908                  * Returns a promise resolving with either the given value or or with
2909                  * the given default in case the input value is a rejecting promise.
2910                  *
2911                  * @instance
2912                  * @memberof LuCI
2913                  *
2914                  * @param {*} value
2915                  * The value to resolve the promise with.
2916                  *
2917                  * @param {*} defvalue
2918                  * The default value to resolve the promise with in case the given
2919                  * input value is a rejecting promise.
2920                  *
2921                  * @returns {Promise<*>}
2922                  * Returns a new promise resolving either to the given input value or
2923                  * to the given default value on error.
2924                  */
2925                 resolveDefault: function(value, defvalue) {
2926                         return Promise.resolve(value).catch(function() { return defvalue });
2927                 },
2928
2929                 /**
2930                  * The request callback function is invoked whenever an HTTP
2931                  * reply to a request made using the `L.get()`, `L.post()` or
2932                  * `L.poll()` function is timed out or received successfully.
2933                  *
2934                  * @instance
2935                  * @memberof LuCI
2936                  *
2937                  * @callback LuCI.requestCallbackFn
2938                  * @param {XMLHTTPRequest} xhr
2939                  * The XMLHTTPRequest instance used to make the request.
2940                  *
2941                  * @param {*} data
2942                  * The response JSON if the response could be parsed as such,
2943                  * else `null`.
2944                  *
2945                  * @param {number} duration
2946                  * The total duration of the request in milliseconds.
2947                  */
2948
2949                 /**
2950                  * Issues a GET request to the given url and invokes the specified
2951                  * callback function. The function is a wrapper around
2952                  * {@link LuCI.request#request Request.request()}.
2953                  *
2954                  * @deprecated
2955                  * @instance
2956                  * @memberof LuCI
2957                  *
2958                  * @param {string} url
2959                  * The URL to request.
2960                  *
2961                  * @param {Object<string, string>} [args]
2962                  * Additional query string arguments to append to the URL.
2963                  *
2964                  * @param {LuCI.requestCallbackFn} cb
2965                  * The callback function to invoke when the request finishes.
2966                  *
2967                  * @return {Promise<null>}
2968                  * Returns a promise resolving to `null` when concluded.
2969                  */
2970                 get: function(url, args, cb) {
2971                         return this.poll(null, url, args, cb, false);
2972                 },
2973
2974                 /**
2975                  * Issues a POST request to the given url and invokes the specified
2976                  * callback function. The function is a wrapper around
2977                  * {@link LuCI.request#request Request.request()}. The request is
2978                  * sent using `application/x-www-form-urlencoded` encoding and will
2979                  * contain a field `token` with the current value of `LuCI.env.token`
2980                  * by default.
2981                  *
2982                  * @deprecated
2983                  * @instance
2984                  * @memberof LuCI
2985                  *
2986                  * @param {string} url
2987                  * The URL to request.
2988                  *
2989                  * @param {Object<string, string>} [args]
2990                  * Additional post arguments to append to the request body.
2991                  *
2992                  * @param {LuCI.requestCallbackFn} cb
2993                  * The callback function to invoke when the request finishes.
2994                  *
2995                  * @return {Promise<null>}
2996                  * Returns a promise resolving to `null` when concluded.
2997                  */
2998                 post: function(url, args, cb) {
2999                         return this.poll(null, url, args, cb, true);
3000                 },
3001
3002                 /**
3003                  * Register a polling HTTP request that invokes the specified
3004                  * callback function. The function is a wrapper around
3005                  * {@link LuCI.request.poll#add Request.poll.add()}.
3006                  *
3007                  * @deprecated
3008                  * @instance
3009                  * @memberof LuCI
3010                  *
3011                  * @param {number} interval
3012                  * The poll interval to use. If set to a value less than or equal
3013                  * to `0`, it will default to the global poll interval configured
3014                  * in `LuCI.env.pollinterval`.
3015                  *
3016                  * @param {string} url
3017                  * The URL to request.
3018                  *
3019                  * @param {Object<string, string>} [args]
3020                  * Specifies additional arguments for the request. For GET requests,
3021                  * the arguments are appended to the URL as query string, for POST
3022                  * requests, they'll be added to the request body.
3023                  *
3024                  * @param {LuCI.requestCallbackFn} cb
3025                  * The callback function to invoke whenever a request finishes.
3026                  *
3027                  * @param {boolean} [post=false]
3028                  * When set to `false` or not specified, poll requests will be made
3029                  * using the GET method. When set to `true`, POST requests will be
3030                  * issued. In case of POST requests, the request body will contain
3031                  * an argument `token` with the current value of `LuCI.env.token` by
3032                  * default, regardless of the parameters specified with `args`.
3033                  *
3034                  * @return {function}
3035                  * Returns the internally created function that has been passed to
3036                  * {@link LuCI.request.poll#add Request.poll.add()}. This value can
3037                  * be passed to {@link LuCI.poll.remove Poll.remove()} to remove the
3038                  * polling request.
3039                  */
3040                 poll: function(interval, url, args, cb, post) {
3041                         if (interval !== null && interval <= 0)
3042                                 interval = this.env.pollinterval;
3043
3044                         var data = post ? { token: this.env.token } : null,
3045                             method = post ? 'POST' : 'GET';
3046
3047                         if (!/^(?:\/|\S+:\/\/)/.test(url))
3048                                 url = this.url(url);
3049
3050                         if (args != null)
3051                                 data = Object.assign(data || {}, args);
3052
3053                         if (interval !== null)
3054                                 return Request.poll.add(interval, url, { method: method, query: data }, cb);
3055                         else
3056                                 return Request.request(url, { method: method, query: data })
3057                                         .then(function(res) {
3058                                                 var json = null;
3059                                                 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
3060                                                         try { json = res.json() } catch(e) {}
3061                                                 cb(res.xhr, json, res.duration);
3062                                         });
3063                 },
3064
3065                 /**
3066                  * Deprecated wrapper around {@link LuCI.poll.remove Poll.remove()}.
3067                  *
3068                  * @deprecated
3069                  * @instance
3070                  * @memberof LuCI
3071                  *
3072                  * @param {function} entry
3073                  * The polling function to remove.
3074                  *
3075                  * @return {boolean}
3076                  * Returns `true` when the function has been removed or `false` if
3077                  * it could not be found.
3078                  */
3079                 stop: function(entry) { return Poll.remove(entry) },
3080
3081                 /**
3082                  * Deprecated wrapper around {@link LuCI.poll.stop Poll.stop()}.
3083                  *
3084                  * @deprecated
3085                  * @instance
3086                  * @memberof LuCI
3087                  *
3088                  * @return {boolean}
3089                  * Returns `true` when the polling loop has been stopped or `false`
3090                  * when it didn't run to begin with.
3091                  */
3092                 halt: function() { return Poll.stop() },
3093
3094                 /**
3095                  * Deprecated wrapper around {@link LuCI.poll.start Poll.start()}.
3096                  *
3097                  * @deprecated
3098                  * @instance
3099                  * @memberof LuCI
3100                  *
3101                  * @return {boolean}
3102                  * Returns `true` when the polling loop has been started or `false`
3103                  * when it was already running.
3104                  */
3105                 run: function() { return Poll.start() },
3106
3107                 /**
3108                  * Legacy `L.dom` class alias. New view code should use `'require dom';`
3109                  * to request the `LuCI.dom` class.
3110                  *
3111                  * @instance
3112                  * @memberof LuCI
3113                  * @deprecated
3114                  */
3115                 dom: DOM,
3116
3117                 /**
3118                  * Legacy `L.view` class alias. New view code should use `'require view';`
3119                  * to request the `LuCI.view` class.
3120                  *
3121                  * @instance
3122                  * @memberof LuCI
3123                  * @deprecated
3124                  */
3125                 view: View,
3126
3127                 /**
3128                  * Legacy `L.Poll` class alias. New view code should use `'require poll';`
3129                  * to request the `LuCI.poll` class.
3130                  *
3131                  * @instance
3132                  * @memberof LuCI
3133                  * @deprecated
3134                  */
3135                 Poll: Poll,
3136
3137                 /**
3138                  * Legacy `L.Request` class alias. New view code should use `'require request';`
3139                  * to request the `LuCI.request` class.
3140                  *
3141                  * @instance
3142                  * @memberof LuCI
3143                  * @deprecated
3144                  */
3145                 Request: Request,
3146
3147                 /**
3148                  * Legacy `L.Class` class alias. New view code should use `'require baseclass';`
3149                  * to request the `LuCI.baseclass` class.
3150                  *
3151                  * @instance
3152                  * @memberof LuCI
3153                  * @deprecated
3154                  */
3155                 Class: Class
3156         });
3157
3158         /**
3159          * @class xhr
3160          * @memberof LuCI
3161          * @deprecated
3162          * @classdesc
3163          *
3164          * The `LuCI.xhr` class is a legacy compatibility shim for the
3165          * functionality formerly provided by `xhr.js`. It is registered as global
3166          * `window.XHR` symbol for compatibility with legacy code.
3167          *
3168          * New code should use {@link LuCI.request} instead to implement HTTP
3169          * request handling.
3170          */
3171         var XHR = Class.extend(/** @lends LuCI.xhr.prototype */ {
3172                 __name__: 'LuCI.xhr',
3173                 __init__: function() {
3174                         if (window.console && console.debug)
3175                                 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
3176                 },
3177
3178                 _response: function(cb, res, json, duration) {
3179                         if (this.active)
3180                                 cb(res, json, duration);
3181                         delete this.active;
3182                 },
3183
3184                 /**
3185                  * This function is a legacy wrapper around
3186                  * {@link LuCI#get LuCI.get()}.
3187                  *
3188                  * @instance
3189                  * @deprecated
3190                  * @memberof LuCI.xhr
3191                  *
3192                  * @param {string} url
3193                  * The URL to request
3194                  *
3195                  * @param {Object} [data]
3196                  * Additional query string data
3197                  *
3198                  * @param {LuCI.requestCallbackFn} [callback]
3199                  * Callback function to invoke on completion
3200                  *
3201                  * @param {number} [timeout]
3202                  * Request timeout to use
3203                  *
3204                  * @return {Promise<null>}
3205                  */
3206                 get: function(url, data, callback, timeout) {
3207                         this.active = true;
3208                         L.get(url, data, this._response.bind(this, callback), timeout);
3209                 },
3210
3211                 /**
3212                  * This function is a legacy wrapper around
3213                  * {@link LuCI#post LuCI.post()}.
3214                  *
3215                  * @instance
3216                  * @deprecated
3217                  * @memberof LuCI.xhr
3218                  *
3219                  * @param {string} url
3220                  * The URL to request
3221                  *
3222                  * @param {Object} [data]
3223                  * Additional data to append to the request body.
3224                  *
3225                  * @param {LuCI.requestCallbackFn} [callback]
3226                  * Callback function to invoke on completion
3227                  *
3228                  * @param {number} [timeout]
3229                  * Request timeout to use
3230                  *
3231                  * @return {Promise<null>}
3232                  */
3233                 post: function(url, data, callback, timeout) {
3234                         this.active = true;
3235                         L.post(url, data, this._response.bind(this, callback), timeout);
3236                 },
3237
3238                 /**
3239                  * Cancels a running request.
3240                  *
3241                  * This function does not actually cancel the underlying
3242                  * `XMLHTTPRequest` request but it sets a flag which prevents the
3243                  * invocation of the callback function when the request eventually
3244                  * finishes or timed out.
3245                  *
3246                  * @instance
3247                  * @deprecated
3248                  * @memberof LuCI.xhr
3249                  */
3250                 cancel: function() { delete this.active },
3251
3252                 /**
3253                  * Checks the running state of the request.
3254                  *
3255                  * @instance
3256                  * @deprecated
3257                  * @memberof LuCI.xhr
3258                  *
3259                  * @returns {boolean}
3260                  * Returns `true` if the request is still running or `false` if it
3261                  * already completed.
3262                  */
3263                 busy: function() { return (this.active === true) },
3264
3265                 /**
3266                  * Ignored for backwards compatibility.
3267                  *
3268                  * This function does nothing.
3269                  *
3270                  * @instance
3271                  * @deprecated
3272                  * @memberof LuCI.xhr
3273                  */
3274                 abort: function() {},
3275
3276                 /**
3277                  * Existing for backwards compatibility.
3278                  *
3279                  * This function simply throws an `InternalError` when invoked.
3280                  *
3281                  * @instance
3282                  * @deprecated
3283                  * @memberof LuCI.xhr
3284                  *
3285                  * @throws {InternalError}
3286                  * Throws an `InternalError` with the message `Not implemented`
3287                  * when invoked.
3288                  */
3289                 send_form: function() { L.error('InternalError', 'Not implemented') },
3290         });
3291
3292         XHR.get = function() { return window.L.get.apply(window.L, arguments) };
3293         XHR.post = function() { return window.L.post.apply(window.L, arguments) };
3294         XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
3295         XHR.stop = Request.poll.remove.bind(Request.poll);
3296         XHR.halt = Request.poll.stop.bind(Request.poll);
3297         XHR.run = Request.poll.start.bind(Request.poll);
3298         XHR.running = Request.poll.active.bind(Request.poll);
3299
3300         window.XHR = XHR;
3301         window.LuCI = LuCI;
3302 })(window, document);