Blame view

bower_components/l20n/dist/compat/tooling/l20n.js 93.8 KB
0e9aeacd   root   localization l20n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  'use strict';
  
  function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
  
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  
  (function () {
    'use strict';
  
    function L10nError(message, id, lang) {
      this.name = 'L10nError';
      this.message = message;
      this.id = id;
      this.lang = lang;
    }
    L10nError.prototype = Object.create(Error.prototype);
    L10nError.prototype.constructor = L10nError;
  
    function load(type, url) {
      return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
  
        if (xhr.overrideMimeType) {
          xhr.overrideMimeType(type);
        }
  
        xhr.open('GET', url, true);
  
        if (type === 'application/json') {
          xhr.responseType = 'json';
        }
  
        xhr.addEventListener('load', function io_onload(e) {
          if (e.target.status === 200 || e.target.status === 0) {
            resolve(e.target.response || e.target.responseText);
          } else {
            reject(new L10nError('Not found: ' + url));
          }
        });
        xhr.addEventListener('error', reject);
        xhr.addEventListener('timeout', reject);
  
        try {
          xhr.send(null);
        } catch (e) {
          if (e.name === 'NS_ERROR_FILE_NOT_FOUND') {
            reject(new L10nError('Not found: ' + url));
          } else {
            throw e;
          }
        }
      });
    }
  
    var io = {
      extra: function (code, ver, path, type) {
        return navigator.mozApps.getLocalizationResource(code, ver, path, type);
      },
      app: function (code, ver, path, type) {
        switch (type) {
          case 'text':
            return load('text/plain', path);
          case 'json':
            return load('application/json', path);
          default:
            throw new L10nError('Unknown file type: ' + type);
        }
      }
    };
  
a1a3bc73   Luigi Serra   graphs updates
71
72
73
74
75
76
    function fetchResource(res, _ref4) {
      var code = _ref4.code;
      var src = _ref4.src;
      var ver = _ref4.ver;
  
      var url = res.replace('{locale}', code);
0e9aeacd   root   localization l20n
77
      var type = res.endsWith('.json') ? 'json' : 'text';
a1a3bc73   Luigi Serra   graphs updates
78
      return io[src](code, ver, url, type);
0e9aeacd   root   localization l20n
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
    }
  
    function emit(listeners) {
      var _this = this;
  
      for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }
  
      var type = args.shift();
  
      if (listeners['*']) {
        listeners['*'].slice().forEach(function (listener) {
          return listener.apply(_this, args);
        });
      }
  
      if (listeners[type]) {
        listeners[type].slice().forEach(function (listener) {
          return listener.apply(_this, args);
        });
      }
    }
  
    function addEventListener(listeners, type, listener) {
      if (!(type in listeners)) {
        listeners[type] = [];
      }
      listeners[type].push(listener);
    }
  
    function removeEventListener(listeners, type, listener) {
      var typeListeners = listeners[type];
      var pos = typeListeners.indexOf(listener);
      if (pos === -1) {
        return;
      }
  
      typeListeners.splice(pos, 1);
    }
  
    var Client = (function () {
      function Client(remote) {
        _classCallCheck(this, Client);
  
        this.id = this;
        this.remote = remote;
  
        var listeners = {};
        this.on = function () {
          for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
  
          return addEventListener.apply(undefined, [listeners].concat(args));
        };
        this.emit = function () {
          for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
            args[_key3] = arguments[_key3];
          }
  
          return emit.apply(undefined, [listeners].concat(args));
        };
      }
  
      Client.prototype.method = function method(name) {
        var _remote;
  
        for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
          args[_key4 - 1] = arguments[_key4];
        }
  
        return (_remote = this.remote)[name].apply(_remote, args);
      };
  
      return Client;
    })();
  
    function broadcast(type, data) {
      Array.from(this.ctxs.keys()).forEach(function (client) {
        return client.emit(type, data);
      });
    }
  
a1a3bc73   Luigi Serra   graphs updates
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    var observerConfig = {
      attributes: true,
      characterData: false,
      childList: true,
      subtree: true,
      attributeFilter: ['data-l10n-id', 'data-l10n-args']
    };
  
    var observers = new WeakMap();
  
    function initMutationObserver(view) {
      observers.set(view, {
        roots: new Set(),
        observer: new MutationObserver(function (mutations) {
          return translateMutations(view, mutations);
        })
      });
    }
  
    function translateRoots(view) {
      return Promise.all([].concat(observers.get(view).roots).map(function (root) {
        return _translateFragment(view, root);
      }));
    }
  
    function observe(view, root) {
      var obs = observers.get(view);
      if (obs) {
        obs.roots.add(root);
        obs.observer.observe(root, observerConfig);
      }
    }
  
    function disconnect(view, root, allRoots) {
      var obs = observers.get(view);
      if (obs) {
        obs.observer.disconnect();
        if (allRoots) {
          return;
        }
        obs.roots.delete(root);
        obs.roots.forEach(function (other) {
          return obs.observer.observe(other, observerConfig);
        });
      }
    }
  
    function reconnect(view) {
      var obs = observers.get(view);
      if (obs) {
        obs.roots.forEach(function (root) {
          return obs.observer.observe(root, observerConfig);
        });
      }
    }
  
0e9aeacd   root   localization l20n
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    var reOverlay = /<|&#?\w+;/;
  
    var allowed = {
      elements: ['a', 'em', 'strong', 'small', 's', 'cite', 'q', 'dfn', 'abbr', 'data', 'time', 'code', 'var', 'samp', 'kbd', 'sub', 'sup', 'i', 'b', 'u', 'mark', 'ruby', 'rt', 'rp', 'bdi', 'bdo', 'span', 'br', 'wbr'],
      attributes: {
        global: ['title', 'aria-label', 'aria-valuetext', 'aria-moz-hint'],
        a: ['download'],
        area: ['download', 'alt'],
  
        input: ['alt', 'placeholder'],
        menuitem: ['label'],
        menu: ['label'],
        optgroup: ['label'],
        option: ['label'],
        track: ['label'],
        img: ['alt'],
        textarea: ['placeholder'],
        th: ['abbr']
      }
    };
  
    function overlayElement(element, translation) {
      var value = translation.value;
  
      if (typeof value === 'string') {
        if (!reOverlay.test(value)) {
          element.textContent = value;
        } else {
          var tmpl = element.ownerDocument.createElement('template');
          tmpl.innerHTML = value;
  
          overlay(element, tmpl.content);
        }
      }
  
      for (var key in translation.attrs) {
        var attrName = camelCaseToDashed(key);
        if (isAttrAllowed({ name: attrName }, element)) {
          element.setAttribute(attrName, translation.attrs[key]);
        }
      }
    }
  
    function overlay(sourceElement, translationElement) {
      var result = translationElement.ownerDocument.createDocumentFragment();
      var k = undefined,
          attr = undefined;
  
      var childElement = undefined;
      while (childElement = translationElement.childNodes[0]) {
        translationElement.removeChild(childElement);
  
        if (childElement.nodeType === childElement.TEXT_NODE) {
          result.appendChild(childElement);
          continue;
        }
  
        var index = getIndexOfType(childElement);
        var sourceChild = getNthElementOfType(sourceElement, childElement, index);
        if (sourceChild) {
          overlay(sourceChild, childElement);
          result.appendChild(sourceChild);
          continue;
        }
  
        if (isElementAllowed(childElement)) {
          var sanitizedChild = childElement.ownerDocument.createElement(childElement.nodeName);
          overlay(sanitizedChild, childElement);
          result.appendChild(sanitizedChild);
          continue;
        }
  
        result.appendChild(translationElement.ownerDocument.createTextNode(childElement.textContent));
      }
  
      sourceElement.textContent = '';
      sourceElement.appendChild(result);
  
      if (translationElement.attributes) {
        for (k = 0, attr; attr = translationElement.attributes[k]; k++) {
          if (isAttrAllowed(attr, sourceElement)) {
            sourceElement.setAttribute(attr.name, attr.value);
          }
        }
      }
    }
  
    function isElementAllowed(element) {
      return allowed.elements.indexOf(element.tagName.toLowerCase()) !== -1;
    }
  
    function isAttrAllowed(attr, element) {
      var attrName = attr.name.toLowerCase();
      var tagName = element.tagName.toLowerCase();
  
      if (allowed.attributes.global.indexOf(attrName) !== -1) {
        return true;
      }
  
      if (!allowed.attributes[tagName]) {
        return false;
      }
  
      if (allowed.attributes[tagName].indexOf(attrName) !== -1) {
        return true;
      }
  
      if (tagName === 'input' && attrName === 'value') {
        var type = element.type.toLowerCase();
        if (type === 'submit' || type === 'button' || type === 'reset') {
          return true;
        }
      }
      return false;
    }
  
    function getNthElementOfType(context, element, index) {
      var nthOfType = 0;
      for (var i = 0, child = undefined; child = context.children[i]; i++) {
        if (child.nodeType === child.ELEMENT_NODE && child.tagName === element.tagName) {
          if (nthOfType === index) {
            return child;
          }
          nthOfType++;
        }
      }
      return null;
    }
  
    function getIndexOfType(element) {
      var index = 0;
      var child = undefined;
      while (child = element.previousElementSibling) {
        if (child.tagName === element.tagName) {
          index++;
        }
      }
      return index;
    }
  
    function camelCaseToDashed(string) {
      if (string === 'ariaValueText') {
        return 'aria-valuetext';
      }
  
      return string.replace(/[A-Z]/g, function (match) {
        return '-' + match.toLowerCase();
      }).replace(/^-/, '');
    }
  
    var reHtml = /[&<>]/g;
    var htmlEntities = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;'
    };
  
0e9aeacd   root   localization l20n
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
    function setAttributes(element, id, args) {
      element.setAttribute('data-l10n-id', id);
      if (args) {
        element.setAttribute('data-l10n-args', JSON.stringify(args));
      }
    }
  
    function getAttributes(element) {
      return {
        id: element.getAttribute('data-l10n-id'),
        args: JSON.parse(element.getAttribute('data-l10n-args'))
      };
    }
  
    function getTranslatables(element) {
      var nodes = Array.from(element.querySelectorAll('[data-l10n-id]'));
  
      if (typeof element.hasAttribute === 'function' && element.hasAttribute('data-l10n-id')) {
        nodes.push(element);
      }
  
      return nodes;
    }
  
a1a3bc73   Luigi Serra   graphs updates
400
    function translateMutations(view, mutations) {
0e9aeacd   root   localization l20n
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
      var targets = new Set();
  
      for (var _iterator = mutations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
        var _ref;
  
        if (_isArray) {
          if (_i >= _iterator.length) break;
          _ref = _iterator[_i++];
        } else {
          _i = _iterator.next();
          if (_i.done) break;
          _ref = _i.value;
        }
  
        var mutation = _ref;
  
        switch (mutation.type) {
          case 'attributes':
            targets.add(mutation.target);
            break;
          case 'childList':
            for (var _iterator2 = mutation.addedNodes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
              var _ref2;
  
              if (_isArray2) {
                if (_i2 >= _iterator2.length) break;
                _ref2 = _iterator2[_i2++];
              } else {
                _i2 = _iterator2.next();
                if (_i2.done) break;
                _ref2 = _i2.value;
              }
  
              var addedNode = _ref2;
  
              if (addedNode.nodeType === addedNode.ELEMENT_NODE) {
                if (addedNode.childElementCount) {
                  getTranslatables(addedNode).forEach(targets.add.bind(targets));
                } else {
                  if (addedNode.hasAttribute('data-l10n-id')) {
                    targets.add(addedNode);
                  }
                }
              }
            }
            break;
        }
      }
  
      if (targets.size === 0) {
        return;
      }
  
a1a3bc73   Luigi Serra   graphs updates
454
      translateElements(view, Array.from(targets));
0e9aeacd   root   localization l20n
455
456
    }
  
a1a3bc73   Luigi Serra   graphs updates
457
458
    function _translateFragment(view, frag) {
      return translateElements(view, getTranslatables(frag));
0e9aeacd   root   localization l20n
459
460
    }
  
a1a3bc73   Luigi Serra   graphs updates
461
    function getElementsTranslation(view, elems) {
0e9aeacd   root   localization l20n
462
463
464
465
466
467
468
469
      var keys = elems.map(function (elem) {
        var id = elem.getAttribute('data-l10n-id');
        var args = elem.getAttribute('data-l10n-args');
        return args ? [id, JSON.parse(args.replace(reHtml, function (match) {
          return htmlEntities[match];
        }))] : id;
      });
  
a1a3bc73   Luigi Serra   graphs updates
470
      return view.formatEntities.apply(view, keys);
0e9aeacd   root   localization l20n
471
472
    }
  
a1a3bc73   Luigi Serra   graphs updates
473
474
    function translateElements(view, elements) {
      return getElementsTranslation(view, elements).then(function (translations) {
0e9aeacd   root   localization l20n
475
476
477
478
479
        return applyTranslations(view, elements, translations);
      });
    }
  
    function applyTranslations(view, elems, translations) {
a1a3bc73   Luigi Serra   graphs updates
480
      disconnect(view, null, true);
0e9aeacd   root   localization l20n
481
482
483
      for (var i = 0; i < elems.length; i++) {
        overlayElement(elems[i], translations[i]);
      }
a1a3bc73   Luigi Serra   graphs updates
484
      reconnect(view);
0e9aeacd   root   localization l20n
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
    }
  
    if (typeof NodeList === 'function' && !NodeList.prototype[Symbol.iterator]) {
      NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    }
  
    function documentReady() {
      if (document.readyState !== 'loading') {
        return Promise.resolve();
      }
  
      return new Promise(function (resolve) {
        document.addEventListener('readystatechange', function onrsc() {
          document.removeEventListener('readystatechange', onrsc);
          resolve();
        });
      });
    }
  
    function getDirection(code) {
      var tag = code.split('-')[0];
      return ['ar', 'he', 'fa', 'ps', 'ur'].indexOf(tag) >= 0 ? 'rtl' : 'ltr';
    }
  
a1a3bc73   Luigi Serra   graphs updates
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    if (navigator.languages === undefined) {
      navigator.languages = [navigator.language];
    }
  
    function getResourceLinks(head) {
      return Array.prototype.map.call(head.querySelectorAll('link[rel="localization"]'), function (el) {
        return el.getAttribute('href');
      });
    }
  
    function getMeta(head) {
      var availableLangs = Object.create(null);
      var defaultLang = null;
      var appVersion = null;
  
      var metas = Array.from(head.querySelectorAll('meta[name="availableLanguages"],' + 'meta[name="defaultLanguage"],' + 'meta[name="appVersion"]'));
      for (var _iterator3 = metas, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
        var _ref3;
  
        if (_isArray3) {
          if (_i3 >= _iterator3.length) break;
          _ref3 = _iterator3[_i3++];
        } else {
          _i3 = _iterator3.next();
          if (_i3.done) break;
          _ref3 = _i3.value;
        }
  
        var meta = _ref3;
  
        var _name = meta.getAttribute('name');
        var content = meta.getAttribute('content').trim();
        switch (_name) {
          case 'availableLanguages':
            availableLangs = getLangRevisionMap(availableLangs, content);
            break;
          case 'defaultLanguage':
            var _getLangRevisionTuple = getLangRevisionTuple(content),
                lang = _getLangRevisionTuple[0],
                rev = _getLangRevisionTuple[1];
  
            defaultLang = lang;
            if (!(lang in availableLangs)) {
              availableLangs[lang] = rev;
            }
            break;
          case 'appVersion':
            appVersion = content;
        }
      }
  
      return {
        defaultLang: defaultLang,
        availableLangs: availableLangs,
        appVersion: appVersion
      };
    }
0e9aeacd   root   localization l20n
566
  
a1a3bc73   Luigi Serra   graphs updates
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
    function getLangRevisionMap(seq, str) {
      return str.split(',').reduce(function (seq, cur) {
        var _getLangRevisionTuple2 = getLangRevisionTuple(cur);
  
        var lang = _getLangRevisionTuple2[0];
        var rev = _getLangRevisionTuple2[1];
  
        seq[lang] = rev;
        return seq;
      }, seq);
    }
  
    function getLangRevisionTuple(str) {
      var _str$trim$split = str.trim().split(':');
  
      var lang = _str$trim$split[0];
      var rev = _str$trim$split[1];
  
      return [lang, parseInt(rev)];
    }
  
    var viewProps = new WeakMap();
