[extensions-web] mustache: drop build_templates.py, update mustache.js



commit c7ef7136c49cc55f36af61f6bc6ebd6c0f78d974
Author: Yuri Konotopov <ykonotopov gnome org>
Date:   Sun Jan 20 12:32:20 2019 +0400

    mustache: drop build_templates.py, update mustache.js

 sweettooth/static/js/diff.js                       |   4 +-
 sweettooth/static/js/extensions.js                 |  16 +-
 sweettooth/static/js/main.js                       |   6 +-
 sweettooth/static/js/mustache.js                   | 623 +--------------------
 sweettooth/static/js/paginator.js                  |  10 +-
 sweettooth/static/js/settings.js                   |   4 +-
 sweettooth/static/js/template.js                   |  29 +
 sweettooth/static/js/templates.js                  |  19 -
 sweettooth/static/js/templates/build_templates.py  |  35 --
 ...als_chunk_row.mustache => equals_chunk_row.mst} |   0
 .../js/templates/extensions/comment.mustache       |  14 -
 .../js/templates/extensions/comments_list.mst      |  24 +
 .../js/templates/extensions/comments_list.mustache |  11 -
 ...template.mustache => error_report_template.mst} |   0
 .../extensions/{info.mustache => info.mst}         |   0
 .../{info_contents.mustache => info_contents.mst}  |   0
 .../{info_list.mustache => info_list.mst}          |   0
 .../extensions/{settings.mustache => settings.mst} |   0
 .../{uninstall.mustache => uninstall.mst}          |   0
 sweettooth/static/js/templates/templatedata.js     |  18 -
 sweettooth/static/js/text.js                       | 408 ++++++++++++++
 21 files changed, 487 insertions(+), 734 deletions(-)
---
diff --git a/sweettooth/static/js/diff.js b/sweettooth/static/js/diff.js
index 913b25b..99bd999 100644
--- a/sweettooth/static/js/diff.js
+++ b/sweettooth/static/js/diff.js
@@ -9,7 +9,7 @@
     (at your option) any later version.
  */
 
