diff options
Diffstat (limited to 'tools/addon-sdk-1.7/packages/api-utils/docs')
48 files changed, 5252 insertions, 0 deletions
diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/api-utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/api-utils.md new file mode 100644 index 0000000..aee88da --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/api-utils.md @@ -0,0 +1,157 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `api-utils` module provides some helpers useful to the SDK's high-level API +implementations. + +Introduction +------------ + +The SDK high-level API design guidelines make a number of recommendations. +This module implements some of those patterns so that your own implementations +don't need to reinvent them. + +For example, public constructors should be callable both with and without the +`new` keyword. Your module can implement this recommendation using the +`publicConstructor` function. + +Options objects or "dictionaries" are also common throughout the high-level +APIs. The guidelines recommend that public constructors should generally define +a single `options` parameter rather than defining many parameters. Since one of +the SDK's principles is to be friendly to developers, ideally all properties on +options dictionaries should be checked for correct type, and informative error +messages should be generated when clients make mistakes. With the +`validateOptions` function, your module can easily do so. + +And objects are sometimes iterable over a custom set of key/value pairs. +Such objects should have custom iterators that let consumers iterate keys, +values, or [key, value] pairs. The `addIterator` function makes it easy to do +so in a way that is consistent with the behavior of default iterators during +`for...in`, `for each...in`, and `for...in Iterator()` loops. + +<api name="publicConstructor"> +@function +Returns a function *C* that creates an instance of `privateConstructor`. *C* +may be called with or without the `new` keyword. + +The prototype of each instance returned from *C* is *C*.`prototype`, and +*C*.`prototype` is an object whose prototype is +`privateConstructor.prototype`. Instances returned from *C* are therefore +instances of both *C* and `privateConstructor`. + +Additionally, the constructor of each instance returned from *C* is *C*. + +Instances returned from *C* are automatically memory tracked using +`memory.track` under the bin name `privateConstructor.name`. + +**Example** + + function MyObject() {} + exports.MyObject = apiUtils.publicConstructor(MyObject); + +@returns {function} +A function that makes new instances of `privateConstructor`. + +@param privateConstructor {constructor} +</api> + +<api name="validateOptions"> +@function +A function to validate an options dictionary according to the specified +constraints. + +`map`, `is`, and `ok` are used in that order. + +The return value is an object whose keys are those keys in `requirements` that +are also in `options` and whose values are the corresponding return values of +`map` or the corresponding values in `options`. Note that any keys not shared +by both `requirements` and `options` are not in the returned object. + +**Examples** + +A typical use: + + var opts = { foo: 1337 }; + var requirements = { + foo: { + map: function (val) val.toString(), + is: ["string"], + ok: function (val) val.length > 0, + msg: "foo must be a non-empty string." + } + }; + var validatedOpts = apiUtils.validateOptions(opts, requirements); + // validatedOpts == { foo: "1337" } + +If the key `foo` is optional and doesn't need to be mapped: + + var opts = { foo: 1337 }; + var validatedOpts = apiUtils.validateOptions(opts, { foo: {} }); + // validatedOpts == { foo: 1337 } + + opts = {}; + validatedOpts = apiUtils.validateOptions(opts, { foo: {} }); + // validatedOpts == {} + +@returns {object} +A validated options dictionary given some requirements. If any of the +requirements are not met, an exception is thrown. + +@param options {object} +The options dictionary to validate. It's not modified. If it's null or +otherwise falsey, an empty object is assumed. + +@param requirements {object} +An object whose keys are the expected keys in `options`. Any key in +`options` that is not present in `requirements` is ignored. Each +value in `requirements` is itself an object describing the requirements +of its key. The keys of that object are the following, and each is optional: + +@prop [map] {function} +A function that's passed the value of the key in the `options`. `map`'s +return value is taken as the key's value in the final validated options, +`is`, and `ok`. If `map` throws an exception it is caught and discarded, +and the key's value is its value in `options`. + +@prop [is] {array} +An array containing the number of `typeof` type names. If the key's value is +none of these types it fails validation. Arrays and nulls are identified by +the special type names "array" and "null"; "object" will not match either. +No type coercion is done. + +@prop [ok] {function} +A function that is passed the key's value. If it returns false, the value +fails validation. + +@prop [msg] {string} +If the key's value fails validation, an exception is thrown. This string +will be used as its message. If undefined, a generic message is used, unless +`is` is defined, in which case the message will state that the value needs to +be one of the given types. +</api> + +<api name="addIterator"> +@function +Adds an iterator to the specified object that iterates keys, values, +or [key, value] pairs depending on how it is invoked, i.e.: + + for (var key in obj) { ... } // iterate keys + for each (var val in obj) { ... } // iterate values + for (var [key, val] in Iterator(obj)) { ... } // iterate pairs + +If your object only iterates either keys or values, you don't need this +function. Simply assign a generator function that iterates the keys/values +to your object's `__iterator__` property instead, f.e.: + + obj.__iterator__ = function () { for each (var i in items) yield i; } + +@param obj {object} +the object to which to add the iterator + +@param keysValsGen {function} +a generator function that yields [key, value] pairs +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/app-strings.md b/tools/addon-sdk-1.7/packages/api-utils/docs/app-strings.md new file mode 100644 index 0000000..c40ddaf --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/app-strings.md @@ -0,0 +1,65 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +The `app-strings` module gives you access to the host application's localized +string bundles (`.properties` files). + +The module exports the `StringBundle` constructor function. To access a string +bundle, construct an instance of `StringBundle`, passing it the bundle's URL: + + var StringBundle = require("app-strings").StringBundle; + var bundle = StringBundle("chrome://browser/locale/browser.properties"); + +To get the value of a string, call the object's `get` method, passing it +the name of the string: + + var accessKey = bundle.get("contextMenuSearchText.accesskey"); + // "S" in the en-US locale + +To get the formatted value of a string that accepts arguments, call the object's +`get` method, passing it the name of the string and an array of arguments +with which to format the string: + + var searchText = bundle.get("contextMenuSearchText", + ["universe", "signs of intelligent life"]); + // 'Search universe for "signs of intelligent life"' in the en-US locale + +To get all strings in the bundle, iterate the object, which returns arrays +of the form [name, value]: + + for (var [name, value] in Iterator(bundle)) + console.log(name + " = " + value); + +Iteration +--------- + +<code>for (var name in bundle) { ... }</code> + +Iterate the names of strings in the bundle. + +<code>for each (var val in bundle) { ... }</code> + +Iterate the values of strings in the bundle. + +<code>for (var [name, value] in Iterator(bundle)) { ... }</code> + +Iterate the names and values of strings in the bundle. + + +<api name="StringBundle"> +@class +The `StringBundle` object represents a string bundle. +<api name="StringBundle"> +@constructor +Creates a StringBundle object that gives you access to a string bundle. +@param url {string} the URL of the string bundle +@returns {StringBundle} the string bundle +</api> +<api name="get"> +@method Get the value of the string with the given name. +@param [name] {string} the name of the string to get +@param [args] {array} (optional) strings that replace placeholders in the string +@returns {string} the value of the string +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/base.md b/tools/addon-sdk-1.7/packages/api-utils/docs/base.md new file mode 100644 index 0000000..7a694f2 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/base.md @@ -0,0 +1,207 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +### Inheritance ### + +Doing [inheritance in JavaScript](https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript) +is both verbose and painful. Reading or writing such code requires requires +sharp eye and lot's of discipline, mainly due to code fragmentation and lots of +machinery exposed: + + // Defining a simple Class + function Dog(name) { + // Classes are for creating instances, calling them without `new` changes + // behavior, which in majority cases you need to handle, so you end up + // with additional boilerplate. + if (!(this instanceof Dog)) return new Dog(name); + + this.name = name; + }; + // To define methods you need to make a dance with a special 'prototype' + // property of the constructor function. This is too much machinery exposed. + Dog.prototype.type = 'dog'; + Dog.prototype.bark = function bark() { + return 'Ruff! Ruff!' + }; + + // Subclassing a `Dog` + function Pet(name, breed) { + // Once again we do our little dance + if (!(this instanceof Pet)) return new Pet(name, breed); + + Dog.call(this, name); + this.breed = breed; + } + // To subclass, you need to make another special dance with special + // 'prototype' properties. + Pet.prototype = Object.create(Dog.prototype); + // If you want correct instanceof behavior you need to make a dance with + // another special `constructor` property of the `prototype` object. + Object.defineProperty(Pet.prototype, 'contsructor', { value: Pet }); + // Finally you can define some properties. + Pet.prototype.call = function(name) { + return this.name === name ? this.bark() : ''; + }; + +An "exemplar" is a factory for instances. Usually exemplars are defined as +(constructor) functions as in examples above. But that does not necessary has +to be the case. Prototype (object) can form far more simpler exemplars. After +all what could be more object oriented than objects that inherit from objects. + + var Dog = { + new: function(name) { + var instance = Object.create(this); + this.initialize.apply(instance, arguments); + return instance; + }, + initialize: function initialize(name) { + this.name = name; + }, + type: 'dog', + bark: function bark() { + return 'Ruff! Ruff!' + } + }; + var fluffy = Dog.new('fluffy'); + + + var Pet = Object.create(Dog); + Pet.initialize = function initialize(name, breed) { + Dog.initialize.call(this, name); + this.breed = breed; + }; + Pet.call = function call(name) { + return this.name === name ? this.bark() : ''; + }; + +While this small trick solves some readability issues, there are still more. To +address them this module exports `Base` exemplar with few methods predefined: + + var Dog = Base.extend({ + initialize: function initialize(name) { + this.name = name; + }, + type: 'dog', + bark: function bark() { + return 'Ruff! Ruff!' + } + }); + + var Pet = Dog.extend({ + initialize: function initialize(name, breed) { + Dog.initialize.call(this, name); + this.breed = breed; + }, + function call(name) { + return this.name === name ? this.bark() : ''; + } + }); + + var fluffy = Dog.new('fluffy'); + dog.bark(); // 'Ruff! Ruff!' + Dog.isPrototypeOf(fluffy); // true + Pet.isPrototypeOf(fluffy); // true + +### Composition ### + +Even though (single) inheritance is very powerful it's not always enough. +Sometimes it's more useful suitable to define reusable pieces of functionality +and then compose bigger pieces out of them: + + var HEX = Base.extend({ + hex: function hex() { + return '#' + this.color + } + }) + + var RGB = Base.extend({ + red: function red() { + return parseInt(this.color.substr(0, 2), 16) + }, + green: function green() { + return parseInt(this.color.substr(2, 2), 16) + }, + blue: function blue() { + return parseInt(this.color.substr(4, 2), 16) + } + }) + + var CMYK = Base.extend(RGB, { + black: function black() { + var color = Math.max(Math.max(this.red(), this.green()), this.blue()) + return (1 - color / 255).toFixed(4) + }, + magenta: function magenta() { + var K = this.black(); + return (((1 - this.green() / 255).toFixed(4) - K) / (1 - K)).toFixed(4) + }, + yellow: function yellow() { + var K = this.black(); + return (((1 - this.blue() / 255).toFixed(4) - K) / (1 - K)).toFixed(4) + }, + cyan: function cyan() { + var K = this.black(); + return (((1 - this.red() / 255).toFixed(4) - K) / (1 - K)).toFixed(4) + } + }) + + // Composing `Color` prototype out of reusable components: + var Color = Base.extend(HEX, RGB, CMYK, { + initialize: function initialize(color) { + this.color = color + } + }) + + var pink = Color.new('FFC0CB') + // RGB + pink.red() // 255 + pink.green() // 192 + pink.blue() // 203 + + // CMYK + pink.magenta() // 0.2471 + pink.yellow() // 0.2039 + pink.cyan() // 0.0000 + +### Combining composition & inheritance ### + +Also it's easy to mix composition with inheritance: + + var Pixel = Color.extend({ + initialize: function initialize(x, y, color) { + Color.initialize.call(this, color) + this.x = x + this.y = y + }, + toString: function toString() { + return this.x + ':' + this.y + '@' + this.hex() + } + }); + + var pixel = Pixel.new(11, 23, 'CC3399'); + pixel.toString() // 11:23@#CC3399 + Pixel.isPrototypeOf(pixel) // true + + // Pixel instances inhertis from `Color` + Color.isPrototypeOf(pixel); // true + + // In fact `Pixel` itself inherits from `Color`, remember just simple and + // pure prototypal inheritance where object inherit from objects. + Color.isPrototypeOf(Pixel); // true + +### Classes ### + +Module exports `Class` function. `Class` takes argument of exemplar object +extending `Base` and returns `constructor` function that can be used for +simulating classes defined by given exemplar. + + var CPixel = Class(Pixel); + var pixel = CPixel(11, 12, '000000'); + pixel instanceof CPixel // true + Pixel.prototypeOf(pixel); // true + + // Use of `new` is optional, but possible. + var p2 = CPixel(17, 2, 'cccccc'); + p2 instanceof CPixel // true + p2.prototypeOf(pixel); // true diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/byte-streams.md b/tools/addon-sdk-1.7/packages/api-utils/docs/byte-streams.md new file mode 100644 index 0000000..1238cd8 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/byte-streams.md @@ -0,0 +1,68 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `byte-streams` module provides streams for reading and writing bytes. + +<api name="ByteReader"> +@class +<api name="ByteReader"> +@constructor + Creates a binary input stream that reads bytes from a backing stream. +@param inputStream {stream} + The backing stream, an <a href="http://mxr.mozilla.org/mozilla-central/ +source/xpcom/io/nsIInputStream.idl"><code>nsIInputStream</code></a>. +</api> +<api name="closed"> +@property {boolean} + True if the stream is closed. +</api> + +<api name="close"> +@method + Closes both the stream and its backing stream. If the stream is already + closed, an exception is thrown. +</api> + +<api name="read"> +@method + Reads a string from the stream. If the stream is closed, an exception is + thrown. +@param [numBytes] {number} + The number of bytes to read. If not given, the remainder of the entire stream + is read. +@returns {string} + A string containing the bytes read. If the stream is at the end, returns the + empty string. +</api> +</api> + +<api name="ByteWriter"> +@class +<api name="ByteWriter"> +@constructor + Creates a binary output stream that writes bytes to a backing stream. +@param outputStream {stream} + The backing stream, an <a href="http://mxr.mozilla.org/mozilla-central/ +source/xpcom/io/nsIOutputStream.idl"><code>nsIOutputStream</code></a>. +</api> +<api name="closed"> +@property {boolean} + True if the stream is closed. +</api> +<api name="close"> +@method + Closes both the stream and its backing stream. If the stream is already + closed, an exception is thrown. +</api> +<api name="write"> +@method + Writes a string to the stream. If the stream is closed, an exception is + thrown. +@param str {string} + The string to write. +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/collection.md b/tools/addon-sdk-1.7/packages/api-utils/docs/collection.md new file mode 100644 index 0000000..1e557c6 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/collection.md @@ -0,0 +1,77 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `collection` module provides a simple list-like class and utilities for +using it. A collection is ordered, like an array, but its items are unique, +like a set. + +<api name="Collection"> +@class +A collection object provides for...in-loop iteration. Items are yielded in the +order they were added. For example, the following code... + + var collection = require("collection"); + var c = new collection.Collection(); + c.add(1); + c.add(2); + c.add(3); + for (item in c) + console.log(item); + +... would print this to the console: + +<pre> + 1 + 2 + 3 +</pre> + +Iteration proceeds over a copy of the collection made before iteration begins, +so it is safe to mutate the collection during iteration; doing so does not +affect the results of the iteration. + +<api name="Collection"> +@constructor +Creates a new collection. The collection is backed by an array. +@param [array] {array} +If *array* is given, it will be used as the backing array. This way the caller +can fully control the collection. Otherwise a new empty array will be used, and +no one but the collection will have access to it. +</api> +<api name="length"> +@property {number} +The number of items in the collection array. +</api> +<api name="add"> +@method +Adds a single item or an array of items to the collection. Any items already +contained in the collection are ignored. +@param itemOrItems {object} An item or array of items. +@returns {Collection} The Collection. +</api> +<api name="remove"> +@method +Removes a single item or an array of items from the collection. Any items not +contained in the collection are ignored. +@param itemOrItems {object} An item or array of items. +@returns {Collection} The Collection. +</api> +</api> + +<api name="addCollectionProperty"> +@function +Adds a collection property to the given object. Setting the property to a +scalar value empties the collection and adds the value. Setting it to an array +empties the collection and adds all the items in the array. +@param object {object} +The property will be defined on this object. +@param propName {string} +The name of the property. +@param [backingArray] {array} +If given, this will be used as the collection's backing array. +</api> + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content.md new file mode 100644 index 0000000..1c25eb4 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/content.md @@ -0,0 +1,15 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> + +The `content` module exports three different traits [Loader][], [Worker][] and +[Symbiont][]. None of this traits is intended to be used directly by programs. +Rather, they are intended to be used by other modules that provide high +level APIs to programs or libraries. + +[Loader]:packages/api-utils/content/loader.html +[Worker]:packages/api-utils/content/worker.html +[Symbiont]:packages/api-utils/content/symbiont.html + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/loader.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/loader.md new file mode 100644 index 0000000..a460476 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/content/loader.md @@ -0,0 +1,92 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> + +Loader is base trait and it provides set of core properties and associated +validations. Trait is useful for all the compositions providing high level +APIs for creating JavaScript contexts that can access web content. + +Loader is composed from the +[EventEmitter](packages/api-utils/events.html) trait, therefore +instances of Loader and their descendants expose all the public properties +exposed by EventEmitter along with additional public properties: + +Value changes on all of the above mentioned properties emit `propertyChange` +events on an instances. + +**Example:** + +The following code creates a wrapper on hidden frame that reloads a web page +in frame every time `contentURL` property is changed: + + var hiddenFrames = require("hidden-frame"); + var { Loader } = require("content"); + var PageLoader = Loader.compose({ + constructor: function PageLoader(options) { + options = options || {}; + if (options.contentURL) + this.contentURL = options.contentURL; + this.on('propertyChange', this._onChange = this._onChange.bind(this)); + let self = this; + hiddenFrames.add(hiddenFrames.HiddenFrame({ + onReady: function onReady() { + let frame = self._frame = this.element; + self._emit('propertyChange', { contentURL: self.contentURL }); + } + })); + }, + _onChange: function _onChange(e) { + if ('contentURL' in e) + this._frame.setAttribute('src', this._contentURL); + } + }); + +<api name="Loader"> +@class +<api name="contentScriptFile"> +@property {array} +The local file URLs of content scripts to load. Content scripts specified by +this property are loaded *before* those specified by the `contentScript` +property. +</api> + +<api name="contentScript"> +@property {array} +The texts of content scripts to load. Content scripts specified by this +property are loaded *after* those specified by the `contentScriptFile` property. +</api> + +<api name="contentScriptWhen"> +@property {string} +When to load the content scripts. This may take one of the following +values: + +* "start": load content scripts immediately after the document +element for the page is inserted into the DOM, but before the DOM content +itself has been loaded +* "ready": load content scripts once DOM content has been loaded, +corresponding to the +[DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) +event +* "end": load content scripts once all the content (DOM, JS, CSS, +images) for the page has been loaded, at the time the +[window.onload event](https://developer.mozilla.org/en/DOM/window.onload) +fires + +</api> + +<api name="contentURL"> +@property {string} +The URL of the content loaded. +</api> + +<api name="allow"> +@property {object} +Permissions for the content, with the following keys: +@prop script {boolean} + Whether or not to execute script in the content. Defaults to true. +</api> +</api> + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/proxy.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/proxy.md new file mode 100644 index 0000000..095e8ff --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/content/proxy.md @@ -0,0 +1,241 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Alexandre Poirot [apoirot@mozilla.com] --> + +Content scripts need access to the DOM of the pages they are attached to. +However, those pages should be considered to be hostile environments: we +have no control over any other scripts loaded by the web page that may be +executing in the same context. If the content scripts and scripts loaded +by the web page were to access the same DOM objects, there are two possible +security problems: + +First, a malicious page might redefine functions and properties of DOM +objects so they don't do what the add-on expects. For example, if a +content script calls `document.getElementById()` to retrieve a DOM +element, then a malicious page could redefine its behavior to return +something unexpected: + +<pre><code> +// If the web document contains the following script: +document.getElementById = function (str) { + // Overload indexOf method of all string instances + str.__proto__.indexOf = function () {return -1;}; + // Overload toString method of all object instances + str.__proto__.__proto__.toString = function () {return "evil";}; +}; +// After the following line, the content script will be compromised: +var node = document.getElementById("element"); +// Then your content script is totally out of control. +</code></pre> + +Second, changes the content script made to the DOM objects would be visible +to the page, leaking information to it. + +The general approach to fixing these problems is to wrap DOM objects in +[`XrayWrappers`](https://developer.mozilla.org/en/XPCNativeWrapper) +(also know as `XPCNativeWrapper`). This guarantees that: + +* when the content script accesses DOM properties and functions it gets the +original native version of them, ignoring any modifications made by the web +page +* changes to the DOM made by the content script are not visible to scripts +running in the page. + +However, `XrayWrapper` has some limitations and bugs, which break many +popular web frameworks. In particular, you can't: + +* define attributes like `onclick`: you have to use `addEventListener` syntax +* overload native methods on DOM objects, like this: +<pre><code> +proxy.addEventListener = function () {}; +</code></pre> +* access named elements using properties like `window[framename]` or +`document[formname]` +* use some other features that have bugs in the `XrayWrapper` +implementation, like `mozMatchesSelector` + +The `proxy` module uses `XrayWrapper` in combination with the +experimental +[Proxy API](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy) +to address both the security vulnerabilities of content scripts and the +limitations of `XrayWrapper`. + +<pre> + /--------------------\ /------------------------\ + | Web document | | Content script sandbox | + | http://mozilla.org | | data/worker.js | + | | require('content-proxy'). | | + | window >-----------|- create(window) -|-> window | + \--------------------/ \------------------------/ +</pre> + + +## The Big Picture ## + +The implementation defines two different kinds of proxy: + + 1. Content script proxies that wrap DOM objects that are exposed to + content scripts as described above. + 2. XrayWrapper proxies that wrap objects from content scripts before handing + them over to XrayWrapper functions. These proxies are internal + and are not exposed to content scripts or document content. + +<pre> + /--------------------\ /------------------------\ + | Web document | | Content script sandbox | + | http://mozilla.org | | data/worker.js | + | | /-------|-> myObject = {} | + | | /----------------v--\ | | + | | | XrayWrapper Proxy | | - document | + | | \---------v---------/ \----^-------------------/ + | | v | + | | /-------------\ /----------\ | + | - document >-------|->| XrayWrapper |<-| CS proxy |-/ + \--------------------/ \-------------/ \----------/ +</pre> + +Everything begins with a single call to the `create` function exported by the +content-proxy module: + + // Retrieve the unwrapped reference to the current web page window object + var win = gBrowser.contentDocument.defaultView.wrappedJSObject; + // Or in addon sdk style + var win = require("tab-browser").activeTab.linkedBrowser.contentWindow.wrappedJSObject; + // Now create a content script proxy for the window object + var windowProxy = require("api-utils/content/content-proxy").create(win); + + // We finally use this window object as sandbox prototype, + // so that all web page globals are accessible in CS too: + var contentScriptSandbox = new Cu.Sandbox(win, { + sandboxPrototype: windowProxy + }); + +Then all other proxies are created from this one. Attempts to access DOM +attributes of this proxy are trapped, and the proxy constructs and returns +content script proxies for those attributes: + + // For example, if you simply do this: + var document = window.document; + // accessing the `document` attribute will be trapped by the `window` content script + // proxy, and that proxy will that create another content script proxy for `document` + +So the main responsibility of the content script proxy implementation is to +ensure that we always return content script proxies to the content script. + +## Internal Implementation ## + +Each content script proxy keeps a reference to the `XrayWrapper` that enables +it to be sure of calling native DOM methods. + +There are two internal functions to convert between content script proxy +values and `XrayWrapper` values. + +1. __`wrap`__ takes an XrayWrapper value and wraps it in a content script +proxy if needed. + This method is called when: + * a content script accesses an attribute of a content script proxy. + * XrayWrapper code calls a callback function defined in the content +script, so that arguments passed into the function by the XrayWrapper are +converted into content script proxies. For example, if a content script +calls `addEventListener`, then the listener function will expect any arguments +to be content script proxies. +<br/><br/> +2. __`unwrap`__ takes an object coming from the content script context and: + * if the object is a content script proxy, unwraps it back to an +XrayWrapper reference + * if the object is not a content script proxy, wraps it in an XrayWrapper +proxy. +<br/><br/> +This means we can call a XrayWrapper method either with: + + * a raw XrayWrapper object. + + // The following line doesn't work if child is a content script proxy, + // it has to be a raw XrayWrapper reference + xrayWrapper.appendChild(child) + + * an XrayWrapper proxy when you pass a custom object from the content +script context. + + var myListener = { + handleEvent: function(event) { + // `event` should be a content script proxy + } + }; + // `myListener` has to be another kind of Proxy: XrayWrapper proxy, + // that aims to catch the call to `handleEvent` in order to wrap its + // arguments in a content script proxy. + xrayWrapper.addEventListener("click", myListener, false); + + +## Stack Traces ## + +The following code: + + function listener(event) { + + } + csProxy.addEventListener("message", listener, false); + +generates the following internal calls: + + -> CS Proxy:: get("addEventListener") + -> wrap(xrayWrapper.addEventListener) + -> NativeFunctionWrapper(xrayWrapper.addEventListener) + // NativeFunctionWrapper generates: + function ("message", listener, false) { + return xraywrapper.addEventListener("message", unwrap(listener), false); + } + -> unwrap(listener) + -> ContentScriptFunctionWrapper(listener) + // ContentScriptFunctionWrapper generates: + function (event) { + return listener(wrap(event)); + } + +<br> + + // First, create an object from content script context + var myListener = { + handleEvent: function (event) { + + } + }; + // Then, pass this object as an argument to a CS proxy method + window.addEventListener("message", myListener, false); + + // Generates the following internal calls: + -> CS Proxy:: get("addEventListener") + -> wrap(xrayWrapper.addEventListener) + -> NativeFunctionWrapper(xrayWrapper.addEventListener) + // Generate the following function: + function ("message", myListener, false) { + return xraywrapper.addEventListener("message", unwrap(myListener), false); + } + -> unwrap(myListener) + -> ContentScriptObjectWrapper(myListener) + // Generate an XrayWrapper proxy and give it to xrayWrapper method. + // Then when native code fires an event, the proxy will catch it: + -> XrayWrapper Proxy:: get("handleEvent") + -> unwrap(myListener.handleEvent) + -> ContentScriptFunctionWrapper(myListener.handleEvent) + // Generate following function: + function (event) { + return myListener.handleEvent(wrap(event)); + } + + +<api name="create"> +@function + Create a content script proxy. <br/> + Doesn't create a proxy if we are not able to create a XrayWrapper for + this object: for example, if the object comes from system principal. + +@param object {Object} + The object to proxify. + +@returns {Object} + A content script proxy that wraps `object`. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/symbiont.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/symbiont.md new file mode 100644 index 0000000..1ff7dd1 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/content/symbiont.md @@ -0,0 +1,140 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Myk Melez [myk@mozilla.org] --> +<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> + + +This module is not intended to be used directly by programs. Rather, it is +intended to be used by other modules that provide APIs to programs. + + +This module exports `Symbiont` trait that can be used for creating JavaScript +contexts that can access web content in host application frames (i.e. XUL +`<iframe>` and `<browser>` elements) and communicate with programs via +asynchronous JSON pipes. It is useful in the construction of APIs that +are compatible with the execution model codenamed "electrolysis" in which +programs run in separate processes from web content. + +Introduction +------------ + +`Symbiont` constructs a content symbiont for a given frame, it loads the +specified contentURL and scripts into it, and plumbs an asynchronous +JSON pipe between the content symbiont object and the content symbiont +context. If frame is not provided hidden frame will be created. + +Examples +-------- + + var { Symbiont } = require('content'); + var Thing = Symbiont.resolve({ constructor: '_init' }).compose({ + constructor: function Thing(options) { + // `getMyFrame` returns the host application frame in which + // the page is loaded. + this._frame = getMyFrame(); + this._init(options) + } + }); + +See the [panel][] module for a real-world example of usage of this module. + +[panel]:packages/addon-kit/panel.html + +Reference +--------- + +<api name="Symbiont"> +@class +Symbiont is composed from the [Worker][] trait, therefore instances +of Symbiont and their descendants expose all the public properties +exposed by [Worker][] along with additional public properties that +are listed below: + +[Worker]:packages/api-utils/content/worker.html + +<api name="Symbiont"> +@constructor +Creates a content symbiont. +@param options {object} + Options for the constructor. Includes all the keys that +the [Worker](packages/api-utils/content/worker.html) +constructor accepts and a few more: + + @prop [frame] {object} + The host application frame in which the page is loaded. + If frame is not provided hidden one will be created. + @prop [contentScriptWhen="end"] {string} + When to load the content scripts. This may take one of the following + values: + + * "start": load content scripts immediately after the document + element for the page is inserted into the DOM, but before the DOM content + itself has been loaded + * "ready": load content scripts once DOM content has been loaded, + corresponding to the + [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) + event + * "end": load content scripts once all the content (DOM, JS, CSS, + images) for the page has been loaded, at the time the + [window.onload event](https://developer.mozilla.org/en/DOM/window.onload) + fires + + This property is optional and defaults to "end". + + @prop [allow] {object} + Permissions for the content, with the following keys: + @prop [script] {boolean} + Whether or not to execute script in the content. Defaults to true. + Optional. + Optional. +</api> + +<api name="contentScriptFile"> +@property {array} +The local file URLs of content scripts to load. Content scripts specified by +this property are loaded *before* those specified by the `contentScript` +property. +</api> + +<api name="contentScript"> +@property {array} +The texts of content scripts to load. Content scripts specified by this +property are loaded *after* those specified by the `contentScriptFile` property. +</api> + +<api name="contentScriptWhen"> +@property {string} +When to load the content scripts. This may have one of the following +values: + +* "start": load content scripts immediately after the document +element for the page is inserted into the DOM, but before the DOM content +itself has been loaded +* "ready": load content scripts once DOM content has been loaded, +corresponding to the +[DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) +event +* "end": load content scripts once all the content (DOM, JS, CSS, +images) for the page has been loaded, at the time the +[window.onload event](https://developer.mozilla.org/en/DOM/window.onload) +fires + +</api> + +<api name="contentURL"> +@property {string} +The URL of the content loaded. +</api> + +<api name="allow"> +@property {object} +Permissions for the content, with a single boolean key called `script` which +defaults to true and indicates whether or not to execute scripts in the +content. +</api> + +</api> + + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/content/worker.md b/tools/addon-sdk-1.7/packages/api-utils/docs/content/worker.md new file mode 100644 index 0000000..b3e17ea --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/content/worker.md @@ -0,0 +1,130 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> + +This module exports the `Worker` trait, which may be used to construct objects +implementing the [Worker][] interface defined by the W3C, with minor +differences. + +Content workers are message-passing facilities for communication between +[content scripts](dev-guide/guides/content-scripts/index.html) and the main +add-on code. + +It is important to note that unlike "web workers," these workers run in the +same process as web content and browser chrome, so code within workers can +block the UI. + +[Worker]:http://www.w3.org/TR/workers/#worker + +<api name="Worker"> +@class +Worker is composed from the [EventEmitter][] trait, therefore instances +of Worker and their descendants expose all the public properties +exposed by [EventEmitter][] along with additional public properties that +are listed below. + +**Example** + + var workers = require("content/worker"); + let worker = workers.Worker({ + window: require("window-utils").activeWindow, + contentScript: + "self.port.on('hello', function(name) { " + + " self.port.emit('response', window.location); " + + "});" + }); + worker.port.emit("hello", { name: "worker"}); + worker.port.on("response", function (location) { + console.log(location); + }); + +[EventEmitter]:packages/api-utils/events.html + +<api name="Worker"> +@constructor +Creates a content worker. +@param options {object} +Options for the constructor, with the following keys: + @prop window {object} + The content window to create JavaScript sandbox for communication with. + @prop [contentScriptFile] {string,array} + The local file URLs of content scripts to load. Content scripts specified + by this option are loaded *before* those specified by the `contentScript` + option. Optional. + @prop [contentScript] {string,array} + The texts of content scripts to load. Content scripts specified by this + option are loaded *after* those specified by the `contentScriptFile` option. + Optional. + @prop [onMessage] {function} + Functions that will registered as a listener to a 'message' events. + @prop [onError] {function} + Functions that will registered as a listener to an 'error' events. +</api> + +<api name="port"> +@property {EventEmitter} +[EventEmitter](packages/api-utils/events.html) object that allows you to: + +* send customized messages to the worker using the `port.emit` function +* receive events from the worker using the `port.on` function + +</api> + +<api name="postMessage"> +@method +Asynchronously emits `"message"` events in the enclosed worker, where content +script was loaded. +@param data {number,string,JSON} +The data to send. Must be stringifiable to JSON. +</api> + +<api name="destroy"> +@method +Destroy the worker by removing the content script from the page and removing +all registered listeners. A `detach` event is fired just before removal. +</api> + +<api name="url"> +@property {string} +The URL of the content. +</api> + +<api name="tab"> +@property {object} +If this worker is attached to a content document, returns the related +[tab](packages/addon-kit/tabs.html). +</api> + +<api name="message"> +@event +This event allows the content worker to receive messages from its associated +content scripts. Calling the `self.postMessage()` function from a content +script will asynchronously emit the `message` event on the corresponding +worker. + +@argument {value} +The event listener is passed the message, which must be a +<a href = "dev-guide/guides/content-scripts/using-port.html#json_serializable">JSON-serializable value</a>. +</api> + +<api name="error"> +@event +This event allows the content worker to react to an uncaught runtime script +error that occurs in one of the content scripts. + +@argument {Error} +The event listener is passed a single argument which is an +[Error](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error) +object. +</api> + +<api name="detach"> +@event +This event is emitted when the document associated with this worker is unloaded +or the worker's `destroy()` method is called. +</api> + +</api> + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/cortex.md b/tools/addon-sdk-1.7/packages/api-utils/docs/cortex.md new file mode 100644 index 0000000..afae8cb --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/cortex.md @@ -0,0 +1,160 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + + +## Property Encapsulation ## + +In JavaScript it is not possible to create properties that have limited or +controlled accessibility. It is possible to create non-enumerable and +non-writable properties, but still they can be discovered and accessed. +Usually so called "closure capturing" is used to encapsulate such properties +in lexical scope: + + function Foo() { + var _secret = 'secret'; + this.hello = function hello() { + return 'Hello ' + _secret; + } + } + +This provides desired result, but has side effect of degrading code readability, +especially with object-oriented programs. Another disadvantage with this pattern +is that there is no immediate solution for inheriting access to the privates +(illustrated by the following example): + + function Derived() { + this.hello = function hello() { + return _secret; + } + this.bye = function bye() { + return _secret; + } + } + Derived.prototype = Object.create(Foo.prototype); + +## Facade Objects ## + +Alternatively constructor can returned facade objects - proxies to the +instance's public properties: + + function Foo() { + var foo = Object.create(Foo.prototype); + return { + bar: foo.hello.bind(foo); + } + } + Foo.prototype._secret = 'secret'; + Foo.prototype.hello = function hello() { + return 'Hello ' + this._secret; + } + + function Derived() { + var derived = Object.create(Derived.prototype); + return { + bar: derived.hello.bind(derived); + bye: derived.bye.bind(derived); + } + } + Derived.prototype = Object.create(Foo.prototype); + Derived.prototype.bye = function bye() { + return 'Bye ' + this._secret; + }; + +While this solution solves given issue and provides proper encapsulation for +both own and inherited private properties, it does not addresses following: + + - Privates defined on the `prototype` can be compromised, since they are + accessible through the constructor (`Foo.prototype._secret`). + - Behavior of `instanceof` is broken, since `new Derived() instanceof Derived` + is going to evaluate to `false`. + +## Tamper Proofing with Property Descriptor Maps ## + +In ES5 new property descriptor maps were introduced, which can be used as a +building blocks for defining reusable peace of functionality. To some degree +they are similar to a `prototype` objects, and can be used so to define pieces +of functionality that is considered to be private (In contrast to `prototype` +they are not exposed by default). + + function Foo() { + var foo = Object.create(Foo.prototype, FooDescriptor); + var facade = Object.create(Foo.prototype); + facade.hello = foo.hello.bind(foo); + return facade; + } + Foo.prototype.hello = function hello() { + return 'Hello ' + this._secret; + } + var FooDescriptor = { + _secret: { value: 'secret' }; + } + + function Derived() { + var derived = Object.create(Derived.prototype, DerivedDescriptor); + var facade = Object.create(Derived.prototype); + facade.hello = derived.hello.bind(derived); + facade.bye = derived.bye.bind(derived); + return facade; + } + Derived.prototype = Object.create(Foo.prototype); + Derived.prototype.bye = function bye() { + return 'Bye ' + this._secret; + }; + DerivedDescriptor = {}; + + Object.keys(FooDescriptor).forEach(function(key) { + DerivedDescriptor[key] = FooDescriptor[key]; + }); + +## Cortex Objects ## + +Last approach solves all of the concerns, but adds complexity, verbosity +and decreases code readability. Combination of `Cortex`'s and `Trait`'s +will gracefully solve all these issues and keep code clean: + + var Cortex = require('cortex').Cortex; + var Trait = require('light-traits').Trait; + + var FooTrait = Trait({ + _secret: 'secret', + hello: function hello() { + return 'Hello ' + this._secret; + } + }); + function Foo() { + return Cortex(FooTrait.create(Foo.prototype)); + } + + var DerivedTrait = Trait.compose(FooTrait, Trait({ + bye: function bye() { + return 'Bye ' + this._secret; + } + })); + function Derived() { + var derived = DerivedTrait.create(Derived.prototype); + return Cortex(derived); + } + +Function `Cortex` takes any object and returns a proxy for its public +properties. By default properties are considered to be public if they don't +start with `"_"`, but default behavior can be overridden if needed, by passing +array of public property names as a second argument. + +## Gotchas ## + +`Cortex` is just a utility function to create a proxy object, and it does not +solve the `prototype`-related issues highlighted earlier, but since traits make +use of property descriptor maps instead of `prototype`s, there aren't any +issues with using `Cortex` to wrap objects created from traits. + +If you want to use `Cortex` with an object that uses a `prototype` chain, +however, you should either make sure you don't have any private properties +in the prototype chain or pass the optional third `prototype` argument. + +In the latter case, the returned proxy will inherit from the given prototype, +and the `prototype` chain of the wrapped object will be inaccessible. +However, note that the behavior of the `instanceof` operator will vary, +as `proxy instanceof Constructor` will return false even if the Constructor +function's prototype is in the wrapped object's prototype chain. + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/cuddlefish.md b/tools/addon-sdk-1.7/packages/api-utils/docs/cuddlefish.md new file mode 100644 index 0000000..27daf30 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/cuddlefish.md @@ -0,0 +1,7 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +`cuddlefish` is the name of the SDK's module loader. + +This module still needs to be documented. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/environment.md b/tools/addon-sdk-1.7/packages/api-utils/docs/environment.md new file mode 100644 index 0000000..b5057a2 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/environment.md @@ -0,0 +1,43 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Module provides API to access, set and unset environment variables via exported +`env` object. + + var { env } = require('api-utils/environment'); + +You can get the value of an environment variable, by accessing property that +has name of desired variable: + + var PATH = env.PATH; + +You can check existence of an environment variable by checking if property with +such variable name exists: + + console.log('PATH' in env); // true + console.log('FOO' in env); // false + +You can set value of an environment variable by setting a property: + + env.FOO = 'foo'; + env.PATH += ':/my/path/' + +You can unset environment variable by deleting a property: + + delete env.FOO; + +## Limitations ## + +There is no way to enumerate existing environment variables, also `env` +won't have any enumerable properties: + + console.log(Object.keys(env)); // [] + +Environment variable will be unset, show up as non-existing if it's set +to `null`, `undefined` or `''`. + + env.FOO = null; + console.log('FOO' in env); // false + env.BAR = ''; + console.log(env.BAR); // undefined diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/errors.md b/tools/addon-sdk-1.7/packages/api-utils/docs/errors.md new file mode 100644 index 0000000..98e94ac --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/errors.md @@ -0,0 +1,42 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> + +The `errors` module provides helpers for safely invoking user callbacks. + +<api name="catchAndLog"> +@function + Wraps a callback in a function that when invoked will catch and log any + exception thrown by the callback. +@param callback {function} + The callback to wrap. +@param [defaultResponse] {value} + This value will be returned by the wrapper if `callback` throws an exception. + If not given, `undefined` is used. +@param [logException] {function} + When `callback` throws an exception, it will be passed to this function. If + not given, the exception is logged using `console.exception()`. +@returns {function} + A function that will invoke `callback` when called. The return value of this + function is the return value of `callback` unless `callback` throws an + exception. In that case, `defaultResponse` is returned or `undefined` if + `defaultResponse` is not given. +</api> + +<api name="catchAndLogProps"> +@function + Replaces methods of an object with wrapped versions of those methods returned + by `catchAndLog()`. +@param object {object} + The object whose methods to replace. +@param props {string,array} + The names of the methods of `object` to replace, either a string for a single + method or an array of strings for multiple methods. +@param [defaultResponse] {value} + This value will be returned by any wrapper whose wrapped method throws an + exception. If not given, `undefined` is used. +@param [logException] {function} + See `catchAndLog()`. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/event/core.md b/tools/addon-sdk-1.7/packages/api-utils/docs/event/core.md new file mode 100644 index 0000000..6ab3317 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/event/core.md @@ -0,0 +1,51 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Module provides core (low level) API for working with events in the SDK. This +API is mainly for implementing higher level event APIs. + +Event `listener` may be registered on any (event `target`) object using +provided `on` function: + + var { on, once, off, emit } = require('api-utils/event/core'); + var target = { name: 'target' }; + on(target, 'message', function listener(event) { + console.log('hello ' + event); + }); + on(target, 'data', console.log); + +Event of specific `type` may be emitted on any event `target` object using +`emit` function. This will call all registered `listener`s for the given `type` +on the given event `target` in the same order they were registered. + + emit(target, 'message', 'event'); + // info: 'hello event' + emit(target, 'data', { type: 'data' }, 'second arg'); + // info: [Object object] 'second arg' + +Registered event listeners may be removed using `off` function: + + off(target, 'message'); + emit(target, 'message', 'bye'); + // info: 'hello bye' + +Sometimes listener only cares about first event of specific `type`. To avoid +hassles of removing such listeners there is convenient `once` function: + + once(target, 'load', function() { + console.log('ready'); + }); + emit(target, 'load') + // info: 'ready' + emit(target, 'load') + +There are also convenient ways to remove registered listeners. All listeners of +the specific type can be easily removed (only two argument must be passed): + + off(target, 'message'); + +Also, removing all registered listeners is possible (only one argument must be +passed): + + off(target); diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/event/target.md b/tools/addon-sdk-1.7/packages/api-utils/docs/event/target.md new file mode 100644 index 0000000..96feb79 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/event/target.md @@ -0,0 +1,95 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Provides an exemplar `EventTarget` object, that implements interface for +adding removing event listeners of a specific type. `EventTarget` is a +base of all objects in SDK on which events are emitted. + +### Instantiation + +It's easy to create event target objects, no special arguments are required. + + const { EventTarget } = require('api-utils/event/target'); + let target = EventTarget.new(); + +For a convenience though optional `options` arguments may be used, in which +case all the function properties with keys like: `onMessage`, `onMyEvent`... +will be auto registered for associated `'message'`, `'myEvent'` events on +the created instance. _All other properties of `options` will be ignored_. + +### Adding listeners + +`EventTarget` interface defines `on` method, that can be used to register +event listeners on them for the given event type: + + target.on('message', function onMessage(message) { + // Note: `this` pseudo variable is an event `target` unless + // intentionally overridden via `.bind()`. + console.log(message); + }); + +Sometimes event listener may care only about very first event of specific +`type`. `EventTarget` interface defines convenience method for adding one +shot event listeners via method `once`. Such listeners are called only once +next time event of the specified type is emitted: + + target.once('ready', function onReady() { + // Do the thing once ready! + }); + +### Removing listeners + +`EventTarget` interface defines API for unregistering event listeners, via +`removeListener` method: + + target.removeListener('message', onMessage); + +### Emitting events + +`EventTarget` interface intentionally does not defines an API for emitting +events. In majority of cases party emitting events is different from party +registering listeners. In order to emit events one needs to use `event/core` +module instead: + + let { emit } = require('api-utils/event/core'); + + target.on('hi', function(person) { console.log(person + 'tells hi'); }); + emit(target, 'hi', 'Mark'); + // info: 'Mark tells hi' + +For more details see **event/core** documentation. + +### More details + +Listeners registered during the event propagation (by one of the listeners) +won't be triggered until next emit of the matching type: + + let { emit } = require('api-utils/event/core'); + + target.on('message', function onMessage(message) { + console.log('listener trigerred'); + target.on('message', function() { + console.log('nested listener triggered'); + }); + }); + + emit(target, 'message'); + // info: 'listener trigerred' + emit(target, 'message'); + // info: 'listener trigerred' + // info: 'nested listener trigerred' + +Exceptions in the listeners can be handled via `'error'` event listeners: + + target.on('boom', function() { + throw Error('Boom!'); + }); + target.once('error', function(error) { + console.log('caught an error: ' + error.message); + }); + emit(target, 'boom'); + // info: caught an error: Boom! + +If there is no listener registered for `error` event or if it also throws +exception then such exceptions are logged into a console. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/events.md b/tools/addon-sdk-1.7/packages/api-utils/docs/events.md new file mode 100644 index 0000000..76f9efd --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/events.md @@ -0,0 +1,78 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +The `events` module provides base API for emitting events. + +This module is not intended to be used directly by programs. Rather, it is +intended to be used by other modules that provide APIs to programs. + +<api name="EventEmitter"> +@class +The EventEmitter is the base building block for all compositions that +would need to broadcast data to multiple consumers. + +Please note that `EventEmitter` does not expose either a method for emitting +events or a list of available event listeners as its public API. Obviously +both are accessible but from the instance itself through the private API. +<api name="EventEmitter"> +@constructor +Creates an EventEmitter object. +</api> + +<api name="on"> +@method +Registers an event `listener` that will be called when events of +specified `type` are emitted. + +If the `listener` is already registered for this `type`, a call to this +method has no effect. + +If the event listener is being registered while an event is being processed, +the event listener is not called during the current emit. + +**Example:** + + // worker is instance of EventEmitter + worker.on('message', function (data) { + console.log('data received: ' + data) + }); + +@param type {String} + The type of the event. +@param listener {Function} + The listener function that processes the event. +</api> + +<api name="once"> +@method +Registers an event `listener` that will only be called once, the next time +an event of the specified `type` is emitted. + +If the event listener is registered while an event of the specified `type` +is being emitted, the event listener will not be called during the current +emit. + +@param type {String} + The type of the event. +@param listener {Function} + The listener function that processes the event. +</api> + +<api name="removeListener"> +@method +Unregisters an event `listener` for the specified event `type`. + +If the `listener` is not registered for this `type`, a call to this +method has no effect. + +If an event listener is removed while an event is being processed, it is +still triggered by the current emit. After it is removed, the event listener +is never invoked again (unless registered again for future processing). + +@param type {String} + The type of the event. +@param listener {Function} + The listener function that processes the event. +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/file.md b/tools/addon-sdk-1.7/packages/api-utils/docs/file.md new file mode 100644 index 0000000..9587353 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/file.md @@ -0,0 +1,151 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `file` module provides access to the local filesystem. + + +Paths +----- + +Path specifications in this API are platform-specific. This means that on +Windows paths are specified using the backslash path separator (`\`), and on +Unix-like systems like Linux and OS X paths are specified using the forward +slash path separator (`/`). + +If your add-on uses literal Windows-style path specifications with this API, +your add-on likely won't work when users run it on Unix-like systems. Likewise, +if your add-on uses literal Unix-style path specifications, it won't work for +users on Windows. + +To ensure your add-on works for everyone, generate paths using the +[`join`](packages/api-utils/file.html#join(...)) function. Unfortunately +this API does not currently provide a way to obtain an absolute base path which +you could then use with `join`. For now, you need to +[`require("chrome")`](dev-guide/tutorials/chrome.html) and use the +XPCOM directory service as described at +[MDN](https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Getting_special_files). + +Note that if you do decide to hardcode Windows-style paths, be sure to escape +backslashes in strings. For example, to specify the file at `C:\Users\Myk`, you +need to use the string `"C:\\Users\\Myk"`, not `"C:\Users\Myk"`. You can read +more about escaping characters in strings at +[MDN](https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Escaping_Characters). + + +<api name="basename"> +@function + Returns the last component of the given path. For example, + `basename("/foo/bar/baz")` returns `"baz"`. If the path has no components, + the empty string is returned. +@param path {string} + The path of a file. +@returns {string} + The last component of the given path. +</api> + +<api name="dirname"> +@function + Returns the path of the directory containing the given file. If the file is + at the top of the volume, the empty string is returned. +@param path {string} + The path of a file. +@returns {string} + The path of the directory containing the file. +</api> + +<api name="exists"> +@function + Returns true if a file exists at the given path and false otherwise. +@param path {string} + The path of a file. +@returns {boolean} + True if the file exists and false otherwise. +</api> + +<api name="join"> +@function + Takes a variable number of strings, joins them on the file system's path + separator, and returns the result. +@param ... {strings} + A variable number of strings to join. The first string must be an absolute + path. +@returns {string} + A single string formed by joining the strings on the file system's path + separator. +</api> + +<api name="list"> +@function + Returns an array of file names in the given directory. +@param path {string} + The path of the directory. +@returns {array} + An array of file names. Each is a basename, not a full path. +</api> + +<api name="mkpath"> +@function + Makes a new directory named by the given path. Any subdirectories that do not + exist are also created. `mkpath` can be called multiple times on the same + path. +@param path {string} + The path to create. +</api> + +<api name="open"> +@function + Returns a stream providing access to the contents of a file. +@param path {string} + The path of the file to open. +@param [mode] {string} + An optional string, each character of which describes a characteristic of the + returned stream. If the string contains `"r"`, the file is opened in + read-only mode. `"w"` opens the file in write-only mode. `"b"` opens the + file in binary mode. If `"b"` is not present, the file is opened in text + mode, and its contents are assumed to be UTF-8. If *`mode`* is not given, + `"r"` is assumed, and the file is opened in read-only text mode. +@returns {stream} + If the file is opened in text read-only `mode`, a `TextReader` is returned, + and if text write-only mode, a `TextWriter` is returned. See + [`text-streams`](packages/api-utils/text-streams.html) for information on + these text stream objects. If the file is opened in binary read-only `mode`, + a `ByteReader` is returned, and if binary write-only mode, a `ByteWriter` is + returned. See + [`byte-streams`](packages/api-utils/byte-streams.html) for more + information on these byte stream objects. Opened files should always be + closed after use by calling `close` on the returned stream. +</api> + +<api name="read"> +@function + Opens a file and returns a string containing its entire contents. +@param path {string} + The path of the file to read. +@param [mode] {string} + An optional string, each character of which describes a characteristic of the + returned stream. If the string contains `"b"`, the contents will be returned + in binary mode. If `"b"` is not present or `mode` is not given, the file + contents will be returned in text mode. +@returns {string} + A string containing the file's entire contents. +</api> + +<api name="remove"> +@function + Removes a file from the file system. To remove directories, use `rmdir`. +@param path {string} + The path of the file to remove. +</api> + +<api name="rmdir"> +@function + Removes a directory from the file system. If the directory is not empty, an + exception is thrown. +@param path {string} + The path of the directory to remove. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/frame/utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/frame/utils.md new file mode 100644 index 0000000..c88d198 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/frame/utils.md @@ -0,0 +1,53 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +The `frame/utils` module provides helper functions for working with platform +internals like [frames](https://developer.mozilla.org/en/XUL/iframe) and +[browsers](https://developer.mozilla.org/en/XUL/browser). + +### create + +Module exports `create` function that takes `nsIDOMDocument` of the +[privileged document](https://developer.mozilla.org/en/Working_with_windows_in_chrome_code) +and creates a `browser` element in it's `documentElement`: + + let { open } = require('api-utils/window/utils'); + let { create } = require('api-utils/frame/utils'); + let window = open('data:text/html,Foo'); + let frame = create(window.document); + +Optionally `create` can be passed set of `options` to configure created frame +even further. Following options are supported: + +- `type` +String that defines access type of the document loaded into it. Defaults to +`'content'`. For more details and other possible values see +[documentation on MDN](https://developer.mozilla.org/en/XUL/Attribute/browser.type) + +- `uri` +URI of the document to be loaded into created frame. Defaults to `about:blank`. + +- `remote` +If `true` separate process will be used for this frame, also in such case all +the following options are ignored. + +- `allowAuth` +Whether to allow auth dialogs. Defaults to `false`. + +- `allowJavascript` +Whether to allow Javascript execution. Defaults to `false`. + +- `allowPlugins` +Whether to allow plugin execution. Defaults to `false`. + +Execution of scripts may easily be enabled: + + let { open } = require('api-utils/window/utils'); + let { create } = require('api-utils/frame/utils'); + let window = open('data:text/html,top'); + let frame = create(window.document, { + uri: 'data:text/html,<script>alert("Hello")</script>', + allowJavascript: true + }); + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/globals.md b/tools/addon-sdk-1.7/packages/api-utils/docs/globals.md new file mode 100644 index 0000000..e6df8a8 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/globals.md @@ -0,0 +1,100 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Globals in this section are subject to change in the future and/or are likely +to be of interest to SDK module developers, rather than add-on developers. + +## Components ## + +To access the infamous and powerful `Components` object, see the +[Chrome Authority](dev-guide/tutorials/chrome.html) documentation. + +## \_\_url\_\_ ## + +The `__url__` global is a string identifying the URL from which the code has +been retrieved. If the code has no identifiable URL, this value may be `null`. + +## packaging ## + +<span class="aside"> +For more information on packaging, see the [Package Specification][] appendix. +</span> + +The `packaging` global contains methods and metadata related to +the packages available in the current environment. + +<code>packaging.**getURLForData**(*path*)</code> + +Given a unix-style path relative to the calling package's `data` +directory, returns an absolute URL to the file or directory. + +By "calling package", we mean the package in which the caller's source +code resides. + +Thus, for example, if a package contains a resource at +`data/mydata.dat` and a module at `lib/foo.js`, the module at +`lib/foo.js` may make the following call to retrieve an absolute URL +to `data/mydata.dat`: + + var myDataURL = packaging.getURLForData("/mydata.dat"); + +If the calling package has no `data` directory, an exception is +thrown. + +## memory ## + +`memory` is an object that exposes functionality to track +objects of interest and help diagnose and prevent memory leaks. + +<code>memory.**track**(*object*, [*bin*])</code> + +Marks *object* for being tracked, and categorizes it with the given +bin name. If *bin* isn't specified, the memory tracker attempts to +infer a bin name by first checking the object's +`constructor.name`; if that fails or results in the generic +`Object`, the stack is inspected and the name of the current +function being executed—which is assumed to be a constructor +function—is used. If that fails, then the object is placed in a +bin named `generic`. + +<code>memory.**getObjects**([*bin*])</code> + +Returns an `Array` containing information about tracked objects +that have been categorized with the given bin name. If *bin* isn't +provided, information about all live tracked objects are returned. + +Each element of the array is an object with the following keys: + +<table> + <tr> + <td><code>weakref</code></td> + <td>A weak reference to the object being tracked. Call + <code>get()</code> on this object to retrieve its strong reference; if + a strong reference to the object no longer exists, <code>get()</code> + will return <code>null</code>.</td> + </tr> + <tr> + <td><code>created</code></td> + <td>A <code>Date</code> representing the date and time that + <code>memory.track()</code> was called on the object being + tracked.</td> + </tr> + <tr> + <td><code>filename</code></td> + <td>The name of the file that called <code>memory.track()</code> on + the object being tracked.</td> + </tr> + <tr> + <td><code>lineNo</code></td> + <td>The line number of the file that called + <code>memory.track()</code> on the object being tracked.</td> + </tr> +</table> + +<code>memory.**getBins**()</code> + +Returns an `Array` containing the names of all bins that aren't +currently empty. + + [Package Specification]: dev-guide/package-spec.html
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/hidden-frame.md b/tools/addon-sdk-1.7/packages/api-utils/docs/hidden-frame.md new file mode 100644 index 0000000..9d16dfa --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/hidden-frame.md @@ -0,0 +1,83 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Myk Melez [myk@mozilla.org] --> + +The `hidden-frame` module creates host application frames (i.e. XUL `<iframe>` +elements) that are not displayed to the user. It is useful in the construction +of APIs that load web content not intended to be directly seen or accessed +by users, like `page-worker`. It is also useful in the construction of APIs +that load web content for intermittent display, such as `panel`. + +This module is not intended to be used directly by programs. Rather, it is +intended to be used by other modules that provide APIs to programs. + +Introduction +------------ + +The module exports a constructor function, `HiddenFrame`, and two other +functions, `add` and `remove`. + +`HiddenFrame` constructs a new hidden frame. `add` registers a hidden frame, +preparing it to load content. `remove` unregisters a frame, unloading any +content that was loaded in it. + +Examples +-------- + +The following code creates a hidden frame, loads a web page into it, and then +logs its title: + + var hiddenFrames = require("hidden-frame"); + let hiddenFrame = hiddenFrames.add(hiddenFrames.HiddenFrame({ + onReady: function() { + this.element.contentWindow.location = "http://www.mozilla.org/"; + let self = this; + this.element.addEventListener("DOMContentLoaded", function() { + console.log(self.element.contentDocument.title); + }, true, true); + } + })); + +See the `panel` module for a real-world example of usage of this module. + +Reference +--------- +<api name="HiddenFrame"> +@class +`HiddenFrame` objects represent hidden frames. +<api name="HiddenFrame"> +@constructor +Creates a hidden frame. +@param options {object} + Options for the frame, with the following keys: + @prop onReady {function,array} + Functions to call when the frame is ready to load content. You must specify + an `onReady` callback and refrain from using the hidden frame until + the callback gets called, because hidden frames are not always ready to load + content the moment they are added. +</api> + +<api name="add"> +@function +Register a hidden frame, preparing it to load content. +@param hiddenFrame {HiddenFrame} the frame to add +</api> + +<api name="remove"> +@function +Unregister a hidden frame, unloading any content that was loaded in it. +@param hiddenFrame {HiddenFrame} the frame to remove +</api> + +<api name="element"> +@property {DOMElement} +The host application frame in which the page is loaded. +</api> + +<api name="onReady"> +@property {array} +Functions to call when the frame is ready to load content. +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/httpd.md b/tools/addon-sdk-1.7/packages/api-utils/docs/httpd.md new file mode 100644 index 0000000..3f131f9 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/httpd.md @@ -0,0 +1,31 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Provides an HTTP server written in JavaScript for the Mozilla platform, which +can be used in unit tests. + +The most basic usage is: + + var {startServerAsync} = require("httpd"); + var srv = startServerAsync(port, basePath); + require("unload").when(function cleanup() { + srv.stop(function() { // you should continue execution from this point. + }) + }); + +This starts a server in background (assuming you're running this code in an +application that has an event loop, such as Firefox). The server listens at +http://localhost:port/ and serves files from the specified directory. You +can serve static content or use SJS scripts, as described in documentation +on developer.mozilla.org. + +You can also use `nsHttpServer` to start the server manually: + + var {nsHttpServer} = require("httpd"); + var srv = new nsHttpServer(); + // further documentation on developer.mozilla.org + +See +[HTTP server for unit tests](https://developer.mozilla.org/En/HTTP_server_for_unit_tests) +for general information. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/light-traits.md b/tools/addon-sdk-1.7/packages/api-utils/docs/light-traits.md new file mode 100644 index 0000000..367a6a9 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/light-traits.md @@ -0,0 +1,295 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + + +[Traits](http://en.wikipedia.org/wiki/Trait_%28computer_science%29) are a simple +mechanism for structuring object-oriented programs. They represent reusable and +composable building blocks of functionality that factor out the common +attributes and behavior of objects. + +They are a more robust alternative to +[mixins](http://en.wikipedia.org/wiki/Mixins) and +[multiple inheritance](http://en.wikipedia.org/wiki/Multiple_inheritance), +because name clashes must be explicitly resolved and composition is commutative +and associative (i.e. the order of traits in a composition is irrelevant). + +Use traits to share functionality between similar objects without duplicating +code or creating complex inheritance chains. + +## Trait Creation ## + +To create a trait, call the `Trait` constructor function exported by this +module, passing it a JavaScript object that specifies the properties of the +trait. + + let Trait = require('light-traits').Trait; + let t = Trait({ + foo: "foo", + bar: function bar() { + return "Hi!" + }, + baz: Trait.required + }); + +Traits can both provide and require properties. A *provided* property is a +property for which the trait itself provides a value. A *required* property is a +property that the trait needs in order to function correctly but for which +it doesn't provide a value. + +Required properties must be provided by another trait or by an object with a +trait. Creation of an object with a trait will fail if required properties are +not provided. Specify a required property by setting the value of the property +to `Trait.required`. + +## Object Creation ## + +Create objects with a single trait by calling the trait's `create` method. The +method takes a single argument, the object to serve as the new object's +prototype. If no prototype is specified, the new object's prototype will be +`Object.prototype`. + + let t = Trait({ + foo: 'foo', + bar: 2 + }); + let foo1 = t.create(); + let foo2 = t.create({ name: 'Super' }); + +## Trait Composition ## + +Traits are designed to be composed with other traits to create objects with the +properties of multiple traits. To compose an object with multiple traits, you +first create a composite trait and then use it to create the object. A composite +trait is a trait that contains all of the properties of the traits from which it +is composed. In the following example, MagnitudeTrait is a composite trait. + + let EqualityTrait = Trait({ + equal: Trait.required, + notEqual: function notEqual(x) { + return !this.equal(x) + } + }); + + let ComparisonTrait = Trait({ + less: Trait.required, + notEqual: Trait.required, + greater: function greater(x) { + return !this.less(x) && this.notEqual(x) + } + }); + + let MagnitudeTrait = Trait.compose(EqualityTrait, ComparisonTrait); + +<?xml version="1.0"?> +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xl="http://www.w3.org/1999/xlink" version="1.1" viewBox="-11 121 490 190" width="490px" height="190px"> + <defs> + <marker orient="auto" overflow="visible" markerUnits="strokeWidth" id="SharpArrow_Marker" viewBox="-4 -4 10 8" markerWidth="10" markerHeight="8" color="black"> + <g> + <path d="M 5 0 L -3 -3 L 0 0 L 0 0 L -3 3 Z" fill="currentColor" stroke="currentColor" stroke-width="1px"/> + </g> + </marker> + </defs> + <g stroke="none" stroke-opacity="1" stroke-dasharray="none" fill="none" fill-opacity="1"> + <g> + <rect x="9" y="165.33334" width="141" height="14"/> + <rect x="9" y="165.33334" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(14 165.33334)" fill="black"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="47.373047">notEqual</tspan> + </text> + <rect x="9" y="151.33334" width="141" height="14"/> + <rect x="9" y="151.33334" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(14 151.33334)" fill="red"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="29.361328">equal</tspan> + </text> + <rect x="9" y="137.33334" width="141" height="14"/> + <rect x="9" y="137.33334" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(14 137.33334)" fill="black"> + <tspan font-family="Helvetica" font-size="12" font-weight="bold" x="38.49707" y="11" textLength="54.00586">EqualityTrait</tspan> + </text> + <rect x="9" y="273" width="141" height="14"/> + <rect x="9" y="273" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(14 273)" fill="black"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="38.021484">greater</tspan> + </text> + <rect x="9" y="259" width="141" height="14"/> + <rect x="9" y="259" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(14 259)" fill="red"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="47.373047">notEqual</tspan> + </text> + <rect x="9" y="245" width="141" height="14"/> + <rect x="9" y="245" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(14 245)" fill="red"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="21.339844">less</tspan> + </text> + <rect x="9" y="231" width="141" height="14"/> + <rect x="9" y="231" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(14 231)" fill="black"> + <tspan font-family="Helvetica" font-size="12" font-weight="bold" x=".15332031" y="11" textLength="112.67578">ComparisonTrait</tspan> + </text> + <rect x="317.75" y="235.5" width="141" height="14"/> + <rect x="317.75" y="235.5" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(322.75 235.5)" fill="black"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="38.021484">greater</tspan> + </text> + <rect x="317.75" y="221.5" width="141" height="14"/> + <rect x="317.75" y="221.5" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(322.75 221.5)" fill="red"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="21.339844">less</tspan> + </text> + <rect x="317.75" y="207.5" width="141" height="14"/> + <rect x="317.75" y="207.5" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(322.75 207.5)" fill="black"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" x="0" y="11" textLength="47.373047">notEqual</tspan> + </text> + <rect x="317.75" y="193.5" width="141" height="14"/> + <rect x="317.75" y="193.5" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(322.75 193.5)" fill="red"> + <tspan font-family="Helvetica" font-size="12" font-weight="500" fill="red" x="0" y="11" textLength="29.361328">equal</tspan> + </text> + <rect x="317.75" y="179.5" width="141" height="14"/> + <rect x="317.75" y="179.5" width="141" height="14" stroke="black" stroke-width="1px"/> + <text transform="translate(322.75 179.5)" fill="black"> + <tspan font-family="Helvetica" font-size="12" font-weight="bold" x="31.83789" y="11" textLength="67.32422">MagnitudeTrait</tspan> + </text> + <path d="M 150 248.83887 L 158.89999 248.83887 L 235.9 248.83887 L 235.9 224.66113 L 308.85 224.66113 L 310.85 224.66113" marker-end="url(#SharpArrow_Marker)" stroke="black" stroke-linecap="butt" stroke-linejoin="miter" stroke-width="1px"/> + <path d="M 150 171.15845 L 158.89999 171.15845 L 233.9 171.15845 L 233.9 201.6749 L 308.85 201.6749 L 310.85 201.6749" marker-end="url(#SharpArrow_Marker)" stroke="black" stroke-linecap="butt" stroke-linejoin="miter" stroke-width="1px"/> + </g> + </g> +</svg> + +## Trait Resolution ## + +Composite traits have conflicts when two of the traits in the composition +provide properties with the same name but different values (when compared using +the `===` strict equality operator). In the following example, `TC` has a +conflict because `T1` and `T2` both define a `foo` property: + + let T1 = Trait({ + foo: function () { + // do something + }, + bar: 'bar', + t1: 1 + }); + + let T2 = Trait({ + foo: function() { + // do something else + }, + bar: 'bar', + t2: 2 + }); + + let TC = Trait.compose(T1, T2); + +Attempting to create an object from a composite trait with conflicts throws a +`remaining conflicting property` exception. To create objects from such traits, +you must resolve the conflict. + +You do so by excluding or renaming the conflicting property of one of the +traits. Excluding a property removes it from the composition, so the composition +only acquires the property from the other trait. Renaming a property gives it a +new, non-conflicting name at which it can be accessed. + +In both cases, you call the `resolve` method on the trait whose property you +want to exclude or rename, passing it an object. Each key in the object is the +name of a conflicting property; each value is either `null` to exclude the +property or a string representing the new name of the property. + +For example, the conflict in the previous example could be resolved by excluding +the `foo` property of the second trait. + + let TC = Trait(T1, T2.resolve({ foo: null })); + +It could also be resolved by renaming the `foo` property of the first trait to +`foo2`: + + let TC = Trait(T1.resolve({ foo: "foo2" }), T2); + +When you resolve a conflict, the same-named property of the other trait (the one +that wasn't excluded or renamed) remains available in the composition under its +original name. + +## Constructor Functions ## + +When your code is going to create more than one object with traits, you may want +to define a constructor function to create them. To do so, create a composite +trait representing the traits the created objects should have, then define a +constructor function that creates objects with that trait and whose prototype is +the prototype of the constructor: + + let PointTrait = Trait.compose(T1, T2, T3); + function Point(options) { + let point = PointTrait.create(Point.prototype); + return point; + } + +## Property Descriptor Maps ## + +Traits are designed to work with the new object manipulation APIs defined in +[ECMAScript-262, Edition +5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) (ES5). +Traits are also property descriptor maps that inherit from `Trait.prototype` to +expose methods for creating objects and resolving conflicts. + +The following trait definition: + + let FooTrait = Trait({ + foo: "foo", + bar: function bar() { + return "Hi!" + }, + baz: Trait.required + }); + +Creates the following property descriptor map: + + { + foo: { + value: 'foo', + enumerable: true, + configurable: true, + writable: true + }, + + bar: { + value: function b() { + return 'bar' + }, + enumerable: true, + configurable: true, + writable: true + }, + + baz: { + get baz() { throw new Error('Missing required property: `baz`') } + set baz() { throw new Error('Missing required property: `baz`') } + }, + + __proto__: Trait.prototype + } + +Since Traits are also property descriptor maps, they can be used with built-in +`Object.*` methods that accept such maps: + + Object.create(proto, FooTrait); + Object.defineProperties(myObject, FooTrait); + +Note that conflicting and required properties won't cause exceptions to be +thrown when traits are used with the `Object.*` methods, since those methods are +not aware of those constraints. However, such exceptions will be thrown when the +property with the conflict or the required but missing property is accessed. + +Property descriptor maps can also be used in compositions. This may be useful +for defining non-enumerable properties, for example: + + let TC = Trait.compose( + Trait({ foo: 'foo' }), + { bar: { value: 'bar', enumerable: false } } + ); + +_When using property descriptor maps in this way, make sure the map is not the +only argument to `Trait.compose`, since in that case it will be interpreted as +an object literal with properties to be defined._ + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/list.md b/tools/addon-sdk-1.7/packages/api-utils/docs/list.md new file mode 100644 index 0000000..fd70698 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/list.md @@ -0,0 +1,98 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Irakli Gozalishvili [gozala@mozilla.com] --> + +The `"list"` module provides base building blocks for composing lists. + +<api name="Iterable"> +@class +Base trait that can be used to compose traits with non-standard +enumeration behaviors. + +This trait is supposed to be used as part of a composition, since it only +provides custom enumeration behavior to a composed object. +It defines one required `_keyValueMap` property, that is used as a hash of +"key-values" to iterate on during enumeration. + +<api name="Iterable"> +@constructor +Constructs an `Iterable` object. +</api> + +<api name="_keyValueMap"> +@property {Object} +Hash map of key-values to iterate over. _Required_ property: that is, the +property must be supplied by objects that compose this trait. +_Note: That this property can be a getter if you need dynamic behavior._ +</api> + +</api> + +<api name="List"> +@class +An ordered collection (also known as a sequence) disallowing duplicate +elements. List is composed out of `Iterable`, therefore it provides custom +enumeration behavior that is similar to array (enumerates only on the +elements of the list). + +List is a base trait and is meant to be part of a +composition, since all of its API is private except for the `length` property. + +**Examples:** + + var MyList = List.compose({ + add: function add(item1, item2, /*item3...*/) { + Array.slice(arguments).forEach(this._add.bind(this)); + }, + remove: function remove(item1, item2, /*item3...*/) { + Array.slice(arguments).forEach(this._remove.bind(this)); + } + }); + MyList('foo', 'bar', 'baz').length == 3; // true + new MyList('new', 'keyword').length == 2; // true + MyList.apply(null, [1, 2, 3]).length == 3; // true + let list = MyList(); + list.length == 0; // true + list.add(1, 2, 3) == 3; // true + +<api name="List"> +@constructor +Constructor can takes any number of elements and creates an instance of +`List` populated with the specified elements. +@param [element1] {Object|String|Number} +@param [element2] {Object|String|Number} +@param [...] {Object|String|Number} +</api> + +<api name="length"> +@property {Number} +Number of elements in this list. +</api> + +<api name="_has"> +@method +@param element {Object|Number|String} +Returns `true` if this list contains the specified `element`. +</api> +<api name="_add"> +@method +@param element {Object|Number|String} +Appends the specified `element` to the end of this list, if it doesn't +contain it. + +_Ignores the call if `element` is already contained._ +</api> +<api name="_remove"> +@method +@param element {Object|Number|String} +Removes specified `element` from this list, if it contains it. + +_Ignores the call if `element` is not contained._ +</api> +<api name="_clear"> +@method +Removes all of the elements from this list. +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/match-pattern.md b/tools/addon-sdk-1.7/packages/api-utils/docs/match-pattern.md new file mode 100644 index 0000000..0222e65 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/match-pattern.md @@ -0,0 +1,246 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +The `match-pattern` module can be used to test strings containing URLs +against simple patterns. + +## Specifying Patterns ## + +There are three ways you can specify patterns: + +* as an exact match string +* using a wildcard in a string +* using a regular expression + +### Exact Matches ### + +**A URL** matches only that URL. The URL must start with a scheme, end with a +slash, and contain no wildcards. + +<table> + + <colgroup> + <col width="30%"> + <col width="35%"> + <col width="35%"> + </colgroup> + + <tr> + <th>Example pattern</th> + <th>Example matching URLs</th> + <th>Example non-matching URLs</th> + </tr> + + <tr> + <td><code>"http://example.com/"</code></td> + <td><code>http://example.com/</code></td> + <td><code>http://example.com</code><br> + <code>http://example.com/foo</code><br> + <code>https://example.com/</code><br> + <code>http://foo.example.com/</code></td> + </tr> + +</table> + +### Wildcards ### + +**A single asterisk** matches any URL with an `http`, `https`, or `ftp` +scheme. For other schemes like `file`, use a scheme followed by an +asterisk, as below. + +<table> + + <colgroup> + <col width="30%"> + <col width="35%"> + <col width="35%"> + </colgroup> + + <tr> + <th>Example pattern</th> + <th>Example matching URLs</th> + <th>Example non-matching URLs</th> + </tr> + + <tr> + <td><code>"*"</code></td> + <td><code>http://example.com/</code><br> + <code>https://example.com/</code><br> + <code>ftp://example.com/</code><br> + <code>http://bar.com/foo.js</code><br> + <code>http://foo.com/</code></td> + <td><code>file://example.js</code></td> + </tr> + +</table> + +**A domain name prefixed with an asterisk and dot** matches any URL of that +domain or a subdomain, using any of `http`, `https`, `ftp`. + +<table> + + <colgroup> + <col width="30%"> + <col width="35%"> + <col width="35%"> + </colgroup> + + <tr> + <th>Example pattern</th> + <th>Example matching URLs</th> + <th>Example non-matching URLs</th> + </tr> + + <tr> + <td><code>"*.example.com"</code></td> + <td><code>http://example.com/</code><br> + <code>http://foo.example.com/</code><br> + <code>https://example.com/</code><br> + <code>http://example.com/foo</code><br> + <code>ftp://foo.example.com/</code></td> + <td><code>ldap://example.com</code><br> + <code>http://example.foo.com/</code></td> + </tr> + +</table> + +**A URL followed by an asterisk** matches that URL and any URL prefixed with +the pattern. + +<table> + + <colgroup> + <col width="30%"> + <col width="35%"> + <col width="35%"> + </colgroup> + + <tr> + <th>Example pattern</th> + <th>Example matching URLs</th> + <th>Example non-matching URLs</th> + </tr> + + <tr> + <td><code>"https://foo.com/*"</code></td> + <td><code>https://foo.com/</code><br> + <code>https://foo.com/bar</code></td> + <td><code>http://foo.com/</code><br> + <code>https://foo.com</code><br> + <code>https://bar.foo.com/</code></td> + </tr> + +</table> + +**A scheme followed by an asterisk** matches all URLs with that scheme. To +match local files, use `file://*`. + +<table> + + <colgroup> + <col width="30%"> + <col width="70%"> + </colgroup> + + <tr> + <th>Example pattern</th> + <th>Example matching URLs</th> + </tr> + + <tr> + <td><code>"file://*"</code></td> + <td><code>file://C:/file.html</code><br> + <code>file:///home/file.png</code></td> + </tr> + +</table> + +### Regular Expressions ### + +You can specify patterns using a +[regular expression](https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions): + + var { MatchPattern } = require("match-pattern"); + var pattern = new MatchPattern(/.*example.*/); + +The regular expression is subject to restrictions based on those applied to the +[HTML5 pattern attribute](http://dev.w3.org/html5/spec/common-input-element-attributes.html#attr-input-pattern). In particular: + +* The pattern must match the entire value, not just any subset. For example, the +pattern `/moz.*/` will not match the URL `http://mozilla.org`. + +* The expression is compiled with the `global`, `ignoreCase`, and `multiline` flags + disabled. The `MatchPattern` constructor will throw an exception + if you try to set any of these flags. + +<table> + + <colgroup> + <col width="30%"> + <col width="35%"> + <col width="35%"> + </colgroup> + + <tr> + <th>Example pattern</th> + <th>Example matching URLs</th> + <th>Example non-matching URLs</th> + </tr> + + <tr> + <td><code>/.*moz.*/</code></td> + <td><code>http://foo.mozilla.org/</code><br> + <code>http://mozilla.org</code><br> + <code>https://mozilla.org</code><br> + <code>http://foo.com/mozilla</code><br> + <code>http://hemozoon.org</code><br> + <code>mozscheme://foo.org</code><br></td> + <td><code>http://foo.org</code><br> + </tr> + + <tr> + <td><code>/http:\/\/moz.*/</code></td> + <td><code>http://mozilla.org</code><br> + <code>http://mozzarella.com</code></td> + <td><code>https://mozilla.org</code><br> + <code>http://foo.mozilla.org/</code><br> + <code>http://foo.com/moz</code></td> + </tr> + + <tr> + <td><code>/http.*moz.*/</code><br></td> + <td><code>http://foo.mozilla.org/</code><br> + <code>http://mozilla.org</code><br> + <code>http://hemozoon.org/</code></td> + <td><code>ftp://http/mozilla.org</code></td> + </tr> + +</table> + +## Examples ## + + var { MatchPattern } = require("match-pattern"); + var pattern = new MatchPattern("http://example.com/*"); + console.log(pattern.test("http://example.com/")); // true + console.log(pattern.test("http://example.com/foo")); // true + console.log(pattern.test("http://foo.com/")); // false! + +<api name="MatchPattern"> +@class +<api name="MatchPattern"> +@constructor + This constructor creates match pattern objects that can be used to test URLs. +@param pattern {string} + The pattern to use. See Patterns above. +</api> + +<api name="test"> +@method + Tests a URL against the match pattern. +@param url {string} + The URL to test. +@returns {boolean} + True if the URL matches the pattern and false otherwise. +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/memory.md b/tools/addon-sdk-1.7/packages/api-utils/docs/memory.md new file mode 100644 index 0000000..04de606 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/memory.md @@ -0,0 +1,7 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +The `memory` module provides a concrete default implementation for the SDK's +`memory` global. For documentation on the `memory` global, see the +[Globals](packages/api-utils/globals.html) reference. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/message-manager.md b/tools/addon-sdk-1.7/packages/api-utils/docs/message-manager.md new file mode 100644 index 0000000..522c613 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/message-manager.md @@ -0,0 +1,13 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Matteo Ferretti [zer0@mozilla.com] --> + +Overview +-------- +The `message-manager` module provides a minimalist implementation +of the [Message Manager](https://developer.mozilla.org/en/The_message_manager) +APIs, in a single process environment. + +It's mainly used internally for Fennec Birch support.
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/namespace.md b/tools/addon-sdk-1.7/packages/api-utils/docs/namespace.md new file mode 100644 index 0000000..07ec96e --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/namespace.md @@ -0,0 +1,71 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Provides an API for creating namespaces for any given objects, which +effectively may be used for creating fields that are not part of objects +public API. + + let { ns } = require('api-utils/namespace'); + let aNamespace = ns(); + + aNamespace(publicAPI).secret = secret; + +One namespace may be used with multiple objects: + + let { ns } = require('api-utils/namespace'); + let dom = ns(); + + function View(element) { + let view = Object.create(View.prototype); + dom(view).element = element; + // .... + } + View.prototype.destroy = function destroy() { + let { element } = dom(this); + element.parentNode.removeChild(element); + // ... + }; + // ... + exports.View = View; + // ... + +Also, multiple namespaces can be used with one object: + + // ./widget.js + + let { Cu } = require('chrome'); + let { ns } = require('api-utils/namespace'); + let { View } = require('./view'); + + // Note this is completely independent from View's internal Namespace object. + let sandboxes = ns(); + + function Widget(options) { + let { element, contentScript } = options; + let widget = Object.create(Widget.prototype); + View.call(widget, options.element); + sandboxes(widget).sandbox = Cu.Sandbox(element.ownerDocument.defaultView); + // ... + } + Widget.prototype = Object.create(View.prototype); + Widget.prototype.postMessage = function postMessage(message) { + let { sandbox } = sandboxes(this); + sandbox.postMessage(JSON.stringify(JSON.parse(message))); + ... + }; + Widget.prototype.destroy = function destroy() { + View.prototype.destroy.call(this); + // ... + delete sandboxes(this).sandbox; + }; + exports.Widget = Widget; + +In addition access to the namespace can be shared with other code by just +handing them a namespace accessor function. + + let { dom } = require('./view'); + Widget.prototype.setInnerHTML = function setInnerHTML(html) { + dom(this).element.innerHTML = String(html); + }; + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/observer-service.md b/tools/addon-sdk-1.7/packages/api-utils/docs/observer-service.md new file mode 100644 index 0000000..4d7cb58 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/observer-service.md @@ -0,0 +1,73 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `observer-service` module provides access to the +application-wide observer service singleton. + +For a list of common observer topics across a variety of Mozilla-based +applications, see the MDC page on +[Observer Notifications](https://developer.mozilla.org/en/Observer_Notifications). + +## Observer Callbacks ## + +Observer callbacks are functions of the following form: + + function callback(subject, data) { + /* Respond to the event notification here... */ + } + +In the above example, `subject` is any JavaScript object, as is +`data`. The particulars of what the two contain are specific +to the notification topic. + +<api name="add"> +@function + Adds an observer callback to be triggered whenever a notification matching the + topic is broadcast throughout the application. + +@param topic {string} + The topic to observe. + +@param callback {function,object} + Either a function or an object that implements [`nsIObserver`](http://mxr.mozilla.org/mozilla-central/source/xpcom/ds/nsIObserver.idl). + If a function, then it is called when the notification occurs. If an object, + then its `observe()` method is called when the notification occurs. + +@param [thisObject] {object} + An optional object to use as `this` when a function callback is called. +</api> + +<api name="remove"> +@function + Unsubscribes a callback from being triggered whenever a notification + matching the topic is broadcast throughout the application. + +@param topic {string} + The topic being observed by the previous call to `add()`. + +@param callback {function,object} + The callback subscribed in the previous call to `add()`, either a function or + object. + +@param [thisObject] {object} + If `thisObject` was passed to the previous call to `add()`, it should be + passed to `remove()` as well. +</api> + +<api name="notify"> +@function + Broadcasts a notification event for a topic, passing a subject and data to all + applicable observers in the application. + +@param topic {string} + The topic about which to broadcast a notification. + +@param [subject] {value} + Optional information about the topic. This can be any JS object or primitive. + If you have multiple values to pass to observers, wrap them in an object, + e.g., `{ foo: 1, bar: "some string", baz: myObject }`. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/plain-text-console.md b/tools/addon-sdk-1.7/packages/api-utils/docs/plain-text-console.md new file mode 100644 index 0000000..d139587 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/plain-text-console.md @@ -0,0 +1,7 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +The `plain-text-console` module provides a minimalist implementation +of the [console](dev-guide/console.html) global, +which simply logs all messages to standard output. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/preferences-service.md b/tools/addon-sdk-1.7/packages/api-utils/docs/preferences-service.md new file mode 100644 index 0000000..03b4725 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/preferences-service.md @@ -0,0 +1,116 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Myk Melez [myk@mozilla.org] --> +<!-- contributed by Daniel Aquino [mr.danielaquino@gmail.com] --> +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `preferences-service` module provides access to the +application-wide preferences service singleton. + + +<api name="set"> +@function +Sets the application preference `name` to `value`. +@param name {string} Preference name. +@param value {string,number,bool} Preference value. + +**Example:** + + var name = "extensions.checkCompatibility.nightly"; + require("preferences-service").set(name, false); +</api> + + +<api name="get"> +@function +Gets the application preference `name`. +@param name {string} +@param defaultValue {string,number,bool} Preference value. +@returns {string,number,bool} Preference value, returns a default value if no +preference is set. + +**Example:** + + var name = "extensions.checkCompatibility.nightly"; + var nightlyCompatChk = require("preferences-service").get(name); +</api> + + +<api name="has"> +@function +@param name {string} Preference name. +@returns {bool} Returns whether or not the application preference `name` exists. + +**Example:** + + var name = "extensions.checkCompatibility.nightly"; + if (require("preferences-service").has(name)) { + // ... + } +</api> + + +<api name="isSet"> +@function +@param name {string} Preference name. +@returns {bool} +Returns whether or not the application preference `name` both exists +and has been set to a non-default value by the user (or a program +acting on the user's behalf). + +**Example:** + + var name = "extensions.checkCompatibility.nightly"; + if (require("preferences-service").isSet(name)) { + // ... + } +</api> + + +<api name="reset"> +@function +Clears a non-default, user-set value from the application preference +`name`. If no user-set value is defined on `name`, the function +does nothing. If no default value exists the preference will cease to exist. +@param name {string} Preference name. + +**Example:** + + var name = "extensions.checkCompatibility.nightly"; + require("preferences-service").reset(name); +</api> + +<api name="getLocalized"> +@function +Gets the localized value for an application preference `name`. +@param name {string} +@param defaultValue {string} Preference value. +@returns {string} Localized preference value, returns a default value if no +preference is set. Some preferences refer to a properties file. +So that `prefs.get` returns the properties file URL whereas +`prefs.getLocalized` returns the value defined in the properties file. + +**Example:** + + var prefs = require("preferences-service"); + var name = "general.useragent.locale"; + prefs.get(name); // is equal to "chrome://global/locale/intl.properties" + prefs.getLocalized(name) // is equal to "en-US" + +</api> + +<api name="setLocalized"> +@function +Sets the localized application preference `name` to `value`. +@param name {string} Preference name. +@param value {string} Preference value, a URL to a properties file + +**Example:** + + require("preferences-service").set("general.useragent.locale", + "chrome://global/locale/intl.properties"); + +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/promise.md b/tools/addon-sdk-1.7/packages/api-utils/docs/promise.md new file mode 100644 index 0000000..d67b820 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/promise.md @@ -0,0 +1,394 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +## Rationale + +Most of the JS APIs are asynchronous complementing it's non-blocking nature. +While this has a good reason and many advantages, it comes with a price. +Instead of structuring our programs into logical black boxes: + + function blackbox(a, b) { + var c = assemble(a); + return combine(b, c); + } + + +We're forced into continuation passing style, involving lot's of machinery: + + function sphagetti(a, b, callback) { + assemble(a, function continueWith(error, c) { + if (error) callback(error); + else combine(b, c, callback); + }); + } + +This style also makes doing things in sequence hard: + + widget.on('click', function onClick() { + promptUserForTwitterHandle(function continueWith(error, handle) { + if (error) return ui.displayError(error); + twitter.getTweetsFor(handle, funtion continueWith(error, tweets) { + if (error) return ui.displayError(error); + ui.showTweets(tweets); + }); + }); + }); + +Doing things in parallel is even harder: + + var tweets, answers, checkins; + twitter.getTweetsFor(user, function continueWith(result) { + tweets = result; + somethingFinished(); + }); + + stackOverflow.getAnswersFor(question, function continueWith(result) { + answers = result; + somethingFinished(); + }); + + fourSquare.getCheckinsBy(user, function continueWith(result) { + checkins=result; + somethingFinished(); + }); + + var finished = 0; + functions somethingFinished() { + if (++finished === 3) + ui.show(tweets, answers, checkins); + } + +This also makes error handling quite of an adventure. + +## Promises + +Consider another approach, where instead of continuation passing via `callback`, +function returns an object, that represents eventual result, either successful +or failed. This object is a promise, both figuratively and by name, to +eventually resolve. We can call a function on the promise to observe +either its fulfillment or rejection. If the promise is rejected and the +rejection is not explicitly observed, any derived promises will be implicitly +rejected for the same reason. + +In the Add-on SDK we follow +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) specification +and model a promise as an object with a `then` method, which can be used to get +the eventual return (fulfillment) value or thrown exception (rejection): + + foo().then(function success(value) { + // ... + }, function failure(reason) { + // ... + }); + +If `foo` returns a promise that gets fulfilled with the `value`, `success` +callback (the value handler) will be called with that `value`. However, +if the returned promise gets rejected, the `failure` callback (the error +handler) will be called with the `reason` of an error. + +## Propagation + +The `then` method of a promise returns a new promise that is resolved with the +return value of either handler. Since function can either return value or throw +an exception, only one handler will be ever called. + + + var bar = foo().then(function success(value) { + // compute something from a value... + }, function failure(reason) { + // handle an error... + }); + +In this example `bar` is a promise and it's fulfilled by one of two handlers +that are responsible for: + + - If handler returns a value, `bar` will be resolved with it. + - If handler throws an exception, `bar` will be rejected with it. + - If handler returns a **promise**, `bar` will "become" that promise. To be + more precise it will be resolved with a resolution value of the returned + promise, which will appear and feel as if it was that returned promise. + +If the `foo()` promise gets rejected and you omit the error handler, the +**error** will propagate to `bar` (`bar` will be rejected with that error): + + var bar = foo().then(function success(value) { + // compute something out of the value... + }); + +If the `foo()` promise gets fulfilled and you omit the value handler, the +**value** will propagate to `bar` (`bar` will be fulfilled with that value): + + var bar = foo().then(null, function failure(error) { + // handle error... + }); + + +## Chaining + +There are two ways to chain promise operations. You can chain them using either +inside or outside handlers. + +### Flat chaining + +You can use `then` for chaining intermediate operations on promises +(`var data = readAsync().then(parse).then(extract)`). You can chain multiple +`then` functions, because `then` returns a promise resolved to a return value +of an operation and errors propagate through the promise chains. In general +good rule of thumb is to prefer `then` based flat chaining. It makes code +easier to read and make changes later: + + var data = readAsync(url). // read content of url asynchronously + then(parse). // parse content from the url + then(extractQuery). // extract SQL query + then(readDBAsync); // exectue extracted query against DB + +### Nested chaining + +Flat chaining is not always an option though, as in some cases you may want to +capture an intermediate values of the chain: + + var result = readAsync(url).then(function(source) { + var json = parse(source) + return readDBAsync(extractQuery(json)).then(function(data) { + return writeAsync(json.url, data); + }); + }); + +In general, nesting is useful for computing values from more then one promise: + + function eventualAdd(a, b) { + return a.then(function (a) { + return b.then(function (b) { + return a + b; + }); + }); + } + + var c = eventualAdd(aAsync(), bAsync()); + +## Error handling + +One sometimes-unintuitive aspect of promises is that if you throw an exception +in the value handler, it will not be be caught by the error handler. + + readAsync(url).then(function (value) { + throw new Error("Can't bar."); + }, function (error) { + // We only get here if `readAsync` fails. + }); + +To see why this is, consider the parallel between promises and `try`/`catch`. +We are `try`-ing to execute `readAsync()`: the error handler represents a +`catch` for `readAsync()`, while the value handler represents code that happens +*after* the `try`/`catch` block. That code then needs its own `try`/`catch` +block to handle errors there. + +In terms of promises, this means chaining your error handler: + + readAsync(url). + then(parse). + then(null, function handleParseError(error) { + // handle here both `readAsync` and `parse` errors. + }); + + +# Consuming promises + +In general, whole purpose of promises is to avoid a callback spaghetti in the +code. As a matter of fact it would be great if we could convert any synchronous +functions to asynchronous by making it aware of promises. Module exports +`promised` function to do exactly that: + + const { promised } = require('api-utils/promise'); + function sum(x, y) { return x + y } + var sumAsync = promised(sum); + + var c = sum(a, b); + var cAsync = asyncSum(aAsync(), bAsinc()); + +`promised` takes normal function and composes new promise aware version of it +that may take both normal values and promises as arguments and returns promise +that will resolve to value that would have being returned by an original +function if it was called with fulfillment values of given arguments. + +This technique is so powerful that it can replace most of the promise utility +functions provided by other promise libraries. For example grouping promises +to observe single resolution of all of them is as simple as this: + + var group = promised(Array); + var abc = group(aAsync, bAsync, cAsync).then(function(items) { + return items[0] + items[1] + items[2]; + }); + +# Making promises + +Everything above assumes you get a promise from somewhere else. This +is the common case, but every once in a while, you will need to create a +promise from scratch. Add-on SDK's `promise` module provides API for doing +that. + +## defer + +Module exports `defer` function, which is where all promises ultimately +come from. Lets see implementation of `readAsync` that we used in lot's +of examples above: + + const { defer } = require('api-utils/promise'); + function readAsync(url) { + var deferred = defer(); + + let xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.onload = function() { + deferred.resolve(xhr.responseText); + } + xhr.onerror = function(event) { + deferred.reject(event); + } + xhr.send(); + + return deferred.promise; + } + +So `defer` returns an object that contains `promise` and two `resolve`, `reject` +functions that can be used to resolve / reject that `promise`. **Note:** that +promise can be rejected or resolved and only once. All subsequent attempts will be +ignored. + +Another simple example may be `delay` function that returns promise which +is fulfilled with a given `value` in a given `ms`, kind of promise based +alternative to `setTimeout`: + + function delay(ms, value) { + let { promise, resolve } = defer(); + setTimeout(resolve, ms, value); + return promise; + } + + delay(10, 'Hello world').then(console.log); + // After 10ms => 'Helo world' + +# Advanced usage + +If general `defer` and `promised` should be enough to doing almost anything +you may think of with promises, but once you start using promises extensively +you may discover some missing pieces and this section of documentation may +help you to discover them. + +## Doing things concurrently + +So far we have being playing with promises that do things sequentially, but +there are bunch of cases where one would need to do things concurrently. In the +following example we implement functions that takes multiple promises and +returns one that resolves to first on being fulfilled: + + function race() { + let { promise, resolve } = defer(); + Array.slice(arguments).forEach(function(promise) { + promise.then(resolve); + }); + return promise; + } + + var asyncAorB = race(readAsync(urlA), readAsync(urlB)); + +*Note: that this implementation forgives failures and would fail if all +promises fail to resolve.* + +There are cases when promise may or may not be fulfilled in a reasonable time. +In such cases it's useful to put a timer on such tasks: + + function timeout(promise, ms) { + let deferred = defer(); + promise.then(deferred.resolve, deferred.reject); + delay(ms, 'timeout').then(deferred.reject); + return deferred.promise; + } + + var tweets = readAsync(url); + timeout(tweets, 20).then(function(data) { + ui.display(data); + }, function() { + alert('Network is being too slow, try again later'); + }); + +## Alternative promise APIs + +There may be a cases where you will want to provide more than just `then` +method on your promises. In fact some other promise frameworks do that. +Such use cases are also supported. Earlier described `defer` may be passed +optional `prototype` argument, in order to make returned promise and all +the subsequent promises decedents of that `prototype`: + + let { promise, resolve } = defer({ + get: function get(name) { + return this.then(function(value) { + return value[name]; + }) + } + }); + + promise.get('foo').get('bar').then(console.log); + resolve({ foo: { bar: 'taram !!' } }); + + // => 'taram !!' + +Also `promised` function maybe passed second optional `prototype` argument to +achieve same effect. + +## Treat all values as promises + +Module provides a simple function for wrapping values into promises: + + const { resolve } = require('api-utils/promise'); + + var a = resolve(5).then(function(value) { + return value + 2 + }); + a.then(console.log); // => 7 + +Also `resolve` not only takes values, but also promises. If you pass it +a promise it will return new identical one: + + const { resolve } = require('api-utils/promise'); + + resolve(resolve(resolve(3))).then(console.log); // => 3 + +If this construct may look strange at first, but it becomes quite handy +when writing functions that deal with both promises and values. In such +cases it's usually easier to wrap value into promise than branch on value +type: + + function or(a, b) { + var second = resolve(b).then(function(bValue) { return !!bValue }); + return resolve(a).then(function(aValue) { + return !!aValue || second; + }, function() { + return second; + }) + } + +*Note: We could not use `promised` function here, as they reject returned +promise if any of the given arguments is rejected.* + +If you need to customize your promises even further you may pass `resolve` a +second optional `prototype` argument that will have same effect as with `defer`. + +## Treat errors as promises + +Now that we can create all kinds of eventual values, it's useful to have a +way to create eventual errors. Module exports `reject` exactly for that. +It takes anything as an argument and returns a promise that is rejected with +it. + + const { reject } = require('api-utils/promise'); + + var boom = reject(Error('boom!')); + + future(function() { + return Math.random() < 0.5 ? boom : value + }) + +As with rest of the APIs error may be given second optional `prototype` +argument to customize resulting promise to your needs. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/querystring.md b/tools/addon-sdk-1.7/packages/api-utils/docs/querystring.md new file mode 100644 index 0000000..30f4117 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/querystring.md @@ -0,0 +1,37 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Module exports utility functions for working with query strings. + +### stringify + +Object may be serialize to a query string via exported `stringify` function: + + querystring.stringify({ foo: 'bar', baz: 4 }); // => 'foo=bar&baz=4' + +Optionally `separator` and `assignment` arguments may be passed to +override default `'&'` and`'='` characters: + + querystring.stringify({ foo: 'bar', baz: 4 }, ';', ':'); // => 'foo:bar;baz:4' + +### parse + +Query string may be deserialized to an object via exported `parse` +function: + + querystring.parse('foo=bar&baz=bla') // => { foo: 'bar', baz: 'bla' } + +Optionally `separator` and `assignment` arguments may be passed to +override default `'&'` and `'='` characters: + + querystring.parse('foo:bar|baz:bla', '|', ':') // => { foo: 'bar', baz: 'bla' } + +### escape + +The escape function used by `stringify` to encodes a string safely +matching RFC 3986 for `application/x-www-form-urlencoded`. + +### unescape + +The unescape function used by `parse` to decode a string safely. diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/runtime.md b/tools/addon-sdk-1.7/packages/api-utils/docs/runtime.md new file mode 100644 index 0000000..c8d8ed3 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/runtime.md @@ -0,0 +1,75 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Wes Kocher [kwierso@gmail.com] --> + +The `runtime` module provides access to information about Firefox's +runtime environment. All properties exposed are read-only. + +For more information, see [nsIXULRuntime][nsIXULRuntime]. +[nsIXULRuntime]: https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIXULRuntime + +<api name="inSafeMode"> +@property {boolean} + This value is `true` if Firefox was started in safe mode, + otherwise `false`. +</api> + +<api name="OS"> +@property {string} + A string identifying the current operating system. For example, . + `"WINNT"`, `"Darwin"`, or `"Linux"`. See [OS_TARGET][OS_TARGET] + for a more complete list of possible values. + +[OS_TARGET]: https://developer.mozilla.org/en/OS_TARGET +</api> + +<api name="processType"> +@property {long} + The type of the caller's process, which will be one of these constants\: +<table> + <tr> + <th>Constant</th> + <th>Value</th> + <th>Description</th> + </tr> + + <tr> + <td>PROCESS_TYPE_DEFAULT</td> + <td>0</td> + <td>The default (chrome) process.</td> + </tr> + + <tr> + <td>PROCESS_TYPE_PLUGIN</td> + <td>1</td> + <td>A plugin subprocess.</td> + </tr> + + <tr> + <td>PROCESS_TYPE_CONTENT</td> + <td>2</td> + <td>A content subprocess.</td> + </tr> + + <tr> + <td>PROCESS_TYPE_IPDLUNITTEST</td> + <td>3</td> + <td>An IPDL unit testing subprocess.</td> + </tr> +</table> +</api> + +<api name="widgetToolkit"> +@property {string} + A string identifying the target widget toolkit in use. +</api> + +<api name="XPCOMABI"> +@property {string} + A string identifying the [ABI][ABI] of the current processor and compiler vtable. + This string takes the form \<`processor`\>-\<`compilerABI`\>, + for example\: "`x86-msvc`" or "`ppc-gcc3`". +[ABI]: https://developer.mozilla.org/en/XPCOM_ABI +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/sandbox.md b/tools/addon-sdk-1.7/packages/api-utils/docs/sandbox.md new file mode 100644 index 0000000..026b569 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/sandbox.md @@ -0,0 +1,51 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Provides an API for creating javascript sandboxes and for executing scripts +in them. + +### Create a sandbox ### + +For the starting point you need to create a sandbox: + + const { sandbox, evaluate, load } = require("api-utils/sandbox"); + let scope = sandbox('http://example.com'); + +Argument passed to the sandbox defines it's privileges. Argument may be an URL +string, in which case sandbox will get exact same privileges as a scripts +loaded from that URL. Argument also could be a DOM window object, to inherit +privileges from the window being passed. Finally if argument is omitted or is +`null` sandbox will have a chrome privileges giving it access to all the XPCOM +components. Optionally `sandbox` function can be passed a second optional +argument (See [sandbox documentation on MDN](https://developer.mozilla.org/en/Components.utils.Sandbox#Optional_parameter) +for details). + +### Evaluate code ### + +Module provides `evaluate` function that allows executing code in the given +sandbox: + + evaluate(scope, 'var a = 5;'); + evaluate(scope, 'a + 2;'); //=> 7 + +More details about evaluated script may be passed via optional arguments that +may improve an exception reporting: + + // Evaluate code as if it was loaded from 'http://foo.com/bar.js' and + // start from 2nd line. + evaluate(scope, 'a ++', 'http://foo.com/bar.js', 2); + +Version of JavaScript can be also specified via optional argument: + + evaluate(scope, 'let b = 2;', 'bar.js', 1, '1.5'); + // throws cause `let` is not defined in JS 1.5. + +### Loading scripts ### + +API provides limited API for loading scripts right form the local URLs, +but data: URLs are supported. + + load(scope, 'resource://path/to/my/script.js'); + load(scope, 'file:///path/to/script.js'); + load(scope, 'data:,var a = 5;');
\ No newline at end of file diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/tab-browser.md b/tools/addon-sdk-1.7/packages/api-utils/docs/tab-browser.md new file mode 100644 index 0000000..295fcc7 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/tab-browser.md @@ -0,0 +1,140 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Dietrich Ayala [dietrich@mozilla.com] --> + +The `tab-browser` module is a low-level API that provides privileged +access to browser tab events and actions. + +Introduction +------------ + +The `tab-browser` module contains helpers for tracking tabbrowser elements +and tabs, as well as a few utilities for actions such as opening a new +tab, and catching all tab content loads. + +This is a low-level API that has full privileges, and is intended to be used +by SDK internal modules. If you just need easy access to tab events for your +add-on, use the Tabs module (JEP 110). + +<api name="activeTab"> +@property {element} +The XUL tab element of the currently active tab. +</api> + +<api name="addTab"> +@function +Adds a new tab. + +**Example** + + var tabBrowser = require("tab-browser"); + tabBrowser.addTab("http://google.com"); + + var tabBrowser = require("tab-browser"); + tabBrowser.addTab("http://google.com", { + inBackground: true + }); + + var tabBrowser = require("tab-browser"); + tabBrowser.addTab("http://google.com", { + inNewWindow: true, + onLoad: function(tab) { + console.log("tab is open."); + } + }); + +@returns {element} +The XUL tab element of the newly created tab. + +@param URL {string} +The URL to be opened in the new tab. + +@param options {object} +Options for how and where to open the new tab. + +@prop [inNewWindow] {boolean} +An optional parameter whose key can be set in `options`. +If true, the tab is opened in a new window. Default is false. + +@prop [inBackground] {boolean} +An optional parameter whose key can be set in `options`. +If true, the tab is opened adjacent to the active tab, but not +switched to. Default is false. + +@prop [onLoad] {function} +An optional parameter whose key can be set in `options`. +A callback function that is called once the tab has loaded. +The XUL element for the tab is passed as a parameter to +this function. +</api> + +<api name="Tracker"> +@function +Register a delegate object to be notified when tabbrowsers are created +and destroyed. + +The onTrack method will be called once per pre-existing tabbrowser, upon +tracker registration. + +**Example** + + var tabBrowser = require("tab-browser"); + let tracker = { + onTrack: function(tabbrowser) { + console.log("A new tabbrowser is being tracked."); + }, + onUntrack: function(tabbrowser) { + console.log("A tabbrowser is no longer being tracked."); + } + }; + tabBrowser.Tracker(tracker); + +@param delegate {object} +Delegate object to be notified each time a tabbrowser is created or destroyed. +The object should contain the following methods: + +@prop [onTrack] {function} +Method of delegate that is called when a new tabbrowser starts to be tracked. +The tabbrowser element is passed as a parameter to this method. + +@prop [onUntrack] {function} +Method of delegate that is called when a tabbrowser stops being tracked. +The tabbrowser element is passed as a parameter to this method. +</api> + +<api name="TabTracker"> +@function +Register a delegate object to be notified when tabs are opened and closed. + + +The onTrack method will be called once per pre-existing tab, upon +tracker registration. + +**Example** + + var tabBrowser = require("tab-browser"); + let tracker = { + onTrack: function(tab) { + console.log("A new tab is being tracked."); + }, + onUntrack: function(tab) { + console.log("A tab is no longer being tracked."); + } + }; + tabBrowser.TabTracker(tracker); + +@param delegate {object} +Delegate object to be notified each time a tab is opened or closed. +The object should contain the following methods: + +@prop [onTrack] {function} +Method of delegate that is called when a new tab starts to be tracked. +The tab element is passed as a parameter to this method. + +@prop [onUntrack] {function} +Method of delegate that is called when a tab stops being tracked. +The tab element is passed as a parameter to this method. +</api> + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/text-streams.md b/tools/addon-sdk-1.7/packages/api-utils/docs/text-streams.md new file mode 100644 index 0000000..55f177c --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/text-streams.md @@ -0,0 +1,102 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `text-streams` module provides streams for reading and writing text using +particular character encodings. + +<api name="TextReader"> +@class +<api name="TextReader"> +@constructor + Creates a buffered input stream that reads text from a backing stream using a + given text encoding. +@param inputStream {stream} + The backing stream, an [`nsIInputStream`](http://mxr.mozilla.org/mozilla-central/source/xpcom/io/nsIInputStream.idl). + It must already be opened. +@param [charset] {string} + `inputStream` is expected to be in the character encoding named by this value. + If not specified, "UTF-8" is assumed. See [`nsICharsetConverterManager.idl`](http://mxr.mozilla.org/mozilla-central/source/intl/uconv/idl/nsICharsetConverterManager.idl) + for documentation on how to determine other valid values for this. +</api> + +<api name="closed"> +@property {boolean} + True if the stream is closed. +</api> + +<api name="close"> +@method + Closes both the stream and its backing stream. +</api> + +<api name="read"> +@method + Reads and returns a string from the stream. If the stream is closed, an + exception is thrown. +@param [numChars] {number} + The number of characters to read. If not given, the remainder of the stream + is read. +@returns {string} + The string read. If the stream is at the end, the empty string is returned. +</api> + +</api> + + +<api name="TextWriter"> +@class +<api name="TextWriter"> +@constructor + Creates a buffered output stream that writes text to a backing stream using a + given text encoding. +@param outputStream {stream} + The backing stream, an [`nsIOutputStream`](http://mxr.mozilla.org/mozilla-central/source/xpcom/io/nsIOutputStream.idl). + It must already be opened. +@param [charset] {string} + Text will be written to `outputStream` using the character encoding named by + this value. If not specified, "UTF-8" is assumed. See [`nsICharsetConverterManager.idl`](http://mxr.mozilla.org/mozilla-central/source/intl/uconv/idl/nsICharsetConverterManager.idl) + for documentation on how to determine other valid values for this. +</api> + +<api name="closed"> +@property {boolean} + True if the stream is closed. +</api> + +<api name="close"> +@method + Flushes the backing stream's buffer and closes both the stream and the backing + stream. If the stream is already closed, an exception is thrown. +</api> + +<api name="flush"> +@method + Flushes the backing stream's buffer. +</api> + +<api name="write"> +@method + Writes a string to the stream. If the stream is closed, an exception is + thrown. +@param str {string} + The string to write. +</api> + +<api name="writeAsync"> +@method + Writes a string on a background thread. After the write completes, the + backing stream's buffer is flushed, and both the stream and the backing stream + are closed, also on the background thread. If the stream is already closed, + an exception is thrown immediately. +@param str {string} + The string to write. +@param [callback] {callback} + *`callback`*, if given, must be a function. It's called as `callback(error)` + when the write completes. `error` is an `Error` object or undefined if there + was no error. Inside *`callback`*, `this` is the `TextWriter` object. +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/traceback.md b/tools/addon-sdk-1.7/packages/api-utils/docs/traceback.md new file mode 100644 index 0000000..b52c183 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/traceback.md @@ -0,0 +1,66 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + + +The `traceback` module contains functionality similar to +Python's [traceback](http://docs.python.org/library/traceback.html) module. + +## JSON Traceback Objects ## + +Tracebacks are stored in JSON format. The stack is represented as an +array in which the most recent stack frame is the last element; each +element thus represents a stack frame and has the following keys: + +<table> + <tr> + <td><code>filename</code></td> + <td>The name of the file that the stack frame takes place in.</td> + </tr> + <tr> + <td><code>lineNo</code></td> + <td>The line number is being executed at the stack frame.</td> + </tr> + <tr> + <td><code>funcName</code></td> + <td>The name of the function being executed at the stack frame, or + <code>null</code> if the function is anonymous or the stack frame is + being executed in a top-level script or module.</td> + </tr> +</table> + +<api name="fromException"> +@function + Attempts to extract the traceback from *`exception`*. + +@returns {traceback} + JSON representation of the traceback or `null` if not found. + +@param exception {exception} + exception where exception is an `nsIException`. +</api> + +See [nsIException](https://developer.mozilla.org/en/NsIException) for more +information. + +<api name="get"> +@function + +@returns {JSON} + Returns the JSON representation of the stack at the point that this + function is called. +</api> + +<api name="format"> +@function +Given a JSON representation of the stack or an exception instance, +returns a formatted plain text representation of it, similar to +Python's formatted stack tracebacks. If no argument is provided, the +stack at the point this function is called is used. + +@param [tbOrException] {object} +</api> + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/traits.md b/tools/addon-sdk-1.7/packages/api-utils/docs/traits.md new file mode 100644 index 0000000..910cd9a --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/traits.md @@ -0,0 +1,244 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Irakli Gozalishvil [gozala@mozilla.com] --> + +The `traits` module provides base building blocks for secure object +composition. It exports base trait / constructor function that +constructs an instance of `Trait`. + +[Traits](http://en.wikipedia.org/wiki/Trait_%28computer_science%29) are a +simple composition mechanism for structuring object-oriented programs. Traits +are similar to +[interfaces](http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29), +except that they often define only a part of an object's data and behavior and +are intended to be used in conjunction with other traits to completely define +the object. + +Traits are also considered to be a more robust alternative to +[mixins](http://en.wikipedia.org/wiki/Mixins) because, name conflicts have to +be resolved explicitly by composer & because trait composition is +order-independent (hence more declarative). + + +There are some other implementations of traits in JavaScript & some ideas / +APIs are borrowed from them: + +- [traitsjs](http://www.traitsjs.org/) +- [joose](http://code.google.com/p/joose-js/) + +Object-capability security model +-------------------------------- + +Implementation uses an +[object-capability security model](http://en.wikipedia.org/wiki/Object-capability_model) +to allow protection of private APIs. At the same private APIs can be shared +between among trait composition parties. To put it simply: All the properties +whose names start with `"_"` are considered to be **private**, and are +unaccessible from anywhere except other **public** methods / accessors of the +instance that had been defined during composition. + +<api name="Trait"> +@class +<api name="Trait"> +@constructor +Creates an instance of Trait and returns it if it has no `constructor` method +defined. If instance has `constructor` method, then it is called with all the +arguments passed to this function and returned value is returned instead, +unless it's `undefined`. In that case instance is returned. + +`Trait` function represents a base trait. As with any other trait it represents +a constructor function for creating instances of its own & a placeholder +for a trait compositions functions. +</api> + +<api name="compose"> +@method +Composes new trait out of itself and traits / property maps passed as an +arguments. If two or more traits / property maps have properties with the same +name, the new trait will contain a "conflict" property for that name (see +examples in Examples section to find out more about "conflict" properties). +This is a commutative and associative operation, and the order of its +arguments is not significant. + +**Examples:** + +Let's say we want to define a reusable piece of code for a lists of elements. + + var { Trait } = require('traits'); + var List = Trait.compose({ + // private API: + _list: null, + // public API + constructor: function List() { + this._list = []; + }, + get length() this._list.length, + add: function add(item) this._list.push(item), + remove: function remove(item) { + let list = this._list; + let index = list.indexOf(item); + if (0 <= index) list.splice(index, 1); + } + }); + +Instances of `List` can be created by calling `List` function with or without +`new` keyword. + + let l1 = List(); + l1 instanceof List; // true + let l2 = new List(); + l2 instanceof List; // true + +As you can see `add` and `remove` functions are capable of accessing private +`_list` property, but thats about it, there's nothing else that will be able +to access this property: + + '_list' in l1; // false + '_list' in l2; // false + '_list' in List.protoype; // false + l1.has = function(name) name in this + l1.has('_list'); // false + l1.length; // 0 + l1.add('test') + l1.length // 1 + +@param trait1 {Object|Function} + Trait or property map to compose new trait from. +@param trait2 {Object|Function} + Trait or property map to compose new trait from. +@param ... {Object|Function} + Traits or property maps to compose new trait from. + +@returns {Function} + New trait containing the combined properties of all the traits. +</api> + +<api name="required"> +@property {Object} +Singleton, used during trait composition to define "required" properties. + +**Example:** + + var Enumerable = Trait.compose({ + list: Trait.required, + forEach: function forEach(consumer) { + return this.list.forEach(consumer); + } + }); + + let c1 = Enumerable(); // Error: Missing required property: list + + var EnumerableList = List.compose({ + get list() this._list.slice(0) + }, Enumerable); + + let c2 = EnumerableList(); + c2.add('test') + c2.length // 1 + c2.list[0] // 'test' + c2.forEach(console.log) // > info: 'test 0 test' + +</api> + + +<api name="resolve"> +@method +Composes a new trait that has all the same properties +as the trait on which it is called, except that each property listed +in the `resolutions` argument will be renamed from the name +of the property in the `resolutions` argument to its value. +And if its value is `null`, the property will become required. + +**Example:** + + var Range = List.resolve({ + constructor: null, + add: '_add', + }).compose({ + min: null, + max: null, + get list() this._list.slice(0), + constructor: function Range(min, max) { + this.min = min; + this.max = max; + this._list = []; + }, + add: function(item) { + if (item <= this.max && item >= this.min) + this._add(item) + } + }); + + + let r = Range(0, 10); + r.min; // 0 + r.max; // 10 + r.length; // 0; + r.add(5); + r.length; // 1 + r.add(12); + r.length; // 1 (12 was not in a range) + +@param resolutions {Object} +@returns {Function} + New resolved trait. +</api> + +<api name="override"> +@method +Composes a new trait with all of the combined properties of `this` and the +argument traits. In contrast to `compose`, `override` immediately resolves +all conflicts resulting from this composition by overriding the properties of +later traits. Trait priority is from left to right. I.e. the properties of +the leftmost trait are never overridden. + +**Example:** + + // will compose trait with conflict property 'constructor' + var ConstructableList = List.compose({ + constructor: function List() this._list = Array.slice(arguments) + }); + // throws error with message 'Remaining conflicting property: constructor' + ConstructableList(1, 2, 3); + + var ConstructableList = List.override({ + constructor: function List() this._list = Array.slice(arguments) + }); + ConstructableList(1, 2, 3).length // 3 + +@param trait1 {Object|Function} + Trait or property map to compose new trait from. +@param trait2 {Object|Function} + Trait or property map to compose new trait from. +@param ... {Object|Function} + Traits or property maps to compose new trait from. + +@returns {Function} + New trait containing the combined properties of all the traits. +</api> + +<api name="_public"> +@property {Object} +Internal property of instance representing public API that is exposed to the +consumers of an instance. +</api> + +<api name='toString'> +@method +Textual representation of an object. All the traits will return: +`'[object Trait]'` string, unless they have `constructor` property, in that +case string `'Trait'` is replaced with the name of `constructor` property. + +**Example:** + + var MyTrait = Trait.compose({ + constructor: function MyTrait() { + // do your initialization here + } + }); + MyTrait().toString(); // [object MyTrait] + +</api> +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/unit-test.md b/tools/addon-sdk-1.7/packages/api-utils/docs/unit-test.md new file mode 100644 index 0000000..6962c41 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/unit-test.md @@ -0,0 +1,393 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> +<!-- edited by Shane Tomlinson[stomlinson@mozilla.com] --> + +The `unit-test` module makes it easy to find and run unit tests. + +<api name="test"> +@class +Each function which represents a test case is passed a single argument +`test`, which represents the test runner. + +<api name="pass"> +@method + Marks a test as passing, with the given optional message. + +@param [message] {string} + Optional passing message. +</api> + + +<api name="fail"> +@method + Marks a test as failing, with the given optional message. + +@param [message] {string} + Optional failure message. +</api> + +<api name="expectFail"> +@method + *experimental* Expect the test enclosed within `func` to fail. + +@param func {function} + A function that should contain a test that is expected to fail. +</api> + +<api name="exception"> +@method + Marks a test as failing due to the given exception having been thrown. + This can be put in a `catch` clause. + +@param e {exception} + An exception. +</api> + +<api name="assert"> +@method + Ensures that `a` has a truthy value. + +@param a {value} + Value to verify. +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + + +<api name="assertEqual"> +@method + Ensures that `a == b` without recursing into `a` or `b`. + +@param a {value} + A value. + +@param b {value} + Another value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + +<api name="assertNotEqual"> +@method + Ensures that `a != b` without recursing into `a` or `b`. + +@param a {value} + A value. + +@param b {value} + Another value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + +<api name="assertStrictEqual"> +@method + Ensures that `a === b` without recursing into `a` or `b`. + +@param a {value} + A value. + +@param b {value} + Another value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + + +<api name="assertNotStrictEqual"> +@method + Ensures that `a !== b` without recursing into `a` or `b`. + +@param a {value} + A value. + +@param b {value} + Another value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + +<api name="assertMatches"> +@method + Ensures that the given string matches the given regular expression. + If it does, marks a test as passing, otherwise marks a test as + failing. + +@param string {string} + The string to test. + +@param regexp {regexp} + The string should match this regular expression. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + + +<api name="assertRaises"> +@method + Calls the function `func` with no arguments, expecting an exception + to be raised. If nothing is raised, marks the test as failing. If an + exception is raised, the exception's `message` property is + compared with `predicate`: if `predicate` is a string, then a + simple equality comparison is done with `message`. Otherwise, + if `predicate` is a regular expression, `message` is tested + against it. + +@param func {function} + A function that should raise an exception when called. + +@param predicate {string,regexp} + A string or regular expression to compare to the exception's message. + +@param [message] {string} + Depending on the outcome, a test is marked as passing or failing, and + *message* is logged. +</api> + + +<api name="assertFunction"> +@method + Ensures that `a` is a function. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertUndefined"> +@method + Ensures that `a` is `undefined`. `null`, `0`, and `false` will all fail. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertNotUndefined"> +@method + Ensures that `a` is not `undefined`. `null`, `0`, and `false` will all pass. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertNull"> +@method + Ensures that `a` is `null`. `undefined`, `0`, and `false` will all fail. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertNotNull"> +@method + Ensures that `a` is not `null`. `undefined`, `0`, and `false` will all pass. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertObject"> +@method + Ensures that `a` is an object. A function, string, or number will fail. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertString"> +@method + Ensures that `a` is a string. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertArray"> +@method + Ensures that `a` is an array. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="assertNumber"> +@method + Ensures that `a` is a number. + +@param a {value} + A value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. + +</api> + + +<api name="waitUntilDone"> +@method + Puts the test runner into asynchronous testing mode, waiting up to + *timeout* milliseconds for `test.done()` to be called. This + is intended for use in situations where a test suite schedules a + callback, calls `test.waitUntilDone()`, and then calls + `test.done()` in the callback. + +@param [timeout] {integer} + If this number of milliseconds elapses and `test.done()` has not yet been + called, the test is marked as failing. +</api> + + +<api name="done"> +@method + Marks a test as being complete. Assumes a previous call to + `test.waitUntilDone()`. +</api> + +</api> + + +<api name="waitUntil"> +@method + Ensures that `a` returns a truthy value within a reasonable amount of time. + +@param a {function} + Function that returns the value to verify. +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + + +<api name="waitUntilEqual"> +@method + Ensures that `a == b` returned values or values without without recursing + into `a` or `b`. + +@param a {Function} + A value, or a function that returns a value. + +@param b {value} + Another value, or a function that returns value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + +<api name="waitUntilNotEqual"> +@method + Ensures that `a != b` without recursing into `a` or `b`. + +@param a {Function} + A value, or a function that returns a value. + +@param b {value} + Another value, or a function that returns another value. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + + +<api name="waitUntilMatches"> +@method + Ensures that the given string matches the given regular expression. + If it does, marks the test as passing, otherwise marks the test as + failing. + +@param string {Function} + A function that returns the string to test. + +@param regexp {regexp} + The string should match this regular expression. + +@param [message] {string} + The test is marked as passing or failing depending on the result, logging + *message* with it. +</api> + + + +<api name="findAndRunTests"> +@function + The list of directories is searched for SecurableModules that start + with the prefix `test-`. Each module matching this criteria is + expected to export functions that are test cases or a suite of test + cases; each is called with a single argument, which is a Test Runner + Object. + +@param options {object} + An object with the following properties: + @prop dirs {string} + A list of absolute paths representing directories to search + for tests in. It's assumed that all of these directories are also + in the module search path, i.e. any JS files found in them are + SecurableModules that can be loaded via a call to + `require()`. + @prop onDone {function} + A function to call when testing is complete. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/unload.md b/tools/addon-sdk-1.7/packages/api-utils/docs/unload.md new file mode 100644 index 0000000..8a76b3f --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/unload.md @@ -0,0 +1,61 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `unload` module allows modules to register callbacks that are called +when they are unloaded. It is similar to the CommonJS module of the same +name in the [Narwhal][] platform. + +[Narwhal]: http://narwhaljs.org/ + +<api name="ensure"> +@function + Calling `ensure()` on an object does two things: + + 1. It replaces a destructor method with a wrapper method that will never call + the destructor more than once. + 2. It ensures that this wrapper method is called when `send()` is + called. + + Therefore, when you register an object with `ensure()`, you can call its + destructor method yourself, you can let it happen for you, or you can do both. + + The destructor will be called with a single argument describing the reason + for the unload; see `when()`. If `object` does not have the expected + destructor method, then an exception is thrown when `ensure()` is called. + +@param object {object} + An object that defines a destructor method. +@param [name] {string} + Optional name of the destructor method. Default is `unload`. +</api> + +<api name="when"> +@function + Registers a function to be called when `send()` is called. + +@param callback {function} + A function that will be called when `send()` is called. It is called with a + single argument, one of the following strings describing the reason for + unload: `"uninstall"`, `"disable"`, `"shutdown"`, `"upgrade"`, or + `"downgrade"`. (On Gecko 1.9.2-based applications such as Firefox 3.6, + `"upgrade"` and `"downgrade"` are not available, and `"shutdown"` will be sent + in their place.) If a reason could not be determined, `undefined` will be + passed instead. Note that if an add-on is unloaded with reason `"disable"`, + it will not be notified about `"uninstall"` while it is disabled. A solution + to this issue is being investigated; see bug 571049. +</api> + +<api name="send"> +@function + Sends an "unload signal", thereby triggering all callbacks registered via + `when()`. In general, this function need not be manually called; it is + automatically triggered by the embedder. + +@param [reason] {string} + An optional string describing the reason for unload; see `unload.when()`. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/url.md b/tools/addon-sdk-1.7/packages/api-utils/docs/url.md new file mode 100644 index 0000000..2974797 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/url.md @@ -0,0 +1,85 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + + +The `url` module provides functionality for the parsing and retrieving of URLs. + +<api name="URL"> +@class +<api name="URL"> +@constructor + The URL constructor creates an object that represents a URL, verifying that + the provided string is a valid URL in the process. Any API in the SDK which + has a URL parameter will accept `URL` objects, not raw strings, unless + otherwise noted. + +@param source {string} + A string to be converted into a URL. If `source` is not a valid URI, this + constructor will throw an exception. + +@param [base] {string} + An optional string used to resolve relative `source` URLs into absolute ones. +</api> + +<api name="scheme"> +@property {string} + The name of the protocol in the URL. +</api> + +<api name="userPass"> +@property {string} + The username:password part of the URL, `null` if not present. +</api> + +<api name="host"> +@property {string} + The host of the URL, `null` if not present. +</api> + +<api name="port"> +@property {integer} + The port number of the URL, `null` if none was specified. +</api> + +<api name="path"> +@property {string} + The path component of the URL. +</api> + +<api name="toString"> +@method + Returns a string representation of the URL. +@returns {string} + The URL as a string. +</api> +</api> + +<api name="toFilename"> +@function + Attempts to convert the given URL to a native file path. This function will + automatically attempt to resolve non-file protocols, such as the `resource:` + protocol, to their place on the file system. An exception is raised if the URL + can't be converted; otherwise, the native file path is returned as a string. + +@param url {string} + The URL, as a string, to be converted. + +@returns {string} + The converted native file path as a string. +</api> + +<api name="fromFilename"> +@function + Converts the given native file path to a `file:` URL. + +@param path {string} + The native file path, as a string, to be converted. + +@returns {string} + The converted URL as a string. +</api> + diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/uuid.md b/tools/addon-sdk-1.7/packages/api-utils/docs/uuid.md new file mode 100644 index 0000000..429e3a0 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/uuid.md @@ -0,0 +1,27 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Module `uuid` provides low level API for generating / parsing UUID, that may +be necessary when hacking on internals of the platform. + + +## Generate UUID + +Module exports `uuid` function. When called without arguments it will uses +platform-specific methods to obtain a `nsID` that can be considered to be +globally unique. + + let uuid = require('api-utils/uuid').uuid() + +## Parsing UUID + +Sometimes one might need to create `nsID` from an existing UUID string. Same +`uuid` function may be used to parse such UUID strings into an `nsID`: + + let { uuid } = require('api-utils/uuid'); + let firefoxUUID = uuid('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}'); + +For more details about UUID representations and what they are used for by the +platform see MDN documentation for +[JSID](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIJSID) diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/window-utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/window-utils.md new file mode 100644 index 0000000..1435fd2 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/window-utils.md @@ -0,0 +1,88 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> +<!-- edited by Erik Vold [erikvvold@gmail.com] --> + +The `window-utils` module provides helpers for accessing and tracking +application windows. These windows implement the [`nsIDOMWindow`][nsIDOMWindow] +interface. + +[nsIDOMWindow]: http://mxr.mozilla.org/mozilla-central/source/dom/interfaces/base/nsIDOMWindow.idl + +<api name="WindowTracker"> +@class +`WindowTracker` objects make it easy to "monkeypatch" windows when a program is +loaded and "un-monkeypatch" those windows when the program is unloaded. For +example, if a Firefox add-on needs to add a status bar icon to all browser +windows, it can use a single `WindowTracker` object to gain access to windows +when they are opened and closed and also when the add-on is loaded and unloaded. + +When a window is opened or closed, a `WindowTracker` notifies its delegate +object, which is passed to the constructor. The delegate is also notified of +all windows that are open at the time that the `WindowTracker` is created and +all windows that are open at the time that the `WindowTracker` is unloaded. The +caller can therefore use the same code to act on all windows, regardless of +whether they are currently open or are opened in the future, or whether they are +closed while the parent program is loaded or remain open when the program is +unloaded. + +When a window is opened or when a window is open at the time that the +`WindowTracker` is created, the delegate's `onTrack()` method is called and +passed the window. + +When a window is closed or when a window is open at the time that the +`WindowTracker` is unloaded, the delegate's `onUntrack()` method is called and +passed the window. (The `WindowTracker` is unloaded when its its `unload()` +method is called, or when its parent program is unloaded, disabled, or +uninstalled, whichever comes first.) + +**Example** + + var delegate = { + onTrack: function (window) { + console.log("Tracking a window: " + window.location); + // Modify the window! + }, + onUntrack: function (window) { + console.log("Untracking a window: " + window.location); + // Undo your modifications! + } + }; + var winUtils = require("window-utils"); + var tracker = new winUtils.WindowTracker(delegate); + +<api name="WindowTracker"> +@constructor + A `WindowTracker` object listens for openings and closings of application + windows. +@param delegate {object} + An object that implements `onTrack()` and `onUntrack()` methods. +@prop onTrack {function} + A function to be called when a window is open or loads, with the window as the + first and only argument. +@prop [onUntrack] {function} + A function to be called when a window unloads, with the window as the first + and only argument. +</api> +</api> + +<api name="windowIterator"> +@function + An iterator for windows currently open in the application. + +**Example** + + var winUtils = require("window-utils"); + for (window in winUtils.windowIterator()) + console.log("An open window! " + window.location); + +</api> + +<api name="closeOnUnload"> +@function + Marks an application window to be closed when the program is unloaded. +@param window {window} + The window to close. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/window/utils.md b/tools/addon-sdk-1.7/packages/api-utils/docs/window/utils.md new file mode 100644 index 0000000..276a17a --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/window/utils.md @@ -0,0 +1,90 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +The `window/utils` module provides helper functions for working with +application windows. + +### getInnerId + +Returns the ID of the given window's current inner window. + +### getOuterId + +Returns the ID of the given window's outer window. + +### getXULWindow + +Module provides `getXULWindow` function that can be used get access +[nsIXULWindow](https://developer.mozilla.org/en/nsIDOMWindow) for the given +[nsIDOMWindow](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIXULWindow): + + let { Ci } = require('chrome'); + let utils = require('api-utils/window-utils'); + let active = utils.activeBrowserWindow; + active instanceof Ci.nsIXULWindow // => false + utils.getXULWindow(active) instanceof Ci.nsIXULWindow // => true + +### getBaseWindow + +Module provides `getBaseWindow` function that can be used get access +[nsIBaseWindow](http://mxr.mozilla.org/mozilla-central/source/widget/nsIBaseWindow.idl) +for the given [nsIDOMWindow](https://developer.mozilla.org/en/nsIDOMWindow): + + let { Ci } = require('chrome'); + let utils = require('api-utils/window-utils'); + let active = utils.activeBrowserWindow; + active instanceof Ci.nsIBaseWindow // => false + utils.getBaseWindow(active) instanceof Ci.nsIBaseWindow // => true + +### open + +Module exports `open` function that may be used to open top level +(application) windows. Function takes `uri` of the window document as a first +argument and optional hash of `options` as second argument. + + let { open } = require('api-utils/window-utils'); + let window = open('data:text/html,Hello Window'); + +Following options may be provided to configure created window behavior: + +- `parent` +If provided must be `nsIDOMWindow` and will be used as parent for the created +window. + +- `name` +Optional name that will be assigned to the window. + +- `features` +Hash of options that will be serialized to features string. See +[features documentation](https://developer.mozilla.org/en/DOM/window.open#Position_and_size_features) +for more details. + + let { open } = require('api-utils/window/utils'); + let window = open('data:text/html,Hello Window', { + name: 'jetpack window', + features: { + width: 200, + height: 50, + popup: true + } + }); + +### backgroundify + +Module exports `backgroundify` function that takes `nsIDOMWindow` and +removes it from the application's window registry, so that they won't appear +in the OS specific window lists for the application. + + let { backgroundify, open } = require('api-utils/window/utils'); + let bgwin = backgroundify(open('data:text/html,Hello backgroundy')); + +Optionally more configuration options via second `options` argument. If +`options.close` is `false` unregistered window won't automatically +be closed on application quit, preventing application from quitting. While this +is possible you should make sure to close all such windows manually: + + let { backgroundify, open } = require('api-utils/window-utils'); + let bgwin = backgroundify(open('data:text/html,Foo'), { + close: false + }); diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/xhr.md b/tools/addon-sdk-1.7/packages/api-utils/docs/xhr.md new file mode 100644 index 0000000..d0381c0 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/xhr.md @@ -0,0 +1,95 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Atul Varma [atul@mozilla.com] --> +<!-- edited by Noelle Murata [fiveinchpixie@gmail.com] --> + +The `xhr` module provides access to `XMLHttpRequest` functionality, also known +as AJAX. + +## Limitations ## + +The `XMLHttpRequest` object is currently fairly limited, and does not +yet implement the `addEventListener()` or `removeEventListener()` +methods. It also doesn't yet implement the `upload` property. + +Furthermore, the `XMLHttpRequest` object does not currently support +the `mozBackgroundRequest` property. All security UI, such as +username/password prompts, are automatically suppressed, so if +required authentication information isn't passed to the `open()` +method, the request will fail. + +## Resource Use ## + +Whenever this module is unloaded, all in-progress requests are immediately +aborted. + +## Security Concerns ## + +By default, the `XMLHttpRequest` object grants full access to any +protocol scheme, which means that it can be used to read from (but not +write to) the host system's entire filesystem. It also has unfettered +access to any local area networks, VPNs, and the internet. + +### Threat Model ### + +The `XMLHttpRequest` object can be used by an add-on to "phone +home" and transmit potentially sensitive user data to third +parties. + +If access to the filesystem isn't prevented, it could easily be used +to access sensitive user data, though this may be inconsequential if +the client can't access the network. + +If access to local area networks isn't prevented, malicious code could access +sensitive data. + +If transmission of cookies isn't prevented, malicious code could access +sensitive data. + +Attenuating access based on a regular expression may be ineffective if +it's easy to write a regular expression that *looks* safe but contains +a special character or two that makes it far less secure than it seems +at first glance. + +### Possible Attenuations ### + +<span class="aside"> +We may also want to consider attenuating further based on domain name +and possibly even restricting the protocol to `https:` only, to reduce +risk. +</span> + +Before being exposed to unprivileged code, this object needs +to be attenuated in such a way that, at the very least, it can't +access the user's filesystem. This can probably be done most securely +by white-listing the protocols that can be used in the URL passed to +the `open()` method, and limiting them to `http:`, `https:`, and +possibly a special scheme that can be used to access the add-on's +packaged, read-only resources. + +Finally, we need to also consider attenuating http/https requests such +that they're "sandboxed" and don't communicate potentially sensitive +cookie information. + +<api name="XMLHttpRequest"> +@class + +<api name="XMLHttpRequest"> +@constructor + Creates an `XMLHttpRequest`. This is a constructor, so its use should always + be preceded by the `new` operator. For more information about + `XMLHttpRequest` objects, see the MDC page on + [Using XMLHttpRequest](https://developer.mozilla.org/En/Using_XMLHttpRequest) + and the Limitations section in this page. +</api> +</api> + +<api name="getRequestCount"> +@function + Returns the number of `XMLHttpRequest` objects that are alive (i.e., currently + active or about to be). +@returns {integer} + The number of live `XMLHttpRequest` objects. +</api> diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md b/tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md new file mode 100644 index 0000000..6d96650 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/xpcom.md @@ -0,0 +1,216 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +Module `xpcom` provides low level API for implementing and registering / +unregistering various XCOM interfaces. + +## Implementing XPCOM interfaces + +Module exports `Unknow` exemplar object, that may be extended to implement +specific XCOM interface(s). For example [nsIObserver] +(https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIObserver) may be +implemented as follows: + + const { Unknown } = require('api-utils/xpcom'); + const { Cc, Ci } = require('chrome') + const observerService = Cc["@mozilla.org/observer-service;1"]. + getService(Ci.nsIObserverService); + + // Create my observer exemplar + const SleepObserver = Unknown.extend({ + interfaces: [ 'nsIObserver' ], // Interfaces component implements + topic: 'sleep_notification', + initialize: function(fn) { this.fn = fn }, + register: function register() { + observerService.addObserver(this, this.topic, false); + }, + unregister: function() { + addObserver.removeObserver(this, this.topic, false); + }, + observe: function observe(subject, topic, data) { + this.fn({ + subject: subject, + type: topic, + data: data + }); + } + }); + + // create instances of observers + let observer = SleepObserver.new(function(event) { + console.log('Going to sleep!') + }); + // register observer + observer.register(); + +## Implementing XCOM factories + +Module exports `Factory` exemplar, object that may be used to create objects +implementing +[nsIFactory](https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIFactory) +interface: + + const { Factory } = require('api-utils/xpcom'); + let Request = Unknown.extend({ + interfaces: [ 'nsIRequest' ], + initialize: function initialize() { + this.pending = false; + // Do some initialization + }, + isPending: function() { return this.pending }, + resume: function() { /* Implementation */ }, + suspend: function() { /* Implementation */ }, + cancel: function() { /* Implementation */ }, + initiate: function() { + this.pending = true; + /* Implementation */ + } + }); + + let requestFactory = Factory.new({ component: Request }); + +Factories registered into a runtime may be accessed from the rest of the +application via standard XPCOM API using factory's auto generated `id` +(optionally you could specify specific `id` by passing it as an option): + + let request = Components.classesByID[requestFactory.id]. + createInstance(Ci.nsIRequest); + request.isPending() // => false + +Be aware that traditional XPCOM API will always return a wrapped JS objects +exposing only properties defined by a given interface (`nsIRequest`) in our +case: + + request.initiate() // TypeError: request.initiate is not a function + +You still can expose unwrapped JS object, by a special `wrappedJSObject` +property of the component: + + let Request = Unknown.extend({ + get wrappedJSObject() this, + interfaces: [ 'nsIRequest' ], + initialize: function initialize() { + this.pending = false; + // Do some initialization + }, + isPending: function() { return this.pending }, + resume: function() { /* Implementation */ }, + suspend: function() { /* Implementation */ }, + cancel: function() { /* Implementation */ }, + initiate: function() { + this.pending = true; + /* Implementation */ + } + }); + + let requestFactory = Factory.new({ component: Request }); + let request = Components.classesByID[requestFactory.id]. + createInstance(Ci.nsIRequest); + request.isPending(); // => false + request.wrappedJSObject.initiate(); + request.isPending(); // => true + +Optionally `Factory.new` may be passed globally unique string in a format of: +`'@domain.com/unique/identifier;1'` as a `contract` option in order to +associate it with it: + + let namedFactory = Factory.new({ + contract: '@examples.com/request/factory;1', + component: Request + }); + +Such factories when registered can be accessed form rest of the application by +human readable `contract` strings: + + let request = Components.classes['@examples.com/request/factory;1']. + createInstance(Components.interfaces.nsIRequest); + +In addition factories associated with a given `contract` may be replaced at +runtime: + + let renewedFactory = Factory.new({ + contract: '@examples.com/request/factory;1', + component: Unknown.extend({ /* Implementation */ }) + }) + +Unfortunately commonly used `Components.classes` won't get updated at runtime +but there is an alternative, more verbose way to access last registered factory +for a given `contract`: + + let id = Components.manager.QueryInterface(Ci.nsIComponentRegistrar). + contractIDToCID('@examples.com/request/factory;1'); + Components.classesByID[requestFactory.id]. + createInstance(Ci.nsISupports); + +Module also exports `factoryByContract` function to simplify this: + + factoryByContract('@examples.com/request/factory;1'). + createInstance(Ci.nsISupports); + +It's also recommended to construct factories with an optional `description` +property, providing human readable description of it: + + let factory = Factory.new({ + contract: '@examples.com/request/factory;1', + description: 'Super duper request factory', + component: Request + }); + +## Registering / Unregistering factories + +All factories created using `Factory.new` get automatically registered into +runtime unless explicitly specified otherwise by setting `register` option to +`false`: + + var factoryToRegister = Factory.new({ + register: false, + component: Unknown.extend({ /* Implementation */ }) + }); + +Such factories still may be registered manually using exported `register` +function: + + const { register } = require('api-utils/xpcom'); + register(factoryToRegister); + +All factories created using `Factory.new` also get unregistered automatically +when add-on is unloaded. This also can be disabled by setting `unregister` +option to `false`. + + var factoryToUnregister = Service.new({ + unregister: false, + component: Unknown.extend({ /* Implementation */ }) + }); + +All registered services may be unregistered at any time using exported +`unregister` function: + + unregister(factoryToUnregister); + +## Implementing XCOM services + +Module exports `Service` exemplar object, that has exact same API as `Factory` +and can be used to register services: + + const { Service } = require('api-utils/xpcom'); + let service = Service.new({ + contract: '@examples/demo/service;1', + description: 'My demo service', + component: Unknown.extend({ + // Implementation + get wrappedJSObject() this + }) + }); + +Registered services can be accessed through the rest of the application via +standard XPCOM API: + + let s = Components.classes['@examples/demo/service;1']. + getService(Components.interfaces.nsISupports); + +In contrast to factories, services do not create instances of enclosed +components, they expose component itself. Also please note that idiomatic way +to work with a service is via `getService` method: + + s.wrappedJSObject === service.component // => true diff --git a/tools/addon-sdk-1.7/packages/api-utils/docs/xul-app.md b/tools/addon-sdk-1.7/packages/api-utils/docs/xul-app.md new file mode 100644 index 0000000..597af56 --- /dev/null +++ b/tools/addon-sdk-1.7/packages/api-utils/docs/xul-app.md @@ -0,0 +1,76 @@ +<!-- This Source Code Form is subject to the terms of the Mozilla Public + - License, v. 2.0. If a copy of the MPL was not distributed with this + - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> + +<!-- contributed by Drew Willcoxon [adw@mozilla.com] --> + +The `xul-app` module provides facilities for introspecting the application on +which your program is running. + +With the exception of `ids`, each of these properties exposes the attribute of +the same name on the [`nsIXULAppInfo`][nsIXULAppInfo] interface. For more +information, see the [MDC documentation][]. + +[nsIXULAppInfo]: http://mxr.mozilla.org/mozilla-central/source/xpcom/system/nsIXULAppInfo.idl +[MDC documentation]: https://developer.mozilla.org/en/nsIXULAppInfo + +<api name="ID"> +@property {string} + The GUID of the host application. For example, for Firefox this value is + `"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"`. +</api> + +<api name="name"> +@property {string} + The host application name. For example, `"Firefox"`. +</api> + +<api name="version"> +@property {string} + The host application version. +</api> + +<api name="platformVersion"> +@property {string} + The Gecko/XULRunner platform version. +</api> + +<api name="ids"> +@property {object} + A mapping of application names to their IDs. For example, + `ids["Firefox"] == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"`. +</api> + +<api name="is"> +@function + Checks whether the host application is the given application. +@param name {string} + A host application name. +@returns {boolean} + True if the host application is `name` and false otherwise. +</api> + +<api name="isOneOf"> +@function + Checks whether the host application is one of the given applications. +@param names {array} + An array of host application names. +@returns {boolean} + True if the host application is one of the `names` and false otherwise. +</api> + +<api name="versionInRange"> +@function + Compares a given version to a version range. See the [MDC documentation](https://developer.mozilla.org/en/Toolkit_version_format#Comparing_versions) + for details on version comparisons. +@param version {string} + The version to compare. +@param lowInclusive {string} + The lower bound of the version range to compare. The range includes this + bound. +@param highExclusive {string} + The upper bound of the version range to compare. The range does not include + this bound. +@returns {boolean} + True if `version` falls in the given range and false otherwise. +</api> |