0e9aeacd   root   localization l20n
589
590
591
592
593
594
595
  
    var View = (function () {
      function View(client, doc) {
        var _this2 = this;
  
        _classCallCheck(this, View);
  
0e9aeacd   root   localization l20n
596
597
598
599
600
        this.pseudo = {
          'fr-x-psaccent': createPseudo(this, 'fr-x-psaccent'),
          'ar-x-psbidi': createPseudo(this, 'ar-x-psbidi')
        };
  
a1a3bc73   Luigi Serra   graphs updates
601
        var initialized = documentReady().then(function () {
0e9aeacd   root   localization l20n
602
603
          return init(_this2, client);
        });
a1a3bc73   Luigi Serra   graphs updates
604
605
606
607
608
609
610
        this._interactive = initialized.then(function () {
          return client;
        });
        this.ready = initialized.then(function (langs) {
          return translateView(_this2, langs);
        });
        initMutationObserver(this);
0e9aeacd   root   localization l20n
611
  
a1a3bc73   Luigi Serra   graphs updates
612
613
614
615
        viewProps.set(this, {
          doc: doc,
          ready: false
        });
0e9aeacd   root   localization l20n
616
  
a1a3bc73   Luigi Serra   graphs updates
617
618
619
        client.on('languageschangerequest', function (requestedLangs) {
          return _this2.requestLanguages(requestedLangs);
        });
0e9aeacd   root   localization l20n
620
621
      }
  
a1a3bc73   Luigi Serra   graphs updates
622
623
624
625
626
627
628
629
630
631
632
633
634
      View.prototype.requestLanguages = function requestLanguages(requestedLangs, isGlobal) {
        var _this3 = this;
  
        var method = isGlobal ? function (client) {
          return client.method('requestLanguages', requestedLangs);
        } : function (client) {
          return changeLanguages(_this3, client, requestedLangs);
        };
        return this._interactive.then(method);
      };
  
      View.prototype.handleEvent = function handleEvent() {
        return this.requestLanguages(navigator.languages);
0e9aeacd   root   localization l20n
635
636
      };
  
a1a3bc73   Luigi Serra   graphs updates
637
638
639
640
641
      View.prototype.formatEntities = function formatEntities() {
        for (var _len5 = arguments.length, keys = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
          keys[_key5] = arguments[_key5];
        }
  
0e9aeacd   root   localization l20n
642
        return this._interactive.then(function (client) {
a1a3bc73   Luigi Serra   graphs updates
643
          return client.method('formatEntities', client.id, keys);
0e9aeacd   root   localization l20n
644
645
646
647
648
649
650
651
652
653
654
655
        });
      };
  
      View.prototype.formatValue = function formatValue(id, args) {
        return this._interactive.then(function (client) {
          return client.method('formatValues', client.id, [[id, args]]);
        }).then(function (values) {
          return values[0];
        });
      };
  
      View.prototype.formatValues = function formatValues() {
a1a3bc73   Luigi Serra   graphs updates
656
657
        for (var _len6 = arguments.length, keys = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
          keys[_key6] = arguments[_key6];
0e9aeacd   root   localization l20n
658
659
660
661
662
663
664
665
        }
  
        return this._interactive.then(function (client) {
          return client.method('formatValues', client.id, keys);
        });
      };
  
      View.prototype.translateFragment = function translateFragment(frag) {
a1a3bc73   Luigi Serra   graphs updates
666
667
        return _translateFragment(this, frag);
      };
0e9aeacd   root   localization l20n
668
  
a1a3bc73   Luigi Serra   graphs updates
669
670
671
672
673
674
      View.prototype.observeRoot = function observeRoot(root) {
        observe(this, root);
      };
  
      View.prototype.disconnectRoot = function disconnectRoot(root) {
        disconnect(this, root);
0e9aeacd   root   localization l20n
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
      };
  
      return View;
    })();
  
    View.prototype.setAttributes = setAttributes;
    View.prototype.getAttributes = getAttributes;
  
    function createPseudo(view, code) {
      return {
        getName: function () {
          return view._interactive.then(function (client) {
            return client.method('getName', code);
          });
        },
        processString: function (str) {
          return view._interactive.then(function (client) {
            return client.method('processString', code, str);
          });
        }
      };
    }
  
    function init(view, client) {
a1a3bc73   Luigi Serra   graphs updates
699
700
701
702
703
704
      var doc = viewProps.get(view).doc;
      var resources = getResourceLinks(doc.head);
      var meta = getMeta(doc.head);
      view.observeRoot(doc.documentElement);
      return getAdditionalLanguages().then(function (additionalLangs) {
        return client.method('registerView', client.id, resources, meta, additionalLangs, navigator.languages);
0e9aeacd   root   localization l20n
705
706
707
      });
    }
  
a1a3bc73   Luigi Serra   graphs updates
708
709
710
711
712
713
714
715
716
    function changeLanguages(view, client, requestedLangs) {
      var doc = viewProps.get(view).doc;
      var meta = getMeta(doc.head);
      return getAdditionalLanguages().then(function (additionalLangs) {
        return client.method('changeLanguages', client.id, meta, additionalLangs, requestedLangs);
      }).then(function (_ref5) {
        var langs = _ref5.langs;
        var haveChanged = _ref5.haveChanged;
        return haveChanged ? translateView(view, langs) : undefined;
0e9aeacd   root   localization l20n
717
718
719
      });
    }
  
a1a3bc73   Luigi Serra   graphs updates
720
721
722
723
724
725
726
727
728
729
730
731
732
    function getAdditionalLanguages() {
      if (navigator.mozApps && navigator.mozApps.getAdditionalLanguages) {
        return navigator.mozApps.getAdditionalLanguages().catch(function () {
          return Object.create(null);
        });
      }
  
      return Promise.resolve(Object.create(null));
    }
  
    function translateView(view, langs) {
      var props = viewProps.get(view);
      var html = props.doc.documentElement;
0e9aeacd   root   localization l20n
733
  
a1a3bc73   Luigi Serra   graphs updates
734
735
      if (props.ready) {
        return translateRoots(view).then(function () {
0e9aeacd   root   localization l20n
736
737
738
739
          return setAllAndEmit(html, langs);
        });
      }
  
a1a3bc73   Luigi Serra   graphs updates
740
      var translated = langs[0].code === html.getAttribute('lang') ? Promise.resolve() : translateRoots(view).then(function () {
0e9aeacd   root   localization l20n
741
742
743
744
745
        return setLangDir(html, langs);
      });
  
      return translated.then(function () {
        setLangs(html, langs);
a1a3bc73   Luigi Serra   graphs updates
746
        props.ready = true;
0e9aeacd   root   localization l20n
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
      });
    }
  
    function setLangs(html, langs) {
      var codes = langs.map(function (lang) {
        return lang.code;
      });
      html.setAttribute('langs', codes.join(' '));
    }
  
    function setLangDir(html, langs) {
      var code = langs[0].code;
      html.setAttribute('lang', code);
      html.setAttribute('dir', getDirection(code));
    }
  
    function setAllAndEmit(html, langs) {
      setLangDir(html, langs);
      setLangs(html, langs);
      html.parentNode.dispatchEvent(new CustomEvent('DOMRetranslated', {
        bubbles: false,
        cancelable: false
      }));
    }
  
a1a3bc73   Luigi Serra   graphs updates
772
773
    var KNOWN_MACROS = ['plural'];
    var MAX_PLACEABLE_LENGTH = 2500;
0e9aeacd   root   localization l20n
774
  
a1a3bc73   Luigi Serra   graphs updates
775
776
    var FSI = '⁨';
    var PDI = '⁩';
0e9aeacd   root   localization l20n
777
  
a1a3bc73   Luigi Serra   graphs updates
778
    var resolutionChain = new WeakSet();
0e9aeacd   root   localization l20n
779
  
a1a3bc73   Luigi Serra   graphs updates
780
781
782
783
    function format(ctx, lang, args, entity) {
      if (typeof entity === 'string') {
        return [{}, entity];
      }
0e9aeacd   root   localization l20n
784
  
a1a3bc73   Luigi Serra   graphs updates
785
786
787
      if (resolutionChain.has(entity)) {
        throw new L10nError('Cyclic reference detected');
      }
0e9aeacd   root   localization l20n
788
  
a1a3bc73   Luigi Serra   graphs updates
789
      resolutionChain.add(entity);
0e9aeacd   root   localization l20n
790
  
a1a3bc73   Luigi Serra   graphs updates
791
      var rv = undefined;
0e9aeacd   root   localization l20n
792
  
a1a3bc73   Luigi Serra   graphs updates
793
794
795
796
797
798
799
      try {
        rv = resolveValue({}, ctx, lang, args, entity.value, entity.index);
      } finally {
        resolutionChain.delete(entity);
      }
      return rv;
    }
0e9aeacd   root   localization l20n
800
  
a1a3bc73   Luigi Serra   graphs updates
801
802
803
804
    function resolveIdentifier(ctx, lang, args, id) {
      if (KNOWN_MACROS.indexOf(id) > -1) {
        return [{}, ctx._getMacro(lang, id)];
      }
0e9aeacd   root   localization l20n
805
  
a1a3bc73   Luigi Serra   graphs updates
806
807
808
809
810
      if (args && args.hasOwnProperty(id)) {
        if (typeof args[id] === 'string' || typeof args[id] === 'number' && !isNaN(args[id])) {
          return [{}, args[id]];
        } else {
          throw new L10nError('Arg must be a string or a number: ' + id);
0e9aeacd   root   localization l20n
811
        }
a1a3bc73   Luigi Serra   graphs updates
812
      }
0e9aeacd   root   localization l20n
813
  
a1a3bc73   Luigi Serra   graphs updates
814
815
816
      if (id === '__proto__') {
        throw new L10nError('Illegal id: ' + id);
      }
0e9aeacd   root   localization l20n
817
  
a1a3bc73   Luigi Serra   graphs updates
818
      var entity = ctx._getEntity(lang, id);
0e9aeacd   root   localization l20n
819
  
a1a3bc73   Luigi Serra   graphs updates
820
821
822
      if (entity) {
        return format(ctx, lang, args, entity);
      }
0e9aeacd   root   localization l20n
823
  
a1a3bc73   Luigi Serra   graphs updates
824
825
      throw new L10nError('Unknown reference: ' + id);
    }
0e9aeacd   root   localization l20n
826
  
a1a3bc73   Luigi Serra   graphs updates
827
828
829
    function subPlaceable(locals, ctx, lang, args, id) {
      var newLocals = undefined,
          value = undefined;
0e9aeacd   root   localization l20n
830
  
a1a3bc73   Luigi Serra   graphs updates
831
832
      try {
        var _resolveIdentifier = resolveIdentifier(ctx, lang, args, id);
0e9aeacd   root   localization l20n
833
  
a1a3bc73   Luigi Serra   graphs updates
834
835
836
837
838
        newLocals = _resolveIdentifier[0];
        value = _resolveIdentifier[1];
      } catch (err) {
        return [{ error: err }, FSI + '{{ ' + id + ' }}' + PDI];
      }
0e9aeacd   root   localization l20n
839
  
a1a3bc73   Luigi Serra   graphs updates
840
841
842
843
      if (typeof value === 'number') {
        var formatter = ctx._getNumberFormatter(lang);
        return [newLocals, formatter.format(value)];
      }
0e9aeacd   root   localization l20n
844
  
a1a3bc73   Luigi Serra   graphs updates
845
846
847
      if (typeof value === 'string') {
        if (value.length >= MAX_PLACEABLE_LENGTH) {
          throw new L10nError('Too many characters in placeable (' + value.length + ', max allowed is ' + MAX_PLACEABLE_LENGTH + ')');
0e9aeacd   root   localization l20n
848
        }
a1a3bc73   Luigi Serra   graphs updates
849
850
        return [newLocals, FSI + value + PDI];
      }
0e9aeacd   root   localization l20n
851
  
a1a3bc73   Luigi Serra   graphs updates
852
853
      return [{}, FSI + '{{ ' + id + ' }}' + PDI];
    }
0e9aeacd   root   localization l20n
854
  
a1a3bc73   Luigi Serra   graphs updates
855
856
857
858
    function interpolate(locals, ctx, lang, args, arr) {
      return arr.reduce(function (_ref6, cur) {
        var localsSeq = _ref6[0];
        var valueSeq = _ref6[1];
0e9aeacd   root   localization l20n
859
  
a1a3bc73   Luigi Serra   graphs updates
860
861
        if (typeof cur === 'string') {
          return [localsSeq, valueSeq + cur];
0e9aeacd   root   localization l20n
862
        } else {
a1a3bc73   Luigi Serra   graphs updates
863
          var _subPlaceable = subPlaceable(locals, ctx, lang, args, cur.name);
0e9aeacd   root   localization l20n
864
  
a1a3bc73   Luigi Serra   graphs updates
865
          var value = _subPlaceable[1];
0e9aeacd   root   localization l20n
866
  
a1a3bc73   Luigi Serra   graphs updates
867
          return [localsSeq, valueSeq + value];
0e9aeacd   root   localization l20n
868
        }
a1a3bc73   Luigi Serra   graphs updates
869
870
      }, [locals, '']);
    }
0e9aeacd   root   localization l20n
871
  
a1a3bc73   Luigi Serra   graphs updates
872
873
874
875
876
877
878
879
    function resolveSelector(ctx, lang, args, expr, index) {
      var selectorName = undefined;
      if (index[0].type === 'call' && index[0].expr.type === 'prop' && index[0].expr.expr.name === 'cldr') {
        selectorName = 'plural';
      } else {
        selectorName = index[0].name;
      }
      var selector = resolveIdentifier(ctx, lang, args, selectorName)[1];
0e9aeacd   root   localization l20n
880
  
a1a3bc73   Luigi Serra   graphs updates
881
882
883
      if (typeof selector !== 'function') {
        return selector;
      }
0e9aeacd   root   localization l20n
884
  
a1a3bc73   Luigi Serra   graphs updates
885
      var argValue = index[0].args ? resolveIdentifier(ctx, lang, args, index[0].args[0].name)[1] : undefined;
0e9aeacd   root   localization l20n
886
  
a1a3bc73   Luigi Serra   graphs updates
887
888
889
      if (selectorName === 'plural') {
        if (argValue === 0 && 'zero' in expr) {
          return 'zero';
0e9aeacd   root   localization l20n
890
        }
a1a3bc73   Luigi Serra   graphs updates
891
892
        if (argValue === 1 && 'one' in expr) {
          return 'one';
0e9aeacd   root   localization l20n
893
        }
a1a3bc73   Luigi Serra   graphs updates
894
895
        if (argValue === 2 && 'two' in expr) {
          return 'two';
0e9aeacd   root   localization l20n
896
        }
a1a3bc73   Luigi Serra   graphs updates
897
      }
0e9aeacd   root   localization l20n
898
  
a1a3bc73   Luigi Serra   graphs updates
899
900
      return selector(argValue);
    }
0e9aeacd   root   localization l20n
901
  
