/*\ title: $:/boot/boot.js type: application/javascript The main boot kernel for TiddlyWiki. This single file creates a barebones TW environment that is just sufficient to bootstrap the modules containing the main logic of the application. On the server this file is executed directly to boot TiddlyWiki. In the browser, this file is packed into a single HTML file along with other elements: # bootprefix.js # # boot.js The module definitions on the browser look like this: $tw.defineModule("MyModule","moduletype",function(module,exports,require) { // Module code inserted here return exports; }); In practice, each module is wrapped in a separate script block. \*/ var _boot = (function($tw) { /*jslint node: true, browser: true */ /*global modules: false, $tw: false */ "use strict"; // Include bootprefix if we're not given module data if(!$tw) { $tw = require("./bootprefix.js").bootprefix(); } $tw.utils = $tw.utils || {}; $tw.boot = $tw.boot || {}; /////////////////////////// Standard node.js libraries var fs, path, vm; if(!$tw.browser) { fs = require("fs"); path = require("path"); vm = require("vm"); } /////////////////////////// Utility functions /* Log a message */ $tw.utils.log = function(/* args */) { if(console !== undefined && console.log !== undefined) { return Function.apply.call(console.log, console, arguments); } }; /* Check if an object has a property */ $tw.utils.hop = function(object,property) { return object ? Object.prototype.hasOwnProperty.call(object,property) : false; }; /* Determine if a value is an array */ $tw.utils.isArray = function(value) { return Object.prototype.toString.call(value) == "[object Array]"; }; /* Determine if a value is a date */ $tw.utils.isDate = function(value) { return Object.prototype.toString.call(value) === "[object Date]"; }; /* Iterate through all the own properties of an object or array. Callback is invoked with (element,title,object) */ $tw.utils.each = function(object,callback) { var f; if(object) { if($tw.utils.isArray(object)) { for(f=0; f and """ to " */ $tw.utils.htmlDecode = function(s) { return s.toString().replace(/</mg,"<").replace(/ /mg,"\x40").replace(/>/mg,">").replace(/"/mg,"\"").replace(/&/mg,"&"); }; /* Pad a string to a given length with "0"s. Length defaults to 2 */ $tw.utils.pad = function(value,length) { length = length || 2; var s = value.toString(); if(s.length < length) { s = "000000000000000000000000000".substr(0,length - s.length) + s; } return s; }; // Convert a date into UTC YYYYMMDDHHMMSSmmm format $tw.utils.stringifyDate = function(value) { return value.getUTCFullYear() + $tw.utils.pad(value.getUTCMonth() + 1) + $tw.utils.pad(value.getUTCDate()) + $tw.utils.pad(value.getUTCHours()) + $tw.utils.pad(value.getUTCMinutes()) + $tw.utils.pad(value.getUTCSeconds()) + $tw.utils.pad(value.getUTCMilliseconds(),3); }; // Parse a date from a UTC YYYYMMDDHHMMSSmmm format string $tw.utils.parseDate = function(value) { if(typeof value === "string") { return new Date(Date.UTC(parseInt(value.substr(0,4),10), parseInt(value.substr(4,2),10)-1, parseInt(value.substr(6,2),10), parseInt(value.substr(8,2)||"00",10), parseInt(value.substr(10,2)||"00",10), parseInt(value.substr(12,2)||"00",10), parseInt(value.substr(14,3)||"000",10))); } else if($tw.utils.isDate(value)) { return value; } else { return null; } }; // Stringify an array of tiddler titles into a list string $tw.utils.stringifyList = function(value) { var result = []; for(var t=0; t 0) { var c = src.shift(); if(c === "..") { // Slice off the last root entry for a double dot if(root.length > 0) { root.splice(root.length-1,1); } } else if(c !== ".") { // Ignore dots root.push(c); // Copy other elements across } } return root.join("/"); } else { // If it isn't relative, just return the path if(rootpath) { var root = rootpath.split("/"); // Remove the filename part of the root root.splice(root.length - 1, 1); return root.join("/") + "/" + sourcepath; } else { return sourcepath; } } }; /* Parse a semantic version string into its constituent parts */ $tw.utils.parseVersion = function(version) { var match = /^((\d+)\.(\d+)\.(\d+))(?:-([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?(?:\+([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?$/.exec(version); if(match) { return { version: match[1], major: parseInt(match[2],10), minor: parseInt(match[3],10), patch: parseInt(match[4],10), prerelease: match[5], build: match[6] }; } else { return null; } }; /* Returns true if the version string A is greater than the version string B */ $tw.utils.checkVersions = function(versionStringA,versionStringB) { var versionA = $tw.utils.parseVersion(versionStringA), versionB = $tw.utils.parseVersion(versionStringB), diff = [ versionA.major - versionB.major, versionA.minor - versionB.minor, versionA.patch - versionB.patch ]; return (diff[0] > 0) || (diff[0] === 0 && diff[1] > 0) || (diff[0] === 0 && diff[1] === 0 && diff[2] > 0); }; /* Register file type information */ $tw.utils.registerFileType = function(type,encoding,extension) { $tw.config.fileExtensionInfo[extension] = {type: type}; $tw.config.contentTypeInfo[type] = {encoding: encoding, extension: extension}; }; /* Run code globally with specified context variables in scope */ $tw.utils.evalGlobal = function(code,context,filename) { var contextCopy = $tw.utils.extend({},context); // Get the context variables as a pair of arrays of names and values var contextNames = [], contextValues = []; $tw.utils.each(contextCopy,function(value,name) { contextNames.push(name); contextValues.push(value); }); // Add the code prologue and epilogue code = "(function(" + contextNames.join(",") + ") {(function(){\n" + code + ";})();\nreturn exports;\n})\n"; // Compile the code into a function var fn; if($tw.browser) { fn = window["eval"](code); } else { fn = vm.runInThisContext(code,filename); } // Call the function and return the exports return fn.apply(null,contextValues); }; /* Run code in a sandbox with only the specified context variables in scope */ $tw.utils.evalSandboxed = $tw.browser ? $tw.utils.evalGlobal : function(code,context,filename) { var sandbox = $tw.utils.extend({},context); vm.runInNewContext(code,sandbox,filename); return sandbox.exports; }; /* Creates a PasswordPrompt object */ $tw.utils.PasswordPrompt = function() { // Store of pending password prompts this.passwordPrompts = []; // Create the wrapper this.promptWrapper = $tw.utils.domMaker("div",{"class":"tw-password-wrapper"}); document.body.appendChild(this.promptWrapper); // Hide the empty wrapper this.setWrapperDisplay(); }; /* Hides or shows the wrapper depending on whether there are any outstanding prompts */ $tw.utils.PasswordPrompt.prototype.setWrapperDisplay = function() { if(this.passwordPrompts.length) { this.promptWrapper.style.display = "block"; } else { this.promptWrapper.style.display = "none"; } }; /* Adds a new password prompt. Options are: submitText: text to use for submit button (defaults to "Login") serviceName: text of the human readable service name noUserName: set true to disable username prompt callback: function to be called on submission with parameter of object {username:,password:}. Callback must return `true` to remove the password prompt */ $tw.utils.PasswordPrompt.prototype.createPrompt = function(options) { // Create and add the prompt to the DOM var submitText = options.submitText || "Login", dm = $tw.utils.domMaker, children = [dm("h1",{text: options.serviceName})]; if(!options.noUserName) { children.push(dm("input",{ attributes: {type: "text", name: "username", placeholder: "Username"}, "class": "input-small" })); } children.push(dm("input",{ attributes: {type: "password", name: "password", placeholder: "Password"}, "class": "input-small" })); children.push(dm("button",{ attributes: {type: "submit"}, text: submitText, "class": "btn" })); var form = dm("form",{ "class": "form-inline", attributes: {autocomplete: "off"}, children: children }); this.promptWrapper.appendChild(form); window.setTimeout(function() { form.elements[0].focus(); },10); // Add a submit event handler var self = this; form.addEventListener("submit",function(event) { // Collect the form data var data = {},t; $tw.utils.each(form.elements,function(element) { if(element.name && element.value) { data[element.name] = element.value; } }); // Call the callback if(options.callback(data)) { // Remove the prompt if the callback returned true var i = self.passwordPrompts.indexOf(promptInfo); if(i !== -1) { self.passwordPrompts.splice(i,1); promptInfo.form.parentNode.removeChild(promptInfo.form); self.setWrapperDisplay(); } } else { // Clear the password if the callback returned false $tw.utils.each(form.elements,function(element) { if(element.name === "password") { element.value = ""; } }); } event.preventDefault(); return false; },true); // Add the prompt to the list var promptInfo = { serviceName: options.serviceName, callback: options.callback, form: form }; this.passwordPrompts.push(promptInfo); // Make sure the wrapper is displayed this.setWrapperDisplay(); }; /* Crypto helper object for encrypted content. It maintains the password text in a closure, and provides methods to change the password, and to encrypt/decrypt a block of text */ $tw.utils.Crypto = function() { var sjcl = $tw.browser ? window.sjcl : require("./sjcl.js"), password = null, callSjcl = function(method,inputText) { var outputText; try { outputText = sjcl[method](password,inputText); } catch(ex) { console.log("Crypto error:" + ex); outputText = null; } return outputText; }; this.setPassword = function(newPassword) { password = newPassword; this.updateCryptoStateTiddler(); }; this.updateCryptoStateTiddler = function() { if($tw.wiki && $tw.wiki.addTiddler) { $tw.wiki.addTiddler(new $tw.Tiddler({title: "$:/isEncrypted", text: password ? "yes" : "no"})); } }; this.hasPassword = function() { return !!password; } this.encrypt = function(text) { return callSjcl("encrypt",text); }; this.decrypt = function(text) { return callSjcl("decrypt",text); }; }; /////////////////////////// Module mechanism /* Execute the module named 'moduleName'. The name can optionally be relative to the module named 'moduleRoot' */ $tw.modules.execute = function(moduleName,moduleRoot) { var name = moduleName[0] === "." ? $tw.utils.resolvePath(moduleName,moduleRoot) : moduleName, moduleInfo = $tw.modules.titles[name] || $tw.modules.titles[name + ".js"] || $tw.modules.titles[moduleName] || $tw.modules.titles[moduleName + ".js"] , tiddler = $tw.wiki.getTiddler(name) || $tw.wiki.getTiddler(name + ".js") || $tw.wiki.getTiddler(moduleName) || $tw.wiki.getTiddler(moduleName + ".js") , _exports = {}, sandbox = { module: {}, //moduleInfo: moduleInfo, exports: _exports, console: console, setInterval: setInterval, clearInterval: clearInterval, setTimeout: setTimeout, clearTimeout: clearTimeout, Buffer: $tw.browser ? {} : Buffer, $tw: $tw, require: function(title) { return $tw.modules.execute(title, name); } }; Object.defineProperty(sandbox.module, "id", { value: name, writable: false, enumerable: true, configurable: false }); if(!$tw.browser) { $tw.utils.extend(sandbox,{ process: process }); } else { /* CommonJS optional require.main property: In a browser we offer a fake main module which points back to the boot function (Theoretically, this may allow TW to eventually load itself as a module in the browser) */ Object.defineProperty(sandbox.require, "main", { value: (typeof(require) !== "undefined") ? require.main : {TiddlyWiki: _boot}, writable: false, enumerable: true, configurable: false }); } if(!moduleInfo) { // We could not find the module on this path // Try to defer to browserify etc, or node var deferredModule; if($tw.browser) { if(window.require) { try { return window.require(moduleName); } catch(e) {} } throw "Cannot find module named '" + moduleName + "' required by module '" + moduleRoot + "', resolved to " + name; } else { // If we don't have a module with that name, let node.js try to find it return require(moduleName); } } // Execute the module if we haven't already done so if(!moduleInfo.exports) { try { // Check the type of the definition if(typeof moduleInfo.definition === "function") { // Function moduleInfo.exports = _exports; moduleInfo.definition(moduleInfo,moduleInfo.exports,sandbox.require); } else if(typeof moduleInfo.definition === "string") { // String moduleInfo.exports = _exports; $tw.utils.evalSandboxed(moduleInfo.definition,sandbox,tiddler.fields.title); } else { // Object moduleInfo.exports = moduleInfo.definition; } } catch(e) { $tw.utils.error("Error executing boot module " + name + ":\n" + e); } } // Return the exports of the module return moduleInfo.exports; }; /* Apply a callback to each module of a particular type moduleType: type of modules to enumerate callback: function called as callback(title,moduleExports) for each module */ $tw.modules.forEachModuleOfType = function(moduleType,callback) { var modules = $tw.modules.types[moduleType]; $tw.utils.each(modules,function(element,title,object) { callback(title,$tw.modules.execute(title)); }); }; /* Get all the modules of a particular type in a hashmap by their `name` field */ $tw.modules.getModulesByTypeAsHashmap = function(moduleType,nameField) { nameField = nameField || "name"; var results = {}; $tw.modules.forEachModuleOfType(moduleType,function(title,module) { results[module[nameField]] = module; }); return results; }; /* Apply the exports of the modules of a particular type to a target object */ $tw.modules.applyMethods = function(moduleType,targetObject) { if(!targetObject) { targetObject = {}; } $tw.modules.forEachModuleOfType(moduleType,function(title,module) { $tw.utils.each(module,function(element,title,object) { targetObject[title] = module[title]; }); }); return targetObject; }; /* Return an array of classes created from the modules of a specified type. Each module should export the properties to be added to those of the optional base class */ $tw.modules.createClassesFromModules = function(moduleType,subType,baseClass) { var classes = {}; $tw.modules.forEachModuleOfType(moduleType,function(title,moduleExports) { if(!subType || moduleExports.types[subType]) { var newClass = function() {}; if(baseClass) { newClass.prototype = new baseClass(); newClass.prototype.constructor = baseClass; } $tw.utils.extend(newClass.prototype,moduleExports); classes[moduleExports.name] = newClass; } }); return classes; }; /////////////////////////// Barebones tiddler object /* Construct a tiddler object from a hashmap of tiddler fields. If multiple hasmaps are provided they are merged, taking precedence to the right */ $tw.Tiddler = function(/* [fields,] fields */) { this.fields = {}; for(var c=0; c=0; t--) { var tiddler = this.plugins[t]; if(tiddler.fields["plugin-type"] === pluginType) { titles.push(tiddler.fields.title); this.plugins.splice(t,1); } } return titles; }; /* Unpack the currently registered plugins, creating shadow tiddlers for their constituent tiddlers */ $tw.Wiki.prototype.unpackPluginTiddlers = function() { var self = this; // Sort the plugin titles by the `plugin-priority` field this.plugins.sort(function(a,b) { if("plugin-priority" in a.fields && "plugin-priority" in b.fields) { return a.fields["plugin-priority"] - b.fields["plugin-priority"]; } else if("plugin-priority" in a.fields) { return -1; } else if("plugin-priority" in b.fields) { return +1; } else if(a.fields.title < b.fields.title) { return -1; } else if(a.fields.title === b.fields.title) { return 0; } else { return +1; } }); // Now go through the plugins in ascending order and assign the shadows this.shadowTiddlers = {}; $tw.utils.each(this.plugins,function(tiddler) { // Get the plugin information var pluginInfo = JSON.parse(tiddler.fields.text); // Extract the constituent tiddlers $tw.utils.each(pluginInfo.tiddlers,function(constituentTiddler,constituentTitle) { // Save the tiddler object if(constituentTitle) { self.shadowTiddlers[constituentTitle] = { source: tiddler.fields.title, tiddler: new $tw.Tiddler(constituentTiddler,{title: constituentTitle}) }; } }); }); }; /* Define all modules stored in ordinary tiddlers */ $tw.Wiki.prototype.defineTiddlerModules = function() { $tw.utils.each(this.tiddlers,function(tiddler,title,object) { if(tiddler.hasField("module-type")) { switch (tiddler.fields.type) { case "application/javascript": // We only define modules that haven't already been defined, because in the browser modules in system tiddlers are defined in inline script if(!$tw.utils.hop($tw.modules.titles,tiddler.fields.title)) { $tw.modules.define(tiddler.fields.title,tiddler.fields["module-type"],tiddler.fields.text); } break; case "application/json": $tw.modules.define(tiddler.fields.title,tiddler.fields["module-type"],JSON.parse(tiddler.fields.text)); break; case "application/x-tiddler-dictionary": $tw.modules.define(tiddler.fields.title,tiddler.fields["module-type"],$tw.utils.parseFields(tiddler.fields.text)); break; } } }); }; /* Register all the module tiddlers that have a module type */ $tw.Wiki.prototype.defineShadowModules = function() { var self = this; $tw.utils.each(this.shadowTiddlers,function(element,title) { var tiddler = self.getTiddler(title); if(!$tw.utils.hop(self.tiddlers,title)) { // Don't define the module if it is overidden by an ordinary tiddler if(tiddler.hasField("module-type")) { // Define the module $tw.modules.define(tiddler.fields.title,tiddler.fields["module-type"],tiddler.fields.text); } } }); }; $tw.Wiki.prototype.getTiddler = function(title) { var t = this.tiddlers[title]; if(t instanceof $tw.Tiddler) { return t; } else if(title !== undefined && $tw.utils.hop(this.shadowTiddlers,title)) { return this.shadowTiddlers[title].tiddler; } else { return undefined; } }; /* Extracts tiddlers from a typed block of text, specifying default field values */ $tw.Wiki.prototype.deserializeTiddlers = function(type,text,srcFields) { srcFields = srcFields || {}; var deserializer = $tw.Wiki.tiddlerDeserializerModules[type], fields = {}; if(!deserializer && $tw.config.fileExtensionInfo[type]) { // If we didn't find the serializer, try converting it from an extension to a content type type = $tw.config.fileExtensionInfo[type].type; deserializer = $tw.Wiki.tiddlerDeserializerModules[type]; } if(!deserializer) { // If we still don't have a deserializer, treat it as plain text deserializer = $tw.Wiki.tiddlerDeserializerModules["text/plain"]; } for(var f in srcFields) { fields[f] = srcFields[f]; } if(deserializer) { return deserializer.call(this,text,fields,type); } else { // Return a raw tiddler for unknown types fields.text = text; return [fields]; } }; /* Register the built in tiddler deserializer modules */ $tw.modules.define("$:/boot/tiddlerdeserializer/js","tiddlerdeserializer",{ "application/javascript": function(text,fields) { var headerCommentRegExp = new RegExp($tw.config.jsModuleHeaderRegExpString,"mg"), match = headerCommentRegExp.exec(text); fields.text = text; if(match) { fields = $tw.utils.parseFields(match[1].split(/\r?\n\r?\n/mg)[0],fields); } return [fields]; } }); $tw.modules.define("$:/boot/tiddlerdeserializer/tid","tiddlerdeserializer",{ "application/x-tiddler": function(text,fields) { var split = text.split(/\r?\n\r?\n/mg); if(split.length >= 1) { fields = $tw.utils.parseFields(split[0],fields); } if(split.length >= 2) { fields.text = split.slice(1).join("\n\n"); } else { fields.text = ""; } return [fields]; } }); $tw.modules.define("$:/boot/tiddlerdeserializer/txt","tiddlerdeserializer",{ "text/plain": function(text,fields,type) { fields.text = text; fields.type = type || "text/plain"; return [fields]; } }); $tw.modules.define("$:/boot/tiddlerdeserializer/html","tiddlerdeserializer",{ "text/html": function(text,fields) { fields.text = text; fields.type = "text/html"; return [fields]; } }); $tw.modules.define("$:/boot/tiddlerdeserializer/json","tiddlerdeserializer",{ "application/json": function(text,fields) { var tiddlers = JSON.parse(text); return tiddlers; } }); /////////////////////////// Browser definitions if($tw.browser) { /* Decrypt any tiddlers stored within the element with the ID "encryptedArea". The function is asynchronous to allow the user to be prompted for a password callback: function to be called the decryption is complete */ $tw.boot.decryptEncryptedTiddlers = function(callback) { var encryptedArea = document.getElementById("encryptedStoreArea"); if(encryptedArea) { var encryptedText = encryptedArea.innerHTML; // Prompt for the password $tw.passwordPrompt.createPrompt({ serviceName: "Enter a password to decrypt this TiddlyWiki", noUserName: true, submitText: "Decrypt", callback: function(data) { // Attempt to decrypt the tiddlers $tw.crypto.setPassword(data.password); var decryptedText = $tw.crypto.decrypt(encryptedText); if(decryptedText) { var json = JSON.parse(decryptedText); for(var title in json) { $tw.preloadTiddler(json[title]); } // Call the callback callback(); // Exit and remove the password prompt return true; } else { // We didn't decrypt everything, so continue to prompt for password return false; } } }); } else { // Just invoke the callback straight away if there weren't any encrypted tiddlers callback(); } }; /* Register a deserializer that can extract tiddlers from the DOM */ $tw.modules.define("$:/boot/tiddlerdeserializer/dom","tiddlerdeserializer",{ "(DOM)": function(node) { var extractTextTiddlers = function(node) { var e = node.firstChild; while(e && e.nodeName.toLowerCase() !== "pre") { e = e.nextSibling; } var title = node.getAttribute ? node.getAttribute("title") : null; if(e && title) { var attrs = node.attributes, tiddler = { text: $tw.utils.htmlDecode(e.innerHTML) }; for(var i=attrs.length-1; i >= 0; i--) { tiddler[attrs[i].name] = attrs[i].value; } return [tiddler]; } else { return null; } }, extractModuleTiddlers = function(node) { if(node.hasAttribute && node.hasAttribute("data-tiddler-title")) { var text = node.innerHTML, s = text.indexOf("{"), e = text.lastIndexOf("}"); if(node.hasAttribute("data-module") && s !== -1 && e !== -1) { text = text.substring(s+1,e); } var fields = {text: text}, attributes = node.attributes; for(var a=0; a