f381e0b649291191c26ec59379a6989f5efbf9cf
[oweals/luci.git] / modules / luci-base / htdocs / luci-static / resources / uci.js
1 'use strict';
2 'require rpc';
3 'require baseclass';
4
5 /**
6  * @class uci
7  * @memberof LuCI
8  * @hideconstructor
9  * @classdesc
10  *
11  * The `LuCI.uci` class utilizes {@link LuCI.rpc} to declare low level
12  * remote UCI `ubus` procedures and implements a local caching and data
13  * manipulation layer on top to allow for synchroneous operations on
14  * UCI configuration data.
15  */
16 return baseclass.extend(/** @lends LuCI.uci.prototype */ {
17         __init__: function() {
18                 this.state = {
19                         newidx:  0,
20                         values:  { },
21                         creates: { },
22                         changes: { },
23                         deletes: { },
24                         reorder: { }
25                 };
26
27                 this.loaded = {};
28         },
29
30         callLoad: rpc.declare({
31                 object: 'uci',
32                 method: 'get',
33                 params: [ 'config' ],
34                 expect: { values: { } }
35         }),
36
37
38         callOrder: rpc.declare({
39                 object: 'uci',
40                 method: 'order',
41                 params: [ 'config', 'sections' ]
42         }),
43
44         callAdd: rpc.declare({
45                 object: 'uci',
46                 method: 'add',
47                 params: [ 'config', 'type', 'name', 'values' ],
48                 expect: { section: '' }
49         }),
50
51         callSet: rpc.declare({
52                 object: 'uci',
53                 method: 'set',
54                 params: [ 'config', 'section', 'values' ]
55         }),
56
57         callDelete: rpc.declare({
58                 object: 'uci',
59                 method: 'delete',
60                 params: [ 'config', 'section', 'options' ]
61         }),
62
63         callApply: rpc.declare({
64                 object: 'uci',
65                 method: 'apply',
66                 params: [ 'timeout', 'rollback' ]
67         }),
68
69         callConfirm: rpc.declare({
70                 object: 'uci',
71                 method: 'confirm'
72         }),
73
74
75         /**
76          * Generates a new, unique section ID for the given configuration.
77          *
78          * Note that the generated ID is temporary, it will get replaced by an
79          * identifier in the form `cfgXXXXXX` once the configuration is saved
80          * by the remote `ubus` UCI api.
81          *
82          * @param {string} config
83          * The configuration to generate the new section ID for.
84          *
85          * @returns {string}
86          * A newly generated, unique section ID in the form `newXXXXXX`
87          * where `X` denotes a hexadecimal digit.
88          */
89         createSID: function(conf) {
90                 var v = this.state.values,
91                     n = this.state.creates,
92                     sid;
93
94                 do {
95                         sid = "new%06x".format(Math.random() * 0xFFFFFF);
96                 } while ((n[conf] && n[conf][sid]) || (v[conf] && v[conf][sid]));
97
98                 return sid;
99         },
100
101         /**
102          * Resolves a given section ID in extended notation to the internal
103          * section ID value.
104          *
105          * @param {string} config
106          * The configuration to resolve the section ID for.
107          *
108          * @param {string} sid
109          * The section ID to resolve. If the ID is in the form `@typename[#]`,
110          * it will get resolved to an internal anonymous ID in the forms
111          * `cfgXXXXXX`/`newXXXXXX` or to the name of a section in case it points
112          * to a named section. When the given ID is not in extended notation,
113          * it will be returned as-is.
114          *
115          * @returns {string|null}
116          * Returns the resolved section ID or the original given ID if it was
117          * not in extended notation. Returns `null` when an extended ID could
118          * not be resolved to existing section ID.
119          */
120         resolveSID: function(conf, sid) {
121                 if (typeof(sid) != 'string')
122                         return sid;
123
124                 var m = /^@([a-zA-Z0-9_-]+)\[(-?[0-9]+)\]$/.exec(sid);
125
126                 if (m) {
127                         var type = m[1],
128                             pos = +m[2],
129                             sections = this.sections(conf, type),
130                             section = sections[pos >= 0 ? pos : sections.length + pos];
131
132                         return section ? section['.name'] : null;
133                 }
134
135                 return sid;
136         },
137
138         /* private */
139         reorderSections: function() {
140                 var v = this.state.values,
141                     n = this.state.creates,
142                     r = this.state.reorder,
143                     tasks = [];
144
145                 if (Object.keys(r).length === 0)
146                         return Promise.resolve();
147
148                 /*
149                  gather all created and existing sections, sort them according
150                  to their index value and issue an uci order call
151                 */
152                 for (var c in r) {
153                         var o = [ ];
154
155                         if (n[c])
156                                 for (var s in n[c])
157                                         o.push(n[c][s]);
158
159                         for (var s in v[c])
160                                 o.push(v[c][s]);
161
162                         if (o.length > 0) {
163                                 o.sort(function(a, b) {
164                                         return (a['.index'] - b['.index']);
165                                 });
166
167                                 var sids = [ ];
168
169                                 for (var i = 0; i < o.length; i++)
170                                         sids.push(o[i]['.name']);
171
172                                 tasks.push(this.callOrder(c, sids));
173                         }
174                 }
175
176                 this.state.reorder = { };
177                 return Promise.all(tasks);
178         },
179
180         /* private */
181         loadPackage: function(packageName) {
182                 if (this.loaded[packageName] == null)
183                         return (this.loaded[packageName] = this.callLoad(packageName));
184
185                 return Promise.resolve(this.loaded[packageName]);
186         },
187
188         /**
189          * Loads the given UCI configurations from the remote `ubus` api.
190          *
191          * Loaded configurations are cached and only loaded once. Subsequent
192          * load operations of the same configurations will return the cached
193          * data.
194          *
195          * To force reloading a configuration, it has to be unloaded with
196          * {@link LuCI.uci#unload uci.unload()} first.
197          *
198          * @param {string|string[]} config
199          * The name of the configuration or an array of configuration
200          * names to load.
201          *
202          * @returns {Promise<string[]>}
203          * Returns a promise resolving to the names of the configurations
204          * that have been successfully loaded.
205          */
206         load: function(packages) {
207                 var self = this,
208                     pkgs = [ ],
209                     tasks = [];
210
211                 if (!Array.isArray(packages))
212                         packages = [ packages ];
213
214                 for (var i = 0; i < packages.length; i++)
215                         if (!self.state.values[packages[i]]) {
216                                 pkgs.push(packages[i]);
217                                 tasks.push(self.loadPackage(packages[i]));
218                         }
219
220                 return Promise.all(tasks).then(function(responses) {
221                         for (var i = 0; i < responses.length; i++)
222                                 self.state.values[pkgs[i]] = responses[i];
223
224                         if (responses.length)
225                                 document.dispatchEvent(new CustomEvent('uci-loaded'));
226
227                         return pkgs;
228                 });
229         },
230
231         /**
232          * Unloads the given UCI configurations from the local cache.
233          *
234          * @param {string|string[]} config
235          * The name of the configuration or an array of configuration
236          * names to unload.
237          */
238         unload: function(packages) {
239                 if (!Array.isArray(packages))
240                         packages = [ packages ];
241
242                 for (var i = 0; i < packages.length; i++) {
243                         delete this.state.values[packages[i]];
244                         delete this.state.creates[packages[i]];
245                         delete this.state.changes[packages[i]];
246                         delete this.state.deletes[packages[i]];
247
248                         delete this.loaded[packages[i]];
249                 }
250         },
251
252         /**
253          * Adds a new section of the given type to the given configuration,
254          * optionally named according to the given name.
255          *
256          * @param {string} config
257          * The name of the configuration to add the section to.
258          *
259          * @param {string} type
260          * The type of the section to add.
261          *
262          * @param {string} [name]
263          * The name of the section to add. If the name is omitted, an anonymous
264          * section will be added instead.
265          *
266          * @returns {string}
267          * Returns the section ID of the newly added section which is equivalent
268          * to the given name for non-anonymous sections.
269          */
270         add: function(conf, type, name) {
271                 var n = this.state.creates,
272                     sid = name || this.createSID(conf);
273
274                 if (!n[conf])
275                         n[conf] = { };
276
277                 n[conf][sid] = {
278                         '.type':      type,
279                         '.name':      sid,
280                         '.create':    name,
281                         '.anonymous': !name,
282                         '.index':     1000 + this.state.newidx++
283                 };
284
285                 return sid;
286         },
287
288         /**
289          * Removes the section with the given ID from the given configuration.
290          *
291          * @param {string} config
292          * The name of the configuration to remove the section from.
293          *
294          * @param {string} sid
295          * The ID of the section to remove.
296          */
297         remove: function(conf, sid) {
298                 var n = this.state.creates,
299                     c = this.state.changes,
300                     d = this.state.deletes;
301
302                 /* requested deletion of a just created section */
303                 if (n[conf] && n[conf][sid]) {
304                         delete n[conf][sid];
305                 }
306                 else {
307                         if (c[conf])
308                                 delete c[conf][sid];
309
310                         if (!d[conf])
311                                 d[conf] = { };
312
313                         d[conf][sid] = true;
314                 }
315         },
316
317         /**
318          * A section object represents the options and their corresponding values
319          * enclosed within a configuration section, as well as some additional
320          * meta data such as sort indexes and internal ID.
321          *
322          * Any internal metadata fields are prefixed with a dot which is isn't
323          * an allowed character for normal option names.
324          *
325          * @typedef {Object<string, boolean|number|string|string[]>} SectionObject
326          * @memberof LuCI.uci
327          *
328          * @property {boolean} .anonymous
329          * The `.anonymous` property specifies whether the configuration is
330          * anonymous (`true`) or named (`false`).
331          *
332          * @property {number} .index
333          * The `.index` property specifes the sort order of the section.
334          *
335          * @property {string} .name
336          * The `.name` property holds the name of the section object. It may be
337          * either an anonymous ID in the form `cfgXXXXXX` or `newXXXXXX` with `X`
338          * being a hexadecimal digit or a string holding the name of the section.
339          *
340          * @property {string} .type
341          * The `.type` property contains the type of the corresponding uci
342          * section.
343          *
344          * @property {string|string[]} *
345          * A section object may contain an arbitrary number of further properties
346          * representing the uci option enclosed in the section.
347          *
348          * All option property names will be in the form `[A-Za-z0-9_]+` and
349          * either contain a string value or an array of strings, in case the
350          * underlying option is an UCI list.
351          */
352
353         /**
354          * The sections callback is invoked for each section found within
355          * the given configuration and receives the section object and its
356          * associated name as arguments.
357          *
358          * @callback LuCI.uci~sectionsFn
359          *
360          * @param {LuCI.uci.SectionObject} section
361          * The section object.
362          *
363          * @param {string} sid
364          * The name or ID of the section.
365          */
366
367         /**
368          * Enumerates the sections of the given configuration, optionally
369          * filtered by type.
370          *
371          * @param {string} config
372          * The name of the configuration to enumerate the sections for.
373          *
374          * @param {string} [type]
375          * Enumerate only sections of the given type. If omitted, enumerate
376          * all sections.
377          *
378          * @param {LuCI.uci~sectionsFn} [cb]
379          * An optional callback to invoke for each enumerated section.
380          *
381          * @returns {Array<LuCI.uci.SectionObject>}
382          * Returns a sorted array of the section objects within the given
383          * configuration, filtered by type of a type has been specified.
384          */
385         sections: function(conf, type, cb) {
386                 var sa = [ ],
387                     v = this.state.values[conf],
388                     n = this.state.creates[conf],
389                     c = this.state.changes[conf],
390                     d = this.state.deletes[conf];
391
392                 if (!v)
393                         return sa;
394
395                 for (var s in v)
396                         if (!d || d[s] !== true)
397                                 if (!type || v[s]['.type'] == type)
398                                         sa.push(Object.assign({ }, v[s], c ? c[s] : undefined));
399
400                 if (n)
401                         for (var s in n)
402                                 if (!type || n[s]['.type'] == type)
403                                         sa.push(Object.assign({ }, n[s]));
404
405                 sa.sort(function(a, b) {
406                         return a['.index'] - b['.index'];
407                 });
408
409                 for (var i = 0; i < sa.length; i++)
410                         sa[i]['.index'] = i;
411
412                 if (typeof(cb) == 'function')
413                         for (var i = 0; i < sa.length; i++)
414                                 cb.call(this, sa[i], sa[i]['.name']);
415
416                 return sa;
417         },
418
419         /**
420          * Gets the value of the given option within the specified section
421          * of the given configuration or the entire section object if the
422          * option name is omitted.
423          *
424          * @param {string} config
425          * The name of the configuration to read the value from.
426          *
427          * @param {string} sid
428          * The name or ID of the section to read.
429          *
430          * @param {string} [option]
431          * The option name to read the value from. If the option name is
432          * omitted or `null`, the entire section is returned instead.
433          *
434          * @returns {null|string|string[]|LuCI.uci.SectionObject}
435          * - Returns a string containing the option value in case of a
436          *   plain UCI option.
437          * - Returns an array of strings containing the option values in
438          *   case of `option` pointing to an UCI list.
439          * - Returns a {@link LuCI.uci.SectionObject section object} if
440          *   the `option` argument has been omitted or is `null`.
441          * - Returns `null` if the config, section or option has not been
442          *   found or if the corresponding configuration is not loaded.
443          */
444         get: function(conf, sid, opt) {
445                 var v = this.state.values,
446                     n = this.state.creates,
447                     c = this.state.changes,
448                     d = this.state.deletes;
449
450                 sid = this.resolveSID(conf, sid);
451
452                 if (sid == null)
453                         return null;
454
455                 /* requested option in a just created section */
456                 if (n[conf] && n[conf][sid]) {
457                         if (!n[conf])
458                                 return undefined;
459
460                         if (opt == null)
461                                 return n[conf][sid];
462
463                         return n[conf][sid][opt];
464                 }
465
466                 /* requested an option value */
467                 if (opt != null) {
468                         /* check whether option was deleted */
469                         if (d[conf] && d[conf][sid]) {
470                                 if (d[conf][sid] === true)
471                                         return undefined;
472
473                                 for (var i = 0; i < d[conf][sid].length; i++)
474                                         if (d[conf][sid][i] == opt)
475                                                 return undefined;
476                         }
477
478                         /* check whether option was changed */
479                         if (c[conf] && c[conf][sid] && c[conf][sid][opt] != null)
480                                 return c[conf][sid][opt];
481
482                         /* return base value */
483                         if (v[conf] && v[conf][sid])
484                                 return v[conf][sid][opt];
485
486                         return undefined;
487                 }
488
489                 /* requested an entire section */
490                 if (v[conf])
491                         return v[conf][sid];
492
493                 return undefined;
494         },
495
496         /**
497          * Sets the value of the given option within the specified section
498          * of the given configuration.
499          *
500          * If either config, section or option is null, or if `option` begins
501          * with a dot, the function will do nothing.
502          *
503          * @param {string} config
504          * The name of the configuration to set the option value in.
505          *
506          * @param {string} sid
507          * The name or ID of the section to set the option value in.
508          *
509          * @param {string} option
510          * The option name to set the value for.
511          *
512          * @param {null|string|string[]} value
513          * The option value to set. If the value is `null` or an empty string,
514          * the option will be removed, otherwise it will be set or overwritten
515          * with the given value.
516          */
517         set: function(conf, sid, opt, val) {
518                 var v = this.state.values,
519                     n = this.state.creates,
520                     c = this.state.changes,
521                     d = this.state.deletes;
522
523                 sid = this.resolveSID(conf, sid);
524
525                 if (sid == null || opt == null || opt.charAt(0) == '.')
526                         return;
527
528                 if (n[conf] && n[conf][sid]) {
529                         if (val != null)
530                                 n[conf][sid][opt] = val;
531                         else
532                                 delete n[conf][sid][opt];
533                 }
534                 else if (val != null && val !== '') {
535                         /* do not set within deleted section */
536                         if (d[conf] && d[conf][sid] === true)
537                                 return;
538
539                         /* only set in existing sections */
540                         if (!v[conf] || !v[conf][sid])
541                                 return;
542
543                         if (!c[conf])
544                                 c[conf] = {};
545
546                         if (!c[conf][sid])
547                                 c[conf][sid] = {};
548
549                         /* undelete option */
550                         if (d[conf] && d[conf][sid])
551                                 d[conf][sid] = d[conf][sid].filter(function(o) { return o !== opt });
552
553                         c[conf][sid][opt] = val;
554                 }
555                 else {
556                         /* only delete in existing sections */
557                         if (!(v[conf] && v[conf][sid] && v[conf][sid].hasOwnProperty(opt)) &&
558                             !(c[conf] && c[conf][sid] && c[conf][sid].hasOwnProperty(opt)))
559                             return;
560
561                         if (!d[conf])
562                                 d[conf] = { };
563
564                         if (!d[conf][sid])
565                                 d[conf][sid] = [ ];
566
567                         if (d[conf][sid] !== true)
568                                 d[conf][sid].push(opt);
569                 }
570         },
571
572         /**
573          * Remove the given option within the specified section of the given
574          * configuration.
575          *
576          * This function is a convenience wrapper around
577          * `uci.set(config, section, option, null)`.
578          *
579          * @param {string} config
580          * The name of the configuration to remove the option from.
581          *
582          * @param {string} sid
583          * The name or ID of the section to remove the option from.
584          *
585          * @param {string} option
586          * The name of the option to remove.
587          */
588         unset: function(conf, sid, opt) {
589                 return this.set(conf, sid, opt, null);
590         },
591
592         /**
593          * Gets the value of the given option or the entire section object of
594          * the first found section of the specified type or the first found
595          * section of the entire configuration if no type is specfied.
596          *
597          * @param {string} config
598          * The name of the configuration to read the value from.
599          *
600          * @param {string} [type]
601          * The type of the first section to find. If it is `null`, the first
602          * section of the entire config is read, otherwise the first section
603          * matching the given type.
604          *
605          * @param {string} [option]
606          * The option name to read the value from. If the option name is
607          * omitted or `null`, the entire section is returned instead.
608          *
609          * @returns {null|string|string[]|LuCI.uci.SectionObject}
610          * - Returns a string containing the option value in case of a
611          *   plain UCI option.
612          * - Returns an array of strings containing the option values in
613          *   case of `option` pointing to an UCI list.
614          * - Returns a {@link LuCI.uci.SectionObject section object} if
615          *   the `option` argument has been omitted or is `null`.
616          * - Returns `null` if the config, section or option has not been
617          *   found or if the corresponding configuration is not loaded.
618          */
619         get_first: function(conf, type, opt) {
620                 var sid = null;
621
622                 this.sections(conf, type, function(s) {
623                         if (sid == null)
624                                 sid = s['.name'];
625                 });
626
627                 return this.get(conf, sid, opt);
628         },
629
630         /**
631          * Sets the value of the given option within the first found section
632          * of the given configuration matching the specified type or within
633          * the first section of the entire config when no type has is specified.
634          *
635          * If either config, type or option is null, or if `option` begins
636          * with a dot, the function will do nothing.
637          *
638          * @param {string} config
639          * The name of the configuration to set the option value in.
640          *
641          * @param {string} [type]
642          * The type of the first section to find. If it is `null`, the first
643          * section of the entire config is written to, otherwise the first
644          * section matching the given type is used.
645          *
646          * @param {string} option
647          * The option name to set the value for.
648          *
649          * @param {null|string|string[]} value
650          * The option value to set. If the value is `null` or an empty string,
651          * the option will be removed, otherwise it will be set or overwritten
652          * with the given value.
653          */
654         set_first: function(conf, type, opt, val) {
655                 var sid = null;
656
657                 this.sections(conf, type, function(s) {
658                         if (sid == null)
659                                 sid = s['.name'];
660                 });
661
662                 return this.set(conf, sid, opt, val);
663         },
664
665         /**
666          * Removes the given option within the first found section of the given
667          * configuration matching the specified type or within the first section
668          * of the entire config when no type has is specified.
669          *
670          * This function is a convenience wrapper around
671          * `uci.set_first(config, type, option, null)`.
672          *
673          * @param {string} config
674          * The name of the configuration to set the option value in.
675          *
676          * @param {string} [type]
677          * The type of the first section to find. If it is `null`, the first
678          * section of the entire config is written to, otherwise the first
679          * section matching the given type is used.
680          *
681          * @param {string} option
682          * The option name to set the value for.
683          */
684         unset_first: function(conf, type, opt) {
685                 return this.set_first(conf, type, opt, null);
686         },
687
688         /**
689          * Move the first specified section within the given configuration
690          * before or after the second specified section.
691          *
692          * @param {string} config
693          * The configuration to move the section within.
694          *
695          * @param {string} sid1
696          * The ID of the section to move within the configuration.
697          *
698          * @param {string} [sid2]
699          * The ID of the target section for the move operation. If the
700          * `after` argument is `false` or not specified, the section named by
701          * `sid1` will be moved before this target section, if the `after`
702          * argument is `true`, the `sid1` section will be moved after this
703          * section.
704          *
705          * When the `sid2` argument is `null`, the section specified by `sid1`
706          * is moved to the end of the configuration.
707          *
708          * @param {boolean} [after=false]
709          * When `true`, the section `sid1` is moved after the section `sid2`,
710          * when `false`, the section `sid1` is moved before `sid2`.
711          *
712          * If `sid2` is null, then this parameter has no effect and the section
713          * `sid1` is moved to the end of the configuration instead.
714          *
715          * @returns {boolean}
716          * Returns `true` when the section was successfully moved, or `false`
717          * when either the section specified by `sid1` or by `sid2` is not found.
718          */
719         move: function(conf, sid1, sid2, after) {
720                 var sa = this.sections(conf),
721                     s1 = null, s2 = null;
722
723                 sid1 = this.resolveSID(conf, sid1);
724                 sid2 = this.resolveSID(conf, sid2);
725
726                 for (var i = 0; i < sa.length; i++) {
727                         if (sa[i]['.name'] != sid1)
728                                 continue;
729
730                         s1 = sa[i];
731                         sa.splice(i, 1);
732                         break;
733                 }
734
735                 if (s1 == null)
736                         return false;
737
738                 if (sid2 == null) {
739                         sa.push(s1);
740                 }
741                 else {
742                         for (var i = 0; i < sa.length; i++) {
743                                 if (sa[i]['.name'] != sid2)
744                                         continue;
745
746                                 s2 = sa[i];
747                                 sa.splice(i + !!after, 0, s1);
748                                 break;
749                         }
750
751                         if (s2 == null)
752                                 return false;
753                 }
754
755                 for (var i = 0; i < sa.length; i++)
756                         this.get(conf, sa[i]['.name'])['.index'] = i;
757
758                 this.state.reorder[conf] = true;
759
760                 return true;
761         },
762
763         /**
764          * Submits all local configuration changes to the remove `ubus` api,
765          * adds, removes and reorders remote sections as needed and reloads
766          * all loaded configurations to resynchronize the local state with
767          * the remote configuration values.
768          *
769          * @returns {string[]}
770          * Returns a promise resolving to an array of configuration names which
771          * have been reloaded by the save operation.
772          */
773         save: function() {
774                 var v = this.state.values,
775                     n = this.state.creates,
776                     c = this.state.changes,
777                     d = this.state.deletes,
778                     r = this.state.reorder,
779                     self = this,
780                     snew = [ ],
781                     pkgs = { },
782                     tasks = [];
783
784                 if (n)
785                         for (var conf in n) {
786                                 for (var sid in n[conf]) {
787                                         var r = {
788                                                 config: conf,
789                                                 values: { }
790                                         };
791
792                                         for (var k in n[conf][sid]) {
793                                                 if (k == '.type')
794                                                         r.type = n[conf][sid][k];
795                                                 else if (k == '.create')
796                                                         r.name = n[conf][sid][k];
797                                                 else if (k.charAt(0) != '.')
798                                                         r.values[k] = n[conf][sid][k];
799                                         }
800
801                                         snew.push(n[conf][sid]);
802                                         tasks.push(self.callAdd(r.config, r.type, r.name, r.values));
803                                 }
804
805                                 pkgs[conf] = true;
806                         }
807
808                 if (c)
809                         for (var conf in c) {
810                                 for (var sid in c[conf])
811                                         tasks.push(self.callSet(conf, sid, c[conf][sid]));
812
813                                 pkgs[conf] = true;
814                         }
815
816                 if (d)
817                         for (var conf in d) {
818                                 for (var sid in d[conf]) {
819                                         var o = d[conf][sid];
820                                         tasks.push(self.callDelete(conf, sid, (o === true) ? null : o));
821                                 }
822
823                                 pkgs[conf] = true;
824                         }
825
826                 if (r)
827                         for (var conf in r)
828                                 pkgs[conf] = true;
829
830                 return Promise.all(tasks).then(function(responses) {
831                         /*
832                          array "snew" holds references to the created uci sections,
833                          use it to assign the returned names of the new sections
834                         */
835                         for (var i = 0; i < snew.length; i++)
836                                 snew[i]['.name'] = responses[i];
837
838                         return self.reorderSections();
839                 }).then(function() {
840                         pkgs = Object.keys(pkgs);
841
842                         self.unload(pkgs);
843
844                         return self.load(pkgs);
845                 });
846         },
847
848         /**
849          * Instructs the remote `ubus` UCI api to commit all saved changes with
850          * rollback protection and attempts to confirm the pending commit
851          * operation to cancel the rollback timer.
852          *
853          * @param {number} [timeout=10]
854          * Override the confirmation timeout after which a rollback is triggered.
855          *
856          * @returns {Promise<number>}
857          * Returns a promise resolving/rejecting with the `ubus` RPC status code.
858          */
859         apply: function(timeout) {
860                 var self = this,
861                     date = new Date();
862
863                 if (typeof(timeout) != 'number' || timeout < 1)
864                         timeout = 10;
865
866                 return self.callApply(timeout, true).then(function(rv) {
867                         if (rv != 0)
868                                 return Promise.reject(rv);
869
870                         var try_deadline = date.getTime() + 1000 * timeout;
871                         var try_confirm = function() {
872                                 return self.callConfirm().then(function(rv) {
873                                         if (rv != 0) {
874                                                 if (date.getTime() < try_deadline)
875                                                         window.setTimeout(try_confirm, 250);
876                                                 else
877                                                         return Promise.reject(rv);
878                                         }
879
880                                         return rv;
881                                 });
882                         };
883
884                         window.setTimeout(try_confirm, 1000);
885                 });
886         },
887
888         /**
889          * An UCI change record is a plain array containing the change operation
890          * name as first element, the affected section ID as second argument
891          * and an optional third and fourth argument whose meanings depend on
892          * the operation.
893          *
894          * @typedef {string[]} ChangeRecord
895          * @memberof LuCI.uci
896          *
897          * @property {string} 0
898          * The operation name - may be one of `add`, `set`, `remove`, `order`,
899          * `list-add`, `list-del` or `rename`.
900          *
901          * @property {string} 1
902          * The section ID targeted by the operation.
903          *
904          * @property {string} 2
905          * The meaning of the third element depends on the operation.
906          * - For `add` it is type of the section that has been added
907          * - For `set` it either is the option name if a fourth element exists,
908          *   or the type of a named section which has been added when the change
909          *   entry only contains three elements.
910          * - For `remove` it contains the name of the option that has been
911          *   removed.
912          * - For `order` it specifies the new sort index of the section.
913          * - For `list-add` it contains the name of the list option a new value
914          *   has been added to.
915          * - For `list-del` it contains the name of the list option a value has
916          *   been removed from.
917          * - For `rename` it contains the name of the option that has been
918          *   renamed if a fourth element exists, else it contains the new name
919          *   a section has been renamed to if the change entry only contains
920          *   three elements.
921          *
922          * @property {string} 4
923          * The meaning of the fourth element depends on the operation.
924          * - For `set` it is the value an option has been set to.
925          * - For `list-add` it is the new value that has been added to a
926          *   list option.
927          * - For `rename` it is the new name of an option that has been
928          *   renamed.
929          */
930
931         /**
932          * Fetches uncommitted UCI changes from the remote `ubus` RPC api.
933          *
934          * @method
935          * @returns {Promise<Object<string, Array<LuCI.uci.ChangeRecord>>>}
936          * Returns a promise resolving to an object containing the configuration
937          * names as keys and arrays of related change records as values.
938          */
939         changes: rpc.declare({
940                 object: 'uci',
941                 method: 'changes',
942                 expect: { changes: { } }
943         })
944 });