a1a3bc73   Luigi Serra   graphs updates
902
903
904
905
    function resolveValue(locals, ctx, lang, args, expr, index) {
      if (!expr) {
        return [locals, expr];
      }
0e9aeacd   root   localization l20n
906
  
a1a3bc73   Luigi Serra   graphs updates
907
908
909
      if (typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {
        return [locals, expr];
      }
0e9aeacd   root   localization l20n
910
  
a1a3bc73   Luigi Serra   graphs updates
911
912
913
      if (Array.isArray(expr)) {
        return interpolate(locals, ctx, lang, args, expr);
      }
0e9aeacd   root   localization l20n
914
  
a1a3bc73   Luigi Serra   graphs updates
915
916
917
918
      if (index) {
        var selector = resolveSelector(ctx, lang, args, expr, index);
        if (selector in expr) {
          return resolveValue(locals, ctx, lang, args, expr[selector]);
0e9aeacd   root   localization l20n
919
        }
a1a3bc73   Luigi Serra   graphs updates
920
      }
0e9aeacd   root   localization l20n
921
  
a1a3bc73   Luigi Serra   graphs updates
922
923
924
925
      var defaultKey = expr.__default || 'other';
      if (defaultKey in expr) {
        return resolveValue(locals, ctx, lang, args, expr[defaultKey]);
      }
0e9aeacd   root   localization l20n
926
  
a1a3bc73   Luigi Serra   graphs updates
927
928
      throw new L10nError('Unresolvable value');
    }
0e9aeacd   root   localization l20n
929
  
a1a3bc73   Luigi Serra   graphs updates
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
    var locales2rules = {
      'af': 3,
      'ak': 4,
      'am': 4,
      'ar': 1,
      'asa': 3,
      'az': 0,
      'be': 11,
      'bem': 3,
      'bez': 3,
      'bg': 3,
      'bh': 4,
      'bm': 0,
      'bn': 3,
      'bo': 0,
      'br': 20,
      'brx': 3,
      'bs': 11,
      'ca': 3,
      'cgg': 3,
      'chr': 3,
      'cs': 12,
      'cy': 17,
      'da': 3,
      'de': 3,
      'dv': 3,
      'dz': 0,
      'ee': 3,
      'el': 3,
      'en': 3,
      'eo': 3,
      'es': 3,
      'et': 3,
      'eu': 3,
      'fa': 0,
      'ff': 5,
      'fi': 3,
      'fil': 4,
      'fo': 3,
      'fr': 5,
      'fur': 3,
      'fy': 3,
      'ga': 8,
      'gd': 24,
      'gl': 3,
      'gsw': 3,
      'gu': 3,
      'guw': 4,
      'gv': 23,
      'ha': 3,
      'haw': 3,
      'he': 2,
      'hi': 4,
      'hr': 11,
      'hu': 0,
      'id': 0,
      'ig': 0,
      'ii': 0,
      'is': 3,
      'it': 3,
      'iu': 7,
      'ja': 0,
      'jmc': 3,
      'jv': 0,
      'ka': 0,
      'kab': 5,
      'kaj': 3,
      'kcg': 3,
      'kde': 0,
      'kea': 0,
      'kk': 3,
      'kl': 3,
      'km': 0,
      'kn': 0,
      'ko': 0,
      'ksb': 3,
      'ksh': 21,
      'ku': 3,
      'kw': 7,
      'lag': 18,
      'lb': 3,
      'lg': 3,
      'ln': 4,
      'lo': 0,
      'lt': 10,
      'lv': 6,
      'mas': 3,
      'mg': 4,
      'mk': 16,
      'ml': 3,
      'mn': 3,
      'mo': 9,
      'mr': 3,
      'ms': 0,
      'mt': 15,
      'my': 0,
      'nah': 3,
      'naq': 7,
      'nb': 3,
      'nd': 3,
      'ne': 3,
      'nl': 3,
      'nn': 3,
      'no': 3,
      'nr': 3,
      'nso': 4,
      'ny': 3,
      'nyn': 3,
      'om': 3,
      'or': 3,
      'pa': 3,
      'pap': 3,
      'pl': 13,
      'ps': 3,
      'pt': 3,
      'rm': 3,
      'ro': 9,
      'rof': 3,
      'ru': 11,
      'rwk': 3,
      'sah': 0,
      'saq': 3,
      'se': 7,
      'seh': 3,
      'ses': 0,
      'sg': 0,
      'sh': 11,
      'shi': 19,
      'sk': 12,
      'sl': 14,
      'sma': 7,
      'smi': 7,
      'smj': 7,
      'smn': 7,
      'sms': 7,
      'sn': 3,
      'so': 3,
      'sq': 3,
      'sr': 11,
      'ss': 3,
      'ssy': 3,
      'st': 3,
      'sv': 3,
      'sw': 3,
      'syr': 3,
      'ta': 3,
      'te': 3,
      'teo': 3,
      'th': 0,
      'ti': 4,
      'tig': 3,
      'tk': 3,
      'tl': 4,
      'tn': 3,
      'to': 0,
      'tr': 0,
      'ts': 3,
      'tzm': 22,
      'uk': 11,
      'ur': 3,
      've': 3,
      'vi': 0,
      'vun': 3,
      'wa': 4,
      'wae': 3,
      'wo': 0,
      'xh': 3,
      'xog': 3,
      'yo': 0,
      'zh': 0,
      'zu': 3
    };
0e9aeacd   root   localization l20n
1102
  
a1a3bc73   Luigi Serra   graphs updates
1103
1104
1105
1106
1107
1108
    function isIn(n, list) {
      return list.indexOf(n) !== -1;
    }
    function isBetween(n, start, end) {
      return typeof n === typeof start && start <= n && n <= end;
    }
0e9aeacd   root   localization l20n
1109
  
a1a3bc73   Luigi Serra   graphs updates
1110
1111
1112
1113
1114
1115
1116
    var pluralRules = {
      '0': function () {
        return 'other';
      },
      '1': function (n) {
        if (isBetween(n % 100, 3, 10)) {
          return 'few';
0e9aeacd   root   localization l20n
1117
        }
a1a3bc73   Luigi Serra   graphs updates
1118
1119
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1120
        }
a1a3bc73   Luigi Serra   graphs updates
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
        if (isBetween(n % 100, 11, 99)) {
          return 'many';
        }
        if (n === 2) {
          return 'two';
        }
        if (n === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1131
      },
a1a3bc73   Luigi Serra   graphs updates
1132
1133
1134
      '2': function (n) {
        if (n !== 0 && n % 10 === 0) {
          return 'many';
0e9aeacd   root   localization l20n
1135
        }
a1a3bc73   Luigi Serra   graphs updates
1136
1137
        if (n === 2) {
          return 'two';
0e9aeacd   root   localization l20n
1138
        }
a1a3bc73   Luigi Serra   graphs updates
1139
1140
1141
1142
        if (n === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1143
      },
a1a3bc73   Luigi Serra   graphs updates
1144
1145
1146
      '3': function (n) {
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1147
        }
a1a3bc73   Luigi Serra   graphs updates
1148
        return 'other';
0e9aeacd   root   localization l20n
1149
      },
a1a3bc73   Luigi Serra   graphs updates
1150
1151
1152
      '4': function (n) {
        if (isBetween(n, 0, 1)) {
          return 'one';
0e9aeacd   root   localization l20n
1153
        }
a1a3bc73   Luigi Serra   graphs updates
1154
        return 'other';
0e9aeacd   root   localization l20n
1155
      },
a1a3bc73   Luigi Serra   graphs updates
1156
1157
1158
      '5': function (n) {
        if (isBetween(n, 0, 2) && n !== 2) {
          return 'one';
0e9aeacd   root   localization l20n
1159
        }
a1a3bc73   Luigi Serra   graphs updates
1160
        return 'other';
0e9aeacd   root   localization l20n
1161
      },
a1a3bc73   Luigi Serra   graphs updates
1162
1163
1164
1165
1166
1167
1168
1169
      '6': function (n) {
        if (n === 0) {
          return 'zero';
        }
        if (n % 10 === 1 && n % 100 !== 11) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1170
      },
a1a3bc73   Luigi Serra   graphs updates
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
      '7': function (n) {
        if (n === 2) {
          return 'two';
        }
        if (n === 1) {
          return 'one';
        }
        return 'other';
      },
      '8': function (n) {
        if (isBetween(n, 3, 6)) {
          return 'few';
        }
        if (isBetween(n, 7, 10)) {
          return 'many';
        }
        if (n === 2) {
          return 'two';
        }
        if (n === 1) {
          return 'one';
        }
        return 'other';
      },
      '9': function (n) {
        if (n === 0 || n !== 1 && isBetween(n % 100, 1, 19)) {
          return 'few';
        }
        if (n === 1) {
          return 'one';
        }
        return 'other';
      },
      '10': function (n) {
        if (isBetween(n % 10, 2, 9) && !isBetween(n % 100, 11, 19)) {
          return 'few';
        }
        if (n % 10 === 1 && !isBetween(n % 100, 11, 19)) {
          return 'one';
        }
        return 'other';
      },
      '11': function (n) {
        if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) {
          return 'few';
        }
        if (n % 10 === 0 || isBetween(n % 10, 5, 9) || isBetween(n % 100, 11, 14)) {
          return 'many';
        }
        if (n % 10 === 1 && n % 100 !== 11) {
          return 'one';
        }
        return 'other';
      },
      '12': function (n) {
        if (isBetween(n, 2, 4)) {
          return 'few';
        }
        if (n === 1) {
          return 'one';
        }
        return 'other';
      },
      '13': function (n) {
        if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) {
          return 'few';
        }
        if (n !== 1 && isBetween(n % 10, 0, 1) || isBetween(n % 10, 5, 9) || isBetween(n % 100, 12, 14)) {
          return 'many';
0e9aeacd   root   localization l20n
1240
        }
a1a3bc73   Luigi Serra   graphs updates
1241
1242
1243
1244
        if (n === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1245
      },
a1a3bc73   Luigi Serra   graphs updates
1246
1247
1248
      '14': function (n) {
        if (isBetween(n % 100, 3, 4)) {
          return 'few';
0e9aeacd   root   localization l20n
1249
        }
a1a3bc73   Luigi Serra   graphs updates
1250
1251
        if (n % 100 === 2) {
          return 'two';
0e9aeacd   root   localization l20n
1252
        }
a1a3bc73   Luigi Serra   graphs updates
1253
1254
1255
1256
        if (n % 100 === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1257
      },
a1a3bc73   Luigi Serra   graphs updates
1258
1259
1260
      '15': function (n) {
        if (n === 0 || isBetween(n % 100, 2, 10)) {
          return 'few';
0e9aeacd   root   localization l20n
1261
        }
a1a3bc73   Luigi Serra   graphs updates
1262
1263
        if (isBetween(n % 100, 11, 19)) {
          return 'many';
0e9aeacd   root   localization l20n
1264
        }
a1a3bc73   Luigi Serra   graphs updates
1265
1266
1267
1268
        if (n === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1269
      },
a1a3bc73   Luigi Serra   graphs updates
1270
1271
1272
      '16': function (n) {
        if (n % 10 === 1 && n !== 11) {
          return 'one';
0e9aeacd   root   localization l20n
1273
        }
a1a3bc73   Luigi Serra   graphs updates
1274
        return 'other';
0e9aeacd   root   localization l20n
1275
      },
a1a3bc73   Luigi Serra   graphs updates
1276
1277
1278
      '17': function (n) {
        if (n === 3) {
          return 'few';
0e9aeacd   root   localization l20n
1279
        }
a1a3bc73   Luigi Serra   graphs updates
1280
1281
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1282
        }
a1a3bc73   Luigi Serra   graphs updates
1283
1284
        if (n === 6) {
          return 'many';
0e9aeacd   root   localization l20n
1285
        }
a1a3bc73   Luigi Serra   graphs updates
1286
1287
        if (n === 2) {
          return 'two';
0e9aeacd   root   localization l20n
1288
        }
a1a3bc73   Luigi Serra   graphs updates
1289
1290
        if (n === 1) {
          return 'one';
0e9aeacd   root   localization l20n
1291
        }
a1a3bc73   Luigi Serra   graphs updates
1292
1293
1294
1295
1296
        return 'other';
      },
      '18': function (n) {
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1297
        }
a1a3bc73   Luigi Serra   graphs updates
1298
1299
1300
1301
        if (isBetween(n, 0, 2) && n !== 0 && n !== 2) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1302
      },
a1a3bc73   Luigi Serra   graphs updates
1303
1304
1305
      '19': function (n) {
        if (isBetween(n, 2, 10)) {
          return 'few';
0e9aeacd   root   localization l20n
1306
        }
a1a3bc73   Luigi Serra   graphs updates
1307
1308
        if (isBetween(n, 0, 1)) {
          return 'one';
0e9aeacd   root   localization l20n
1309
        }
a1a3bc73   Luigi Serra   graphs updates
1310
1311
1312
1313
1314
        return 'other';
      },
      '20': function (n) {
        if ((isBetween(n % 10, 3, 4) || n % 10 === 9) && !(isBetween(n % 100, 10, 19) || isBetween(n % 100, 70, 79) || isBetween(n % 100, 90, 99))) {
          return 'few';
0e9aeacd   root   localization l20n
1315
        }
a1a3bc73   Luigi Serra   graphs updates
1316
1317
        if (n % 1000000 === 0 && n !== 0) {
          return 'many';
0e9aeacd   root   localization l20n
1318
        }
a1a3bc73   Luigi Serra   graphs updates
1319
1320
        if (n % 10 === 2 && !isIn(n % 100, [12, 72, 92])) {
          return 'two';
0e9aeacd   root   localization l20n
1321
        }
a1a3bc73   Luigi Serra   graphs updates
1322
1323
        if (n % 10 === 1 && !isIn(n % 100, [11, 71, 91])) {
          return 'one';
0e9aeacd   root   localization l20n
1324
        }
a1a3bc73   Luigi Serra   graphs updates
1325
        return 'other';
0e9aeacd   root   localization l20n
1326
      },
a1a3bc73   Luigi Serra   graphs updates
1327
1328
1329
      '21': function (n) {
        if (n === 0) {
          return 'zero';
0e9aeacd   root   localization l20n
1330
        }
a1a3bc73   Luigi Serra   graphs updates
1331
1332
1333
1334
        if (n === 1) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1335
      },
a1a3bc73   Luigi Serra   graphs updates
1336
1337
1338
      '22': function (n) {
        if (isBetween(n, 0, 1) || isBetween(n, 11, 99)) {
          return 'one';
0e9aeacd   root   localization l20n
1339
        }
a1a3bc73   Luigi Serra   graphs updates
1340
1341
1342
1343
1344
        return 'other';
      },
      '23': function (n) {
        if (isBetween(n % 10, 1, 2) || n % 20 === 0) {
          return 'one';
0e9aeacd   root   localization l20n
1345
        }
a1a3bc73   Luigi Serra   graphs updates
1346
        return 'other';
0e9aeacd   root   localization l20n
1347
      },
a1a3bc73   Luigi Serra   graphs updates
1348
1349
1350
      '24': function (n) {
        if (isBetween(n, 3, 10) || isBetween(n, 13, 19)) {
          return 'few';
0e9aeacd   root   localization l20n
1351
        }
a1a3bc73   Luigi Serra   graphs updates
1352
1353
1354
1355
1356
1357
1358
        if (isIn(n, [2, 12])) {
          return 'two';
        }
        if (isIn(n, [1, 11])) {
          return 'one';
        }
        return 'other';
0e9aeacd   root   localization l20n
1359
1360
1361
      }
    };
  
a1a3bc73   Luigi Serra   graphs updates
1362
1363
1364
1365
1366
1367
1368
1369
1370
    function getPluralRule(code) {
      var index = locales2rules[code.replace(/-.*$/, '')];
      if (!(index in pluralRules)) {
        return function () {
          return 'other';
        };
      }
      return pluralRules[index];
    }
0e9aeacd   root   localization l20n
1371
  
a1a3bc73   Luigi Serra   graphs updates
1372
1373
1374
1375
1376
1377
1378
1379
1380
    var L20nIntl = typeof Intl !== 'undefined' ? Intl : {
      NumberFormat: function () {
        return {
          format: function (v) {
            return v;
          }
        };
      }
    };
0e9aeacd   root   localization l20n
1381
  