-define(['jquery', 'templates'], function ($, templates) {
+define(['jquery', 'template!diff/equals_chunk_row'], function ($, rowTemplate) {
        "use strict";
 
        var exports = {};
@@ -29,7 +29,7 @@ define(['jquery', 'templates'], function ($, templates) {
 
                        var contents = oldContents[line.oldindex];
 
-                       var $row = $(templates.get('diff/equals_chunk_row')({
+                       var $row = $(rowTemplate.render({
                                oldlinenum: line.oldlinenum,
                                newlinenum: line.newlinenum,
                                contents: contents
diff --git a/sweettooth/static/js/extensions.js b/sweettooth/static/js/extensions.js
index 7cc4d58..e2e964f 100644
--- a/sweettooth/static/js/extensions.js
+++ b/sweettooth/static/js/extensions.js
@@ -9,8 +9,12 @@
     (at your option) any later version.
  */
 
-define(['jquery', 'messages', 'dbus!_', 'extensionUtils', 'templates', 'voca' 'paginator', 'switch'],
-       function ($, messages, dbusProxy, extensionUtils, templates, voca) {
+define(['jquery', 'messages', 'dbus!_', 'extensionUtils',
+       'template!extensions/uninstall', 'template!extensions/info',
+       'template!extensions/info_contents', 'template!extensions/error_report_template',
+       'voca', 'paginator', 'switch'],
+       function ($, messages, dbusProxy, extensionUtils, uninstallTemplate,
+                       infoTemplate, infoContentsTemplate, reportTemplate, voca) {
                "use strict";
 
                var ExtensionState = extensionUtils.ExtensionState;
@@ -257,7 +261,7 @@ define(['jquery', 'messages', 'dbus!_', 'extensionUtils', 'templates', 'voca' 'p
                                                {
                                                        $elem.removeClass('installed upgradable 
configurable');
                                                }
-                                               messages.addInfo(templates.get('extensions/uninstall')(meta));
+                                               messages.addInfo(uninstallTemplate.render(meta));
                                        }
                                });
                        });
@@ -451,7 +455,9 @@ define(['jquery', 'messages', 'dbus!_', 'extensionUtils', 'templates', 'voca' 'p
                                                                        extension.first_line_of_description = 
extension.description.split('\n')[0];
                                                                }
 
-                                                               $elem = 
$(templates.get('extensions/info')(extension)).replaceAll($elem);
+                                                               $elem = $(infoTemplate.render(extension, {
+                                                                       [infoContentsTemplate.name()]: 
infoContentsTemplate.template()
+                                                               })).replaceAll($elem);
 
                                                                addExtensionSwitch(uuid, $elem, extension);
                                                        }
@@ -497,7 +503,7 @@ define(['jquery', 'messages', 'dbus!_', 'extensionUtils', 'templates', 'voca' 'p
                                                        errors: errors
                                                };
 
-                                               
$textarea.text(templates.get('extensions/error_report_template')(context));
+                                               $textarea.text(reportTemplate.render(context));
                                        });
                                });
                        });
diff --git a/sweettooth/static/js/main.js b/sweettooth/static/js/main.js
index 5025ba6..290cfed 100644
--- a/sweettooth/static/js/main.js
+++ b/sweettooth/static/js/main.js
@@ -10,9 +10,9 @@
  */
 
 define(['jquery', 'messages', 'modal', 'hashParamUtils',
-        'templates', 'staticfiles', 'js.cookie', 'extensions', 'uploader', 'fsui', 'settings',
+        'template!extensions/comments_list', 'staticfiles', 'js.cookie', 'extensions', 'uploader', 'fsui', 
'settings',
         'jquery.jeditable', 'jquery.timeago', 'jquery.raty', 'jquery.colorbox'],
-function($, messages, modal, hashParamUtils, templates, staticfiles, cookie) {
+function($, messages, modal, hashParamUtils, commentsTemplate, staticfiles, cookie) {
     "use strict";
 
     if (!$.ajaxSettings.headers)
@@ -230,7 +230,7 @@ function($, messages, modal, hashParamUtils, templates, staticfiles, cookie) {
                         showAll = false;
 
                     var data = { comments: comments, show_all: showAll };
-                    var $newContent = $('<div>').append(templates.get('extensions/comments_list')(data));
+                    var $newContent = $('<div>').append(commentsTemplate.render(data));
                     $newContent.addClass('comments-holder');
 
                     $newContent.find('time').timeago();
diff --git a/sweettooth/static/js/mustache.js b/sweettooth/static/js/mustache.js
index 7165a8a..7ad4c00 100644
--- a/sweettooth/static/js/mustache.js
+++ b/sweettooth/static/js/mustache.js
@@ -1,622 +1 @@
-/*!
- * mustache.js - Logic-less {{mustache}} templates with JavaScript
- * http://github.com/janl/mustache.js
- */
-
-/*global define: false*/
-
-var Mustache;
-
-(function (exports) {
-  if (typeof module !== "undefined" && module.exports) {
-    module.exports = exports; // CommonJS
-  } else if (typeof define === "function") {
-    define(exports); // AMD
-  } else {
-    Mustache = exports; // <script>
-  }
-}((function () {
-
-  var exports = {};
-
-  exports.name = "mustache.js";
-  exports.version = "0.7.0";
-  exports.tags = ["{{", "}}"];
-
-  exports.Scanner = Scanner;
-  exports.Context = Context;
-  exports.Writer = Writer;
-
-  var whiteRe = /\s*/;
-  var spaceRe = /\s+/;
-  var nonSpaceRe = /\S/;
-  var eqRe = /\s*=/;
-  var curlyRe = /\s*\}/;
-  var tagRe = /#|\^|\/|>|\{|&|=|!/;
-
-  // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
-  // See https://github.com/janl/mustache.js/issues/189
-  function testRe(re, string) {
-    return RegExp.prototype.test.call(re, string);
-  }
-
-  function isWhitespace(string) {
-    return !testRe(nonSpaceRe, string);
-  }
-
-  var isArray = Array.isArray || function (obj) {
-    return Object.prototype.toString.call(obj) === "[object Array]";
-  };
-
-  function escapeRe(string) {
-    return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
-  }
-
-  var entityMap = {
-    "&": "&amp;",
-    "<": "&lt;",
-    ">": "&gt;",
-    '"': '&quot;',
-    "'": '&#39;',
-    "/": '&#x2F;'
-  };
-
-  function escapeHtml(string) {
-    return String(string).replace(/[&<>"'\/]/g, function (s) {
-      return entityMap[s];
-    });
-  }
-
-  // Export the escaping function so that the user may override it.
-  // See https://github.com/janl/mustache.js/issues/244
-  exports.escape = escapeHtml;
-
-  function Scanner(string) {
-    this.string = string;
-    this.tail = string;
-    this.pos = 0;
-  }
-
-  /**
-   * Returns `true` if the tail is empty (end of string).
-   */
-  Scanner.prototype.eos = function () {
-    return this.tail === "";
-  };
-
-  /**
-   * Tries to match the given regular expression at the current position.
-   * Returns the matched text if it can match, the empty string otherwise.
-   */
-  Scanner.prototype.scan = function (re) {
-    var match = this.tail.match(re);
-
-    if (match && match.index === 0) {
-      this.tail = this.tail.substring(match[0].length);
-      this.pos += match[0].length;
-      return match[0];
-    }
-
-    return "";
-  };
-
-  /**
-   * Skips all text until the given regular expression can be matched. Returns
-   * the skipped string, which is the entire tail if no match can be made.
-   */
-  Scanner.prototype.scanUntil = function (re) {
-    var match, pos = this.tail.search(re);
-
-    switch (pos) {
-    case -1:
-      match = this.tail;
-      this.pos += this.tail.length;
-      this.tail = "";
-      break;
-    case 0:
-      match = "";
-      break;
-    default:
-      match = this.tail.substring(0, pos);
-      this.tail = this.tail.substring(pos);
-      this.pos += pos;
-    }
-
-    return match;
-  };
-
-  function Context(view, parent) {
-    this.view = view;
-    this.parent = parent;
-    this.clearCache();
-  }
-
-  Context.make = function (view) {
-    return (view instanceof Context) ? view : new Context(view);
-  };
-
-  Context.prototype.clearCache = function () {
-    this._cache = {};
-  };
-
-  Context.prototype.push = function (view) {
-    return new Context(view, this);
-  };
-
-  Context.prototype.lookup = function (name) {
-    var value = this._cache[name];
-
-    if (!value) {
-      if (name === ".") {
-        value = this.view;
-      } else {
-        var context = this;
-
-        while (context) {
-          if (name.indexOf(".") > 0) {
-            var names = name.split("."), i = 0;
-
-            value = context.view;
-
-            while (value && i < names.length) {
-              value = value[names[i++]];
-            }
-          } else {
-            value = context.view[name];
-          }
-
-          if (value != null) {
-            break;
-          }
-
-          context = context.parent;
-        }
-      }
-
-      this._cache[name] = value;
-    }
-
-    if (typeof value === "function") {
-      value = value.call(this.view);
-    }
-
-    return value;
-  };
-
-  function Writer() {
-    this.clearCache();
-  }
-
-  Writer.prototype.clearCache = function () {
-    this._cache = {};
-    this._partialCache = {};
-  };
-
-  Writer.prototype.compile = function (template, tags) {
-    var fn = this._cache[template];
-
-    if (!fn) {
-      var tokens = exports.parse(template, tags);
-      fn = this._cache[template] = this.compileTokens(tokens, template);
-    }
-
-    return fn;
-  };
-
-  Writer.prototype.compilePartial = function (name, template, tags) {
-    var fn = this.compile(template, tags);
-    this._partialCache[name] = fn;
-    return fn;
-  };
-
-  Writer.prototype.compileTokens = function (tokens, template) {
-    var fn = compileTokens(tokens);
-    var self = this;
-
-    return function (view, partials) {
-      if (partials) {
-        if (typeof partials === "function") {
-          self._loadPartial = partials;
-        } else {
-          for (var name in partials) {
-            self.compilePartial(name, partials[name]);
-          }
-        }
-      }
-
-      return fn(self, Context.make(view), template);
-    };
-  };
-
-  Writer.prototype.render = function (template, view, partials) {
-    return this.compile(template)(view, partials);
-  };
-
-  Writer.prototype._section = function (name, context, text, callback) {
-    var value = context.lookup(name);
-
-    switch (typeof value) {
-    case "object":
-      if (isArray(value)) {
-        var buffer = "";
-
-        for (var i = 0, len = value.length; i < len; ++i) {
-          buffer += callback(this, context.push(value[i]));
-        }
-
-        return buffer;
-      }
-
-      return value ? callback(this, context.push(value)) : "";
-    case "function":
-      var self = this;
-      var scopedRender = function (template) {
-        return self.render(template, context);
-      };
-
-      return value.call(context.view, text, scopedRender) || "";
-    default:
-      if (value) {
-        return callback(this, context);
-      }
-    }
-
-    return "";
-  };
-
-  Writer.prototype._inverted = function (name, context, callback) {
-    var value = context.lookup(name);
-
-    // Use JavaScript's definition of falsy. Include empty arrays.
-    // See https://github.com/janl/mustache.js/issues/186
-    if (!value || (isArray(value) && value.length === 0)) {
-      return callback(this, context);
-    }
-
-    return "";
-  };
-
-  Writer.prototype._partial = function (name, context) {
-    if (!(name in this._partialCache) && this._loadPartial) {
-      this.compilePartial(name, this._loadPartial(name));
-    }
-
-    var fn = this._partialCache[name];
-
-    return fn ? fn(context) : "";
-  };
-
-  Writer.prototype._name = function (name, context) {
-    var value = context.lookup(name);
-
-    if (typeof value === "function") {
-      value = value.call(context.view);
-    }
-
-    return (value == null) ? "" : String(value);
-  };
-
-  Writer.prototype._escaped = function (name, context) {
-    return exports.escape(this._name(name, context));
-  };
-
-  /**
-   * Calculates the bounds of the section represented by the given `token` in
-   * the original template by drilling down into nested sections to find the
-   * last token that is part of that section. Returns an array of [start, end].
-   */
-  function sectionBounds(token) {
-    var start = token[3];
-    var end = start;
-
-    var tokens;
-    while ((tokens = token[4]) && tokens.length) {
-      token = tokens[tokens.length - 1];
-      end = token[3];
-    }
-
-    return [start, end];
-  }
-
-  /**
-   * Low-level function that compiles the given `tokens` into a function
-   * that accepts three arguments: a Writer, a Context, and the template.
-   */
-  function compileTokens(tokens) {
-    var subRenders = {};
-
-    function subRender(i, tokens, template) {
-      if (!subRenders[i]) {
-        var fn = compileTokens(tokens);
-        subRenders[i] = function (writer, context) {
-          return fn(writer, context, template);
-        };
-      }
-
-      return subRenders[i];
-    }
-
-    return function (writer, context, template) {
-      var buffer = "";
-      var token, sectionText;
-
-      for (var i = 0, len = tokens.length; i < len; ++i) {
-        token = tokens[i];
-
-        switch (token[0]) {
-        case "#":
-          sectionText = template.slice.apply(template, sectionBounds(token));
-          buffer += writer._section(token[1], context, sectionText, subRender(i, token[4], template));
-          break;
-        case "^":
-          buffer += writer._inverted(token[1], context, subRender(i, token[4], template));
-          break;
-        case ">":
-          buffer += writer._partial(token[1], context);
-          break;
-        case "&":
-          buffer += writer._name(token[1], context);
-          break;
-        case "name":
-          buffer += writer._escaped(token[1], context);
-          break;
-        case "text":
-          buffer += token[1];
-          break;
-        }
-      }
-
-      return buffer;
-    };
-  }
-
-  /**
-   * Forms the given array of `tokens` into a nested tree structure where
-   * tokens that represent a section have a fifth item: an array that contains
-   * all tokens in that section.
-   */
-  function nestTokens(tokens) {
-    var tree = [];
-    var collector = tree;
-    var sections = [];
-    var token, section;
-
-    for (var i = 0; i < tokens.length; ++i) {
-      token = tokens[i];
-
-      switch (token[0]) {
-      case "#":
-      case "^":
-        token[4] = [];
-        sections.push(token);
-        collector.push(token);
-        collector = token[4];
-        break;
-      case "/":
-        if (sections.length === 0) {
-          throw new Error("Unopened section: " + token[1]);
-        }
-
-        section = sections.pop();
-
-        if (section[1] !== token[1]) {
-          throw new Error("Unclosed section: " + section[1]);
-        }
-
-        if (sections.length > 0) {
-          collector = sections[sections.length - 1][4];
-        } else {
-          collector = tree;
-        }
-        break;
-      default:
-        collector.push(token);
-      }
-    }
-
-    // Make sure there were no open sections when we're done.
-    section = sections.pop();
-
-    if (section) {
-      throw new Error("Unclosed section: " + section[1]);
-    }
-
-    return tree;
-  }
-
-  /**
-   * Combines the values of consecutive text tokens in the given `tokens` array
-   * to a single token.
-   */
-  function squashTokens(tokens) {
-    var token, lastToken;
-
-    for (var i = 0; i < tokens.length; ++i) {
-      token = tokens[i];
-
-      if (lastToken && lastToken[0] === "text" && token[0] === "text") {
-        lastToken[1] += token[1];
-        lastToken[3] = token[3];
-        tokens.splice(i--, 1); // Remove this token from the array.
-      } else {
-        lastToken = token;
-      }
-    }
-  }
-
-  function escapeTags(tags) {
-    if (tags.length !== 2) {
-      throw new Error("Invalid tags: " + tags.join(" "));
-    }
-
-    return [
-      new RegExp(escapeRe(tags[0]) + "\\s*"),
-      new RegExp("\\s*" + escapeRe(tags[1]))
-    ];
-  }
-
-  /**
-   * Breaks up the given `template` string into a tree of token objects. If
-   * `tags` is given here it must be an array with two string values: the
-   * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of
-   * course, the default is to use mustaches (i.e. Mustache.tags).
-   */
-  exports.parse = function (template, tags) {
-    tags = tags || exports.tags;
-
-    var tagRes = escapeTags(tags);
-    var scanner = new Scanner(template);
-
-    var tokens = [],      // Buffer to hold the tokens
-        spaces = [],      // Indices of whitespace tokens on the current line
-        hasTag = false,   // Is there a {{tag}} on the current line?
-        nonSpace = false; // Is there a non-space char on the current line?
-
-    // Strips all whitespace tokens array for the current line
-    // if there was a {{#tag}} on it and otherwise only space.
-    function stripSpace() {
-      if (hasTag && !nonSpace) {
-        while (spaces.length) {
-          tokens.splice(spaces.pop(), 1);
-        }
-      } else {
-        spaces = [];
-      }
-
-      hasTag = false;
-      nonSpace = false;
-    }
-
-    var start, type, value, chr;
-
-    while (!scanner.eos()) {
-      start = scanner.pos;
-      value = scanner.scanUntil(tagRes[0]);
-
-      if (value) {
-        for (var i = 0, len = value.length; i < len; ++i) {
-          chr = value.charAt(i);
-
-          if (isWhitespace(chr)) {
-            spaces.push(tokens.length);
-          } else {
-            nonSpace = true;
-          }
-
-          tokens.push(["text", chr, start, start + 1]);
-          start += 1;
-
-          if (chr === "\n") {
-            stripSpace(); // Check for whitespace on the current line.
-          }
-        }
-      }
-
-      start = scanner.pos;
-
-      // Match the opening tag.
-      if (!scanner.scan(tagRes[0])) {
-        break;
-      }
-
-      hasTag = true;
-      type = scanner.scan(tagRe) || "name";
-
-      // Skip any whitespace between tag and value.
-      scanner.scan(whiteRe);
-
-      // Extract the tag value.
-      if (type === "=") {
-        value = scanner.scanUntil(eqRe);
-        scanner.scan(eqRe);
-        scanner.scanUntil(tagRes[1]);
-      } else if (type === "{") {
-        var closeRe = new RegExp("\\s*" + escapeRe("}" + tags[1]));
-        value = scanner.scanUntil(closeRe);
-        scanner.scan(curlyRe);
-        scanner.scanUntil(tagRes[1]);
-        type = "&";
-      } else {
-        value = scanner.scanUntil(tagRes[1]);
-      }
-
-      // Match the closing tag.
-      if (!scanner.scan(tagRes[1])) {
-        throw new Error("Unclosed tag at " + scanner.pos);
-      }
-
-      tokens.push([type, value, start, scanner.pos]);
-
-      if (type === "name" || type === "{" || type === "&") {
-        nonSpace = true;
-      }
-
-      // Set the tags for the next time around.
-      if (type === "=") {
-        tags = value.split(spaceRe);
-        tagRes = escapeTags(tags);
-      }
-    }
-
-    squashTokens(tokens);
-
-    return nestTokens(tokens);
-  };
-
-  // The high-level clearCache, compile, compilePartial, and render functions
-  // use this default writer.
-  var _writer = new Writer();
-
-  /**
-   * Clears all cached templates and partials in the default writer.
-   */
-  exports.clearCache = function () {
-    return _writer.clearCache();
-  };
-
-  /**
-   * Compiles the given `template` to a reusable function using the default
-   * writer.
-   */
-  exports.compile = function (template, tags) {
-    return _writer.compile(template, tags);
-  };
-
-  /**
-   * Compiles the partial with the given `name` and `template` to a reusable
-   * function using the default writer.
-   */
-  exports.compilePartial = function (name, template, tags) {
-    return _writer.compilePartial(name, template, tags);
-  };
-
-  /**
-   * Compiles the given array of tokens (the output of a parse) to a reusable
-   * function using the default writer.
-   */
-  exports.compileTokens = function (tokens, template) {
-    return _writer.compileTokens(tokens, template);
-  };
-
-  /**
-   * Renders the `template` with the given `view` and `partials` using the
-   * default writer.
-   */
-  exports.render = function (template, view, partials) {
-    return _writer.render(template, view, partials);
-  };
-
-  // This is here for backwards compatibility with 0.4.x.
-  exports.to_html = function (template, view, partials, send) {
-    var result = exports.render(template, view, partials);
-
-    if (typeof send === "function") {
-      send(result);
-    } else {
-      return result;
-    }
-  };
-
-  return exports;
-
-}())));
+(function defineMustache(global,factory){if(typeof exports==="object"&&exports&&typeof 
exports.nodeName!=="string"){factory(exports)}else if(typeof 
define==="function"&&define.amd){define(["exports"],factory)}else{global.Mustache={};factory(global.Mustache)}})(this,function
 mustacheFactory(mustache){var objectToString=Object.prototype.toString;var isArray=Array.isArray||function 
isArrayPolyfill(object){return objectToString.call(object)==="[object Array]"};function 
isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof 
obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function 
hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}function 
primitiveHasOwnProperty(primitive,propName){return primitive!=null&&typeof 
primitive!=="object"&&primitive.hasOwnProperty&&primitive.hasOwnProperty(propName)}var 
regExpTest=RegExp.prototype.test;function testRegExp
 (re,stri
 ng){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function 
isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var 
entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function
 escapeHtml(string){return String(string).replace(/[&<>"'`=\/]/g,function fromEntityMap(s){return 
entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var 
tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var 
tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function 
stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete 
tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var 
openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof 
tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw
 new Error("Invalid tags: "+
 tagsToCo
 mpile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*");closingTagRe=new 
RegExp("\\s*"+escapeRegExp(tagsToCompile[1]));closingCurlyRe=new 
RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new 
Scanner(template);var 
start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var
 
i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else
 
if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingT
 agRe)}if
 (!scanner.scan(closingTagRe))throw new Error("Unclosed tag at 
"+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else
 if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at 
'+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else 
if(type==="name"||type==="{"||type==="&"){nonSpace=true}else 
if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed 
section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function 
squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var 
i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return
 squashedTokens}function nestT
 okens(to
 kens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var 
i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return
 nestedTokens}function 
Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function eos(){return 
this.tail===""};Scanner.prototype.scan=function scan(re){var 
match=this.tail.match(re);if(!match||match.index!==0)return"";var 
string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return 
string};Scanner.prototype.scanUntil=function scanUntil(re){var 
index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 
0:match="";break;default:match=this.tail.substring(0,inde
 x);this.
 tail=this.tail.substring(index)}this.pos+=match.length;return match};function 
Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function
 push(view){return new Context(view,this)};Context.prototype.lookup=function lookup(name){var 
cache=this.cache;var value;if(cache.hasOwnProperty(name)){value=cache[name]}else{var 
context=this,intermediateValue,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){intermediateValue=context.view;names=name.split(".");index=0;while(intermediateValue!=null&&index<names.length){if(index===names.length-1)lookupHit=hasProperty(intermediateValue,names[index])||primitiveHasOwnProperty(intermediateValue,names[index]);intermediateValue=intermediateValue[names[index++]]}}else{intermediateValue=context.view[name];lookupHit=hasProperty(context.view,name)}if(lookupHit){value=intermediateValue;break}context=context.parent}cache[name]=value}if(isFunction(value))value=value.call
 (this.vi
 ew);return value};function Writer(){this.cache={}}Writer.prototype.clearCache=function 
clearCache(){this.cache={}};Writer.prototype.parse=function parse(template,tags){var cache=this.cache;var 
cacheKey=template+":"+(tags||mustache.tags).join(":");var 
tokens=cache[cacheKey];if(tokens==null)tokens=cache[cacheKey]=parseTemplate(template,tags);return 
tokens};Writer.prototype.render=function render(template,view,partials,tags){var 
tokens=this.parse(template,tags);var context=view instanceof Context?view:new Context(view);return 
this.renderTokens(tokens,context,partials,template,tags)};Writer.prototype.renderTokens=function 
renderTokens(tokens,context,partials,originalTemplate,tags){var buffer="";var token,symbol,value;for(var 
i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this.renderSection(token,context,partials,originalTemplate);else
 if(symbol==="^")value=this.renderInverted(token,context,partials,originalTempl
 ate);els
 e if(symbol===">")value=this.renderPartial(token,context,partials,tags);else 
if(symbol==="&")value=this.unescapedValue(token,context);else 
if(symbol==="name")value=this.escapedValue(token,context);else 
if(symbol==="text")value=this.rawValue(token);if(value!==undefined)buffer+=value}return 
buffer};Writer.prototype.renderSection=function renderSection(token,context,partials,originalTemplate){var 
self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return 
self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var 
j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else
 if(typeof value==="object"||typeof value==="string"||typeof 
value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else 
if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections 
 without 
 the original 
template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return
 buffer};Writer.prototype.renderInverted=function renderInverted(token,context,partials,originalTemplate){var 
value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return 
this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype.renderPartial=function 
renderPartial(token,context,partials,tags){if(!partials)return;var 
value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return 
this.renderTokens(this.parse(value,tags),context,partials,value)};Writer.prototype.unescapedValue=function 
unescapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return 
value};Writer.prototype.escapedValue=function escapedValue(token,context){var 
value=context.lookup(token[1]);if(value!=null)retur
 n mustac
 he.escape(value)};Writer.prototype.rawValue=function rawValue(token){return 
token[1]};mustache.name="mustache.js";mustache.version="3.0.1";mustache.tags=["{{","}}"];var 
defaultWriter=new Writer;mustache.clearCache=function clearCache(){return 
defaultWriter.clearCache()};mustache.parse=function parse(template,tags){return 
defaultWriter.parse(template,tags)};mustache.render=function render(template,view,partials,tags){if(typeof 
template!=="string"){throw new TypeError('Invalid template! Template should be a "string" '+'but 
"'+typeStr(template)+'" was given as the first '+"argument for mustache#render(template, view, 
partials)")}return defaultWriter.render(template,view,partials,tags)};mustache.to_html=function 
to_html(template,view,partials,send){var 
result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return 
result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;return
 mustache});
diff --git a/sweettooth/static/js/paginator.js b/sweettooth/static/js/paginator.js
index 52bc7a7..79603bf 100644
--- a/sweettooth/static/js/paginator.js
+++ b/sweettooth/static/js/paginator.js
@@ -1,7 +1,7 @@
 /*
     GNOME Shell extensions repository
     Copyright (C) 2011-2012  Jasper St. Pierre <jstpierre mecheye net>
-    Copyright (C) 2017  Yuri Konotopov <ykonotopov gnome org>
+    Copyright (C) 2017-2019  Yuri Konotopov <ykonotopov gnome org>
 
     This program is free software: you can redistribute it and/or modify
     it under the terms of the GNU Affero General Public License as published by
@@ -9,7 +9,9 @@
     (at your option) any later version.
  */
 
-define(['jquery', 'hashParamUtils', 'paginatorUtils', 'dbus!_', 'templates', 'jquery.hashchange'], function 
($, hashParamUtils, paginatorUtils, dbusProxy, templates) {
+define(['jquery', 'hashParamUtils', 'paginatorUtils', 'dbus!_',
+               'template!extensions/info_list', 'template!extensions/info_contents', 'jquery.hashchange'],
+               function ($, hashParamUtils, paginatorUtils, dbusProxy, infoTemplate, infoContentsTemplate) {
        "use strict";
 
        $.fn.paginatorify = function (context) {
@@ -97,7 +99,9 @@ define(['jquery', 'hashParamUtils', 'paginatorUtils', 'dbus!_', 'templates', 'jq
                                        }
                                });
 
-                               var $newContent = $(templates.get('extensions/info_list')(result));
+                               var $newContent = $(infoTemplate.render(result, {
+                                       [infoContentsTemplate.name()]: infoContentsTemplate.template()
+                               }));
 
                                
$elem.removeClass('loading').empty().append($beforePaginator).append($newContent).append($afterPaginator).trigger('page-loaded');
                        });
diff --git a/sweettooth/static/js/settings.js b/sweettooth/static/js/settings.js
index a99c555..9e244e3 100644
--- a/sweettooth/static/js/settings.js
+++ b/sweettooth/static/js/settings.js
@@ -8,7 +8,7 @@
     (at your option) any later version.
  */
 
-define(['jquery', 'dbus!_', 'templates'], function ($, dbusProxy, templates) {
+define(['jquery', 'dbus!_', 'template!extensions/settings'], function ($, dbusProxy, settingsTemplate) {
                "use strict";
                const SETTINGS = [
                        {
@@ -72,7 +72,7 @@ define(['jquery', 'dbus!_', 'templates'], function ($, dbusProxy, templates) {
 
                                for(let setting of SETTINGS)
                                {
-                                       let $elem = $(templates.get('extensions/settings')(setting))
+                                       let $elem = $(settingsTemplate.render(setting))
                                        $elem.data('value', setting.get());
                                        $container.append($elem)
 
diff --git a/sweettooth/static/js/template.js b/sweettooth/static/js/template.js
new file mode 100644
index 0000000..7e47d76
--- /dev/null
+++ b/sweettooth/static/js/template.js
@@ -0,0 +1,29 @@
+/*
+    GNOME Shell extensions repository
+    Copyright (C) 2019  Yuri Konotopov <ykonotopov gnome org>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+ */
+
+define(['mustache'], function(Mustache) {
+       return {
+               load: (templateFile, parentRequire, onload, config) => {
+                       parentRequire(['text!templates/' + templateFile + '.mst'], (loadedTemplate) => {
+                               onload({
+                                       name: () => {
+                                               return templateFile;
+                                       },
+                                       render: (model, partials) => {
+                                               return Mustache.render(loadedTemplate, model, partials);
+                                       },
+                                       template: () => {
+                                               return loadedTemplate
+                                       }
+                               });
+                       });
+               }
+       }
+});
diff --git a/sweettooth/static/js/templates/diff/equals_chunk_row.mustache 
b/sweettooth/static/js/templates/diff/equals_chunk_row.mst
similarity index 100%
rename from sweettooth/static/js/templates/diff/equals_chunk_row.mustache
rename to sweettooth/static/js/templates/diff/equals_chunk_row.mst
diff --git a/sweettooth/static/js/templates/extensions/comments_list.mst 
b/sweettooth/static/js/templates/extensions/comments_list.mst
new file mode 100644
index 0000000..9e73bb2
--- /dev/null
+++ b/sweettooth/static/js/templates/extensions/comments_list.mst
@@ -0,0 +1,24 @@
+{{#comments}}
+  <div class="comment">
+    {{#is_extension_creator}}
+    <div class="extension-creator-badge">Author</div>
+    {{/is_extension_creator}}
+    <img src="{{gravatar}}" class="gravatar">
+    <div class="rating-author">
+      {{#rating}}
+        <div class="rating" data-rating-value="{{rating}}"></div> by
+      {{/rating}}
+      <a class="comment-author" href="{{author.url}}">{{author.username}}</a>
+      <p>{{comment}}</p>
+      <time datetime="{{date.timestamp}}Z">{{date.standard}}</time>
+    </div>
+  </div>
+  <hr>
+{{/comments}}
+{{^show_all}}
+<p class="show-all">Show more reviews</p>
+{{/show_all}}
+
+{{^comments}}
+  <p>There are no comments. Be the first!</p>
+{{/comments}}
diff --git a/sweettooth/static/js/templates/extensions/error_report_template.mustache 
b/sweettooth/static/js/templates/extensions/error_report_template.mst
similarity index 100%
rename from sweettooth/static/js/templates/extensions/error_report_template.mustache
rename to sweettooth/static/js/templates/extensions/error_report_template.mst
diff --git a/sweettooth/static/js/templates/extensions/info.mustache 
b/sweettooth/static/js/templates/extensions/info.mst
similarity index 100%
rename from sweettooth/static/js/templates/extensions/info.mustache
rename to sweettooth/static/js/templates/extensions/info.mst
diff --git a/sweettooth/static/js/templates/extensions/info_contents.mustache 
b/sweettooth/static/js/templates/extensions/info_contents.mst
similarity index 100%
rename from sweettooth/static/js/templates/extensions/info_contents.mustache
rename to sweettooth/static/js/templates/extensions/info_contents.mst
diff --git a/sweettooth/static/js/templates/extensions/info_list.mustache 
b/sweettooth/static/js/templates/extensions/info_list.mst
similarity index 100%
rename from sweettooth/static/js/templates/extensions/info_list.mustache
rename to sweettooth/static/js/templates/extensions/info_list.mst
diff --git a/sweettooth/static/js/templates/extensions/settings.mustache 
b/sweettooth/static/js/templates/extensions/settings.mst
similarity index 100%
rename from sweettooth/static/js/templates/extensions/settings.mustache
rename to sweettooth/static/js/templates/extensions/settings.mst
diff --git a/sweettooth/static/js/templates/extensions/uninstall.mustache 
b/sweettooth/static/js/templates/extensions/uninstall.mst
similarity index 100%
rename from sweettooth/static/js/templates/extensions/uninstall.mustache
rename to sweettooth/static/js/templates/extensions/uninstall.mst
diff --git a/sweettooth/static/js/text.js b/sweettooth/static/js/text.js
new file mode 100644
index 0000000..b8370d6
--- /dev/null
+++ b/sweettooth/static/js/text.js
@@ -0,0 +1,408 @@
+/**
+ * @license text 2.0.15 Copyright jQuery Foundation and other contributors.
+ * Released under MIT license, http://github.com/requirejs/text/LICENSE
+ */
+/*jslint regexp: true */
+/*global require, XMLHttpRequest, ActiveXObject,
+  define, window, process, Packages,
+  java, location, Components, FileUtils */
+
+define(['module'], function (module) {
+    'use strict';
+
+    var text, fs, Cc, Ci, xpcIsWindows,
+        progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
+        xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
+        bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
+        hasLocation = typeof location !== 'undefined' && location.href,
+        defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''),
+        defaultHostName = hasLocation && location.hostname,
+        defaultPort = hasLocation && (location.port || undefined),
+        buildMap = {},
+        masterConfig = (module.config && module.config()) || {};
+
+    function useDefault(value, defaultValue) {
+        return value === undefined || value === '' ? defaultValue : value;
+    }
+
+    //Allow for default ports for http and https.
+    function isSamePort(protocol1, port1, protocol2, port2) {
+        if (port1 === port2) {
+            return true;
+        } else if (protocol1 === protocol2) {
+            if (protocol1 === 'http') {
+                return useDefault(port1, '80') === useDefault(port2, '80');
+            } else if (protocol1 === 'https') {
+                return useDefault(port1, '443') === useDefault(port2, '443');
+            }
+        }
+        return false;
+    }
+
+    text = {
+        version: '2.0.15',
+
+        strip: function (content) {
+            //Strips <?xml ...?> declarations so that external SVG and XML
+            //documents can be added to a document without worry. Also, if the string
+            //is an HTML document, only the part inside the body tag is returned.
+            if (content) {
+                content = content.replace(xmlRegExp, "");
+                var matches = content.match(bodyRegExp);
+                if (matches) {
+                    content = matches[1];
+                }
+            } else {
+                content = "";
+            }
+            return content;
+        },
+
+        jsEscape: function (content) {
+            return content.replace(/(['\\])/g, '\\$1')
+                .replace(/[\f]/g, "\\f")
+                .replace(/[\b]/g, "\\b")
+                .replace(/[\n]/g, "\\n")
+                .replace(/[\t]/g, "\\t")
+                .replace(/[\r]/g, "\\r")
+                .replace(/[\u2028]/g, "\\u2028")
+                .replace(/[\u2029]/g, "\\u2029");
+        },
+
+        createXhr: masterConfig.createXhr || function () {
+            //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
+            var xhr, i, progId;
+            if (typeof XMLHttpRequest !== "undefined") {
+                return new XMLHttpRequest();
+            } else if (typeof ActiveXObject !== "undefined") {
+                for (i = 0; i < 3; i += 1) {
+                    progId = progIds[i];
+                    try {
+                        xhr = new ActiveXObject(progId);
+                    } catch (e) {}
+
+                    if (xhr) {
+                        progIds = [progId];  // so faster next time
+                        break;
+                    }
+                }
+            }
+
+            return xhr;
+        },
+
+        /**
+         * Parses a resource name into its component parts. Resource names
+         * look like: module/name.ext!strip, where the !strip part is
+         * optional.
+         * @param {String} name the resource name
+         * @returns {Object} with properties "moduleName", "ext" and "strip"
+         * where strip is a boolean.
+         */
+        parseName: function (name) {
+            var modName, ext, temp,
+                strip = false,
+                index = name.lastIndexOf("."),
+                isRelative = name.indexOf('./') === 0 ||
+                             name.indexOf('../') === 0;
+
+            if (index !== -1 && (!isRelative || index > 1)) {
+                modName = name.substring(0, index);
+                ext = name.substring(index + 1);
+            } else {
+                modName = name;
+            }
+
+            temp = ext || modName;
+            index = temp.indexOf("!");
+            if (index !== -1) {
+                //Pull off the strip arg.
+                strip = temp.substring(index + 1) === "strip";
+                temp = temp.substring(0, index);
+                if (ext) {
+                    ext = temp;
+                } else {
+                    modName = temp;
+                }
+            }
+
+            return {
+                moduleName: modName,
+                ext: ext,
+                strip: strip
+            };
+        },
+
+        xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/,
+
+        /**
+         * Is an URL on another domain. Only works for browser use, returns
+         * false in non-browser environments. Only used to know if an
+         * optimized .js version of a text resource should be loaded
+         * instead.
+         * @param {String} url
+         * @returns Boolean
+         */
+        useXhr: function (url, protocol, hostname, port) {
+            var uProtocol, uHostName, uPort,
+                match = text.xdRegExp.exec(url);
+            if (!match) {
+                return true;
+            }
+            uProtocol = match[2];
+            uHostName = match[3];
+
+            uHostName = uHostName.split(':');
+            uPort = uHostName[1];
+            uHostName = uHostName[0];
+
+            return (!uProtocol || uProtocol === protocol) &&
+                   (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) &&
+                   ((!uPort && !uHostName) || isSamePort(uProtocol, uPort, protocol, port));
+        },
+
+        finishLoad: function (name, strip, content, onLoad) {
+            content = strip ? text.strip(content) : content;
+            if (masterConfig.isBuild) {
+                buildMap[name] = content;
+            }
+            onLoad(content);
+        },
+
+        load: function (name, req, onLoad, config) {
+            //Name has format: some.module.filext!strip
+            //The strip part is optional.
+            //if strip is present, then that means only get the string contents
+            //inside a body tag in an HTML string. For XML/SVG content it means
+            //removing the <?xml ...?> declarations so the content can be inserted
+            //into the current doc without problems.
+
+            // Do not bother with the work if a build and text will
+            // not be inlined.
+            if (config && config.isBuild && !config.inlineText) {
+                onLoad();
+                return;
+            }
+
+            masterConfig.isBuild = config && config.isBuild;
+
+            var parsed = text.parseName(name),
+                nonStripName = parsed.moduleName +
+                    (parsed.ext ? '.' + parsed.ext : ''),
+                url = req.toUrl(nonStripName),
+                useXhr = (masterConfig.useXhr) ||
+                         text.useXhr;
+
+            // Do not load if it is an empty: url
+            if (url.indexOf('empty:') === 0) {
+                onLoad();
+                return;
+            }
+
+            //Load the text. Use XHR if possible and in a browser.
+            if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) {
+                text.get(url, function (content) {
+                    text.finishLoad(name, parsed.strip, content, onLoad);
+                }, function (err) {
+                    if (onLoad.error) {
+                        onLoad.error(err);
+                    }
+                });
+            } else {
+                //Need to fetch the resource across domains. Assume
+                //the resource has been optimized into a JS module. Fetch
+                //by the module name + extension, but do not include the
+                //!strip part to avoid file system issues.
+                req([nonStripName], function (content) {
+                    text.finishLoad(parsed.moduleName + '.' + parsed.ext,
+                                    parsed.strip, content, onLoad);
+                });
+            }
+        },
+
+        write: function (pluginName, moduleName, write, config) {
+            if (buildMap.hasOwnProperty(moduleName)) {
+                var content = text.jsEscape(buildMap[moduleName]);
+                write.asModule(pluginName + "!" + moduleName,
+                               "define(function () { return '" +
+                                   content +
+                               "';});\n");
+            }
+        },
+
+        writeFile: function (pluginName, moduleName, req, write, config) {
+            var parsed = text.parseName(moduleName),
+                extPart = parsed.ext ? '.' + parsed.ext : '',
+                nonStripName = parsed.moduleName + extPart,
+                //Use a '.js' file name so that it indicates it is a
+                //script that can be loaded across domains.
+                fileName = req.toUrl(parsed.moduleName + extPart) + '.js';
+
+            //Leverage own load() method to load plugin value, but only
+            //write out values that do not have the strip argument,
+            //to avoid any potential issues with ! in file names.
+            text.load(nonStripName, req, function (value) {
+                //Use own write() method to construct full module value.
+                //But need to create shell that translates writeFile's
+                //write() to the right interface.
+                var textWrite = function (contents) {
+                    return write(fileName, contents);
+                };
+                textWrite.asModule = function (moduleName, contents) {
+                    return write.asModule(moduleName, fileName, contents);
+                };
+
+                text.write(pluginName, nonStripName, textWrite, config);
+            }, config);
+        }
+    };
+
+    if (masterConfig.env === 'node' || (!masterConfig.env &&
+            typeof process !== "undefined" &&
+            process.versions &&
+            !!process.versions.node &&
+            !process.versions['node-webkit'] &&
+            !process.versions['atom-shell'])) {
+        //Using special require.nodeRequire, something added by r.js.
+        fs = require.nodeRequire('fs');
+
+        text.get = function (url, callback, errback) {
+            try {
+                var file = fs.readFileSync(url, 'utf8');
+                //Remove BOM (Byte Mark Order) from utf8 files if it is there.
+                if (file[0] === '\uFEFF') {
+                    file = file.substring(1);
+                }
+                callback(file);
+            } catch (e) {
+                if (errback) {
+                    errback(e);
+                }
+            }
+        };
+    } else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
+            text.createXhr())) {
+        text.get = function (url, callback, errback, headers) {
+            var xhr = text.createXhr(), header;
+            xhr.open('GET', url, true);
+
+            //Allow plugins direct access to xhr headers
+            if (headers) {
+                for (header in headers) {
+                    if (headers.hasOwnProperty(header)) {
+                        xhr.setRequestHeader(header.toLowerCase(), headers[header]);
+                    }
+                }
+            }
+
+            //Allow overrides specified in config
+            if (masterConfig.onXhr) {
+                masterConfig.onXhr(xhr, url);
+            }
+
+            xhr.onreadystatechange = function (evt) {
+                var status, err;
+                //Do not explicitly handle errors, those should be
+                //visible via console output in the browser.
+                if (xhr.readyState === 4) {
+                    status = xhr.status || 0;
+                    if (status > 399 && status < 600) {
+                        //An http 4xx or 5xx error. Signal an error.
+                        err = new Error(url + ' HTTP status: ' + status);
+                        err.xhr = xhr;
+                        if (errback) {
+                            errback(err);
+                        }
+                    } else {
+                        callback(xhr.responseText);
+                    }
+
+                    if (masterConfig.onXhrComplete) {
+                        masterConfig.onXhrComplete(xhr, url);
+                    }
+                }
+            };
+            xhr.send(null);
+        };
+    } else if (masterConfig.env === 'rhino' || (!masterConfig.env &&
+            typeof Packages !== 'undefined' && typeof java !== 'undefined')) {
+        //Why Java, why is this so awkward?
+        text.get = function (url, callback) {
+            var stringBuffer, line,
+                encoding = "utf-8",
+                file = new java.io.File(url),
+                lineSeparator = java.lang.System.getProperty("line.separator"),
+                input = new java.io.BufferedReader(new java.io.InputStreamReader(new 
java.io.FileInputStream(file), encoding)),
+                content = '';
+            try {
+                stringBuffer = new java.lang.StringBuffer();
+                line = input.readLine();
+
+                // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
+                // http://www.unicode.org/faq/utf_bom.html
+
+                // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to 
this bug in the JDK:
+                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
+                if (line && line.length() && line.charAt(0) === 0xfeff) {
+                    // Eat the BOM, since we've already found the encoding on this file,
+                    // and we plan to concatenating this buffer with others; the BOM should
+                    // only appear at the top of a file.
+                    line = line.substring(1);
+                }
+
+                if (line !== null) {
+                    stringBuffer.append(line);
+                }
+
+                while ((line = input.readLine()) !== null) {
+                    stringBuffer.append(lineSeparator);
+                    stringBuffer.append(line);
+                }
+                //Make sure we return a JavaScript string and not a Java string.
+                content = String(stringBuffer.toString()); //String
+            } finally {
+                input.close();
+            }
+            callback(content);
+        };
+    } else if (masterConfig.env === 'xpconnect' || (!masterConfig.env &&
+            typeof Components !== 'undefined' && Components.classes &&
+            Components.interfaces)) {
+        //Avert your gaze!
+        Cc = Components.classes;
+        Ci = Components.interfaces;
+        Components.utils['import']('resource://gre/modules/FileUtils.jsm');
+        xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc);
+
+        text.get = function (url, callback) {
+            var inStream, convertStream, fileObj,
+                readData = {};
+
+            if (xpcIsWindows) {
+                url = url.replace(/\//g, '\\');
+            }
+
+            fileObj = new FileUtils.File(url);
+
+            //XPCOM, you so crazy
+            try {
+                inStream = Cc['@mozilla.org/network/file-input-stream;1']
+                           .createInstance(Ci.nsIFileInputStream);
+                inStream.init(fileObj, 1, 0, false);
+
+                convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
+                                .createInstance(Ci.nsIConverterInputStream);
+                convertStream.init(inStream, "utf-8", inStream.available(),
+                Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
+
+                convertStream.readString(inStream.available(), readData);
+                convertStream.close();
+                inStream.close();
+                callback(readData.value);
+            } catch (e) {
+                throw new Error((fileObj && fileObj.path || '') + ': ' + e);
+            }
+        };
+    }
+    return text;
+});


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]