a1a3bc73   Luigi Serra   graphs updates
1382
1383
1384
    var Context = (function () {
      function Context(env, langs, resIds) {
        var _this4 = this;
0e9aeacd   root   localization l20n
1385
  
a1a3bc73   Luigi Serra   graphs updates
1386
        _classCallCheck(this, Context);
0e9aeacd   root   localization l20n
1387
  
a1a3bc73   Luigi Serra   graphs updates
1388
1389
1390
1391
1392
1393
        this.langs = langs;
        this.resIds = resIds;
        this.env = env;
        this.emit = function (type, evt) {
          return env.emit(type, evt, _this4);
        };
0e9aeacd   root   localization l20n
1394
1395
      }
  
a1a3bc73   Luigi Serra   graphs updates
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
      Context.prototype._formatTuple = function _formatTuple(lang, args, entity, id, key) {
        try {
          return format(this, lang, args, entity);
        } catch (err) {
          err.id = key ? id + '::' + key : id;
          err.lang = lang;
          this.emit('resolveerror', err);
          return [{ error: err }, err.id];
        }
      };
0e9aeacd   root   localization l20n
1406
  
a1a3bc73   Luigi Serra   graphs updates
1407
1408
      Context.prototype._formatEntity = function _formatEntity(lang, args, entity, id) {
        var _formatTuple2 = this._formatTuple(lang, args, entity, id);
0e9aeacd   root   localization l20n
1409
  
a1a3bc73   Luigi Serra   graphs updates
1410
        var value = _formatTuple2[1];
0e9aeacd   root   localization l20n
1411
  
a1a3bc73   Luigi Serra   graphs updates
1412
1413
1414
1415
        var formatted = {
          value: value,
          attrs: null
        };
0e9aeacd   root   localization l20n
1416
  
a1a3bc73   Luigi Serra   graphs updates
1417
1418
1419
1420
1421
1422
1423
1424
1425
        if (entity.attrs) {
          formatted.attrs = Object.create(null);
          for (var key in entity.attrs) {
            var _formatTuple3 = this._formatTuple(lang, args, entity.attrs[key], id, key);
  
            var attrValue = _formatTuple3[1];
  
            formatted.attrs[key] = attrValue;
          }
0e9aeacd   root   localization l20n
1426
        }
0e9aeacd   root   localization l20n
1427
  
a1a3bc73   Luigi Serra   graphs updates
1428
1429
        return formatted;
      };
0e9aeacd   root   localization l20n
1430
  
a1a3bc73   Luigi Serra   graphs updates
1431
1432
1433
      Context.prototype._formatValue = function _formatValue(lang, args, entity, id) {
        return this._formatTuple(lang, args, entity, id)[1];
      };
0e9aeacd   root   localization l20n
1434
  
a1a3bc73   Luigi Serra   graphs updates
1435
1436
      Context.prototype.fetch = function fetch() {
        var _this5 = this;
0e9aeacd   root   localization l20n
1437
  
a1a3bc73   Luigi Serra   graphs updates
1438
        var langs = arguments.length <= 0 || arguments[0] === undefined ? this.langs : arguments[0];
0e9aeacd   root   localization l20n
1439
  
a1a3bc73   Luigi Serra   graphs updates
1440
1441
1442
        if (langs.length === 0) {
          return Promise.resolve(langs);
        }
0e9aeacd   root   localization l20n
1443
  
a1a3bc73   Luigi Serra   graphs updates
1444
1445
1446
1447
1448
1449
        return Promise.all(this.resIds.map(function (resId) {
          return _this5.env._getResource(langs[0], resId);
        })).then(function () {
          return langs;
        });
      };
0e9aeacd   root   localization l20n
1450
  
a1a3bc73   Luigi Serra   graphs updates
1451
1452
      Context.prototype._resolve = function _resolve(langs, keys, formatter, prevResolved) {
        var _this6 = this;
0e9aeacd   root   localization l20n
1453
  
a1a3bc73   Luigi Serra   graphs updates
1454
        var lang = langs[0];
0e9aeacd   root   localization l20n
1455
  
a1a3bc73   Luigi Serra   graphs updates
1456
1457
        if (!lang) {
          return reportMissing.call(this, keys, formatter, prevResolved);
0e9aeacd   root   localization l20n
1458
        }
0e9aeacd   root   localization l20n
1459
  
a1a3bc73   Luigi Serra   graphs updates
1460
        var hasUnresolved = false;
0e9aeacd   root   localization l20n
1461
  
a1a3bc73   Luigi Serra   graphs updates
1462
1463
1464
1465
        var resolved = keys.map(function (key, i) {
          if (prevResolved && prevResolved[i] !== undefined) {
            return prevResolved[i];
          }
0e9aeacd   root   localization l20n
1466
  
a1a3bc73   Luigi Serra   graphs updates
1467
          var _ref7 = Array.isArray(key) ? key : [key, undefined];
0e9aeacd   root   localization l20n
1468
  
a1a3bc73   Luigi Serra   graphs updates
1469
1470
          var id = _ref7[0];
          var args = _ref7[1];
0e9aeacd   root   localization l20n
1471
  
a1a3bc73   Luigi Serra   graphs updates
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
          var entity = _this6._getEntity(lang, id);
  
          if (entity) {
            return formatter.call(_this6, lang, args, entity, id);
          }
  
          _this6.emit('notfounderror', new L10nError('"' + id + '"' + ' not found in ' + lang.code, id, lang));
          hasUnresolved = true;
        });
  
        if (!hasUnresolved) {
          return resolved;
0e9aeacd   root   localization l20n
1484
        }
0e9aeacd   root   localization l20n
1485
  
a1a3bc73   Luigi Serra   graphs updates
1486
1487
1488
1489
        return this.fetch(langs.slice(1)).then(function (nextLangs) {
          return _this6._resolve(nextLangs, keys, formatter, resolved);
        });
      };
0e9aeacd   root   localization l20n
1490
  
a1a3bc73   Luigi Serra   graphs updates
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
      Context.prototype.formatEntities = function formatEntities() {
        var _this7 = this;
  
        for (var _len7 = arguments.length, keys = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
          keys[_key7] = arguments[_key7];
        }
  
        return this.fetch().then(function (langs) {
          return _this7._resolve(langs, keys, _this7._formatEntity);
        });
      };
  
      Context.prototype.formatValues = function formatValues() {
        var _this8 = this;
  
        for (var _len8 = arguments.length, keys = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
          keys[_key8] = arguments[_key8];
        }
0e9aeacd   root   localization l20n
1509
  
a1a3bc73   Luigi Serra   graphs updates
1510
1511
1512
1513
        return this.fetch().then(function (langs) {
          return _this8._resolve(langs, keys, _this8._formatValue);
        });
      };
0e9aeacd   root   localization l20n
1514
  
a1a3bc73   Luigi Serra   graphs updates
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
      Context.prototype._getEntity = function _getEntity(lang, id) {
        var cache = this.env.resCache;
  
        for (var i = 0, resId = undefined; resId = this.resIds[i]; i++) {
          var resource = cache.get(resId + lang.code + lang.src);
          if (resource instanceof L10nError) {
            continue;
          }
          if (id in resource) {
            return resource[id];
          }
0e9aeacd   root   localization l20n
1526
        }
a1a3bc73   Luigi Serra   graphs updates
1527
1528
1529
1530
1531
1532
        return undefined;
      };
  
      Context.prototype._getNumberFormatter = function _getNumberFormatter(lang) {
        if (!this.env.numberFormatters) {
          this.env.numberFormatters = new Map();
0e9aeacd   root   localization l20n
1533
        }
a1a3bc73   Luigi Serra   graphs updates
1534
1535
1536
1537
        if (!this.env.numberFormatters.has(lang)) {
          var formatter = L20nIntl.NumberFormat(lang);
          this.env.numberFormatters.set(lang, formatter);
          return formatter;
0e9aeacd   root   localization l20n
1538
        }
a1a3bc73   Luigi Serra   graphs updates
1539
1540
        return this.env.numberFormatters.get(lang);
      };
0e9aeacd   root   localization l20n
1541
  
a1a3bc73   Luigi Serra   graphs updates
1542
1543
1544
1545
1546
1547
1548
1549
      Context.prototype._getMacro = function _getMacro(lang, id) {
        switch (id) {
          case 'plural':
            return getPluralRule(lang.code);
          default:
            return undefined;
        }
      };
0e9aeacd   root   localization l20n
1550
  
a1a3bc73   Luigi Serra   graphs updates
1551
1552
      return Context;
    })();
0e9aeacd   root   localization l20n
1553
  
a1a3bc73   Luigi Serra   graphs updates
1554
1555
    function reportMissing(keys, formatter, resolved) {
      var _this9 = this;
0e9aeacd   root   localization l20n
1556
  
a1a3bc73   Luigi Serra   graphs updates
1557
      var missingIds = new Set();
0e9aeacd   root   localization l20n
1558
  
a1a3bc73   Luigi Serra   graphs updates
1559
1560
1561
      keys.forEach(function (key, i) {
        if (resolved && resolved[i] !== undefined) {
          return;
0e9aeacd   root   localization l20n
1562
        }
a1a3bc73   Luigi Serra   graphs updates
1563
1564
1565
1566
        var id = Array.isArray(key) ? key[0] : key;
        missingIds.add(id);
        resolved[i] = formatter === _this9._formatValue ? id : { value: id, attrs: null };
      });
0e9aeacd   root   localization l20n
1567
  
a1a3bc73   Luigi Serra   graphs updates
1568
      this.emit('notfounderror', new L10nError('"' + Array.from(missingIds).join(', ') + '"' + ' not found in any language', missingIds));
0e9aeacd   root   localization l20n
1569
  
a1a3bc73   Luigi Serra   graphs updates
1570
      return resolved;
0e9aeacd   root   localization l20n
1571
1572
    }
  
a1a3bc73   Luigi Serra   graphs updates
1573
    var MAX_PLACEABLES$2 = 100;
0e9aeacd   root   localization l20n
1574
  
a1a3bc73   Luigi Serra   graphs updates
1575
1576
1577
1578
    var PropertiesParser = {
      patterns: null,
      entryIds: null,
      emit: null,
0e9aeacd   root   localization l20n
1579
  
a1a3bc73   Luigi Serra   graphs updates
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
      init: function () {
        this.patterns = {
          comment: /^\s*#|^\s*$/,
          entity: /^([^=\s]+)\s*=\s*(.*)$/,
          multiline: /[^\\]\\$/,
          index: /\{\[\s*(\w+)(?:\(([^\)]*)\))?\s*\]\}/i,
          unicode: /\\u([0-9a-fA-F]{1,4})/g,
          entries: /[^\r\n]+/g,
          controlChars: /\\([\\\n\r\t\b\f\{\}\"\'])/g,
          placeables: /\{\{\s*([^\s]*?)\s*\}\}/
        };
0e9aeacd   root   localization l20n
1591
      },
a1a3bc73   Luigi Serra   graphs updates
1592
1593
1594
1595
  
      parse: function (emit, source) {
        if (!this.patterns) {
          this.init();
0e9aeacd   root   localization l20n
1596
        }
a1a3bc73   Luigi Serra   graphs updates
1597
1598
1599
1600
1601
1602
1603
        this.emit = emit;
  
        var entries = {};
  
        var lines = source.match(this.patterns.entries);
        if (!lines) {
          return entries;
0e9aeacd   root   localization l20n
1604
        }
a1a3bc73   Luigi Serra   graphs updates
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
        for (var i = 0; i < lines.length; i++) {
          var line = lines[i];
  
          if (this.patterns.comment.test(line)) {
            continue;
          }
  
          while (this.patterns.multiline.test(line) && i < lines.length) {
            line = line.slice(0, -1) + lines[++i].trim();
          }
  
          var entityMatch = line.match(this.patterns.entity);
          if (entityMatch) {
            try {
              this.parseEntity(entityMatch[1], entityMatch[2], entries);
            } catch (e) {
              if (!this.emit) {
                throw e;
              }
            }
          }
0e9aeacd   root   localization l20n
1626
        }
a1a3bc73   Luigi Serra   graphs updates
1627
        return entries;
0e9aeacd   root   localization l20n
1628
      },
a1a3bc73   Luigi Serra   graphs updates
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
  
      parseEntity: function (id, value, entries) {
        var name, key;
  
        var pos = id.indexOf('[');
        if (pos !== -1) {
          name = id.substr(0, pos);
          key = id.substring(pos + 1, id.length - 1);
        } else {
          name = id;
          key = null;
0e9aeacd   root   localization l20n
1640
        }
a1a3bc73   Luigi Serra   graphs updates
1641
1642
1643
1644
1645
  
        var nameElements = name.split('.');
  
        if (nameElements.length > 2) {
          throw this.error('Error in ID: "' + name + '".' + ' Nested attributes are not supported.');
0e9aeacd   root   localization l20n
1646
        }
a1a3bc73   Luigi Serra   graphs updates
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
  
        var attr;
        if (nameElements.length > 1) {
          name = nameElements[0];
          attr = nameElements[1];
  
          if (attr[0] === '$') {
            throw this.error('Attribute can\'t start with "$"');
          }
        } else {
          attr = null;
0e9aeacd   root   localization l20n
1658
        }
a1a3bc73   Luigi Serra   graphs updates
1659
1660
  
        this.setEntityValue(name, attr, key, this.unescapeString(value), entries);
0e9aeacd   root   localization l20n
1661
      },
a1a3bc73   Luigi Serra   graphs updates
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
  
      setEntityValue: function (id, attr, key, rawValue, entries) {
        var value = rawValue.indexOf('{{') > -1 ? this.parseString(rawValue) : rawValue;
  
        var isSimpleValue = typeof value === 'string';
        var root = entries;
  
        var isSimpleNode = typeof entries[id] === 'string';
  
        if (!entries[id] && (attr || key || !isSimpleValue)) {
          entries[id] = Object.create(null);
          isSimpleNode = false;
0e9aeacd   root   localization l20n
1674
        }
a1a3bc73   Luigi Serra   graphs updates
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
  
        if (attr) {
          if (isSimpleNode) {
            var val = entries[id];
            entries[id] = Object.create(null);
            entries[id].value = val;
          }
          if (!entries[id].attrs) {
            entries[id].attrs = Object.create(null);
          }
          if (!entries[id].attrs && !isSimpleValue) {
            entries[id].attrs[attr] = Object.create(null);
          }
          root = entries[id].attrs;
          id = attr;
0e9aeacd   root   localization l20n
1690
        }
a1a3bc73   Luigi Serra   graphs updates
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
  
        if (key) {
          isSimpleNode = false;
          if (typeof root[id] === 'string') {
            var val = root[id];
            root[id] = Object.create(null);
            root[id].index = this.parseIndex(val);
            root[id].value = Object.create(null);
          }
          root = root[id].value;
          id = key;
          isSimpleValue = true;
0e9aeacd   root   localization l20n
1703
        }
a1a3bc73   Luigi Serra   graphs updates
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
  
        if (isSimpleValue) {
          if (id in root) {
            throw this.error('Duplicated id: ' + id);
          }
          root[id] = value;
        } else {
          if (!root[id]) {
            root[id] = Object.create(null);
          }
          root[id].value = value;
0e9aeacd   root   localization l20n
1715
        }
0e9aeacd   root   localization l20n
1716
      },
a1a3bc73   Luigi Serra   graphs updates
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
  
      parseString: function (str) {
        var chunks = str.split(this.patterns.placeables);
        var complexStr = [];
  
        var len = chunks.length;
        var placeablesCount = (len - 1) / 2;
  
        if (placeablesCount >= MAX_PLACEABLES$2) {
          throw this.error('Too many placeables (' + placeablesCount + ', max allowed is ' + MAX_PLACEABLES$2 + ')');
0e9aeacd   root   localization l20n
1727
        }
a1a3bc73   Luigi Serra   graphs updates
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
  
        for (var i = 0; i < chunks.length; i++) {
          if (chunks[i].length === 0) {
            continue;
          }
          if (i % 2 === 1) {
            complexStr.push({ type: 'idOrVar', name: chunks[i] });
          } else {
            complexStr.push(chunks[i]);
          }
0e9aeacd   root   localization l20n
1738
        }
a1a3bc73   Luigi Serra   graphs updates
1739
        return complexStr;
0e9aeacd   root   localization l20n
1740
      },
a1a3bc73   Luigi Serra   graphs updates
1741
1742
1743
1744
  
      unescapeString: function (str) {
        if (str.lastIndexOf('\\') !== -1) {
          str = str.replace(this.patterns.controlChars, '$1');
0e9aeacd   root   localization l20n
1745
        }
a1a3bc73   Luigi Serra   graphs updates
1746
1747
1748
1749
1750
1751
1752
1753
1754
        return str.replace(this.patterns.unicode, function (match, token) {
          return String.fromCodePoint(parseInt(token, 16));
        });
      },
  
      parseIndex: function (str) {
        var match = str.match(this.patterns.index);
        if (!match) {
          throw new L10nError('Malformed index');
0e9aeacd   root   localization l20n
1755
        }
a1a3bc73   Luigi Serra   graphs updates
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
        if (match[2]) {
          return [{
            type: 'call',
            expr: {
              type: 'prop',
              expr: {
                type: 'glob',
                name: 'cldr'
              },
              prop: 'plural',
              cmpt: false
            }, args: [{
              type: 'idOrVar',
              name: match[2]
            }]
          }];
        } else {
          return [{ type: 'idOrVar', name: match[1] }];
0e9aeacd   root   localization l20n
1774
        }
0e9aeacd   root   localization l20n
1775
      },
a1a3bc73   Luigi Serra   graphs updates
1776
1777
1778
1779
1780
1781
1782
  
      error: function (msg) {
        var type = arguments.length <= 1 || arguments[1] === undefined ? 'parsererror' : arguments[1];
  
        var err = new L10nError(msg);
        if (this.emit) {
          this.emit(type, err);
0e9aeacd   root   localization l20n
1783
        }
a1a3bc73   Luigi Serra   graphs updates
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
        return err;
      }
    };
  
    var MAX_PLACEABLES$1 = 100;
  
    var L20nParser = {
      parse: function (emit, string) {
        this._source = string;
        this._index = 0;
        this._length = string.length;
        this.entries = Object.create(null);
        this.emit = emit;
  
        return this.getResource();
0e9aeacd   root   localization l20n
1799
      },
a1a3bc73   Luigi Serra   graphs updates
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
  
      getResource: function () {
        this.getWS();
        while (this._index < this._length) {
          try {
            this.getEntry();
          } catch (e) {
            if (e instanceof L10nError) {
              this.getJunkEntry();
              if (!this.emit) {
                throw e;
              }
            } else {
              throw e;
            }
          }
  
          if (this._index < this._length) {
            this.getWS();
          }
0e9aeacd   root   localization l20n
1820
        }
a1a3bc73   Luigi Serra   graphs updates
1821
1822
  
        return this.entries;
0e9aeacd   root   localization l20n
1823
      },
a1a3bc73   Luigi Serra   graphs updates
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
  
      getEntry: function () {
        if (this._source[this._index] === '<') {
          ++this._index;
          var id = this.getIdentifier();
          if (this._source[this._index] === '[') {
            ++this._index;
            return this.getEntity(id, this.getItemList(this.getExpression, ']'));
          }
          return this.getEntity(id);
0e9aeacd   root   localization l20n
1834
        }
a1a3bc73   Luigi Serra   graphs updates
1835
1836
1837
  
        if (this._source.startsWith('/*', this._index)) {
          return this.getComment();
0e9aeacd   root   localization l20n
1838
        }
a1a3bc73   Luigi Serra   graphs updates
1839
1840
  
        throw this.error('Invalid entry');
0e9aeacd   root   localization l20n
1841
      },
a1a3bc73   Luigi Serra   graphs updates
1842
1843
1844
1845
  
      getEntity: function (id, index) {
        if (!this.getRequiredWS()) {
          throw this.error('Expected white space');
0e9aeacd   root   localization l20n
1846
        }
a1a3bc73   Luigi Serra   graphs updates
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
  
        var ch = this._source[this._index];
        var hasIndex = index !== undefined;
        var value = this.getValue(ch, hasIndex, hasIndex);
        var attrs = undefined;
  
        if (value === undefined) {
          if (ch === '>') {
            throw this.error('Expected ">"');
          }
          attrs = this.getAttributes();
        } else {
          var ws1 = this.getRequiredWS();
          if (this._source[this._index] !== '>') {
            if (!ws1) {
              throw this.error('Expected ">"');
            }
            attrs = this.getAttributes();
          }
0e9aeacd   root   localization l20n
1866
        }
a1a3bc73   Luigi Serra   graphs updates
1867
1868
1869
1870
1871
  
        ++this._index;
  
        if (id in this.entries) {
          throw this.error('Duplicate entry ID "' + id, 'duplicateerror');
0e9aeacd   root   localization l20n
1872
        }
a1a3bc73   Luigi Serra   graphs updates
1873
1874
1875
1876
1877
1878
1879
1880
        if (!attrs && !index && typeof value === 'string') {
          this.entries[id] = value;
        } else {
          this.entries[id] = {
            value: value,
            attrs: attrs,
            index: index
          };
0e9aeacd   root   localization l20n
1881
        }
0e9aeacd   root   localization l20n
1882
      },
a1a3bc73   Luigi Serra   graphs updates
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
  
      getValue: function () {
        var ch = arguments.length <= 0 || arguments[0] === undefined ? this._source[this._index] : arguments[0];
        var index = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
        var required = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
  
        switch (ch) {
          case '\'':
          case '"':
            return this.getString(ch, 1);
          case '{':
            return this.getHash(index);
0e9aeacd   root   localization l20n
1895
        }
a1a3bc73   Luigi Serra   graphs updates
1896
1897
1898
  
        if (required) {
          throw this.error('Unknown value type');
0e9aeacd   root   localization l20n
1899
        }
a1a3bc73   Luigi Serra   graphs updates
1900
1901
  
        return;
0e9aeacd   root   localization l20n
1902
      },
a1a3bc73   Luigi Serra   graphs updates
1903
1904
1905
1906
1907
1908
  
      getWS: function () {
        var cc = this._source.charCodeAt(this._index);
  
        while (cc === 32 || cc === 10 || cc === 9 || cc === 13) {
          cc = this._source.charCodeAt(++this._index);
0e9aeacd   root   localization l20n
1909
        }
0e9aeacd   root   localization l20n
1910
      },
a1a3bc73   Luigi Serra   graphs updates
1911
1912
1913
1914
1915
1916
1917
  
      getRequiredWS: function () {
        var pos = this._index;
        var cc = this._source.charCodeAt(pos);
  
        while (cc === 32 || cc === 10 || cc === 9 || cc === 13) {
          cc = this._source.charCodeAt(++this._index);
0e9aeacd   root   localization l20n
1918
        }
a1a3bc73   Luigi Serra   graphs updates
1919
        return this._index !== pos;
0e9aeacd   root   localization l20n
1920
      },
a1a3bc73   Luigi Serra   graphs updates
1921
1922
1923
1924
1925
1926
1927
1928
1929
  
      getIdentifier: function () {
        var start = this._index;
        var cc = this._source.charCodeAt(this._index);
  
        if (cc >= 97 && cc <= 122 || cc >= 65 && cc <= 90 || cc === 95) {
          cc = this._source.charCodeAt(++this._index);
        } else {
          throw this.error('Identifier has to start with [a-zA-Z_]');
0e9aeacd   root   localization l20n
1930
        }
a1a3bc73   Luigi Serra   graphs updates
1931
1932
1933
  
        while (cc >= 97 && cc <= 122 || cc >= 65 && cc <= 90 || cc >= 48 && cc <= 57 || cc === 95) {
          cc = this._source.charCodeAt(++this._index);
0e9aeacd   root   localization l20n
1934
        }
a1a3bc73   Luigi Serra   graphs updates
1935
1936
  
        return this._source.slice(start, this._index);
0e9aeacd   root   localization l20n
1937
      },
a1a3bc73   Luigi Serra   graphs updates
1938
1939
1940
1941
1942
1943
1944
1945
  
      getUnicodeChar: function () {
        for (var i = 0; i < 4; i++) {
          var cc = this._source.charCodeAt(++this._index);
          if (cc > 96 && cc < 103 || cc > 64 && cc < 71 || cc > 47 && cc < 58) {
            continue;
          }
          throw this.error('Illegal unicode escape sequence');
0e9aeacd   root   localization l20n
1946
        }
a1a3bc73   Luigi Serra   graphs updates
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
        this._index++;
        return String.fromCharCode(parseInt(this._source.slice(this._index - 4, this._index), 16));
      },
  
      stringRe: /"|'|{{|\\/g,
      getString: function (opchar, opcharLen) {
        var body = [];
        var placeables = 0;
  
        this._index += opcharLen;
        var start = this._index;
  
        var bufStart = start;
        var buf = '';
  
        while (true) {
          this.stringRe.lastIndex = this._index;
          var match = this.stringRe.exec(this._source);
  
          if (!match) {
            throw this.error('Unclosed string literal');
          }
  
          if (match[0] === '"' || match[0] === '\'') {
            if (match[0] !== opchar) {
              this._index += opcharLen;
              continue;
            }
            this._index = match.index + opcharLen;
            break;
          }
  
          if (match[0] === '{{') {
            if (placeables > MAX_PLACEABLES$1 - 1) {
              throw this.error('Too many placeables, maximum allowed is ' + MAX_PLACEABLES$1);
            }
            placeables++;
            if (match.index > bufStart || buf.length > 0) {
              body.push(buf + this._source.slice(bufStart, match.index));
              buf = '';
            }
            this._index = match.index + 2;
            this.getWS();
            body.push(this.getExpression());
            this.getWS();
            this._index += 2;
            bufStart = this._index;
            continue;
          }
  
          if (match[0] === '\\') {
            this._index = match.index + 1;
            var ch2 = this._source[this._index];
            if (ch2 === 'u') {
              buf += this._source.slice(bufStart, match.index) + this.getUnicodeChar();
            } else if (ch2 === opchar || ch2 === '\\') {
              buf += this._source.slice(bufStart, match.index) + ch2;
              this._index++;
            } else if (this._source.startsWith('{{', this._index)) {
              buf += this._source.slice(bufStart, match.index) + '{{';
              this._index += 2;
            } else {
              throw this.error('Illegal escape sequence');
            }
            bufStart = this._index;
          }
0e9aeacd   root   localization l20n
2013
        }
a1a3bc73   Luigi Serra   graphs updates
2014
2015
2016
  
        if (body.length === 0) {
          return buf + this._source.slice(bufStart, this._index - opcharLen);
0e9aeacd   root   localization l20n
2017
        }
a1a3bc73   Luigi Serra   graphs updates
2018
2019
2020
  
        if (this._index - opcharLen > bufStart || buf.length > 0) {
          body.push(buf + this._source.slice(bufStart, this._index - opcharLen));
0e9aeacd   root   localization l20n
2021
        }
a1a3bc73   Luigi Serra   graphs updates
2022
2023
  
        return body;
0e9aeacd   root   localization l20n
2024
      },
a1a3bc73   Luigi Serra   graphs updates
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
  
      getAttributes: function () {
        var attrs = Object.create(null);
  
        while (true) {
          this.getAttribute(attrs);
          var ws1 = this.getRequiredWS();
          var ch = this._source.charAt(this._index);
          if (ch === '>') {
            break;
          } else if (!ws1) {
            throw this.error('Expected ">"');
          }
0e9aeacd   root   localization l20n
2038
        }
a1a3bc73   Luigi Serra   graphs updates
2039
        return attrs;
0e9aeacd   root   localization l20n
2040
      },
a1a3bc73   Luigi Serra   graphs updates
2041
2042
2043
2044
2045
2046
2047
2048
2049
  
      getAttribute: function (attrs) {
        var key = this.getIdentifier();
        var index = undefined;
  
        if (this._source[this._index] === '[') {
          ++this._index;
          this.getWS();
          index = this.getItemList(this.getExpression, ']');
0e9aeacd   root   localization l20n
2050
        }
a1a3bc73   Luigi Serra   graphs updates
2051
2052
2053
        this.getWS();
        if (this._source[this._index] !== ':') {
          throw this.error('Expected ":"');
0e9aeacd   root   localization l20n
2054
        }
a1a3bc73   Luigi Serra   graphs updates
2055
2056
2057
2058
2059
2060
2061
        ++this._index;
        this.getWS();
        var hasIndex = index !== undefined;
        var value = this.getValue(undefined, hasIndex);
  
        if (key in attrs) {
          throw this.error('Duplicate attribute "' + key, 'duplicateerror');
0e9aeacd   root   localization l20n
2062
        }
a1a3bc73   Luigi Serra   graphs updates
2063
2064
2065
2066
2067
2068
2069
2070
  
        if (!index && typeof value === 'string') {
          attrs[key] = value;
        } else {
          attrs[key] = {
            value: value,
            index: index
          };
0e9aeacd   root   localization l20n
2071
        }
0e9aeacd   root   localization l20n
2072
      },
0e9aeacd   root   localization l20n
2073
  
a1a3bc73   Luigi Serra   graphs updates
2074
2075
      getHash: function (index) {
        var items = Object.create(null);
0e9aeacd   root   localization l20n
2076
  
a1a3bc73   Luigi Serra   graphs updates
2077
2078
        ++this._index;
        this.getWS();
0e9aeacd   root   localization l20n
2079
  
a1a3bc73   Luigi Serra   graphs updates
2080
        var defKey = undefined;
0e9aeacd   root   localization l20n
2081
  
a1a3bc73   Luigi Serra   graphs updates
2082
2083
        while (true) {
          var _getHashItem = this.getHashItem();
0e9aeacd   root   localization l20n
2084
  
a1a3bc73   Luigi Serra   graphs updates
2085
2086
2087
          var key = _getHashItem[0];
          var value = _getHashItem[1];
          var def = _getHashItem[2];
0e9aeacd   root   localization l20n
2088
  
a1a3bc73   Luigi Serra   graphs updates
2089
          items[key] = value;
0e9aeacd   root   localization l20n
2090
  
a1a3bc73   Luigi Serra   graphs updates
2091
2092
2093
2094
2095
2096
2097
          if (def) {
            if (defKey) {
              throw this.error('Default item redefinition forbidden');
            }
            defKey = key;
          }
          this.getWS();
0e9aeacd   root   localization l20n
2098
  
a1a3bc73   Luigi Serra   graphs updates
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
          var comma = this._source[this._index] === ',';
          if (comma) {
            ++this._index;
            this.getWS();
          }
          if (this._source[this._index] === '}') {
            ++this._index;
            break;
          }
          if (!comma) {
            throw this.error('Expected "}"');
0e9aeacd   root   localization l20n
2110
2111
2112
          }
        }
  
a1a3bc73   Luigi Serra   graphs updates
2113
2114
2115
2116
2117
        if (defKey) {
          items.__default = defKey;
        } else if (!index) {
          throw this.error('Unresolvable Hash Value');
        }
0e9aeacd   root   localization l20n
2118
  
a1a3bc73   Luigi Serra   graphs updates
2119
2120
        return items;
      },
0e9aeacd   root   localization l20n
2121
  
a1a3bc73   Luigi Serra   graphs updates
2122
2123
2124
2125
2126
      getHashItem: function () {
        var defItem = false;
        if (this._source[this._index] === '*') {
          ++this._index;
          defItem = true;
0e9aeacd   root   localization l20n
2127
2128
        }
  
a1a3bc73   Luigi Serra   graphs updates
2129
2130
2131
2132
2133
2134
2135
        var key = this.getIdentifier();
        this.getWS();
        if (this._source[this._index] !== ':') {
          throw this.error('Expected ":"');
        }
        ++this._index;
        this.getWS();
0e9aeacd   root   localization l20n
2136
  
a1a3bc73   Luigi Serra   graphs updates
2137
2138
        return [key, this.getValue(), defItem];
      },
0e9aeacd   root   localization l20n
2139
  
a1a3bc73   Luigi Serra   graphs updates
2140
2141
2142
2143
      getComment: function () {
        this._index += 2;
        var start = this._index;
        var end = this._source.indexOf('*/', start);
0e9aeacd   root   localization l20n
2144
  
a1a3bc73   Luigi Serra   graphs updates
2145
2146
        if (end === -1) {
          throw this.error('Comment without a closing tag');
0e9aeacd   root   localization l20n
2147
2148
        }
  
a1a3bc73   Luigi Serra   graphs updates
2149
2150
        this._index = end + 2;
      },
0e9aeacd   root   localization l20n
2151
  
a1a3bc73   Luigi Serra   graphs updates
2152
2153
      getExpression: function () {
        var exp = this.getPrimaryExpression();
0e9aeacd   root   localization l20n
2154
  
a1a3bc73   Luigi Serra   graphs updates
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
        while (true) {
          var ch = this._source[this._index];
          if (ch === '.' || ch === '[') {
            ++this._index;
            exp = this.getPropertyExpression(exp, ch === '[');
          } else if (ch === '(') {
            ++this._index;
            exp = this.getCallExpression(exp);
          } else {
            break;
          }
        }
0e9aeacd   root   localization l20n
2167
  
a1a3bc73   Luigi Serra   graphs updates
2168
2169
        return exp;
      },
0e9aeacd   root   localization l20n
2170
  
a1a3bc73   Luigi Serra   graphs updates
2171
2172
      getPropertyExpression: function (idref, computed) {
        var exp = undefined;
0e9aeacd   root   localization l20n
2173
  
a1a3bc73   Luigi Serra   graphs updates
2174
2175
2176
2177
2178
2179
        if (computed) {
          this.getWS();
          exp = this.getExpression();
          this.getWS();
          if (this._source[this._index] !== ']') {
            throw this.error('Expected "]"');
0e9aeacd   root   localization l20n
2180
          }
a1a3bc73   Luigi Serra   graphs updates
2181
2182
2183
2184
          ++this._index;
        } else {
          exp = this.getIdentifier();
        }
0e9aeacd   root   localization l20n
2185
  
a1a3bc73   Luigi Serra   graphs updates
2186
2187
2188
2189
2190
2191
2192
        return {
          type: 'prop',
          expr: idref,
          prop: exp,
          cmpt: computed
        };
      },
0e9aeacd   root   localization l20n
2193
  
a1a3bc73   Luigi Serra   graphs updates
2194
2195
      getCallExpression: function (callee) {
        this.getWS();
0e9aeacd   root   localization l20n
2196
  
a1a3bc73   Luigi Serra   graphs updates
2197
2198
2199
2200
2201
2202
        return {
          type: 'call',
          expr: callee,
          args: this.getItemList(this.getExpression, ')')
        };
      },
0e9aeacd   root   localization l20n
2203
  
a1a3bc73   Luigi Serra   graphs updates
2204
2205
      getPrimaryExpression: function () {
        var ch = this._source[this._index];
0e9aeacd   root   localization l20n
2206
  
a1a3bc73   Luigi Serra   graphs updates
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
        switch (ch) {
          case '$':
            ++this._index;
            return {
              type: 'var',
              name: this.getIdentifier()
            };
          case '@':
            ++this._index;
            return {
              type: 'glob',
              name: this.getIdentifier()
            };
          default:
            return {
              type: 'id',
              name: this.getIdentifier()
            };
        }
      },
0e9aeacd   root   localization l20n
2227
  
a1a3bc73   Luigi Serra   graphs updates
2228
2229
2230
      getItemList: function (callback, closeChar) {
        var items = [];
        var closed = false;
0e9aeacd   root   localization l20n
2231
  
a1a3bc73   Luigi Serra   graphs updates
2232
        this.getWS();
0e9aeacd   root   localization l20n
2233
  
a1a3bc73   Luigi Serra   graphs updates
2234
2235
2236
2237
        if (this._source[this._index] === closeChar) {
          ++this._index;
          closed = true;
        }
0e9aeacd   root   localization l20n
2238
  
a1a3bc73   Luigi Serra   graphs updates
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
        while (!closed) {
          items.push(callback.call(this));
          this.getWS();
          var ch = this._source.charAt(this._index);
          switch (ch) {
            case ',':
              ++this._index;
              this.getWS();
              break;
            case closeChar:
              ++this._index;
              closed = true;
              break;
            default:
              throw this.error('Expected "," or "' + closeChar + '"');
0e9aeacd   root   localization l20n
2254
2255
          }
        }
0e9aeacd   root   localization l20n
2256
  
a1a3bc73   Luigi Serra   graphs updates
2257
2258
        return items;
      },
0e9aeacd   root   localization l20n
2259
  
a1a3bc73   Luigi Serra   graphs updates
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
      getJunkEntry: function () {
        var pos = this._index;
        var nextEntity = this._source.indexOf('<', pos);
        var nextComment = this._source.indexOf('/*', pos);
  
        if (nextEntity === -1) {
          nextEntity = this._length;
        }
        if (nextComment === -1) {
          nextComment = this._length;
0e9aeacd   root   localization l20n
2270
        }
0e9aeacd   root   localization l20n
2271
  
a1a3bc73   Luigi Serra   graphs updates
2272
        var nextEntry = Math.min(nextEntity, nextComment);
0e9aeacd   root   localization l20n
2273
  
a1a3bc73   Luigi Serra   graphs updates
2274
2275
        this._index = nextEntry;
      },
0e9aeacd   root   localization l20n
2276
  
a1a3bc73   Luigi Serra   graphs updates
2277
2278
      error: function (message) {
        var type = arguments.length <= 1 || arguments[1] === undefined ? 'parsererror' : arguments[1];
0e9aeacd   root   localization l20n
2279
  
a1a3bc73   Luigi Serra   graphs updates
2280
        var pos = this._index;
0e9aeacd   root   localization l20n
2281
  
a1a3bc73   Luigi Serra   graphs updates
2282
2283
2284
2285
        var start = this._source.lastIndexOf('<', pos - 1);
        var lastClose = this._source.lastIndexOf('>', pos - 1);
        start = lastClose > start ? lastClose + 1 : start;
        var context = this._source.slice(start, pos + 10);
0e9aeacd   root   localization l20n
2286
  
a1a3bc73   Luigi Serra   graphs updates
2287
2288
2289
2290
2291
2292
2293
2294
        var msg = message + ' at pos ' + pos + ': `' + context + '`';
        var err = new L10nError(msg);
        if (this.emit) {
          this.emit(type, err);
        }
        return err;
      }
    };
0e9aeacd   root   localization l20n
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
  
    function walkEntry(entry, fn) {
      if (typeof entry === 'string') {
        return fn(entry);
      }
  
      var newEntry = Object.create(null);
  
      if (entry.value) {
        newEntry.value = walkValue(entry.value, fn);
      }
  
      if (entry.index) {
        newEntry.index = entry.index;
      }
  
      if (entry.attrs) {
        newEntry.attrs = Object.create(null);
        for (var key in entry.attrs) {
          newEntry.attrs[key] = walkEntry(entry.attrs[key], fn);
        }
      }
  
      return newEntry;
    }
  
    function walkValue(value, fn) {
      if (typeof value === 'string') {
        return fn(value);
      }
  
      if (value.type) {
        return value;
      }
  
      var newValue = Array.isArray(value) ? [] : Object.create(null);
      var keys = Object.keys(value);
  
      for (var i = 0, key = undefined; key = keys[i]; i++) {
        newValue[key] = walkValue(value[key], fn);
      }
  
      return newValue;
    }
  
    function createGetter(id, name) {
      var _pseudo = null;
  
      return function getPseudo() {
        if (_pseudo) {
          return _pseudo;
        }
  
        var reAlphas = /[a-zA-Z]/g;
        var reVowels = /[aeiouAEIOU]/g;
        var reWords = /[^\W0-9_]+/g;
  
        var reExcluded = /(%[EO]?\w|\{\s*.+?\s*\}|&[#\w]+;|<\s*.+?\s*>)/;
  
        var charMaps = {
          'fr-x-psaccent': 'ȦƁƇḒḖƑƓĦĪĴĶĿḾȠǾƤɊŘŞŦŬṼẆẊẎẐ[\\]^_`ȧƀƈḓḗƒɠħīĵķŀḿƞǿƥɋřşŧŭṽẇẋẏẑ',
          'ar-x-psbidi': '∀ԐↃpƎɟפHIſӼ˥WNOԀÒᴚS⊥∩ɅMXʎZ[\\]ᵥ_,ɐqɔpǝɟƃɥıɾʞʅɯuodbɹsʇnʌʍxʎz'
        };
  
        var mods = {
          'fr-x-psaccent': function (val) {
            return val.replace(reVowels, function (match) {
              return match + match.toLowerCase();
            });
          },
  
          'ar-x-psbidi': function (val) {
            return val.replace(reWords, function (match) {
              return '‮' + match + '‬';
            });
          }
        };
  
        var replaceChars = function (map, val) {
          return val.replace(reAlphas, function (match) {
            return map.charAt(match.charCodeAt(0) - 65);
          });
        };
  
        var transform = function (val) {
          return replaceChars(charMaps[id], mods[id](val));
        };
  
        var apply = function (fn, val) {
          if (!val) {
            return val;
          }
  
          var parts = val.split(reExcluded);
          var modified = parts.map(function (part) {
            if (reExcluded.test(part)) {
              return part;
            }
            return fn(part);
          });
          return modified.join('');
        };
  
        return _pseudo = {
          name: transform(name),
          process: function (str) {
            return apply(transform, str);
          }
        };
      };
    }
  
    var pseudo = Object.defineProperties(Object.create(null), {
      'fr-x-psaccent': {
        enumerable: true,
        get: createGetter('fr-x-psaccent', 'Runtime Accented')
      },
      'ar-x-psbidi': {
        enumerable: true,
        get: createGetter('ar-x-psbidi', 'Runtime Bidi')
      }
    });
  
0e9aeacd   root   localization l20n
2418
    var Env = (function () {
a1a3bc73   Luigi Serra   graphs updates
2419
      function Env(fetchResource) {
0e9aeacd   root   localization l20n
2420
2421
        _classCallCheck(this, Env);
  
0e9aeacd   root   localization l20n
2422
2423
        this.fetchResource = fetchResource;
  
a1a3bc73   Luigi Serra   graphs updates
2424
2425
2426
2427
2428
2429
2430
        this.resCache = new Map();
        this.resRefs = new Map();
        this.numberFormatters = null;
        this.parsers = {
          properties: PropertiesParser,
          l20n: L20nParser
        };
0e9aeacd   root   localization l20n
2431
2432
2433
2434
2435
2436
2437
  
        var listeners = {};
        this.emit = emit.bind(this, listeners);
        this.addEventListener = addEventListener.bind(this, listeners);
        this.removeEventListener = removeEventListener.bind(this, listeners);
      }
  
a1a3bc73   Luigi Serra   graphs updates
2438
2439
2440
2441
2442
2443
2444
2445
2446
      Env.prototype.createContext = function createContext(langs, resIds) {
        var _this10 = this;
  
        var ctx = new Context(this, langs, resIds);
        resIds.forEach(function (resId) {
          var usedBy = _this10.resRefs.get(resId) || 0;
          _this10.resRefs.set(resId, usedBy + 1);
        });
  
0e9aeacd   root   localization l20n
2447
2448
2449
2450
        return ctx;
      };
  
      Env.prototype.destroyContext = function destroyContext(ctx) {
a1a3bc73   Luigi Serra   graphs updates
2451
2452
2453
2454
        var _this11 = this;
  
        ctx.resIds.forEach(function (resId) {
          var usedBy = _this11.resRefs.get(resId) || 0;
0e9aeacd   root   localization l20n
2455
  
a1a3bc73   Luigi Serra   graphs updates
2456
2457
2458
          if (usedBy > 1) {
            return _this11.resRefs.set(resId, usedBy - 1);
          }
0e9aeacd   root   localization l20n
2459
  
a1a3bc73   Luigi Serra   graphs updates
2460
2461
2462
2463
          _this11.resRefs.delete(resId);
          _this11.resCache.forEach(function (val, key) {
            return key.startsWith(resId) ? _this11.resCache.delete(key) : null;
          });
0e9aeacd   root   localization l20n
2464
2465
2466
2467
        });
      };
  
      Env.prototype._parse = function _parse(syntax, lang, data) {
a1a3bc73   Luigi Serra   graphs updates
2468
        var _this12 = this;
0e9aeacd   root   localization l20n
2469
  
a1a3bc73   Luigi Serra   graphs updates
2470
        var parser = this.parsers[syntax];
0e9aeacd   root   localization l20n
2471
2472
2473
2474
2475
        if (!parser) {
          return data;
        }
  
        var emit = function (type, err) {
a1a3bc73   Luigi Serra   graphs updates
2476
          return _this12.emit(type, amendError(lang, err));
0e9aeacd   root   localization l20n
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
        };
        return parser.parse.call(parser, emit, data);
      };
  
      Env.prototype._create = function _create(lang, entries) {
        if (lang.src !== 'pseudo') {
          return entries;
        }
  
        var pseudoentries = Object.create(null);
        for (var key in entries) {
          pseudoentries[key] = walkEntry(entries[key], pseudo[lang.code].process);
        }
        return pseudoentries;
      };
  
      Env.prototype._getResource = function _getResource(lang, res) {
a1a3bc73   Luigi Serra   graphs updates
2494
        var _this13 = this;
0e9aeacd   root   localization l20n
2495
  
a1a3bc73   Luigi Serra   graphs updates
2496
        var cache = this.resCache;
0e9aeacd   root   localization l20n
2497
2498
2499
2500
2501
2502
2503
2504
2505
        var id = res + lang.code + lang.src;
  
        if (cache.has(id)) {
          return cache.get(id);
        }
  
        var syntax = res.substr(res.lastIndexOf('.') + 1);
  
        var saveEntries = function (data) {
a1a3bc73   Luigi Serra   graphs updates
2506
2507
          var entries = _this13._parse(syntax, lang, data);
          cache.set(id, _this13._create(lang, entries));
0e9aeacd   root   localization l20n
2508
2509
2510
2511
        };
  
        var recover = function (err) {
          err.lang = lang;
a1a3bc73   Luigi Serra   graphs updates
2512
          _this13.emit('fetcherror', err);
0e9aeacd   root   localization l20n
2513
2514
2515
          cache.set(id, err);
        };
  
a1a3bc73   Luigi Serra   graphs updates
2516
        var langToFetch = lang.src === 'pseudo' ? { code: 'en-US', src: 'app', ver: lang.ver } : lang;
0e9aeacd   root   localization l20n
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
  
        var resource = this.fetchResource(res, langToFetch).then(saveEntries, recover);
  
        cache.set(id, resource);
  
        return resource;
      };
  
      return Env;
    })();
  
0e9aeacd   root   localization l20n
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
    function amendError(lang, err) {
      err.lang = lang;
      return err;
    }
  
    function prioritizeLocales(def, availableLangs, requested) {
      var supportedLocale = undefined;
  
      for (var i = 0; i < requested.length; i++) {
        var locale = requested[i];
        if (availableLangs.indexOf(locale) !== -1) {
          supportedLocale = locale;
          break;
        }
      }
      if (!supportedLocale || supportedLocale === def) {
        return [def];
      }
  
      return [supportedLocale, def];
    }
  
a1a3bc73   Luigi Serra   graphs updates
2550
2551
2552
2553
    function negotiateLanguages(_ref8, additionalLangs, prevLangs, requestedLangs) {
      var appVersion = _ref8.appVersion;
      var defaultLang = _ref8.defaultLang;
      var availableLangs = _ref8.availableLangs;
0e9aeacd   root   localization l20n
2554
  
a1a3bc73   Luigi Serra   graphs updates
2555
      var allAvailableLangs = Object.keys(availableLangs).concat(Object.keys(additionalLangs)).concat(Object.keys(pseudo));
0e9aeacd   root   localization l20n
2556
2557
2558
2559
2560
      var newLangs = prioritizeLocales(defaultLang, allAvailableLangs, requestedLangs);
  
      var langs = newLangs.map(function (code) {
        return {
          code: code,
a1a3bc73   Luigi Serra   graphs updates
2561
2562
          src: getLangSource(appVersion, availableLangs, additionalLangs, code),
          ver: appVersion
0e9aeacd   root   localization l20n
2563
2564
2565
        };
      });
  
a1a3bc73   Luigi Serra   graphs updates
2566
      return { langs: langs, haveChanged: !arrEqual(prevLangs, newLangs) };
0e9aeacd   root   localization l20n
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
    }
  
    function arrEqual(arr1, arr2) {
      return arr1.length === arr2.length && arr1.every(function (elem, i) {
        return elem === arr2[i];
      });
    }
  
    function getMatchingLangpack(appVersion, langpacks) {
      for (var i = 0, langpack = undefined; langpack = langpacks[i]; i++) {
        if (langpack.target === appVersion) {
          return langpack;
        }
      }
      return null;
    }
  
    function getLangSource(appVersion, availableLangs, additionalLangs, code) {
      if (additionalLangs && additionalLangs[code]) {
        var lp = getMatchingLangpack(appVersion, additionalLangs[code]);
        if (lp && (!(code in availableLangs) || parseInt(lp.revision) > availableLangs[code])) {
          return 'extra';
        }
      }
  
      if (code in pseudo && !(code in availableLangs)) {
        return 'pseudo';
      }
  
      return 'app';
    }
  
    var Remote = (function () {
a1a3bc73   Luigi Serra   graphs updates
2600
      function Remote(fetchResource, broadcast) {
0e9aeacd   root   localization l20n
2601
2602
        _classCallCheck(this, Remote);
  
0e9aeacd   root   localization l20n
2603
        this.broadcast = broadcast;
a1a3bc73   Luigi Serra   graphs updates
2604
        this.env = new Env(fetchResource);
0e9aeacd   root   localization l20n
2605
        this.ctxs = new Map();
0e9aeacd   root   localization l20n
2606
2607
      }
  
a1a3bc73   Luigi Serra   graphs updates
2608
2609
      Remote.prototype.registerView = function registerView(view, resources, meta, additionalLangs, requestedLangs) {
        var _negotiateLanguages = negotiateLanguages(meta, additionalLangs, [], requestedLangs);
0e9aeacd   root   localization l20n
2610
  
a1a3bc73   Luigi Serra   graphs updates
2611
        var langs = _negotiateLanguages.langs;
0e9aeacd   root   localization l20n
2612
  
a1a3bc73   Luigi Serra   graphs updates
2613
2614
        this.ctxs.set(view, this.env.createContext(langs, resources));
        return langs;
0e9aeacd   root   localization l20n
2615
2616
2617
      };
  
      Remote.prototype.unregisterView = function unregisterView(view) {
a1a3bc73   Luigi Serra   graphs updates
2618
2619
        this.ctxs.delete(view);
        return true;
0e9aeacd   root   localization l20n
2620
2621
      };
  
a1a3bc73   Luigi Serra   graphs updates
2622
2623
2624
2625
      Remote.prototype.formatEntities = function formatEntities(view, keys) {
        var _ctxs$get;
  
        return (_ctxs$get = this.ctxs.get(view)).formatEntities.apply(_ctxs$get, keys);
0e9aeacd   root   localization l20n
2626
2627
2628
      };
  
      Remote.prototype.formatValues = function formatValues(view, keys) {
a1a3bc73   Luigi Serra   graphs updates
2629
        var _ctxs$get2;
0e9aeacd   root   localization l20n
2630
  
a1a3bc73   Luigi Serra   graphs updates
2631
        return (_ctxs$get2 = this.ctxs.get(view)).formatValues.apply(_ctxs$get2, keys);
0e9aeacd   root   localization l20n
2632
2633
      };
  
a1a3bc73   Luigi Serra   graphs updates
2634
2635
2636
2637
2638
2639
      Remote.prototype.changeLanguages = function changeLanguages(view, meta, additionalLangs, requestedLangs) {
        var oldCtx = this.ctxs.get(view);
        var prevLangs = oldCtx.langs;
        var newLangs = negotiateLanguages(meta, additionalLangs, prevLangs, requestedLangs);
        this.ctxs.set(view, this.env.createContext(newLangs.langs, oldCtx.resIds));
        return newLangs;
0e9aeacd   root   localization l20n
2640
2641
2642
      };
  
      Remote.prototype.requestLanguages = function requestLanguages(requestedLangs) {
a1a3bc73   Luigi Serra   graphs updates
2643
        this.broadcast('languageschangerequest', requestedLangs);
0e9aeacd   root   localization l20n
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
      };
  
      Remote.prototype.getName = function getName(code) {
        return pseudo[code].name;
      };
  
      Remote.prototype.processString = function processString(code, str) {
        return pseudo[code].process(str);
      };
  
0e9aeacd   root   localization l20n
2654
2655
2656
      return Remote;
    })();
  
0e9aeacd   root   localization l20n
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
    var Node = function Node() {
      _classCallCheck(this, Node);
  
      this.type = this.constructor.name;
    };
  
    var Entry = (function (_Node) {
      _inherits(Entry, _Node);
  
      function Entry() {
        _classCallCheck(this, Entry);
  
        _Node.call(this);
      }
  
      return Entry;
    })(Node);
  
    var Identifier = (function (_Node2) {
      _inherits(Identifier, _Node2);
  
      function Identifier(name) {
        _classCallCheck(this, Identifier);
  
        _Node2.call(this);
        this.name = name;
      }
  
      return Identifier;
    })(Node);
  
    var Variable = (function (_Node3) {
      _inherits(Variable, _Node3);
  
      function Variable(name) {
        _classCallCheck(this, Variable);
  
        _Node3.call(this);
        this.name = name;
      }
  
      return Variable;
    })(Node);
  
    var Global = (function (_Node4) {
      _inherits(Global, _Node4);
  
      function Global(name) {
        _classCallCheck(this, Global);
  
        _Node4.call(this);
        this.name = name;
      }
  
      return Global;
    })(Node);
  
    var Value = (function (_Node5) {
      _inherits(Value, _Node5);
  
      function Value() {
        _classCallCheck(this, Value);
  
        _Node5.call(this);
      }
  
      return Value;
    })(Node);
  
    var String$1 = (function (_Value) {
      _inherits(String$1, _Value);
  
      function String$1(source, content) {
        _classCallCheck(this, String$1);
  
        _Value.call(this);
        this.source = source;
        this.content = content;
  
        this._opchar = '"';
      }
  
      return String$1;
    })(Value);
  
    var Hash = (function (_Value2) {
      _inherits(Hash, _Value2);
  
      function Hash(items) {
        _classCallCheck(this, Hash);
  
        _Value2.call(this);
        this.items = items;
      }
  
      return Hash;
    })(Value);
  
    var Entity = (function (_Entry) {
      _inherits(Entity, _Entry);
  
      function Entity(id) {
        var value = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
        var index = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
        var attrs = arguments.length <= 3 || arguments[3] === undefined ? [] : arguments[3];
  
        _classCallCheck(this, Entity);
  
        _Entry.call(this);
        this.id = id;
        this.value = value;
        this.index = index;
        this.attrs = attrs;
      }
  
      return Entity;
    })(Entry);
  
    var Resource = (function (_Node6) {
      _inherits(Resource, _Node6);
  
      function Resource() {
        _classCallCheck(this, Resource);
  
        _Node6.call(this);
        this.body = [];
      }
  
      return Resource;
    })(Node);
  
    var Attribute = (function (_Node7) {
      _inherits(Attribute, _Node7);
  
      function Attribute(id, value) {
        var index = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  
        _classCallCheck(this, Attribute);
  
        _Node7.call(this);
        this.id = id;
        this.value = value;
        this.index = index;
      }
  
      return Attribute;
    })(Node);
  
    var HashItem = (function (_Node8) {
      _inherits(HashItem, _Node8);
  
      function HashItem(id, value, defItem) {
        _classCallCheck(this, HashItem);
  
        _Node8.call(this);
        this.id = id;
        this.value = value;
        this.default = defItem;
      }
  
      return HashItem;
    })(Node);
  
    var Comment = (function (_Entry2) {
      _inherits(Comment, _Entry2);
  
      function Comment(body) {
        _classCallCheck(this, Comment);
  
        _Entry2.call(this);
        this.body = body;
      }
  
      return Comment;
    })(Entry);
  
    var Expression = (function (_Node9) {
      _inherits(Expression, _Node9);
  
      function Expression() {
        _classCallCheck(this, Expression);
  
        _Node9.call(this);
      }
  
      return Expression;
    })(Node);
  
    var PropertyExpression = (function (_Expression) {
      _inherits(PropertyExpression, _Expression);
  
      function PropertyExpression(idref, exp) {
        var computed = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  
        _classCallCheck(this, PropertyExpression);
  
        _Expression.call(this);
        this.idref = idref;
        this.exp = exp;
        this.computed = computed;
      }
  
      return PropertyExpression;
    })(Expression);
  
    var CallExpression = (function (_Expression2) {
      _inherits(CallExpression, _Expression2);
  
      function CallExpression(callee, args) {
        _classCallCheck(this, CallExpression);
  
        _Expression2.call(this);
        this.callee = callee;
        this.args = args;
      }
  
      return CallExpression;
    })(Expression);
  
    var JunkEntry = (function (_Entry3) {
      _inherits(JunkEntry, _Entry3);
  
      function JunkEntry(content) {
        _classCallCheck(this, JunkEntry);
  
        _Entry3.call(this);
        this.content = content;
      }
  
      return JunkEntry;
    })(Entry);
  
    var AST = {
      Node: Node,
      Identifier: Identifier,
      Value: Value,
      String: String$1,
      Hash: Hash,
      Entity: Entity,
      Resource: Resource,
      Attribute: Attribute,
      HashItem: HashItem,
      Comment: Comment,
      Variable: Variable,
      Global: Global,
      Expression: Expression,
      PropertyExpression: PropertyExpression,
      CallExpression: CallExpression,
      JunkEntry: JunkEntry
    };
  
    var MAX_PLACEABLES = 100;
  
    var ParseContext = (function () {
      function ParseContext(string, pos) {
        _classCallCheck(this, ParseContext);
  
        this._config = {
          pos: pos
        };
        this._source = string;
        this._index = 0;
        this._length = string.length;
        this._curEntryStart = 0;
      }
  
      ParseContext.prototype.setPosition = function setPosition(node, start, end) {
        if (!this._config.pos) {
          return;
        }
        node._pos = { start: start, end: end };
      };
  
      ParseContext.prototype.getResource = function getResource() {
        var resource = new AST.Resource();
        this.setPosition(resource, 0, this._length);
        resource._errors = [];
  
        this.getWS();
        while (this._index < this._length) {
          try {
            resource.body.push(this.getEntry());
          } catch (e) {
            if (e instanceof L10nError) {
              resource._errors.push(e);
              resource.body.push(this.getJunkEntry());
            } else {
              throw e;
            }
          }
          if (this._index < this._length) {
            this.getWS();
          }
        }
  
        return resource;
      };
  
      ParseContext.prototype.getEntry = function getEntry() {
        this._curEntryStart = this._index;
  
        if (this._source[this._index] === '<') {
          ++this._index;
          var id = this.getIdentifier();
          if (this._source[this._index] === '[') {
            ++this._index;
            return this.getEntity(id, this.getItemList(this.getExpression, ']'));
          }
          return this.getEntity(id);
        }
  
        if (this._source.startsWith('/*', this._index)) {
          return this.getComment();
        }
  
        throw this.error('Invalid entry');
      };
  
      ParseContext.prototype.getEntity = function getEntity(id, index) {
        if (!this.getRequiredWS()) {
          throw this.error('Expected white space');
        }
  
        var ch = this._source.charAt(this._index);
a1a3bc73   Luigi Serra   graphs updates
2981
2982
        var hasIndex = index !== undefined;
        var value = this.getValue(ch, hasIndex, hasIndex);
0e9aeacd   root   localization l20n
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
        var attrs = undefined;
  
        if (value === null) {
          if (ch === '>') {
            throw this.error('Expected ">"');
          }
          attrs = this.getAttributes();
        } else {
          var ws1 = this.getRequiredWS();
          if (this._source[this._index] !== '>') {
            if (!ws1) {
              throw this.error('Expected ">"');
            }
            attrs = this.getAttributes();
          }
        }
  
        ++this._index;
  
        var entity = new AST.Entity(id, value, index, attrs);
        this.setPosition(entity, this._curEntryStart, this._index);
        return entity;
      };
  
      ParseContext.prototype.getValue = function getValue() {
        var ch = arguments.length <= 0 || arguments[0] === undefined ? this._source[this._index] : arguments[0];
a1a3bc73   Luigi Serra   graphs updates
3009
3010
        var index = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
        var required = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
0e9aeacd   root   localization l20n
3011
3012
3013
3014
3015
3016
  
        switch (ch) {
          case '\'':
          case '"':
            return this.getString(ch, 1);
          case '{':
a1a3bc73   Luigi Serra   graphs updates
3017
            return this.getHash(index);
0e9aeacd   root   localization l20n
3018
3019
        }
  
a1a3bc73   Luigi Serra   graphs updates
3020
        if (required) {
0e9aeacd   root   localization l20n
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
          throw this.error('Unknown value type');
        }
        return null;
      };
  
      ParseContext.prototype.getWS = function getWS() {
        var cc = this._source.charCodeAt(this._index);
  
        while (cc === 32 || cc === 10 || cc === 9 || cc === 13) {
          cc = this._source.charCodeAt(++this._index);
        }
      };
  
      ParseContext.prototype.getRequiredWS = function getRequiredWS() {
        var pos = this._index;
        var cc = this._source.charCodeAt(pos);
  
        while (cc === 32 || cc === 10 || cc === 9 || cc === 13) {
          cc = this._source.charCodeAt(++this._index);
        }
        return this._index !== pos;
      };
  
      ParseContext.prototype.getIdentifier = function getIdentifier() {
        var start = this._index;
        var cc = this._source.charCodeAt(this._index);
  
        if (cc >= 97 && cc <= 122 || cc >= 65 && cc <= 90 || cc === 95) {
          cc = this._source.charCodeAt(++this._index);
        } else {
          throw this.error('Identifier has to start with [a-zA-Z_]');
        }
  
        while (cc >= 97 && cc <= 122 || cc >= 65 && cc <= 90 || cc >= 48 && cc <= 57 || cc === 95) {
          cc = this._source.charCodeAt(++this._index);
        }
  
        var id = new AST.Identifier(this._source.slice(start, this._index));
        this.setPosition(id, start, this._index);
        return id;
      };
  
      ParseContext.prototype.getUnicodeChar = function getUnicodeChar() {
        for (var i = 0; i < 4; i++) {
          var cc = this._source.charCodeAt(++this._index);
          if (cc > 96 && cc < 103 || cc > 64 && cc < 71 || cc > 47 && cc < 58) {
            continue;
          }
          throw this.error('Illegal unicode escape sequence');
        }
        return '\\u' + this._source.slice(this._index - 3, this._index + 1);
      };
  
      ParseContext.prototype.getString = function getString(opchar, opcharLen) {
        var body = [];
        var buf = '';
        var placeables = 0;
  
        this._index += opcharLen - 1;
  
        var start = this._index + 1;
  
        var closed = false;
  
        while (!closed) {
          var ch = this._source[++this._index];
  
          switch (ch) {
            case '\\':
              var ch2 = this._source[++this._index];
              if (ch2 === 'u') {
                buf += this.getUnicodeChar();
              } else if (ch2 === opchar || ch2 === '\\') {
                buf += ch2;
              } else if (ch2 === '{' && this._source[this._index + 1] === '{') {
                buf += '{';
              } else {
                throw this.error('Illegal escape sequence');
              }
              break;
            case '{':
              if (this._source[this._index + 1] === '{') {
                if (placeables > MAX_PLACEABLES - 1) {
                  throw this.error('Too many placeables, maximum allowed is ' + MAX_PLACEABLES);
                }
                if (buf.length) {
                  body.push(buf);
                  buf = '';
                }
                this._index += 2;
                this.getWS();
                body.push(this.getExpression());
                this.getWS();
                if (!this._source.startsWith('}}', this._index)) {
                  throw this.error('Expected "}}"');
                }
                this._index += 1;
                placeables++;
                break;
              }
  
            default:
              if (ch === opchar) {
                this._index++;
                closed = true;
                break;
              }
  
              buf += ch;
              if (this._index + 1 >= this._length) {
                throw this.error('Unclosed string literal');
              }
          }
        }
  
        if (buf.length) {
          body.push(buf);
        }
  
        var string = new AST.String(this._source.slice(start, this._index - 1), body);
        this.setPosition(string, start, this._index);
        string._opchar = opchar;
  
        return string;
      };
  
      ParseContext.prototype.getAttributes = function getAttributes() {
        var attrs = [];
  
        while (true) {
          var attr = this.getAttribute();
          attrs.push(attr);
          var ws1 = this.getRequiredWS();
          var ch = this._source.charAt(this._index);
          if (ch === '>') {
            break;
          } else if (!ws1) {
            throw this.error('Expected ">"');
          }
        }
        return attrs;
      };
  
      ParseContext.prototype.getAttribute = function getAttribute() {
        var start = this._index;
        var key = this.getIdentifier();
        var index = undefined;
  
        if (this._source[this._index] === '[') {
          ++this._index;
          this.getWS();
          index = this.getItemList(this.getExpression, ']');
        }
        this.getWS();
        if (this._source[this._index] !== ':') {
          throw this.error('Expected ":"');
        }
        ++this._index;
        this.getWS();
a1a3bc73   Luigi Serra   graphs updates
3180
3181
        var hasIndex = index !== undefined;
        var attr = new AST.Attribute(key, this.getValue(undefined, hasIndex), index);
0e9aeacd   root   localization l20n
3182
3183
3184
3185
        this.setPosition(attr, start, this._index);
        return attr;
      };
  
a1a3bc73   Luigi Serra   graphs updates
3186
      ParseContext.prototype.getHash = function getHash(index) {
0e9aeacd   root   localization l20n
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
        var start = this._index;
        var items = [];
  
        ++this._index;
        this.getWS();
  
        while (true) {
          items.push(this.getHashItem());
          this.getWS();
  
          var comma = this._source[this._index] === ',';
          if (comma) {
            ++this._index;
            this.getWS();
          }
          if (this._source[this._index] === '}') {
            ++this._index;
            break;
          }
          if (!comma) {
            throw this.error('Expected "}"');
          }
        }
  
a1a3bc73   Luigi Serra   graphs updates
3211
3212
3213
3214
3215
3216
3217
3218
        if (!index) {
          if (!items.some(function (item) {
            return item.default;
          })) {
            throw this.error('Unresolvable Hash Value');
          }
        }
  
0e9aeacd   root   localization l20n
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
        var hash = new AST.Hash(items);
        this.setPosition(hash, start, this._index);
        return hash;
      };
  
      ParseContext.prototype.getHashItem = function getHashItem() {
        var start = this._index;
  
        var defItem = false;
        if (this._source[this._index] === '*') {
          ++this._index;
          defItem = true;
        }
  
        var key = this.getIdentifier();
        this.getWS();
        if (this._source[this._index] !== ':') {
          throw this.error('Expected ":"');
        }
        ++this._index;
        this.getWS();
  
        var hashItem = new AST.HashItem(key, this.getValue(), defItem);
        this.setPosition(hashItem, start, this._index);
        return hashItem;
      };
  
      ParseContext.prototype.getComment = function getComment() {
        this._index += 2;
        var start = this._index;
        var end = this._source.indexOf('*/', start);
  
        if (end === -1) {
          throw this.error('Comment without a closing tag');
        }
  
        this._index = end + 2;
        var comment = new AST.Comment(this._source.slice(start, end));
        this.setPosition(comment, start - 2, this._index);
        return comment;
      };
  
      ParseContext.prototype.getExpression = function getExpression() {
        var start = this._index;
        var exp = this.getPrimaryExpression();
  
        while (true) {
          var ch = this._source[this._index];
          if (ch === '.' || ch === '[') {
            ++this._index;
            exp = this.getPropertyExpression(exp, ch === '[', start);
          } else if (ch === '(') {
            ++this._index;
            exp = this.getCallExpression(exp, start);
          } else {
            break;
          }
        }
  
        return exp;
      };
  
      ParseContext.prototype.getPropertyExpression = function getPropertyExpression(idref, computed, start) {
        var exp = undefined;
  
        if (computed) {
          this.getWS();
          exp = this.getExpression();
          this.getWS();
          if (this._source[this._index] !== ']') {
            throw this.error('Expected "]"');
          }
          ++this._index;
        } else {
          exp = this.getIdentifier();
        }
  
        var propExpr = new AST.PropertyExpression(idref, exp, computed);
        this.setPosition(propExpr, start, this._index);
        return propExpr;
      };
  
      ParseContext.prototype.getCallExpression = function getCallExpression(callee, start) {
        this.getWS();
  
        var callExpr = new AST.CallExpression(callee, this.getItemList(this.getExpression, ')'));
        this.setPosition(callExpr, start, this._index);
        return callExpr;
      };
  
      ParseContext.prototype.getPrimaryExpression = function getPrimaryExpression() {
        var start = this._index;
        var ch = this._source[this._index];
  
        switch (ch) {
          case '$':
            ++this._index;
            var variable = new AST.Variable(this.getIdentifier());
            this.setPosition(variable, start, this._index);
            return variable;
          case '@':
            ++this._index;
            var global = new AST.Global(this.getIdentifier());
            this.setPosition(global, start, this._index);
            return global;
          default:
            return this.getIdentifier();
        }
      };
  
      ParseContext.prototype.getItemList = function getItemList(callback, closeChar) {
        var items = [];
        var closed = false;
  
        this.getWS();
  
        if (this._source[this._index] === closeChar) {
          ++this._index;
          closed = true;
        }
  
        while (!closed) {
          items.push(callback.call(this));
          this.getWS();
          var ch = this._source.charAt(this._index);
          switch (ch) {
            case ',':
              ++this._index;
              this.getWS();
              break;
            case closeChar:
              ++this._index;
              closed = true;
              break;
            default:
              throw this.error('Expected "," or "' + closeChar + '"');
          }
        }
  
        return items;
      };
  
      ParseContext.prototype.error = function error(message) {
        var pos = this._index;
  
        var start = this._source.lastIndexOf('<', pos - 1);
        var lastClose = this._source.lastIndexOf('>', pos - 1);
        start = lastClose > start ? lastClose + 1 : start;
        var context = this._source.slice(start, pos + 10);
  
        var msg = message + ' at pos ' + pos + ': `' + context + '`';
  
        var err = new L10nError(msg);
        err._pos = { start: pos, end: undefined };
        err.offset = pos - start;
        err.description = message;
        err.context = context;
        return err;
      };
  
      ParseContext.prototype.getJunkEntry = function getJunkEntry() {
        var pos = this._index;
        var nextEntity = this._source.indexOf('<', pos);
        var nextComment = this._source.indexOf('/*', pos);
  
        if (nextEntity === -1) {
          nextEntity = this._length;
        }
        if (nextComment === -1) {
          nextComment = this._length;
        }
  
        var nextEntry = Math.min(nextEntity, nextComment);
  
        this._index = nextEntry;
  
        var junk = new AST.JunkEntry(this._source.slice(this._curEntryStart, nextEntry));
  
        this.setPosition(junk, this._curEntryStart, nextEntry);
        return junk;
      };
  
      return ParseContext;
    })();
  
    var ASTParser = {
      parseResource: function (string) {
        var pos = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
  
        var parseContext = new ParseContext(string, pos);
        return parseContext.getResource();
      }
    };
  
    var ASTSerializer = {
      serialize: function (ast) {
        var string = '';
        for (var id in ast) {
          string += this.dumpEntry(ast[id]) + '\n';
        }
        return string;
      },
  
      serializeString: function (ast) {
        var string = '';
  
        if (typeof ast === 'object') {
          string += this.dumpValue(ast, 0);
        } else {
          string += this.dumpString(ast);
        }
  
        return string;
      },
  
      dumpEntry: function (entry) {
        return this.dumpEntity(entry);
      },
  
      dumpEntity: function (entity) {
        var id,
            val = null,
            attrs = {};
        var index = '';
  
        for (var key in entity) {
          switch (key) {
            case '$v':
              val = entity.$v;
              break;
            case '$x':
              index = this.dumpIndex(entity.$x);
              break;
            case '$i':
              id = this.dumpIdentifier(entity.$i);
              break;
            default:
              attrs[key] = entity[key];
          }
        }
  
        if (Object.keys(attrs).length === 0) {
          return '<' + id + index + ' ' + this.dumpValue(val, 0) + '>';
        } else {
          return '<' + id + index + ' ' + this.dumpValue(val, 0) + '\n' + this.dumpAttributes(attrs) + '>';
        }
      },
  
      dumpIdentifier: function (id) {
        return id.replace(/-/g, '_');
      },
  
      dumpValue: function (value, depth) {
        if (value === null) {
          return '';
        }
  
        if (typeof value === 'string') {
          return this.dumpString(value);
        }
        if (Array.isArray(value)) {
          return this.dumpComplexString(value);
        }
        if (typeof value === 'object') {
          if (value.o) {
            return this.dumpValue(value.v);
          }
          return this.dumpHash(value, depth);
        }
      },
  
      dumpString: function (str) {
        if (str) {
          return '"' + str.replace(/"/g, '\\"') + '"';
        }
        return '';
      },
  
      dumpComplexString: function (chunks) {
        var str = '"';
        for (var i = 0; i < chunks.length; i++) {
          if (typeof chunks[i] === 'string') {
            str += chunks[i].replace(/"/g, '\\"');
          } else {
            str += '{{ ' + this.dumpExpression(chunks[i]) + ' }}';
          }
        }
        return str + '"';
      },
  
      dumpAttributes: function (attrs) {
        var str = '';
        for (var key in attrs) {
          if (attrs[key].x) {
            str += '  ' + key + this.dumpIndex(attrs[key].x) + ': ' + this.dumpValue(attrs[key].v, 1) + '\n';
          } else {
            str += '  ' + key + ': ' + this.dumpValue(attrs[key], 1) + '\n';
          }
        }
  
        return str;
      },
  
      dumpExpression: function (exp) {
        switch (exp.t) {
          case 'call':
            return this.dumpCallExpression(exp);
          case 'prop':
            return this.dumpPropertyExpression(exp);
        }
  
        return this.dumpPrimaryExpression(exp);
      },
  
      dumpPropertyExpression: function (exp) {
        var idref = this.dumpExpression(exp.e);
        var prop = undefined;
  
        if (exp.c) {
          prop = this.dumpExpression(exp.p);
          return idref + '[' + prop + ']';
        }
  
        prop = this.dumpIdentifier(exp.p);
        return idref + '.' + prop;
      },
  
      dumpCallExpression: function (exp) {
        var pexp = this.dumpExpression(exp.v);
  
        var attrs = this.dumpItemList(exp.a, this.dumpExpression.bind(this));
        pexp += '(' + attrs + ')';
        return pexp;
      },
  
      dumpPrimaryExpression: function (exp) {
        var ret = '';
  
        if (typeof exp === 'string') {
          return exp;
        }
  
        switch (exp.t) {
          case 'glob':
            ret += '@';
            ret += exp.v;
            break;
          case 'var':
            ret += '$';
            ret += exp.v;
            break;
          case 'id':
            ret += this.dumpIdentifier(exp.v);
            break;
          case 'idOrVar':
            ret += this.dumpIdentifier(exp.v);
            break;
          default:
            throw new L10nError('Unknown primary expression');
        }
  
        return ret;
      },
  
      dumpHash: function (hash, depth) {
        var items = [];
        var str;
  
        var defIndex;
        if ('__default' in hash) {
          defIndex = hash.__default;
        }
  
        for (var key in hash) {
          var _indent = '  ';
          if (key.charAt(0) === '_' && key.charAt(1) === '_') {
            continue;
          }
  
          if (key === defIndex) {
            _indent = ' *';
          }
          str = _indent + key + ': ' + this.dumpValue(hash[key], depth + 1);
          items.push(str);
        }
  
        var indent = new Array(depth + 1).join('  ');
        return '{\n' + indent + items.join(',\n' + indent) + '\n' + indent + '}';
      },
  
      dumpItemList: function (itemList, cb) {
        return itemList.map(cb).join(', ');
      },
  
      dumpIndex: function (index) {
        return '[' + this.dumpItemList(index, this.dumpExpression.bind(this)) + ']';
      }
    };
  
    function EntriesSerializer() {
      this.serialize = function (ast) {
        var string = '';
        for (var id in ast) {
          string += dumpEntry(ast[id]) + '\n';
        }
  
        return string;
      };
  
      function dumpEntry(entry) {
        return dumpEntity(entry);
      }
  
      function dumpEntity(entity) {
        var id,
            val = null,
            attrs = {};
        var index = '';
  
        for (var key in entity) {
          switch (key) {
            case '$v':
              val = entity.$v;
              break;
            case '$x':
              index = dumpIndex(entity.$x);
              break;
            case '$i':
              id = entity.$i.replace(/-/g, '_');
              break;
            default:
              attrs[key] = entity[key];
          }
        }
  
        if (Object.keys(attrs).length === 0) {
          return '<' + id + index + ' ' + dumpValue(val, 0) + '>';
        } else {
          return '<' + id + index + ' ' + dumpValue(val, 0) + '\n' + dumpAttributes(attrs) + '>';
        }
      }
  
      function dumpIndex(index) {
        if (index[0].v === 'plural') {
          return '[ @cldr.plural($' + index[1] + ') ]';
        }
      }
  
      function dumpValue(value, depth) {
        if (value === null) {
          return '';
        }
        if (typeof value === 'string') {
          return dumpString(value);
        }
        if (Array.isArray(value)) {
          return dumpComplexString(value);
        }
        if (typeof value === 'object') {
          if (value.$o) {
            return dumpValue(value.$o);
          }
          return dumpHash(value, depth);
        }
      }
  
      function dumpString(str) {
        if (str) {
          return '"' + str.replace(/"/g, '\\"') + '"';
        }
        return '';
      }
  
      function dumpComplexString(chunks) {
        var str = '"';
        for (var i = 0; i < chunks.length; i++) {
          if (typeof chunks[i] === 'string') {
            str += chunks[i];
          } else {
            str += '{{ ' + chunks[i].v.replace(/-/g, '_') + ' }}';
          }
        }
        return str + '"';
      }
  
      function dumpHash(hash, depth) {
        var items = [];
        var str;
  
        for (var key in hash) {
          str = '  ' + key + ': ' + dumpValue(hash[key]);
          items.push(str);
        }
  
        var indent = depth ? '  ' : '';
        return '{\n' + indent + items.join(',\n' + indent) + '\n' + indent + '}';
      }
  
      function dumpAttributes(attrs) {
        var str = '';
        for (var key in attrs) {
          if (attrs[key].$x) {
            str += '  ' + key + dumpIndex(attrs[key].$x) + ': ' + dumpValue(attrs[key].$v, 1) + '\n';
          } else {
            str += '  ' + key + ': ' + dumpValue(attrs[key], 1) + '\n';
          }
        }
  
        return str;
      }
    }
  
    var lang = {
      code: 'en-US',
      src: 'app'
    };
  
    function MockContext(entries) {
      this._getNumberFormatter = function () {
        return {
          format: function (value) {
            return value;
          }
        };
      };
      this._getEntity = function (lang, id) {
        return entries[id];
      };
  
      this._getMacro = function (lang, id) {
        switch (id) {
          case 'plural':
            return getPluralRule(lang.code);
          default:
            return undefined;
        }
      };
    }
  
    window.L20n = {
      fetchResource: fetchResource, Client: Client, Remote: Remote, View: View, broadcast: broadcast,
      ASTParser: ASTParser, ASTSerializer: ASTSerializer, EntriesParser: L20nParser, EntriesSerializer: EntriesSerializer, PropertiesParser: PropertiesParser,
      Context: Context, Env: Env, L10nError: L10nError, emit: emit, addEventListener: addEventListener, removeEventListener: removeEventListener,
      prioritizeLocales: prioritizeLocales, MockContext: MockContext, lang: lang, getPluralRule: getPluralRule, walkEntry: walkEntry, walkValue: walkValue,
      pseudo: pseudo, format: format
    };
  })();